def askDate(canBeNull=True): startDate = "" duration = -1 while "check date is empty or valid": dateCriteria = inquirer.prompt([ inquirer.Text('startDate', message="Entrez une date de début", validate=lambda x: isValidDateOrNone(x)) ]) startDateStr = dateCriteria.get('startDate') # Si l'utilisateur fournit une date on lui force à mettre une durée if startDateStr: startDate = datetime.strptime(startDateStr, '%d/%m/%Y') durationCriteria = inquirer.prompt([ inquirer.Text( 'duration', message="Entrez une durée (nombre de jours)", validate=lambda x: isNumber(x) and int(x) > 0), ]) duration = int(durationCriteria.get('duration')) break else: if canBeNull: break print( "la date doit être au format jour/mois/annee => eg: 12/12/2020" ) return startDate, duration
def login_(): em = EntityManager() db = em.get_db() userId = -1 questions = [ inquirer.RequiredText("email", "Addresse email"), inquirer.Password("password", "Mot de passe") ] while "Verfication de l'utilisateur": try: answers = inquirer.prompt(questions) if len(answers.keys()) != 2: return False username = answers["email"] password = answers["password"] #cuGetTypeBien = db.cursor(dictionary=True) users = Personne.where( "email= '{}' AND mot_de_passe='{}' LIMIT 0,1".format( username, password)) #userRes = cuGetTypeBien.fetchall() if len(users) == 1: g = Gui() g.user = users[0] userId = users[0].id break print("L'utilisateur n'existe pas") except KeyboardInterrupt: return False return True
def change_email(): g = Gui() current_user = g.user questions = [inquirer.Email("email", message="nouvelle email")] answers = inquirer.prompt(questions) if "email" not in answers.keys(): return False email = answers["email"] if len(Personne.where("`email`='{}'".format(email))) > 0: print("Un utilisateur possède déjà cette email...") Page.wait_input() return False query = "UPDATE personne SET email='{}' WHERE id = {}".format( answers["email"], current_user.id) logging.debug("QUERY: %s", query) cursor = db.cursor() cursor.execute(query) db.commit() if cursor.rowcount > 0: print("Email mis à jour") else: print("Echec de la mise à jour") Page.wait_input() return True
def rentals_before(): Page.clear() g = Gui() current_user = g.user logging.debug("Current user id %s", current_user.id) #Print my buildings cursor = db.cursor(dictionary=True) query = "SELECT *, location.id location_id, location.date_arrivee, DATE_ADD(location.date_arrivee, INTERVAL location.duree DAY) as date_depart FROM location_prioprietaire INNER JOIN location on location.bien_immobilier_id = location_prioprietaire.bien_id WHERE proprietaire_id = {} AND estConfirme = 1 AND location.date_arrivee < DATE(NOW())".format( current_user.id) logging.debug("QUERY: %s", query) cursor.execute(query) my_rentals = cursor.fetchall() db.commit() logging.debug("LOCATION EN ATTENTE : %s", my_rentals) headers = [ "id", "Type de bien", "description", "addresse", "date arrivée", "date départ" ] def build_addresse(ad): if ad is None: return "" return "" + ad["rue"] + " " + ad["numero"] + " " + ad[ "etat"] + "(" + ad["commune"] + ")" data = list( map( lambda x: (x["bien_id"], x["type_bien"], x["description"][:20], build_addresse(x), x["date_arrivee"], x["date_depart"]), my_rentals)) if len(data) <= 0: data = [["" for i in range(len(headers))]] string = tt.to_string( data, header=headers, style=tt.styles.ascii_thin_double, ) print(string) #Actions on buildings mapping_actions = {"Retour": "return"} actions = [ inquirer.List("action", message="Que voulez vous faire?", choices=["Retour"]) ] action = inquirer.prompt(actions) logging.debug("CHOOSING TO DO %s ON BUILDING", action) if action is None or "action" not in action.keys(): return False action = mapping_actions[action["action"]] if action == "return": return False
def register_(): print("Hello new user, please fill out the following form \n\n") entity = Personne() answers = None fields = [ "nom", "prenom", ] questions = [ inquirer.Text("nom", message="Nouveau nom"), inquirer.Text("prenom", message="Nouveau prénom"), inquirer.List("genre", message="Genre", choices=["Homme", "Femme", "Agender", "Pangender", "Androgyne", "Genre fluide"]), inquirer.Email("email","Email"), inquirer.Password("mot_de_passe", message="Mot de passe") ] while "Create a user uniquely with his email": answers = inquirer.prompt(questions) if answers is None or not len(answers.keys()) : return False #check if user doesn't aready exist #TODO change he email field to actual email table field if len(Personne.where("`email` = '{}'".format(answers["email"]))) > 0: print("Un utilisateur avec l'email {} existe déjà...\n\n".format(answers["email"])) else: break logging.debug("Creating user (%s) with values %s", entity, answers) for field, value in answers.items(): setattr(entity, field, value) logging.debug("Entite personne %s", entity) print("\nMerci, maintenant nous voulons encore recuillir votre adresse \n") ad_data = get_address() if not len(ad_data.keys()): return False adresse = Addresse.create(**ad_data) p = Personne(**answers) p.adresse_id = adresse.id p.save() logging.debug("personne %s", p) g = Gui() g.user = p print("Utilisateur crée avec succès!") Page.wait_input() return True
def get_address(): communes = Commune.find() commune_mapping = {x.nom + "(" + x.pays_nom + ")": x.nom for x in communes} fields = [ inquirer.RequiredText("rue", message="Rue"), inquirer.RequiredText("numero", message="Numéro"), inquirer.RequiredText("complement_rue", message="Complément"), inquirer.Numeric("npa", message="Npa"), #inquirer.Text("ville", message="Ville"), inquirer.List("commune_nom", message="Commune", choices=list(commune_mapping.keys())) ] answers = inquirer.prompt(fields) if answers is None and not len(answers.keys()): return None answers["commune_nom"] = commune_mapping[answers["commune_nom"]] return answers
def change_password(): g = Gui() current_user = g.user questions = [inquirer.Password("password", message="nouveau mot de passe")] answers = inquirer.prompt(questions) if "password" not in answers.keys(): return False query = "UPDATE personne SET mot_de_passe='{}' WHERE id = {}".format( answers["password"], current_user.id) logging.debug("QUERY: %s", query) cursor = db.cursor() cursor.execute(query) db.commit() if cursor.rowcount > 0: print("Mot de passe mis à jour") else: print("Echec de la mise à jour") Page.wait_input() return True
def change_data(): g = Gui() current_user = g.user questions = [ inquirer.Text("nom", message="Nouveau nom"), inquirer.Text("prenom", message="Nouveau prénom"), inquirer.List("genre", message="Genre", choices=[ "Homme", "Femme", "Agender", "Pangender", "Androgyne", "Genre fluide" ], default=current_user.genre) ] answers = inquirer.prompt(questions) if "genre" not in answers.keys(): return False fields = {k: v for k, v in answers.items() if v} if len(fields.keys()) <= 0: return False set_query = "SET " for k, v in fields.items(): set_query += "{} = '{}', ".format(k, v) query = "UPDATE personne {} WHERE id = {}".format(set_query[:-2], current_user.id) logging.debug("QUERY: %s", query) cursor = db.cursor() cursor.execute(query) db.commit() if cursor.rowcount > 0: print("Mot de passe mis à jour") else: print("Echec de la mise à jour") Page.wait_input() return True print("Mise à jour de vos donnée personnel effectué avec succès") Page.wait_input()
def rentals_future(): Page.clear() g = Gui() current_user = g.user logging.debug("Current user id %s", current_user.id) #Print my buildings cursor = db.cursor(dictionary=True) query = "SELECT *, location.id location_id, location.date_arrivee, DATE_ADD(location.date_arrivee, INTERVAL location.duree DAY) date_depart FROM location_prioprietaire INNER JOIN location on location.bien_immobilier_id = location_prioprietaire.bien_id WHERE proprietaire_id = {} AND estConfirme = 1 AND DATE_ADD(location.date_arrivee, INTERVAL location.duree DAY) > DATE(NOW())".format( current_user.id) logging.debug("QUERY: %s", query) cursor.execute(query) my_rentals = cursor.fetchall() db.commit() logging.debug("LOCATION EN ATTENTE : %s", my_rentals) headers = [ "id", "Type de bien", "description", "addresse", "date arrivée", "date départ" ] def build_addresse(ad): if ad is None: return "" return "" + ad["rue"] + " " + ad["numero"] + " " + ad[ "etat"] + "(" + ad["commune"] + ")" data = list( map( lambda x: (x["bien_id"], x["type_bien"], x["description"][:20], build_addresse(x), x["date_arrivee"], x["date_depart"]), my_rentals)) if len(data) <= 0: data = [["" for i in range(len(headers))]] string = tt.to_string( data, header=headers, style=tt.styles.ascii_thin_double, ) print(string) #Actions on buildings mapping_actions = {"Refuser la location": "refuse", "Retour": "return"} actions = [ inquirer.List("action", message="Que voulez vous faire?", choices=["Refuser la location", "Retour"]) ] action = inquirer.prompt(actions) logging.debug("CHOOSING TO DO %s ON BUILDING", action) if action is None or "action" not in action.keys(): return False action = mapping_actions[action["action"]] if action == "return": return False #Check that it actually is our building building_id = input("\n Numéro du bien: ") if not len(building_id): return False building_id = int(building_id) building_by_id = {x["bien_immobilier_id"]: x for x in my_rentals} logging.debug(building_by_id) if building_id not in building_by_id.keys(): print("Vous ne pouvez editer ce bien.") Page.wait_input() return False #Build query query = "" if action == "refuse": query = "UPDATE location SET `estConfirme` = NULL WHERE bien_immobilier_id = {}".format( building_id) logging.debug("QUERY: %s", query) cursor = db.cursor() cursor.execute(query) try: db.commit() if cursor.rowcount > 0: print("Location mis à jour avec succès") return True else: print("Impossible de mettre à jour la location") return False except: db.rollback() Page.wait_input()
def building_modal(building=None): existed = False if building is None: building = BienImmobilier() else: building = BienImmobilier.find(building["bien_id"]) existed = True type_bien = TypeBien.find() type_bien_default = building.type_bien_nom if building.exists else None fields = [ inquirer.RequiredText("description", message="Description"), inquirer.Numeric("charges", message="Charges"), inquirer.Numeric("tarif_journalier", message="Tarifs journaliers"), inquirer.Numeric("capacite", message="Capacité"), inquirer.Numeric("taille", message="Taille"), inquirer.List("type_bien_nom", message="Type de bien", choices=list(map(lambda x: x.nom, type_bien)), default=type_bien_default) ] if building.exists: msg_address = "Voulez vous changer l'adresse actuel" fields.append(inquirer.Confirm("address_change", message=msg_address)) answers = inquirer.prompt(fields) if answers is None: return False answers = {k: v for k, v in answers.items() if str(v).strip()} #filter out empty answers if not len(answers.keys()): return False if building.exists and answers["address_change"] is True: query = "SET FOREIGN_KEY_CHECKS=0; DELETE FROM adresse WHERE id = {}; SET FOREIGN_KEY_CHECKS=1;".format( building.adresse_id) cursor = db.cursor() logging.debug("QUERY: %s", query) for res in cursor.execute(query, multi=True): pass db.commit() building.adresse_id = None # saving part g = Gui() current_user = g.user data_for_building = { k: v for k, v in answers.items() if k is not "address_change" } building._fill(**data_for_building) if not building.exists: try: address_data = get_address() address = Addresse.create(**address_data) building.adresse_id = address.id building.proprietaire_id = current_user.id building.save() print("Bien immobilier crée correctement") return True except Exception as e: logging.debug(e) print("Impossible d'insérer le bien immobilier") return False else: try: if answers["address_change"]: address_data = get_address() address = Addresse.create(**address_data) building.adresse_id = address.id building.proprietaire_id = current_user.id building.save() print("Bien immobilier mis à jour correctement") return True except Exception as e: logging.debug(e) print("Impossible d'insérer le bien immobilier") return False
def my_properties_(): Page.clear() g = Gui() current_user = g.user logging.debug("Current user id %s", current_user.id) #Print my buildings cursor = db.cursor(dictionary=True) query = "SELECT * FROM search_biens WHERE proprietaire = {}".format( current_user.id) logging.debug("QUERY: %s", query) cursor.execute(query) my_rentals = cursor.fetchall() db.commit() logging.debug(my_rentals) headers = ["id", "Type de bien", "description", "addresse"] def build_addresse(ad): if ad is None: return "" return "" + ad["rue"] + " " + ad["numero"] + " " + ad[ "etat"] + "(" + ad["commune"] + ")" data = list( map( lambda x: (x["bien_id"], x["type_bien"], x["description"][:20], build_addresse(x)), my_rentals)) if len(data) <= 0: data = [["" for i in range(len(headers))]] string = tt.to_string( data, header=headers, style=tt.styles.ascii_thin_double, ) print(string) #Actions on buildings mapping_actions = { "Créer un nouveau bien": "create", "Mettre à jour un bien": "update", "Supprimer un bien": "delete", "Retour": "return" } actions = [ inquirer.List("action", message="Que voulez vous faire?", choices=[ "Créer un nouveau bien", "Mettre à jour un bien", "Supprimer un bien", "Retour" ]) ] action = inquirer.prompt(actions) logging.debug("CHOOSING TO DO %s ON BUILDING", action) if action is None or "action" not in action.keys(): return False action = mapping_actions[action["action"]] if action == "return": return False if action == "create": b = building_modal() if b: print("Nouvelle imeuble créé!") Page.wait_input() return True building_id = input("\n Numéro du bien: ") if not len(building_id): return False building_id = int(building_id) building_by_id = {x["bien_id"]: x for x in my_rentals} logging.debug("MES APPARTEMENTS %s", building_by_id) if building_id not in building_by_id.keys(): print("Vous ne pouvez editer ce bien.") Page.wait_input() return False current_building = building_by_id[building_id] if action == "update": building_modal(current_building) Page.wait_input() elif action == "delete": #get building query = "DELETE from bien_immobilier WHERE id = {}".format(building_id) logging.debug("QUERY: %s", query) cursor = db.cursor() cursor.execute(query) try: db.commit() if cursor.rowcount > 0: print("Bien immobilier supprimé avec succès") return True else: print("Impossible de supprimer le bien immobilier") return False except: db.rollback() Page.wait_input()
def search_(): # permet d'envoyer une requete et renvoie le résultat def getQueryRes(query): cu = db.cursor() cu.execute(query) return cu.fetchall() # permet d'insérer les résultat au moyen d'une requete def insert(query): cu = db.cursor() cu.execute(query) db.commit() logging.debug(cu.statement) return cu.rowcount is 1 # ajouter une query def addAndToQuery(query, fieldName, value): if query: query += " AND {} = '{}'".format(fieldName, value) else: query = " {} = '{}'".format(fieldName, value) return query # permet de créer une requete where avec les fields spécifier def createWhere(choices, field, binaryOp="OR"): firstLoop = True query = "" for choice in choices.get('interests'): if not firstLoop: query += " {} ".format(binaryOp) query += "{} = '{}'".format(field, choice) firstLoop = False return query # permet de créer le where de l'adresse / position de bien def createWherePosition(answers): query = "" if answers.get('pays'): query = "pays='{}'".format(answers.get('pays')) if answers.get('commune'): query = addAndToQuery(query, "commune", answers.get('commune')) if answers.get('postalCode'): query = addAndToQuery(query, "npa", answers.get('postalCode')) return query # https://stackoverflow.com/questions/354038/how-do-i-check-if-a-string-is-a-number-float def isNumber(s): try: int(s) return True except ValueError: return False # use to check date def isValidDate(date): try: datetime.strptime(date, '%d/%m/%Y') return True except ValueError: return False # use to check user date input def isValidDateOrNone(date): if date: return isValidDate(date) else: return True # demande la date def askDate(canBeNull=True): startDate = "" duration = -1 while "check date is empty or valid": dateCriteria = inquirer.prompt([ inquirer.Text('startDate', message="Entrez une date de début", validate=lambda x: isValidDateOrNone(x)) ]) startDateStr = dateCriteria.get('startDate') # Si l'utilisateur fournit une date on lui force à mettre une durée if startDateStr: startDate = datetime.strptime(startDateStr, '%d/%m/%Y') durationCriteria = inquirer.prompt([ inquirer.Text( 'duration', message="Entrez une durée (nombre de jours)", validate=lambda x: isNumber(x) and int(x) > 0), ]) duration = int(durationCriteria.get('duration')) break else: if canBeNull: break print( "la date doit être au format jour/mois/annee => eg: 12/12/2020" ) return startDate, duration def isNumberOrQ(number, maxIdx): return (isNumber(number) and int(number) > 0 and int(number) <= maxIdx) or str(number) is "Q" def createSearchQuery(fournitreWhere, typeBienWhere, positionWhere, unavailableBienQuery): searchQuery = "SELECT * FROM search_biens" # Si il y a des fourniture, on fait un jointure if fournitreWhere: searchQuery += " INNER JOIN fourniture ON bien_id = bien_immobilier_id" # Si il y a des critères à la recherche on ajoute le mot clé WHERE à la requête if fournitreWhere or positionWhere or typeBienWhere or unavailableBienQuery: searchQuery += " WHERE " whereQuery = "" # On ajoute les différents critères à la requête if fournitreWhere: whereQuery += fournitureWhere if typeBienWhere: if whereQuery: whereQuery = "(" + whereQuery + ") AND (" + typeBienWhere + ")" else: whereQuery += typeBienWhere if positionWhere: if whereQuery: whereQuery = "(" + whereQuery + ") AND (" + positionWhere + ")" else: whereQuery += positionWhere if unavailableBienQuery: if whereQuery: whereQuery = "(" + whereQuery + ") AND (" + unavailableBienQuery + ")" else: whereQuery += unavailableBienQuery return searchQuery + whereQuery # TYPE DE BIEN bienChoices = inquirer.prompt([ inquirer.Checkbox('interests', message="Quel genre de bien cherchez-vous ?", choices=list( map(lambda bien: bien[0], getQueryRes("SELECT * FROM type_bien")))), ]) # FOURNITURE fournitureChoices = inquirer.prompt([ inquirer.Checkbox( 'interests', message="Quel genre de fourniture sont nécessaire pour vous ?", choices=list( map(lambda type: type[0], getQueryRes("SELECT nom FROM type_fourniture")))), ]) print("\n") positionCriteria = inquirer.prompt([ inquirer.Text('pays', message="Entrez un pays"), inquirer.Text('commune', message="Entrez une commune"), inquirer.Text('postalCode', message="Entrez une NPA") ]) positionWhere = createWherePosition(positionCriteria) typeBienWhere = createWhere(bienChoices, "type_bien") fournitureWhere = createWhere(fournitureChoices, "nom_fourniture", "OR") fournitureQuery = "" if fournitureWhere: fournitureQuery = "bien_id IN (SELECT bien_immobilier_id FROM fourniture WHERE {} GROUP BY bien_immobilier_id HAVING COUNT(*) = {})".format( fournitureWhere, len(fournitureChoices.get('interests'))) startDate = "" duration = "" startDate, duration = askDate() unavailableBienQuery = "" if startDate: endDate = startDate + timedelta(days=duration) sqlStartDate = startDate.strftime('%Y-%m-%d') # date, pas datetime sqlEndDate = endDate.strftime('%Y-%m-%d') print() unavailableBienQuery = "bien_id NOT IN (SELECT DISTINCT bien_immobilier_id FROM location WHERE (('{}' BETWEEN date_arrivee AND DATE_ADD(date_arrivee, INTERVAL duree DAY )) OR (date_arrivee BETWEEN '{}' AND '{}') OR (DATE_ADD(date_arrivee, INTERVAL duree DAY) BETWEEN '{}' AND '{}')) AND estConfirme = 1) ".format( sqlStartDate, sqlStartDate, sqlEndDate, sqlStartDate, sqlEndDate) searchQuery = createSearchQuery(fournitureQuery, typeBienWhere, positionWhere, unavailableBienQuery) goodsRes = getQueryRes(searchQuery) if (len(goodsRes) == 0): print("Aucun resultat") input("Tappez une touche pour continuer") return False headerBiens = [ "Indice ", "ID", "Cap. person.", "Taille (m²)", "type_bien", "Description", "Rue", "Commune", "Etat" ] # affichage des résultat while True: biens = [] Page.clear() idx = 1 for good in goodsRes: biens.append([ idx, good[0], good[2], good[1], good[5], good[3], good[9], good[7], good[8] ]) idx = idx + 1 print( tt.to_string( data=biens, header=headerBiens, style=tt.styles.ascii_thin_double, )) bienIdx = inquirer.prompt([ inquirer.Text('bienIdx', message="Sélectionnez un bien (ou q pour quitter) ", validate=lambda idx: isNumberOrQ(idx, len(goodsRes))) ]) bienIdx = bienIdx["bienIdx"] # afficher un bien ou quitter if bienIdx is "Q": return False idx = int(bienIdx) idx = idx - 1 fournitures = getQueryRes( "SELECT * FROM fourniture WHERE bien_immobilier_id = {}".format( goodsRes[idx][0])) print("Info appartement ----------------") print("id du bien : {}".format(goodsRes[idx][0])) print("Capacite personne : {}".format(goodsRes[idx][2])) print("Taille (m²) : {}".format(goodsRes[idx][1])) print("Type bien: {}".format(goodsRes[idx][5])) print("Description: {}".format(goodsRes[idx][3])) print("Tarif: {}".format(goodsRes[idx][14])) print("Charge: {}".format(goodsRes[idx][15])) print("Adresse: {} {} {} {} {}".format(goodsRes[idx][9], goodsRes[idx][11], goodsRes[idx][12], goodsRes[idx][7], goodsRes[idx][4])) if fournitures: print("Fournitures Disponbiles: ") for fourniture in fournitures: print(" -" + fourniture[3]) # réserver ? reserver = inquirer.prompt([ inquirer.Text("ouiNon", message="Souhaitez-vous réserver ce bien (O/N) ?", validate=lambda x: x is "O" or x is "N") ]) # si O on réserve autrement on réaffiche les résultats if reserver.get('ouiNon') is "O": if startDate == "": startDate, duration = askDate(False) g = Gui() isFreeQuery = getQueryRes( "SELECT bien_est_libre({},'{}',{})".format( goodsRes[idx][0], startDate, duration)) query = "INSERT INTO location(date_arrivee, duree, estConfirme, locataire_id, bien_immobilier_id) VALUES('{}',{}, NULL,{},{})".format( startDate, duration, g.user.id, goodsRes[idx][0]) if isFreeQuery[0][0] and insert(query): print("Votre réservation à bien été faite...") input("Appuyez sur une touche") return True else: print("Bien indisponible") input("Appuyez sur une touche") return False