def get_customer_address_other(): customer_address_others = input( "Enter other address information (NA = Not applies): ") v = Validators(customer_address_others) validated_customer_address_others = v.validate_customer_address_others( ) return validated_customer_address_others
def deleteCategorieProduit(request): if (request.method == "DELETE"): if Validators.is_not_empty(request.body): data = Validators.is_valid_json(request.body) if data == False: return HttpResponseBadRequest("Le JSON dans le corps de votre requête est mal formaté") fields = ["id"] errors = Validators.keys_are_inside_arrays(data, fields) if Validators.is_type(errors, list): return HttpResponseBadRequest("Champs manquants : " + json.dumps(errors)) id = data["id"] categorieProduit = CategorieProduit.objects.filter(pk=id) if not Validators.is_not_empty(categorieProduit): return HttpResponseBadRequest("Catégorie non existante") categorieProduit[0].delete() return JsonResponse({'etat' : "Catégorie supprimée"}) else: return HttpResponseBadRequest("Vous n'avez pas mis de corps à votre requête") return HttpResponseForbidden("Accès refusé")
def get_customer_address_street_and_number(): customer_address_street_and_number = input( "Enter the customer's street and street number: ") v = Validators(customer_address_street_and_number) validated_customer_address_street_and_number = v.validate_customer_address_street_and_number( ) return validated_customer_address_street_and_number
def login(request): if (request.method == "POST"): data = Validators.is_valid_json(request.body) if data == False: return HttpResponseBadRequest( "Le JSON dans le corps de votre requête est mal formaté") fields = ["login", "mdp"] errors = Validators.keys_are_inside_arrays(data, fields) if Validators.is_type(errors, list): return HttpResponseBadRequest("Champs manquants : " + json.dumps(errors)) user = User.objects.filter(login=data['login']) if Validators.is_not_empty(user): hashmdp = hashlib.md5(data['mdp'].encode() + user[0].grainsel.encode()) hashmdp = hashmdp.hexdigest() if user[0].mdp.lower() == hashmdp.lower(): user.update(dateDerniereConnexion=datetime.datetime.now(), token=random_generator(size=30)) return JsonResponse({ 'etat': "Connexion réussie", 'lvl': user[0].niveauAuth, 'token': user[0].token }) else: return HttpResponseBadRequest("Mauvais indentifiants") else: return HttpResponseBadRequest("Identifiants non existants") else: return HttpResponseForbidden("Accès refusé")
def deleteUser(request): if (request.method == "DELETE"): if Validators.is_not_empty(request.body): data = Validators.is_valid_json(request.body) if data == False: return HttpResponseBadRequest( "Le JSON dans le corps de votre requête est mal formaté") fields = ["login"] errors = Validators.keys_are_inside_arrays(data, fields) if Validators.is_type(errors, list): return HttpResponseBadRequest("Champs manquants : " + json.dumps(errors)) login = data["login"] userExist = User.objects.filter(login=login) if Validators.is_not_empty(userExist): userExist[0].delete() else: return HttpResponseForbidden("Utilisateur non existant") return JsonResponse({'etat': "Utilisateur supprimé"}) else: return HttpResponseBadRequest( "Vous n'avez pas mis de corps à votre requête") return HttpResponseForbidden("Accès refusé")
def getVenteDF(request): reponse = [] if(request.method == "POST"): data = Validators.is_valid_json(request.body) if data == False: return HttpResponseBadRequest("Probleme data") else: dateDebut = data["DateDebut"] dateFin = data["DateFin"] allVente = Vente.objects.all() for vente in allVente: if dateDebut <= vente.dateVente <= dateFin : reponse.append(Vente_to_json(vente)) return JsonResponse(reponse, safe= False) else: print("pas un get") return HttpResponseBadRequest("Mauvaise requête")
def editUser(request): if (request.method == "PUT"): if Validators.is_not_empty(request.body): data = Validators.is_valid_json(request.body) if data == False: return HttpResponseBadRequest( "Le JSON dans le corps de votre requête est mal formaté") fields = ["login", "mdp", "niveauAuth"] errors = Validators.keys_are_inside_arrays(data, fields) if Validators.is_type(errors, list): return HttpResponseBadRequest("Champs manquants : " + json.dumps(errors)) login = data["login"] mdp = data["mdp"] niveauAuth = data["niveauAuth"] user = User.objects.filter(login=login) if not Validators.is_not_empty(user): return HttpResponseBadRequest("Utilisateur non existant") user = user[0] if Validators.is_not_empty(login): user.login = login if Validators.is_not_empty(mdp): randomStr = random_generator() grainsel = hashlib.md5(randomStr.encode()) grainsel = grainsel.hexdigest() user.grainsel = grainsel mdpHashed = hashlib.md5(mdp.encode() + grainsel.encode()) user.mdp = mdpHashed.hexdigest() if Validators.is_not_empty(niveauAuth): try: int(niveauAuth) except ValueError: return HttpResponseBadRequest( "Niveau d'authentification doit être un entier") user.niveauAuth = niveauAuth user.save() return JsonResponse({'etat': "Utilisateur modifié"}) else: return HttpResponseBadRequest( "Vous n'avez pas mis de corps à votre requête") else: return HttpResponseForbidden("Accès refusé")
def post(self): """User can login""" request_data = Login.parser.parse_args() username = request_data['username'] password = request_data['password'] if not Validators().valid_username(username): return {'message': 'enter a valid username'}, 401 if not Validators().valid_password(password): return {'message': 'Enter a valid password'}, 401 user = User().get_user_by_username(username) if not user: return {'message': 'user does not exist'}, 404 if not check_password_hash(user.password, password): return { 'message': 'Invalid password, enter the correct password' }, 401 return {'message': f'successfully logged in as {user.username}'}
def post(self): """User can signup""" request_data = SignUp.parser.parse_args() fname = request_data['first_name'] lname = request_data['last_name'] username = request_data['username'] email = request_data['email'] password = request_data['password'] confirm_password = request_data['confirm_password'] if not Validators().valid_fname(first_name): return {'message': 'enter a valid first_name'}, 401 if not Validators().valid_lname(last_name): return {'message': 'enter a valid last_name'}, 401 if User().get_user_by_username(username): return {"message": f"User with username {username} already exists"} if not Validators().valid_username(username): return {'message': 'enter a valid username'}, 401 if not Validators().valid_email(email): return {"message": "Enter a valid email"}, 401 if not Validators().valid_password(password): return {'message': 'Enter a valid password'}, 401 if password != confirm_password: return {'message': 'passwords do not match'}, 200 user = User(first_name, last_name, username, email, password, confirm_password) users.append(user) return {'message': f'Account for {username} created successfully'}, 201
def editCategorieProduit(request): if (request.method == "PUT"): if Validators.is_not_empty(request.body): data = Validators.is_valid_json(request.body) if data == False: return HttpResponseBadRequest("Le JSON dans le corps de votre requête est mal formaté") fields = ["id", "nom", "colorGraph"] errors = Validators.keys_are_inside_arrays(data, fields) if Validators.is_type(errors, list): return HttpResponseBadRequest("Champs manquants : " + json.dumps(errors)) categorie = CategorieProduit() id = data["id"] nom = data["nom"] colorGraph = data["colorGraph"] categorie = CategorieProduit.objects.filter(pk=id) if not Validators.is_not_empty(categorie): return HttpResponseBadRequest("Categorie non existante") categorie = categorie[0] if Validators.is_not_empty(nom) & Validators.is_not_empty(colorGraph): categorie.nom = nom categorie.colorGraph = colorGraph else: return HttpResponseBadRequest("Un des champs est vide") categorie.save() return JsonResponse({'etat' : "Categorie modifiée"}) else: return HttpResponseBadRequest("Vous n'avez pas mis de corps à votre requête") else: return HttpResponseForbidden("Accès refusé")
def get_customer_address_city(): customer_address_city = input("Enter the customer's city: ") v = Validators(customer_address_city) validated_customer_address_city = v.validate_customer_adress_city() return validated_customer_address_city
def get_customer_forename(): customer_forename = input("Enter the customer's forename: ") v = Validators(customer_forename) validated_customer_forename = v.validate_customer_forename() return validated_customer_forename
def get_user_input(self, CHOOSE_OPTION_TEXT, VALID_OPTIONS): user_input = input(CHOOSE_OPTION_TEXT) v = Validators(user_input) self.validated_user_input = v.validate_selected_input( VALID_OPTIONS, CHOOSE_OPTION_TEXT) print("")
def get_appointment_day(): appointment_day = input("Enter the appointment's day: ") v = Validators(appointment_day) validated_appointment_day = v.validate_appointment_day() return validated_appointment_day
def get_customer_address_state(): customer_address_state = input("Enter the customer's state: ") v = Validators(customer_address_state) validated_customer_address_state = v.validate_customer_adress_state() return validated_customer_address_state
def editProduit(request): if (request.method == "PUT"): if Validators.is_not_empty(request.body): data = Validators.is_valid_json(request.body) if data == False: return HttpResponseBadRequest("Le JSON dans le corps de votre requête est mal formaté") fields = ["id", "categorieProduit", "nom", "prixAchat", "prixVente", "disponible"] errors = Validators.keys_are_inside_arrays(data, fields) if Validators.is_type(errors, list): return HttpResponseBadRequest("Champs manquants : " + json.dumps(errors)) produit = Produit() categorieProduit = data["categorieProduit"] id = data["id"] nom = data["nom"] prixAchat = data["prixAchat"] prixVente = data["prixVente"] disponible = data["disponible"] quantite = data["quantite"] produit = Produit.objects.filter(pk=id) if not Validators.is_not_empty(produit): return HttpResponseBadRequest("Produit non existant") produit = produit[0] if Validators.is_not_empty(categorieProduit): categorieProduitExist = CategorieProduit.objects.filter(nom=categorieProduit) if Validators.is_not_empty(categorieProduitExist) == False: return HttpResponseBadRequest("Catégorie de produit non existante") produit.idCategorieProduit = categorieProduitExist[0] else: return HttpResponseBadRequest("Champ catégorie produit vide") if Validators.is_not_empty(nom) & Validators.is_not_empty(prixAchat) & Validators.is_not_empty(prixVente) & Validators.is_not_empty(disponible) & Validators.is_not_empty(quantite): produit.nom = nom produit.prixAchat = prixAchat produit.prixVente = prixVente produit.quantite = quantite produit.alt = nom.lower() if (disponible.lower() == "false"): produit.disponible = False elif (disponible.lower() == "true"): produit.disponible = True else: produit.disponible = True else: return HttpResponseBadRequest("Un des champs est vide") produit.save() return JsonResponse({'etat' : "Produit modifié"}) else: return HttpResponseBadRequest("Vous n'avez pas mis de corps à votre requête") else: return HttpResponseForbidden("Accès refusé")
def get_customer_id(): customer_id = input("Enter the customer's ID: ") v = Validators(customer_id) validated_customer_id = v.validate_customer_id() return validated_customer_id
def get_customer_birthday(): customer_birthdate = input( "Enter the customer's birthday (DD-MM-YYYY): ") v = Validators(customer_birthdate) validated_customer_birthday = v.validate_customer_birthdate() return validated_customer_birthday
def get_appointment_duration(self): appointment_duration = input( "Enter the Appointment's duration (HH:MM-HH:MM): ") v = Validators(appointment_duration) validated_appointment_duration = v.validate_appointment_duration() return validated_appointment_duration
def get_customer_personal_id(): customer_personal_id = input("Enter the customer's ID number: ") v = Validators(customer_personal_id) validated_customer_personal_id = v.validate_customer_personal_id() return validated_customer_personal_id
def load(request): if (request.method == "POST"): try: # Verification qu'un fichier file est bien présent file = request.FILES["file"] print("c'est un file") except Exception as error: print("c'est pas un file") return HttpResponseBadRequest(error) print(file.content_type) print(file) if(file.content_type == 'application/vnd.ms-excel'): # Verification du type de fichier print("c'est une csv") firstLine = file.readline().decode('utf-8') secondLine = file.readline().decode('utf-8') thirdLine = file.readline().decode('utf-8') print(firstLine) print(secondLine) print(thirdLine) lineColonne = file.readline() # enlever la ligne des noms de colonnes fields = ["DATE", "COMPTOIR", "BARMAN", "CLIENT", "ETIQUETTE","QUANTITE","TOTAL","METHODE DE PAIEMENT", "SELLING PRICE", "PURCHASE PRICE", "BENEFIT"] lineColonne2 = lineColonne.decode('utf-8') lineColonne3 = lineColonne2.split(';') i = 0 for word in lineColonne3: wordUp = word.upper() wordUpRight = wordUp.replace('\"', "") wordUpRightRight = unicodedata.normalize('NFKD', wordUpRight).encode('ascii', 'ignore').strip().decode('utf-8') if wordUpRightRight != fields[i]: return HttpResponseBadRequest("le fichier csv n'est pas au bon format") i+=1 o = 3 ventesNouvellesTotal = 0 for line in file.readlines():# on balaye tout les lignes du fichier puis on fait les requetes necessaire au remplissage de la BDD line2 = line.decode('utf-8') line3 = line2.split(';') produit = Produit() produit.nom = line3[4].replace('\"', "") productExist = Produit.objects.filter(nom=produit.nom) if Validators.is_not_empty(productExist): #print("produit déjà existant") produit = productExist[0] else: produit.prixAchat = line3[-2].replace('\"', "") produit.prixVente = line3[-3].replace('\"', "") produit.save() listNewProduct.append(produit) lieuDeVie = LieuDeVie() lieuDeVie.nom = line3[1].replace('\"', "") lieuDeVieExist = LieuDeVie.objects.filter(nom=lieuDeVie.nom) if Validators.is_not_empty(lieuDeVieExist): #print("lieuDeVie déjà existant") lieuDeVie = lieuDeVieExist[0] else: #print("existe pas") lieuDeVie.nom = lieuDeVie.nom lieuDeVie.save() vente = Vente() vente.dateVente = line3[0].replace('\"', "") vente.idProduit = produit vente.idLieuDeVie = lieuDeVie vente.selledBy = line3[2].replace('\"', "") vente.purchaseBy = line3[3].replace('\"', "") vente.quantite = line3[5].replace('\"', "") vente.amount = line3[6].replace('\"', "") vente.benefit = line3[10].replace('\"', "") venteExist = Vente.objects.filter(dateVente = vente.dateVente) if Validators.is_not_empty(venteExist): print(o) listVenteAlreadyExist.append(Vente_to_json(vente)) else : print("vente existe pas") ventesNouvellesTotal += 1 vente.save() o += 1 reponse = JsonResponse({"ventesNouvellesTotal" : ventesNouvellesTotal},safe=False) """for d in listVenteAlreadyExist: listVenteAlreadyExist.remove(d)""" return reponse else : print("c'est pas une csv") return HttpResponseBadRequest("Fichier incompatible ! Veuillez upload un fichier CSV") else: return HttpResponseForbidden("Demande refusée")
def remove_customer_from_registry_by_index(self, max_range): inputed_customer_index = input( "Enter the id of the customer to be removed: ") v = Validators(inputed_customer_index) validated_customer_index = v.validate_customer_index(max_range) return validated_customer_index