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 __check_auth(*args, **kwargs): session['url'] = request.path try: # TODO: better name and configurability for the token if level > 0: user = user_from_token(request.cookies['token']) else: user = user_from_token() if user.id_profil < level: log.info('Privilege too low') return Response('Forbidden', 403) if get_user: kwargs['id_user'] = user.id_user g.user = user return fn(*args, **kwargs) except AccessRightsExpiredError: if redirect_on_expiration: res = redirect(redirect_on_expiration, code=302) else: res = Response('Token Expired', 403) res.set_cookie('token', '', expires=0) return res except KeyError as e: if level > 0: if 'token' not in e.args: raise if redirect_on_expiration: return redirect(redirect_on_expiration, code=302) return Response('No token', 403) else: pass except UnreadableAccessRightsError: log.info('Invalid Token : BadSignature') # invalid token, if redirect_on_invalid_token: res = redirect(redirect_on_invalid_token, code=302) else: res = Response('Token BadSignature', 403) res.set_cookie('token', '', expires=0) return res except Exception as e: trap_all_exceptions = current_app.config.get( 'TRAP_ALL_EXCEPTIONS', True) if not trap_all_exceptions: raise log.critical(e) msg = json.dumps({'type': 'Exception', 'msg': repr(e)}) return Response(msg, 403)
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 profils(): """ Route qui affiche la liste des profils 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 roles du profil --> 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 listes --> 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 == 6: user_right = ['C','R','U','D'] else: user_right = ['R'] fLine = ['Code', 'Nom', 'Description'] columns = ['id_profil', 'profil_code', 'profil_name', 'profil_comment'] tab = [data for data in TProfils.get_all()] return render_template( 'table_database.html', user_right=user_right, fLine=fLine, line=columns, table=tab, key='id_profil', pathU=config.URL_APPLICATION + '/profil/update/', pathD=config.URL_APPLICATION + '/profil/delete/', pathA=config.URL_APPLICATION + '/profil/add/new', pathP=config.URL_APPLICATION + "/profil/users/", name="un profil", name_list="Profils", otherCol='True', Members="Utilisateurs" )
def info(id_delivery): """ Route affichant le résumé d'une livraison Des liens permettent de créer ou de voir la commande des relais """ if 'token' in request.cookies: user_profil = user_from_token(request.cookies['token']).id_profil else: user_profil = 0 user_right = list() if user_profil >= 4: user_right = ['C', 'R', 'U', 'D'] elif user_profil >= 3: user_right = ['C', 'R'] 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') if delivery['order_limit_date']: delivery['order_limit_date'] = datetime.strptime( delivery['order_limit_date'], '%Y-%m-%d').strftime('%d/%m/%Y') # get delivery products with id_delivery filter q = db.session.query(TProducts) q = q.filter(TProducts.id_delivery == id_delivery) q = q.order_by(TProducts.product_name) data = q.all() if data: products = [p.as_dict() for p in data] else: products = list() return render_template('info_delivery.html', user_right=user_right, url=config.URL_APPLICATION + '/order/choice/' + id_delivery, products=products, delivery=delivery, title="Livraison " + delivery['delivery_name'])
def deliveries(): """ Route qui affiche la liste des livraisons 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 de la page d'information --> pathI - une clé (clé primaire dans la plupart des cas) --> key - un nom (nom de la table) pour le bouton ajout --> name - un nom de listes --> name_list - ajoute une colonne pour accéder aux infos de l'utilisateur --> see """ 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 = ['Active', 'Ouverte', 'Nom', 'Date', 'Commentaire', 'Commander'] columns = [ 'active', 'is_open', 'id_delivery', 'delivery_name', 'delivery_date', 'delivery_comment' ] contents = TDeliveries.get_all(columns=columns, orderbyfields=['delivery_date'], sortdirection='desc') # contents.append(c['delivery_order_link']) for c in contents: c['delivery_date'] = datetime.strptime(c['delivery_date'], '%Y-%m-%d').strftime('%d/%m/%Y') if c['is_open']: c['delivery_order_link'] = '<a href="' + config.URL_APPLICATION + '/order/choice/' + str( c['id_delivery'] ) + '">' + config.URL_APPLICATION + '/order/choice/' + str( c['id_delivery']) + '</a>' else: c['delivery_order_link'] = "Commande fermée" columns.append('delivery_order_link') return render_template('table_database.html', user_right=user_right, table=contents, fLine=fLine, line=columns, sortdirection='desc', sortcol=3, pathI=config.URL_APPLICATION + '/delivery/info/', pathU=config.URL_APPLICATION + '/delivery/update/', key='id_delivery', pathD=config.URL_APPLICATION + '/delivery/delete/', pathA=config.URL_APPLICATION + '/delivery/add/new', pathP=config.URL_APPLICATION + '/order/info/', otherCol='True', Members="Commandes", name="une livraison", name_list="Livraisons", see="True")
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 products(): """ Route qui affiche la liste des utilisateurs 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 de la page d'information --> pathI - une clé (clé primaire dans la plupart des cas) --> key - un nom (nom de la table) pour le bouton ajout --> name - un nom de listes --> name_list - ajoute une colonne pour accéder aux infos de l'utilisateur --> see """ 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', 'Livraison', 'Nom', 'Unité', 'Achat', 'Vente', 'Poids', 'Remarques' ] # noqa columns = [ 'active', 'id_product', 'delivery_name', 'product_name', 'product_unit', 'buying_price', 'selling_price', 'case_weight', 'product_comment' ] # noqa contents = TProducts.get_all(columns=columns, orderbyfields=['id_product'], sortdirection='desc') tab = [] for data in contents: g = data g['delivery_name'] = '<a href="' + config.URL_APPLICATION + '/delivery/info/' + str( data['delivery_rel']['id_delivery'] ) + '">' + data['delivery_rel']['delivery_name'] + '</a>' tab.append(g) return render_template("table_database.html", user_right=user_right, fLine=fLine, line=columns, table=tab, sortdirection='desc', sortcol=1, see="False", duplicate="True", key="id_product", pathI=config.URL_APPLICATION + "/product/info/", pathU=config.URL_APPLICATION + "/product/update/", pathD=config.URL_APPLICATION + "/product/delete/", pathA=config.URL_APPLICATION + "/product/add/new", pathC=config.URL_APPLICATION + "/product/duplicate/", name="un produit", name_list="Produits")
def users(): """ Route qui affiche la liste des utilisateurs 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 de la page d'information --> pathI - une clé (clé primaire dans la plupart des cas) --> key - un nom (nom de la table) pour le bouton ajout --> name - un nom de listes --> name_list - ajoute une colonne pour accéder aux infos de l'utilisateur --> see """ user_profil = user_from_token(request.cookies['token']).id_profil user_right = list() if user_profil >= 4: user_right = ['C','R','U','D'] elif user_profil == 3 or user_profil == 2: user_right = ['R','U'] else: user_right = ['R'] fLine = ['Actif', 'Identifiant', 'Nom', 'Prenom', 'Email', config.WORD_GROUP.capitalize(), 'Remarques'] # noqa columns = ['active', 'id_user', 'identifiant', 'last_name', 'first_name', 'email', 'group_name', 'user_comment'] # noqa if user_profil >= 4: contents = TUsers.get_all(columns, None, ['last_name','first_name']) if user_profil == 3: id_group = user_from_token(request.cookies['token']).id_group q = db.session.query(TUsers).filter(TUsers.id_group==id_group) contents = [data.as_dict(True,columns) for data in q.all()] if user_profil == 2: id_user = user_from_token(request.cookies['token']).id_user q = db.session.query(TUsers).filter(TUsers.id_user==id_user) contents = [data.as_dict(True,columns) for data in q.all()] tab = [] for data in contents: g = data # g['group_name'] = data['group_rel']['group_name'] g['group_name'] = '<a href="'+config.URL_APPLICATION + '/group/members/' + str(data['group_rel']['id_group']) +'">'+ str(data['group_rel']['group_name']) + '</a>' tab.append(g) return render_template( "table_database.html", user_right=user_right, fLine=fLine, line=columns, table=tab, see="False", key="id_user", pathI=config.URL_APPLICATION + "/user/info/", pathU=config.URL_APPLICATION + "/user/update/", pathD=config.URL_APPLICATION + "/user/delete/", pathA=config.URL_APPLICATION + "/user/add/new", name="un utilisateur", name_list="Utilisateurs" )