Example #1
0
def receiveDelivery():
    formQuantities = ProductQuantityForm(request.form)
    maker_id = request.form['maker_id']
    if not maker_id:
        flash(gettext("Maker not found."))
        return redirect(url_for("deliveries"))

    if formQuantities.validate_on_submit():

        new_delivery = Delivery()
        #TODO other date than now   new_delivery.created_dt =
        new_delivery.maker_id = maker_id
        new_delivery.user_id = g.user.id
        db.session.add(new_delivery)
        db.session.commit()

        #variable for reporting purposes
        report = {'recipient': g.user.nickname, 'maker': Maker.query.filter_by(id=maker_id).first().name, 'products': [], 'closed_orders': [],
                  'changed_orders': [], 'overreceived_products': False}

        #add received products to new delivery
        form_data = formQuantities.data['fields']
        for product in form_data:
            new_quantity = int(product['qty_order'])
            if new_quantity > 0:
                new_product = Product.query.filter_by(id=int(product['product_id'])).first()
                if new_product:

                    dp = DeliveredProducts(quantity=new_quantity)
                    dp.product = new_product
                    dp.delivery_id = new_delivery.id
                    new_delivery.products.append(dp)

                    report_details = {'product': new_product, 'qty': new_quantity, 'over': 0}

                    '''Here we are going to take each order for given product (from oldest),
                    and add delivered quantity and also product stock quantity by subtracting
                    new quantity, one order a time, until new quantity reaches zero.
                    If delivered quantity of given order reaches ordered quantity, then we
                    have to check, whether all other products of that order have been delivered.
                    If so, the order is complete and we'll switch it's active flag to False.'''

                    #create temp qty equal to new quanity that will be substracted until there are orders
                    temp_qty = new_quantity
                    #get ordered products for product from oldest
                    ordered_products = new_product.order_assocs
                    ordered_products.sort(key=lambda x: x.order.created_dt, reverse=False)
                    for op in ordered_products:
                        #count ordered products quantity - qty_delivered = delta qty
                        if op.qty_delivered is None:
                            op.qty_delivered = 0
                        delta_qty = op.quantity - op.qty_delivered

                        if delta_qty <= temp_qty:

                            if new_product.qty_stock is not None:
                                new_product.qty_stock += (op.quantity - op.qty_delivered)

                            op.qty_delivered = op.quantity

                            #if order completely delivered add to report
                            if op.order.active_flg:
                                if op.order.check_completely_delivered():
                                    while True:
                                        if op.order in report['changed_orders']:
                                            report['changed_orders'].remove(op.order)
                                        else:
                                            break
                                    report['closed_orders'].append(op.order)
                                else:
                                    if op.order not in report['changed_orders']:
                                        report['changed_orders'].append(op.order)

                            if delta_qty == temp_qty:
                                temp_qty = 0
                                break
                        else:
                            if new_product.qty_stock is not None:
                                new_product.qty_stock += temp_qty

                            op.qty_delivered += temp_qty
                            temp_qty -= op.qty_delivered
                            if op.order not in report['changed_orders']:
                                report['changed_orders'].append(op.order)
                            break

                        temp_qty -= delta_qty

                    if temp_qty > 0:
                        if new_product.qty_stock is not None:
                            new_product.qty_stock += temp_qty

                        report_details['over'] = temp_qty
                        report['overreceived_products'] = True
                    report['products'].append(report_details)

        db.session.commit()

        # Send e-mail to customers with delivered products notification
        send_delivery_notification_to_customers(report['maker'], report['products'])

        flash( gettext('New delivery received sucessfully.') )
        print(report)

        return render_template('deliveries/deliveryReport.html',
                           title=gettext("Delivery Report"),
                           report=report)

    #if not validated return to maker select
    products = Product.query.order_by(Product.maker_id, Product.code)\
        .filter_by(maker_id=int(maker_id),
                   active_flg=True).all()
    formMaker = SelectMakerForm()
    formMaker.maker.choices = [(a.id, a.name) for a in Maker.query.all()]
    return render_template('deliveries/newDelivery.html',
                           title=gettext("New Delivery"),
                           formMaker=formMaker,
                           formQuantities=formQuantities,
                           products=products)
Example #2
0
def placeOrder():
    formQuantities = ProductQuantityForm(request.form)
    maker_id = request.form['maker_id']
    if not maker_id:
        flash(gettext("Maker not found."))
        return redirect(url_for("orders"))

    if formQuantities.validate_on_submit():

        new_order = Order()
        #TODO other date than now   new_order.created_dt =
        new_order.maker_id = maker_id
        new_order.user_id = g.user.id
        db.session.add(new_order)
        db.session.commit()

        #add ordered products to new order
        form_data = formQuantities.data['fields']
        for product in form_data:
            new_quantity = int(product['qty_order'])
            if new_quantity > 0:
                new_product = Product.query.filter_by(id=int(product['product_id'])).first()
                if new_product:
                    op = OrderedProducts(quantity=new_quantity)
                    op.product = new_product
                    op.order_id = new_order.id
                    new_order.products.append(op)

        db.session.commit()

        # Create order sheet xls
        xls = CreateXls()
        maker = Maker.query.filter_by(id=maker_id).first()
        maker_name = maker.name
        data = []
        for item in form_data:
            if item['qty_order'] < 1:
                continue
            product = Product.query.filter_by(id=item['product_id']).first()
            if product:
                data.append({'product_code': product.code, 'product_maker_code': product.maker_code,\
                             'product_name': product.desc_CS, 'quantity': item['qty_order']})
        order_xls = xls.order_sheet(maker_name, data)
        match = re.search(r"[^a-zA-Z](ordersheet)[^a-zA-Z]", order_xls)
        pos = match.start(1)
        filename = order_xls[pos:]

        flash(gettext('New order to maker was successfully created.'))

        return render_template('orders/ordersheet.html',
                               title=gettext("Order Sheet Management"),
                               ordersheet_file=filename,
                               maker=maker,
                               mail_sent=False)

    #if not validated return to maker select
    products = Product.query.order_by(Product.maker_id, Product.code)\
        .filter_by(maker_id=int(maker_id),
                   active_flg=True).all()
    formMaker = SelectMakerForm()
    formMaker.maker.choices = [(a.id, a.name) for a in Maker.query.all()]
    return render_template('orders/createOrder.html',
                           title=gettext("Place new order to maker"),
                           formMaker=formMaker,
                           formQuantities=formQuantities,
                           products=products)