Ejemplo n.º 1
0
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
Ejemplo n.º 2
0
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
Ejemplo n.º 3
0
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
Ejemplo n.º 4
0
def change_address():
    g = Gui()
    current_user = g.user
    query = "DELETE FROM adresse WHERE id = {}".format(current_user.adresse_id)
    logging.debug("EXECUTING QUERY: %s", query)
    cursor = db.cursor()
    cursor.execute(query)
    db.commit()
    if cursor.rowcount > 0:
        address = Addresse.create(**get_address())
        current_user.adresse_id = address.id
        current_user.save()
        print("Mise à jour de l'adresse effectué!")
    else:
        print("Impossible de mettre à jour l'adresse actuel")
    Page.wait_input()
    return True
Ejemplo n.º 5
0
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
Ejemplo n.º 6
0
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()
Ejemplo n.º 7
0
        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


login = Page("Login")
login.set_main(login_)
login.set_next(mode_select_page)
Ejemplo n.º 8
0
from app.gui.page import Page
from app.gui.gui import Gui

from .register import register_page
from .login import login

home = Page("home", title="Accueil")

home.append_item(register_page)
home.append_item(login)

#mode_select_page.set_next(main)
Ejemplo n.º 9
0
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()
Ejemplo n.º 10
0
    query = "SELECT * FROM location_personne INNER JOIN search_biens ON bien_immobilier_id = search_biens.bien_id WHERE location_personne.date_arrivee > NOW() AND location_personne.estConfirme IS TRUE AND personne_id = {}".format(
        g.user.id)
    logging.debug(query)
    locations = getQueryRes(query)
    headerBiens = [
        "Cap. person.", "Taille (m²)", "type_bien", "Description", "Rue",
        "Commune", "Etat", "date arrivee", "date depart"
    ]

    biens = []
    for location in locations:
        biens.append([
            location["capacite"], location["taille"], location["type_bien"],
            location["description"], location["rue"], location["commune"],
            location["etat"], location["date_arrivee"], location["date_depart"]
        ])

    if biens:
        print(
            tt.to_string(
                data=biens,
                header=headerBiens,
                style=tt.styles.ascii_thin_double,
            ))
    input("Appuyez sur une touche")
    return True


ConfirmedRental = Page("Confirmed Rental")
ConfirmedRental.set_main(displayRental)
Ejemplo n.º 11
0
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()
Ejemplo n.º 12
0
    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()


my_properties = Page("my_properties", title="Gérer mes biens")
my_properties.set_main(my_properties_)
my_properties.set_next(my_properties)

pending_locations = Page("pending_rentals", title="Locations en attente")
pending_locations.set_main(waiting_rentals)
pending_locations.set_next(pending_locations)

rentals_occuring_now = Page("rentals_occuring_now", title="Locations en cours")
rentals_occuring_now.set_main(rentals_now)

rentals_in_the_past = Page("past_rentals", title="Locations terminées")
rentals_in_the_past.set_main(rentals_before)

rentals_in_the_future = Page("future_rentals",
                             title="Locations qui vont arriver")
Ejemplo n.º 13
0
from app.gui.page import Page
from app.gui.gui import Gui
from .main import main

mode_select_page = Page("User type select")

def set_user_mode(mode):
   g = Gui()
   g.user_type = mode
   return True

mode_select_page.append_item(lambda : set_user_mode("proprietaire"), "Propriétaire")
mode_select_page.append_item(lambda : set_user_mode("locataire"), "Locataire")
mode_select_page.set_next(main)
Ejemplo n.º 14
0
         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

register_page = Page("Enregistrer un nouvelle utilisateur")
register_page.set_main(register_)
register_page.set_next(mode_select_page)


if __name__ == "__main__":
   mode_select_page.show()
Ejemplo n.º 15
0
def getQueryRes(query):
    cu = db.cursor(dictionary=True)
    cu.execute(query)
    return cu.fetchall()

