def new_order(supplierid): supplier = Supplier.query.filter_by(id=supplierid).first_or_404() form = OrderForm() try: if form.is_submitted(): # when a post is submitted, we first check if all fields are valid if form.validate(): order = create_order(form, supplier) if order: db.session.add(order) db.session.commit() app.logger.info('Order "{}" criada com sucesso'.format( order.id)) return redirect( url_for('detail_supplier', supplierid=supplier.id)) else: flash(('A compra não foi registrada porque o valor total ' 'dos produtos foi R$0,00!')) return redirect( url_for('detail_supplier', supplierid=supplier.id)) else: # when a field is not valid, we flash a message with the error. app.logger.error(str(form.errors)) flash("Erro! Detalhes: {}".format(str(form.errors))) # when the page is loaded, a GET is executed. # In this case, we only fill table fields. else: if len(supplier.portfolio) == 0: msg = ('O fornecedor "{}"" não tem nenhum produto em seu' ' portfolio. Antes de cadastrar uma compra, você' ' precisa adicionar produtos ao seu portfolio.').format( supplier.name) app.logger.info(msg) flash(msg) return redirect( url_for('edit_supplier', supplierid=supplier.id)) for item in supplier.portfolio: order_item_form = OrderItemForm() order_item_form.item = item.name order_item_form.quantity = 0 order_item_form.unit_price = 0 order_item_form.unity = "" form.order_items.append_entry(order_item_form) except Exception as err: db.session.rollback() app.logger.error(str(err)) flash('ERRO: {}'.format(str(err))) return render_template('orderform.html', title="Cadastrar compra", form=form, supplier=supplier)
def edit_order(orderid): order = Order.query.filter_by(id=orderid).first_or_404() supplier = Supplier.query.filter_by(id=order.supplier_id).first_or_404() form = OrderForm(obj=order) try: if form.is_submitted(): # when a post is submitted, we first check if all fields are valid if form.validate(): order = create_order(form, supplier, order) if order: db.session.commit() app.logger.info('Order "{}" editada com sucesso'.format( order.id)) return redirect( url_for('detail_supplier', supplierid=supplier.id)) else: flash(('A compra não foi alterada porque o valor total ' 'dos produtos foi R$0,00!')) return redirect( url_for('detail_supplier', supplierid=supplier.id)) else: # when a field is not valid, we flash a message with the error. app.logger.error(str(form.errors)) flash('Erro! Detalhes: {}'.format(str(form.errors))) else: for item in supplier.portfolio: if not order.has_item(item): order_item_form = OrderItemForm() order_item_form.item = item.name order_item_form.quantity = 0 order_item_form.unit_price = 0 order_item_form.unity = "" form.order_items.append_entry(order_item_form) except Exception as err: db.session.rollback() app.logger.error(str(err)) flash('ERRO: {}'.format(str(err))) return render_template('orderform.html', title="Editar compra", form=form, supplier=supplier)