def affaires_search_view(request): """ Search affaires """ # Check connected if not Utils.check_connected(request): raise exc.HTTPForbidden() settings = request.registry.settings search_limit = int(settings['search_limit']) params_affaires = {} client_id = None date_from = None date_to = None limitNbResults = True for key in request.params.keys(): if "client" in key: client_id = request.params[key] elif "date_from" in key: date_from = datetime.strptime(request.params[key], '%Y-%m-%d') elif "date_to" in key: date_to = datetime.strptime(request.params[key], '%Y-%m-%d') elif "limitNbResults" in key: if request.params[key] == "true": limitNbResults = True else: limitNbResults = False else: params_affaires[key] = request.params[key] # Chercher les affaires par les clients de facture affaires_id_by_clients_facture = [] if client_id is not None: query_facture = request.dbsession.query(Facture).filter(Facture.client_id == client_id).all() # Récupérer la liste des id des affaires retenues for facture in query_facture: affaires_id_by_clients_facture.append(int(facture.affaire_id)) # Chercher les affaires par les conditions (sauf client_facture) conditions = Utils.get_search_conditions(VAffaire, params_affaires) query = request.dbsession.query(VAffaire).filter(*conditions) if client_id is not None: query = query.filter(or_( VAffaire.client_commande_id == client_id, VAffaire.client_envoi_id == client_id, VAffaire.id.in_(affaires_id_by_clients_facture) )) # filtrer les affaires par critères temporels if not date_from is None: query = query.filter(VAffaire.date_ouverture >= date_from) if not date_to is None: query = query.filter(VAffaire.date_ouverture <= date_to) if limitNbResults: query = query.limit(search_limit) query = query.all() results = Utils.serialize_many(query) for i, result in enumerate(results): clients_facture = request.dbsession.query( Client.entreprise, Client.titre, Client.prenom, Client.nom ).filter( Facture.affaire_id == result['id'] ).filter( Facture.client_id == Client.id ).all() results[i]["client_facture"] = [{'entreprise': x[0], 'titre': x[1], 'nom': x[2], 'prenom': x[3]} for x in clients_facture] return results
def affaires_new_view(request): """ Add new affaire """ # Get role depending on affaire type affaire_type = request.params['type_id'] if 'type_id' in request.params else None # Permission (fonction) par défaut permission = request.registry.settings['affaire_edition'] # Affaire de cadastration if affaire_type == request.registry.settings['affaire_type_cadastration_id']: permission = request.registry.settings['affaire_cadastration_edition'] # Affaire de PPE elif affaire_type == request.registry.settings['affaire_type_ppe_id']: permission = request.registry.settings['affaire_ppe_edition'] # Affaire de révision d'abornement elif affaire_type == request.registry.settings['affaire_type_revision_abornement_id']: permission = request.registry.settings['affaire_revision_abornement_edition'] # Affaire de rétablissement de PFP3 elif affaire_type == request.registry.settings['affaire_type_retablissement_pfp3_id']: permission = request.registry.settings['affaire_retablissement_pfp3_edition'] # Affaire pcop elif affaire_type == request.registry.settings['affaire_type_part_copropriete_id']: permission = request.registry.settings['affaire_pcop_edition'] # Affaire mpd elif affaire_type == request.registry.settings['affaire_type_mpd_id']: permission = request.registry.settings['affaire_mpd_edition'] # Affaire autre elif affaire_type == request.registry.settings['affaire_type_autre_id']: permission = request.registry.settings['affaire_autre_edition'] # Check authorization if not Utils.has_permission(request, permission): raise exc.HTTPForbidden() model = Affaire() model = Utils.set_model_record(model, request.params) request.dbsession.add(model) # Récupèrer l'id de la nouvelle affaire request.dbsession.flush() # Créer le chemin du dossier de l'affaire if model.type_id != request.registry.settings['affaire_type_mpd_id']: affaire_chemin_full_path = os.path.join(request.registry.settings['affaires_directory'], str(model.id)) model.chemin = str(model.id) # chemin relatif else: affaire_chemin_full_path = None # Copier le dossier __template pour une nouvelle affaire if not affaire_chemin_full_path is None: Utils.create_affaire_folder(request, affaire_chemin_full_path) # Créer les formulaires de contrôle params = {'affaire_id': model.id} if not model.type_id in [int(request.registry.settings['affaire_type_part_copropriete_id']), int(request.registry.settings['affaire_type_autre_id'])]: if model.type_id == int(request.registry.settings['affaire_type_ppe_id']): # Create controle PPE Utils.addNewRecord(request, ControlePPE, params) else: # Create controle Mutation Utils.addNewRecord(request, ControleMutation, params) Utils.addNewRecord(request, SuiviMandat, params) Utils.addNewRecord(request, ControleGeometre, params) # Créer l'étape de création d'affaire params['etape_id'] = request.registry.settings['affaire_premiere_etape_defaut_id'] tmp = request.dbsession.query(AffaireType).filter(AffaireType.id == model.type_id).first() if tmp and tmp.logique_processus: if len(tmp.logique_processus) > 0: params['etape_id'] = tmp.logique_processus[0] params['operateur_id'] = request.params['operateur_id'] if 'operateur_id' in request.params else None params['datetime'] = datetime.now() Utils.addNewRecord(request, AffaireEtape, params) # Envoyer e-mail si l'affaire est urgente (sauf si c'est une PPE ou modif de PPE) if model.urgent and (model.type_id != int(request.registry.settings['affaire_type_ppe_id']) or model.type_id != int(request.registry.settings['affaire_type_modification_ppe_id'])): Utils.sendMailAffaireUrgente(request, model) # Add facture if 'facture_client_id' in request.params: params = { 'type_id': request.registry.settings['facture_type_facture_id'], 'affaire_id': model.id, 'client_id': request.params['facture_client_id'], 'client_co_id': request.params['facture_client_co_id'] if 'facture_client_co_id' in request.params else None, 'client_complement': request.params['facture_client_complement'] if 'facture_client_complement' in request.params else None, 'client_premiere_ligne': request.params['facture_client_premiere_ligne'] if 'facture_client_premiere_ligne' in request.params else None, 'montant_mo': 0, 'montant_rf': 0, 'montant_mat_diff': 0, 'montant_tva': 0, 'montant_total': 0 } Utils.addNewRecord(request, Facture, params) return model.id
def raise_forbidden(**kwargs): # A ``403`` error response does not natively rollback the transaction. transaction.doom() kwargs.update(errno=ERRORS.FORBIDDEN) raise errors.http_error(httpexceptions.HTTPForbidden(), **kwargs)
def render(self): settings = self.request.registry.settings if not self.user: raise exc.HTTPForbidden() params = self.request.params if (asbool(settings['pyshop.upload.sanitize']) and not re.match( settings['pyshop.upload.sanitize.regex'], params['version'])): raise exc.HTTPForbidden( "Provided version ({}) should match " "regexp {}".format(params['version'], settings['pyshop.upload.sanitize.regex'])) pkg = Package.by_name(self.session, params['name']) if pkg and pkg.local: auth = [ user for user in pkg.owners + pkg.maintainers if user == self.user ] if not auth: raise exc.HTTPForbidden() elif not pkg: pkg = Package(name=params['name'], local=True) pkg.owners.append(self.user) content = self.request.POST['content'] input_file = content.file if asbool(settings.get('pyshop.upload.rewrite_filename', '1')): # rewrite the filename, do not use the posted one for security filename = self._guess_filename(params, content.filename) else: filename = content.filename dir_ = os.path.join(settings['pyshop.repository'], filename[0].lower()) if not os.path.exists(dir_): os.makedirs(dir_, 0o750) filepath = os.path.join(dir_, filename) while os.path.exists(filepath): log.warning('File %s exists but new upload self.request, deleting', filepath) os.unlink(filepath) size = 0 with open(filepath, 'wb') as output_file: input_file.seek(0) while True: data = input_file.read(2 << 16) if not data: break size += len(data) output_file.write(data) release = Release.by_version(self.session, pkg.name, params['version']) if not release: release = Release( package=pkg, version=params['version'], summary=params.get('summary'), author=self.user, home_page=params.get('home_page'), license=params.get('license'), description=params.get('description'), keywords=params.get('keywords'), platform=params.get('platform'), download_url=params.get('download_url'), docs_url=params.get('docs_url'), ) classifiers = params.getall('classifiers') for name in classifiers: classifier = Classifier.by_name(self.session, name, create_if_not_exists=True) while classifier: if classifier not in release.classifiers: release.classifiers.append(classifier) if classifier not in pkg.classifiers: pkg.classifiers.append(classifier) classifier = classifier.parent rfile = ReleaseFile.by_filename(self.session, release, filename) if not rfile: rfile = ReleaseFile( release=release, filename=filename, size=size, md5_digest=params.get('md5_digest'), package_type=params['filetype'], python_version=params.get('pyversion'), comment_text=params.get('comment'), ) self.session.add(rfile) self.session.add(release) pkg.update_at = func.now() self.session.add(pkg) return {'release_file': rfile}
def error_403(request): """Return a 403 error.""" raise http_exc.HTTPForbidden('You shall not pass')
def reservation_numeros_new_view(request): """ Add new numeros in affaire """ # Check authorization if not Utils.has_permission( request, request.registry.settings['affaire_numero_edition']): raise exc.HTTPForbidden() nombre = int( request.params["nombre"]) if "nombre" in request.params else None affaire_id = int(request.params["affaire_id"] ) if "affaire_id" in request.params else None cadastre_id = int(request.params["cadastre_id"] ) if "cadastre_id" in request.params else None etat_id = int( request.params["etat_id"]) if "etat_id" in request.params else None type_id = int( request.params["type_id"]) if "type_id" in request.params else None numero_base_id = int(request.params["numero_base_id"] ) if "numero_base_id" in request.params else None ppe_suffixe_start = request.params[ "ppe_suffixe_start"] if "ppe_suffixe_start" in request.params else None if not (affaire_id and nombre and cadastre_id and etat_id and type_id): raise CustomError(CustomError.GENERAL_EXCEPTION) settings = request.registry.settings # Récupère les id des états des biens-fonds de la config numero_projet_id = int(settings['numero_projet_id']) # Récupère les id des biens-fonds de la config numero_bf_id = int(settings['numero_bf_id']) numero_ddp_id = int(settings['numero_ddp_id']) numero_ppe_id = int(settings['numero_ppe_id']) numero_pcop_id = int(settings['numero_pcop_id']) affaire_numero_type_nouveau_id = int( settings['affaire_numero_type_nouveau_id']) numero_relation_mutation_id = int(settings['numero_relation_mutation_id']) numero_relation_ddp_id = int(settings['numero_relation_ddp_id']) numero_relation_ppe_id = int(settings['numero_relation_ppe_id']) numero_relation_pcop_id = int(settings['numero_relation_pcop_id']) # Définit la relation entre le numéro de base et le numéro associé # + Récupère l'id du suffixe de l'unité PPE de départ suffixe = None if type_id == numero_ddp_id: relation_type_id = numero_relation_ddp_id elif type_id == numero_ppe_id: relation_type_id = numero_relation_ppe_id unite_start_idx = Utils.get_index_from_unite( request.params["ppe_suffixe_start"].upper( )) if "ppe_suffixe_start" in request.params else 0 elif type_id == numero_pcop_id: relation_type_id = numero_relation_pcop_id suffixe = "part" # Récupère le dernier numéro de bien-fonds réservé dans le cadastre ln = Utils.last_number( request, cadastre_id, [numero_bf_id, numero_ddp_id, numero_ppe_id, numero_pcop_id]) # Enregistrer le numéro for i in range(nombre): if type_id == numero_ppe_id: # Update suffixe = Utils.get_unite_from_index(unite_start_idx + i) params = Utils._params(cadastre_id=cadastre_id, type_id=type_id, etat_id=etat_id, numero=ln + i + 1, suffixe=suffixe) numero_id = numeros_new_view(request, params) # enregistrer le lien affaire-numéro params = Utils._params(affaire_id=affaire_id, numero_id=numero_id, actif=True, type_id=affaire_numero_type_nouveau_id) affaire_numero_new_view(request, params) # enregistrer l'historique de l'état params = Utils._params(numero_id=numero_id, numero_etat_id=etat_id) numeros_etat_histo_new_view(request, params) # enregistrer le numéro sur un bien-fonds de base si nécessaire if numero_base_id: params = Utils._params(numero_id_base=numero_base_id, numero_id_associe=numero_id, relation_type_id=relation_type_id, affaire_id=affaire_id) numeros_relations_new_view(request, params) return Utils.get_data_save_response( Constant.SUCCESS_SAVE.format(Numero.__tablename__))
def __call__(self, event): request = event.request if self.header not in request.headers: raise exc.HTTPForbidden() elif request.headers[self.header] != self.value: raise exc.HTTPForbidden()
def bank_process(context, request): """Give the trainer their allowance, or let them deposit money.""" trainer = request.user if can_collect_allowance(request.user): allowance_form = AllowanceForm(request.POST, csrf_context=request.session) else: allowance_form = None deposit_form = DepositForm(request.POST, csrf_context=request.session) transactions = recent_transactions(trainer) clear_form = TransactionClearForm(request.POST, csrf_context=request.session) stuff = {'allowance_form': allowance_form, 'deposit_form': deposit_form, 'recent_transactions': transactions, 'clear_form': clear_form} if allowance_form is not None and allowance_form.collect_allowance.data: # Make sure everything's in order if not can_collect_allowance(trainer): raise httpexc.HTTPForbidden( "You've already collected this week's allowance!") if not allowance_form.validate(): return stuff # Give the trainer their allowance trainer.money += 3 trainer.last_collected_allowance = datetime.datetime.utcnow().date() return httpexc.HTTPSeeOther('/bank') elif deposit_form.add_rows.data: # Add five rows to the deposit form for n in range(5): deposit_form.transactions.append_entry() return stuff elif deposit_form.deposit.data: # Validate valid = deposit_form.validate() valid = deposit_form.check_for_dupes(request) and valid if not valid: return stuff # Add the transactions for transaction_field in deposit_form.transactions: if transaction_field.amount.data: transaction = db.BankTransaction( trainer_id=trainer.id, amount=transaction_field.amount.data, tcod_post_id=transaction_field.link.post_id ) db.DBSession.add(transaction) # Add note, if applicable if transaction_field.notes.data: db.DBSession.flush() db.DBSession.add(db.BankTransactionNote( bank_transaction_id=transaction.id, trainer_id=trainer.id, note=transaction_field.notes.data )) request.session.flash("Success! You'll receive your money as soon as " "an ASB mod verifies and approves your transaction.") return httpexc.HTTPSeeOther('/bank') elif clear_form.clear.data: # Mark the user's processed transactions as acknowledged for transaction in itertools.chain(transactions['approved'], transactions['denied']): transaction.state = 'acknowledged' return httpexc.HTTPSeeOther('/bank') # Fallback return stuff
def _admin_only(*args, **kwargs): user = args[1].user if user is None or not user.admin: print user, "is forbidden" raise exc.HTTPForbidden('You do not have sufficient permissions to view this page') return func(args, **kwargs)
def new_post(request): if request.authenticated_userid != 'Administrator': raise exc.HTTPForbidden() return {}
def balance_check_existing_oldBF_new_view(request): """ Check if oldBF already exist in DB and create it otherwise """ # Check connected if not Utils.has_permission(request, request.registry.settings['affaire_numero_edition']): raise exc.HTTPForbidden() affaire_id = request.params['affaire_id'] oldBF = json.loads(request.params['oldBF']) # Control existance of each oldBF numero_obj = [] for bf in oldBF: bf_cadastre_id, bf_numero = bf.split("_") numero = request.dbsession.query(Numero).filter(and_( Numero.cadastre_id == bf_cadastre_id, Numero.numero == bf_numero )).first() # Create number if it doesn't exist if not numero: numero = Numero( cadastre_id = bf_cadastre_id, type_id = request.registry.settings['numero_bf_id'], numero = bf_numero, etat_id = request.registry.settings['numero_vigueur_id'] ) request.dbsession.flush() # Add numero to array of Numeros created numero_obj.append(numero) # Add numero_affaire link affnum_exists = request.dbsession.query(AffaireNumero).filter(and_( AffaireNumero.numero_id == numero.id, AffaireNumero.affaire_id == affaire_id )).first() if (affnum_exists is None): affNum = AffaireNumero( affaire_id = affaire_id, numero_id = numero.id, type_id = request.registry.settings['numero_bf_id'], actif = True ) request.dbsession.add(affNum) # Add numero_etat_histo link numEtatHisto_exists = request.dbsession.query(NumeroEtatHisto).filter(and_( NumeroEtatHisto.numero_id == numero.id, NumeroEtatHisto.numero_etat_id == request.registry.settings['numero_vigueur_id'] )).first() if (numEtatHisto_exists is None): numEtatHisto = NumeroEtatHisto( numero_id = numero.id, numero_etat_id = request.registry.settings['numero_vigueur_id'], date = datetime.now().date() ) request.dbsession.add(numEtatHisto) return Utils.serialize_many(numero_obj)