def displayRental():
    g = Gui()
    # a ajouter avant where 
    query = "SELECT * FROM location_personne INNER JOIN search_biens ON bien_immobilier_id = search_biens.bien_id WHERE DATE_ADD(location_personne.date_arrivee, INTERVAL location_personne.duree DAY) < NOW() AND location_personne.estConfirme = TRUE AND personne_id = {}".format(g.user.id) 
    locations = getQueryRes(query)
    headerBiens = ["Cap. person.", "Taille (m²)", "type_bien", "Description", "Rue","Commune", "Etat", "date arrivee", "date depart"]

    
    biens = []
    for location in locations:
        biens.append([location["capacite"], location["taille"], location["type_bien"], location["description"], location["rue"], location["commune"], location["etat"],location["date_arrivee"],location["date_depart"] ])

    if biens:
        print( tt.to_string(
                data=biens,
                header=headerBiens,
                style=tt.styles.ascii_thin_double,
             ))
    input("Appuyez sur une touche")
    return True

PastRental = Page("Past Rental")
PastRental.set_main(displayRental)

Ejemplo n.º 16
0
from app.gui.page import Page
from app.gui.gui import Gui
from app.db.entity_manager import EntityManager
from app.entities.personne import Personne

from .past_rental import PastRental
from .confirmed_rental import ConfirmedRental
from .waiting_rental import WaitingRental

RentalMenu = Page("MyRentals", title="Mes locations")
RentalMenu.append_item(PastRental)
RentalMenu.append_item(ConfirmedRental)
RentalMenu.append_item(WaitingRental)
Ejemplo n.º 17
0
from app.entities.personne import Personne
from app.utils.path import get_config_path
import app.gui.pages.inquirer as inquirer
import logging
from .adresse import get_address
from app.entities.addrese import Addresse
import json
import mysql.connector
import functools
config = {}
with open(get_config_path("db.json"), "r") as f:
    config = json.load(f)

db = mysql.connector.connect(**config)

profil_page = Page("Profile")


def change_address():
    g = Gui()
    current_user = g.user
    query = "DELETE FROM adresse WHERE id = {}".format(current_user.adresse_id)
    logging.debug("EXECUTING QUERY: %s", query)
    cursor = db.cursor()
    cursor.execute(query)
    db.commit()
    if cursor.rowcount > 0:
        address = Addresse.create(**get_address())
        current_user.adresse_id = address.id
        current_user.save()
        print("Mise à jour de l'adresse effectué!")
Ejemplo n.º 18
0
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
Ejemplo n.º 19
0
                          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


# Search page
search = Page("search", title="Rechercher un bien")
search.set_main(search_)
Ejemplo n.º 20
0
    query = "SELECT * FROM location_personne INNER JOIN search_biens ON bien_immobilier_id = search_biens.bien_id WHERE location_personne.date_arrivee > NOW() AND location_personne.estConfirme IS NULL AND personne_id = {}".format(
        g.user.id)
    logging.debug(query)
    locations = getQueryRes(query)
    headerBiens = [
        "Cap. person.", "Taille (m²)", "type_bien", "Description", "Rue",
        "Commune", "Etat", "date arrivee", "date depart"
    ]

    biens = []
    for location in locations:
        biens.append([
            location["capacite"], location["taille"], location["type_bien"],
            location["description"], location["rue"], location["commune"],
            location["etat"], location["date_arrivee"], location["date_depart"]
        ])

    if biens:
        print(
            tt.to_string(
                data=biens,
                header=headerBiens,
                style=tt.styles.ascii_thin_double,
            ))
    input("Appuyez sur une touche")
    return True


WaitingRental = Page("Waiting Rental")
WaitingRental.set_main(displayRental)
Ejemplo n.º 21
0
from app.gui.page import Page
from app.gui.gui import Gui
from .search import search
from .my_rentals import RentalMenu

from .my_properties import manage_properties
from .profil import profil_page
main = Page("main", title="Dashboard")

def change_menu():
   g = Gui()
   user_type = g.user_type

   if user_type == "proprietaire":
      main.append_item(search)
      main.append_item(RentalMenu)
      main.append_item(manage_properties)
      main.append_item(profil_page)
   else:
      main.append_item(search)
      main.append_item(RentalMenu)
      main.append_item(profil_page)

main.set_before_show(change_menu)

# mainMenuPage = Page("Menu principale", should_exit=True)
# mainMenuPage.append_item(search)