def addorupdate(id_group): """ Route affichant un formulaire vierge ou non (selon l'url) pour ajouter ou mettre à jour un relais L'envoie du formulaire permet l'ajout ou la maj du relais dans la base Retourne un template accompagné d'un formulaire pré-rempli ou non selon le paramètre id_group Une fois le formulaire validé on retourne une redirection vers la liste des relais """ form = groupforms.Group() if id_group == None: if request.method == 'POST': if form.validate_on_submit() and form.validate(): form_group = pops(form.data) form_group.pop('id_group') TGroups.post(form_group) return redirect(url_for('group.groups')) return render_template('group.html', form=form, title="Formulaire des " + config.WORD_GROUP) else: group = TGroups.get_one(id_group) if request.method == 'GET': form = process(form, group) if request.method == 'POST': if form.validate_on_submit() and form.validate(): form_group = pops(form.data) form_group['id_group'] = group['id_group'] TGroups.update(form_group) return redirect(url_for('group.groups')) return render_template('group.html', form=form, title="Formulaire " + config.WORD_GROUP.capitalize())
def addorupdate(id_user): """ Route affichant un formulaire vierge ou non (selon l'url) pour ajouter ou mettre à jour un utilisateurs L'envoie du formulaire permet l'ajout ou la mise à jour de l'utilisateur dans la base Retourne un template accompagné du formulaire pré-rempli ou non selon le paramètre id_user Une fois le formulaire validé on retourne une redirection vers la liste des users """ user_profil = user_from_token(request.cookies['token']).id_profil form = t_usersforms.Utilisateur() if user_profil <= 2: id_group = user_from_token(request.cookies['token']).id_group form.id_group.choices = TGroups.selectActiveGroups(id_group) else: form.id_group.choices = TGroups.selectActiveGroups() if id_user is not None: user = TUsers.get_one(id_user) if request.method == 'GET': form = process(form, user) if request.method == 'POST': if form.validate_on_submit() and form.validate(): form_user = pops(form.data) form_user.pop('id_user') if form.pass_plus.data: try: ( form_user['pass_plus'] ) = TUsers.set_password( form.pass_plus.data, form.mdpconf.data ) except Exception as exp: flash(str(exp)) return render_template( 'user.html', form=form, title="Formulaire Utilisateur" ) else: form_user.pop('pass_plus') if id_user is not None: form_user['id_user'] = id_user TUsers.update(form_user) else: TUsers.post(form_user) return redirect(url_for('user.users')) else: errors = form.errors flash(errors) return render_template( 'user.html', form=form, title="Formulaire Utilisateur" )
def delete(id_group): """ Route qui supprime un relais dont l'id est donné en paramètres dans l'url Retourne une redirection vers la liste des relais """ try: TGroups.delete(id_group) return redirect(url_for('group.groups')) except (exc.SQLAlchemyError, exc.DBAPIError) as e: flash( "Peut-être que tu essaies de faire quelque chose qui n'est pas cohérent." ) flash(e) return render_template('error.html', title="Houps ! Une erreur s'est produite")
def orderchoice(id_delivery=None, id_group=None): """ Route affichant un formulaire préalable à la commande Il permet de choisir sa commande et son relais L'envoi du formulaire passe les paramètres id_delivery et id_group au formulaire principal de la commande Retourne un template accompagné du formulaire pré-rempli ou non """ user_profil = user_from_token(request.cookies['token']).id_profil user_right = list() if user_profil >= 2: user_right = ['C','R','U','D'] form = orderchoiceform() form.id_delivery.choices = TDeliveries.selectActiveDeliveries(True) # True select only open deliveries if user_profil <= 3: id_group = user_from_token(request.cookies['token']).id_group form.id_group.choices = TGroups.selectActiveGroups(id_group) else: form.id_group.choices = TGroups.selectActiveGroups() title = "Choisir une livraison et un " + config.WORD_GROUP if id_delivery is not None: delivery = TDeliveries.get_one(id_delivery) title = "Choisir un "+config.WORD_GROUP+" pour la livraison '" + delivery['delivery_name'] + "'" if request.method == 'GET': form.id_delivery.process_data(id_delivery) form.id_group.process_data(id_group) del form.id_delivery if request.method == 'POST': if form.validate_on_submit() and form.validate(): if id_delivery is None: id_delivery = form.data['id_delivery'] if id_group is None: id_group = form.data['id_group'] return redirect(url_for('order.addorupdate', id_delivery=id_delivery, id_group=id_group)) else: errors = form.errors flash(errors) return render_template('order_choice.html', form=form, title=title)
def groups(): """ Route qui affiche la liste des relais Retourne un template avec pour paramètres : - les droits de l'utilisateur selon son porfil --> user_right - une entête de tableau --> fLine - le nom des colonnes de la base --> line - le contenu du tableau --> table - le chemin de mise à jour --> pathU - le chemin de suppression --> pathD - le chemin d'ajout --> pathA - le chemin des membres du relais --> pathP - une clé (clé primaire dans la plupart des cas) --> key - un nom (nom de la table) pour le bouton ajout --> name - un nom de relais --> name_list - ajoute une colonne de bouton ('True' doit être de type string)--> otherCol - nom affiché sur le bouton --> Members """ user_profil = user_from_token(request.cookies['token']).id_profil user_right = list() if user_profil >= 4: user_right = ['C', 'R', 'U', 'D'] else: user_right = ['R'] fLine = ['Actif', 'Nom', 'Responsable', 'email', 'tel', 'Remarques'] columns = [ 'active', 'id_group', 'group_name', 'group_leader', 'group_main_email', 'group_main_tel', 'group_comment' ] contents = TGroups.get_all(columns) return render_template('table_database.html', user_right=user_right, fLine=fLine, line=columns, table=contents, sortdirection='asc', sortcol=1, key="id_group", pathI=config.URL_APPLICATION + '/group/info/', pathU=config.URL_APPLICATION + "/group/update/", pathD=config.URL_APPLICATION + "/group/delete/", pathA=config.URL_APPLICATION + '/group/add/new', pathP=config.URL_APPLICATION + '/group/members/', name="un " + config.WORD_GROUP, name_list=config.WORD_GROUP.capitalize(), otherCol='True', Members="Membres", see='False')
def membres(id_group): """ Route retournant la liste des users appartenant au relais Avec pour paramètre un id de relais (id_group) """ q = db.session.query(TUsers) q = q.order_by(TUsers.last_name) q = q.filter(TUsers.id_group == id_group) tab = [data.as_dict() for data in q.all()] group = TGroups.get_one(id_group) return render_template("info_relais.html", table=tab, group=group, name_list="Membres du " + config.WORD_GROUP)
def addorupdate(id_delivery, id_group): """ Route affichant un formulaire pour ajouter ou mettre à jour une commande L'envoie du formulaire permet l'ajout ou la mise à jour de la commande dans la base Retourne un template accompagné du formulaire pré-rempli ou non Une fois le formulaire validé on retourne une redirection vers un résumé de la commande """ user_profil = user_from_token(request.cookies['token']).id_profil user_right = list() if user_profil == 6: user_right = ['C','R','U','D'] elif user_profil >= 3 and user_profil < 6: user_right = ['C','R','U'] else: user_right = ['R'] # get delivery informations with id_delivery filter delivery = TDeliveries.get_one(id_delivery) delivery['delivery_date'] = datetime.strptime(delivery['delivery_date'],'%Y-%m-%d').strftime('%d/%m/%Y') is_open = delivery['is_open'] if is_open: # get active products order in t_products table with id_delivery filter q = db.session.query(TProducts) q = q.filter(and_(TProducts.id_delivery == id_delivery, TProducts.active == True)) q = q.order_by(TProducts.product_name) products = [p.as_dict() for p in q.all()] if len(products) == 0: flash("Aucun produit n'a été enregistré pour cette livraison.") return render_template( 'error.html', title="Houps ! Un petit soucis" ) # destroy products fields in form for a construction with differents field # in case of switch between differents deliveries orderform(request.form).clean_attr() # construct new form with delivery products nbcase = list() for p in products: formlabel = p['product_name'] + ' (' + p['product_unit'] + ' de ' + str(p['case_weight']) + ' kg)' if p['product_comment']: formlabel += ' - ' + p['product_comment'] orderform.append_nbcase( 'nb'+str(p['id_product']), formlabel ) nbcase.append('nb'+str(p['id_product'])) form = orderform(request.form) form.id_group.choices = TGroups.selectActiveGroups() is_update = False if id_group is not None: # prevent manual change of id_group in the URL for unauthorized users if user_profil <= 3 and int(id_group) != user_from_token(request.cookies['token']).id_group: id_group = user_from_token(request.cookies['token']).id_group flash("Vous ne pouvez passer commande que pour votre " + config.WORD_GROUP) return render_template( 'error.html', title="Hum ! petit soucis" ) for p in products: try: order = TOrders.get_one((id_group, p['id_product'])) is_update = True if request.method == 'GET': form = process(form, order) except: pass del form.id_group group = TGroups.get_one(id_group) title = "Commande du " + config.WORD_GROUP + " '" + group['group_name']+"' pour la livraison " + delivery['delivery_name'] else: title = "Nouvelle commande pour la livraison " + delivery['delivery_name'] if request.method == 'POST' and user_profil < 4: form.hidden_group_discount.process_data(form.data['hidden_group_discount']) else: form.hidden_group_discount.process_data(form.data['group_discount']) if user_profil < 4: del form.group_discount if request.method == 'POST': if form.validate_on_submit() and form.validate(): if id_group is None: id_group = form.data['id_group'] group = TGroups.get_one(id_group) form_order = pops(form.data) for key, value in form_order.items(): post_order = dict() post_order['id_group'] = id_group post_order['group_discount'] = form.data['hidden_group_discount'] if key[0:2] == 'nb': post_order['id_product'] = key[2:] post_order['product_case_number'] = value try: TOrders.update(post_order) except (exc.SQLAlchemyError, exc.DBAPIError) as e: flash("Peut-être que tu essaies de faire quelque chose qui n'est pas cohérent.") flash(e) return render_template( 'error.html', title="Houps ! Une erreur s'est produite" ) q = db.session.query(VGroupOrdersDetail) q = q.filter(and_(VGroupOrdersDetail.id_delivery == id_delivery, VGroupOrdersDetail.id_group == id_group)).order_by(VGroupOrdersDetail.group_name, VGroupOrdersDetail.product_name) group_order = [go.as_dict() for go in q.all()] group_order_sum = VGroupOrdersSum.get_one((id_delivery, id_group)) return render_template( 'info_group_order.html', user_right=user_right, group_order=group_order, group_order_sum=group_order_sum, group=group, delivery=delivery, title="Résumé de votre commande (livraison du " + delivery['delivery_date'] +")" ) else: errors = form.errors flash(errors) return render_template( 'order.html', is_update=is_update, nbcase=nbcase, form=form, title=title ) else: flash("Aucune modification n'est possible sur cette commande.") return render_template( 'error.html', title="La commande est fermée." )
def info(id_delivery): """ Route affichant le résumé d'une commande Des liens permettent de modifier la commande d'un relais """ user_profil = user_from_token(request.cookies['token']).id_profil user_right = list() if user_profil == 6: user_right = ['C','R','U','D'] elif user_profil >= 3 and user_profil < 6: user_right = ['C','R','U'] else: user_right = ['R'] # get delivery informations with id_delivery filter delivery = TDeliveries.get_one(id_delivery) delivery['delivery_date'] = datetime.strptime(delivery['delivery_date'],'%Y-%m-%d').strftime('%d/%m/%Y') # get all active groups ordered by name q = db.session.query(TGroups.id_group) q = q.filter(and_(TGroups.active, TGroups.id_group > 0)) q = q.order_by(TGroups.group_name) data = q.all() if data: orderedgroups = [p[0] for p in data] else: flash("Aucun produit n'a été enregistré pour cette livraison.") return render_template( 'error.html', title="Houps ! Un petit soucis" ) # get orders details orders = list() for og in orderedgroups: order = dict() q = db.session.query(TOrders) q = q.join(TProducts, TProducts.id_product == TOrders.id_product) q = q.join(TDeliveries, TDeliveries.id_delivery == TProducts.id_delivery) q = q.filter(and_(TProducts.id_delivery == id_delivery, TProducts.active == True, TOrders.id_group == og)) q = q.order_by(TProducts.product_name) order['products'] = [{'product':o.product_rel.as_dict(), 'nb':o.product_case_number, 'price':round(o.product_case_number*o.product_rel.selling_price*(1+(o.group_discount/100)),2)} for o in q.all()] order['group'] = TGroups.get_one(og) mysum = 0 if len(order['products']) > 0: for p in order['products']: mysum = mysum + p['price'] order['group_price'] = round(mysum,2) else: order['group_price'] = 0 order['products'] = {} orders.append(order) if len(orders) == 0: flash("Aucun " + config.WORD_GROUP + " n'a passé commande pour le moment sur cette livraison.") return render_template( 'error.html', title="Houps ! Un petit soucis" ) # get orders sums q = db.session.query(VOrdersResult).filter(VOrdersResult.id_delivery == id_delivery).order_by(VOrdersResult.product_name) results = list() nbc = 0 w = 0 selling = 0 buying = 0 benef = 0 for r in q.all(): result = dict() result = r.as_dict() results.append(result) nbc = nbc + r.case_number w = w + r.weight selling = selling + r.selling_price buying = buying + r.buying_price benef = benef + r.benefice sums = dict() sums['case_number'] = nbc sums['weight'] = w sums['selling'] = round(selling, 2) sums['buying'] = buying sums['benefice'] = benef if len(results) == 0: flash("Aucun " + config.WORD_GROUP + " n'a passé commande pour le moment sur cette livraison.") return render_template( 'error.html', title="Houps ! Un petit soucis" ) return render_template( 'info_order.html', user_right=user_right, orders=orders, delivery=delivery, results=results, sums=sums, title="Commandes pour la livraison du " + delivery['delivery_date'] )
def printorderinfo(id_delivery, id_group=None, action='print'): """ Route permettant d'imprimer le résumé d'une livraison ou la commande d'un groupe """ # get delivery informations with id_delivery filter delivery = TDeliveries.get_one(id_delivery) delivery['delivery_date'] = datetime.strptime(delivery['delivery_date'],'%Y-%m-%d').strftime('%d/%m/%Y') # get all active groups ordered by name q = db.session.query(TGroups.id_group) q = q.filter(and_(TGroups.active, TGroups.id_group > 0)) if id_group is not None: q = q.filter(TGroups.id_group == id_group) q = q.order_by(TGroups.group_name) data = q.all() if data: orderedgroups = [p[0] for p in data] else: flash("Aucun produit n'a été enregistré pour cette livraison.") return render_template( 'error.html', title="Houps ! Un petit soucis" ) # get orders details orders = list() for og in orderedgroups: order = dict() q = db.session.query(TOrders) q = q.join(TProducts, TProducts.id_product == TOrders.id_product) q = q.join(TDeliveries, TDeliveries.id_delivery == TProducts.id_delivery) q = q.filter(and_(TProducts.id_delivery == id_delivery, TProducts.active == True, TOrders.id_group == og)) q = q.order_by(TProducts.product_name) order['products'] = [{'product':o.product_rel.as_dict(), 'nb':o.product_case_number, 'price':round(o.product_case_number*o.product_rel.selling_price*(1+(o.group_discount/100)),2)} for o in q.all()] order['group'] = TGroups.get_one(og) mysum = 0 if len(order['products']) > 0: for p in order['products']: mysum = mysum + p['price'] order['group_price'] = mysum orders.append(order) if len(orders) == 0: flash("Aucun " + config.WORD_GROUP + " n'a passé commande pour le moment sur cette livraison.") return render_template( 'error.html', title="Houps ! Un petit soucis" ) if id_group is None: # get orders sums q = db.session.query(VOrdersResult).filter(VOrdersResult.id_delivery == id_delivery).order_by(VOrdersResult.product_name) results = list() nbc = 0 w = 0 selling = 0 buying = 0 benef = 0 for r in q.all(): result = dict() result = r.as_dict() results.append(result) nbc = nbc + r.case_number w = w + r.weight selling = selling + r.selling_price buying = buying + r.buying_price benef = benef + r.benefice sums = dict() sums['case_number'] = nbc sums['weight'] = w sums['selling'] = round(selling, 2) sums['buying'] = buying sums['benefice'] = benef else: results = list() sums = dict() if action == 'print': return render_template( 'print_order.html', orders=orders, delivery=delivery, results=results, sums=sums, title=delivery['delivery_name'] ) if action == 'export': data = list() productline = ['RELAIS/PRODUITS'] priceline = ['Prix'] unitline = ['Unité'] weightline = ['Poids'] count = 0 for o in orders: line = list() line.append(o['group']['group_name'].upper()) if len(o['products']) > 0: for p in o['products']: if count == 0: productline.append(p['product']['product_name'].upper()) priceline.append(p['product']['selling_price']) unitline.append(p['product']['product_unit']) weightline.append(p['product']['case_weight']) line.append(p['nb'] or 0) if count == 0: productline.append('TOTAL') priceline.append('') unitline.append('') weightline.append('') data.extend([productline, priceline, unitline, weightline]) count = 1 line.append("%.2f" % o['group_price'] or 0) data.append(line) return data