def signup_company(): if not request.is_json: return "Missing JSON in request", 400 data = request.get_json() errors = {} errors.update(validateUser(data)) errors.update(validateCompany(data)) if errors: return errors, 422 if User.get_by_username(data['username']): return {"username": ["Nombre de usuario no disponible"]}, 422 if Company.get_by_cif(data['cif']): return {"cif": ["Este CIF ya ha sido registrado"]}, 422 user = User(username=data['username'], user_type=0) user.set_password(data['password']) user.save() company = Company(cif=data['cif'].upper(), name=data['name'], address=data['address'], url=data['url'], email=data['email'], company_type=data['companytype'], phone=data['phone'], user_id=user.id) company.save() return "", 200
def signup_customer(): if not request.is_json: return "Missing JSON in request", 400 data = request.get_json() errors = {} errors.update(validateUser(data)) errors.update(validateCustomer(data)) if errors: return errors, 422 if User.get_by_username(data['username']): return {"username": ["Nombre de usuario no disponible"]}, 422 if Customer.get_by_nif(data['nif']): return {"nif": ["Este NIF ya ha sido registrado"]}, 422 user = User(username=data['username'], user_type=1) user.set_password(data['password']) user.save() customer = Customer(nif=data['nif'].upper(), name=data['name'], surname=data['surname'], email=data['email'], user_id=user.id) customer.save() companies = Company.get_random_companies(random.randint(20, 40)) for company in companies: p_c_n = Potential_Customer_Notification(nif=customer.nif, cif=company.cif) p_c_n.save() return "", 200
def get_trading_company_offers(cif): result = [] offers = Offer.get_all_by_cif(cif) for offer in offers: company = Company.get_by_cif(offer.cif).to_dict() result.append({ "offerInfo": __get_offer_info(offer), "companyInfo": company }) return jsonify(result)
def get_received_offers(): logged_user = User.get_by_username(get_jwt_identity()) logged_customer = Customer.get_by_user_id(logged_user.id) offers_notifications = Offer_Notification.get_all_by_nif( logged_customer.nif) result = [] for offer_notification in offers_notifications: offer = Offer.get_by_id(offer_notification.offer_id) company = Company.get_by_cif(offer_notification.cif).to_dict() result.append({ "offerInfo": __get_offer_info(offer), "companyInfo": company }) return jsonify(result)
def __get_all_companies(): regions_result = [] _regions = {} companies_result = [] companies = Company.get_all() for company in companies: companies_result.append(company.to_dict()) if company.address in _regions: _regions[company.address] = _regions[company.address] + 1 else: _regions[company.address] = 1 for key, value in _regions.items(): regions_result.append({ "hc-key": regions[key], "value": value }) return regions_result, companies_result
def login(): if not request.is_json: return "Missing JSON in request", 400 data = request.get_json() username = data['username'] password = data['password'] user = User.get_by_username(username) if user and user.check_password(password): access_token = create_access_token(identity=username) refresh_token = create_refresh_token(identity=username) result_response = {"login": True, "user_type": user.user_type} if user.user_type == 0: company = Company.get_by_user_id(user.id) result_response["company_type"] = company.company_type response = make_response(result_response) set_access_cookies(response, access_token) set_refresh_cookies(response, refresh_token) return response, 200 return "User or password incorrect", 400
def get_historical_prices(): historical_prices = TradingCompanyPrices.get_all() result = {} for historical_price in historical_prices: company = Company.get_by_cif(historical_price.cif) if company.address in result: year = historical_price.year if year in result[company.address]: year_prices = result[company.address][year] year_prices.append(historical_price.price) else: result[company.address][year] = [historical_price.price] else: result[company.address] = { historical_price.year: [historical_price.price] } for address in result: for year in result[address]: result[address][year] = round(sum(result[address][year]) / len(result[address][year]), 4) return result
def test_company_sign_up_correctly(self): with self.app.app_context(): res = self.client.post("/api/auth/signup-company", json={ "username": "******", "password": "******", "passwordconfirmation": "12341234", "name": "Iberdrola", "cif": "A12368224", "companytype": "0", "phone": "632541870", "email": "", "address": "Baleares", "url": "" }) user = User.get_by_username("test1") company = Company.get_by_cif("A12368224") self.assertEqual(200, res.status_code) self.assertEqual("test1", user.username) self.assertEqual("A12368224", company.cif)
def __get_all_trading_companies(): result = [] companies = Company.get_all_trading_companies() for company in companies: result.append(company.to_dict()) return result
def process_bill(): try: file = request.files["file"] except BadRequestKeyError: return { "message": "No se ha seleccionado ningún archivo", "type": "error" }, 200 if not __allowed_file(file.filename): return { "message": "Los tipos de fichero permitidos son txt, pdf, png, jpg, jpeg, gif", "type": "error" }, 200 # save file to upload directory with a hash code file_extension = file.filename.rsplit(".", 1)[1].lower() filename = str(uuid.uuid4()) + "." + file_extension bill_path = os.path.join(app.config["UPLOAD_FOLDER"], filename) file.save(bill_path) # information extraction from the bill results = docreco.process_bill(bill_path, file_extension) # Delete the bill uploaded os.remove(bill_path) contract_number = __get_first_value( results["Datos del contrato"]["ReferenciaContrato"]).split( '/')[0].split('-')[0].split(' ')[0] if contract_number: contract = Contract.get_by_contract_number(contract_number) if not contract: cif = __get_first_value(results["Datos de la factura"]["CIF"]) if cif: trading_company = Company.get_by_cif(cif) if not trading_company: return { "message": "No se encuentra la comercializadora", "type": "error" }, 200 else: company_name = __get_first_value( results["Datos de la factura"]["Comercializadora"]) if company_name: trading_company = Company.get_trading_company_by_name( company_name, unidecode.unidecode(company_name)) if trading_company: cif = trading_company.cif else: return { "message": "No se encuentra la comercializadora ni el cif en la factura", "type": "error" }, 200 else: return { "message": "No se encuentra el nombre de la comercializadora en la factura", "type": "error" }, 200 contract_data = __get_contract_data(results) contract = Contract( contract_number=contract_number, contracted_power=contract_data["contracted_power"], toll_access=contract_data["toll_access"], end_date=contract_data["end_date"], CNAE=contract_data["CNAE"], tariff_access=contract_data["tariff_access"], cif=cif) contract.save() else: return { "message": "No se encuentra el número de referencia del contrato", "type": "error" }, 200 invoice_data = __get_invoice_data(results, contract_number) invoice = Invoice( invoice_number=invoice_data["invoice_number"], contracted_power_amount=invoice_data["contracted_power_amount"], consumed_energy_amount=invoice_data["consumed_energy_amount"], issue_date=invoice_data["issue_date"], charge_date=invoice_data["charge_date"], init_date=invoice_data["init_date"], end_date=invoice_data["end_date"], total_amount=invoice_data["total_amount"], contract_reference=invoice_data["contract_reference"], contract_number=invoice_data["contract_number"], document=file.read()) try: invoice.save() except IntegrityError: return { "message": "Esta factura ya está registrada", "type": "error" }, 200 cups = __get_first_value(results["Datos del contrato"]["CUPS"]) if cups: if not Dwelling.get_by_cups(cups): __create_dwelling_with_cups(results, cups) else: cups = __create_dwelling_with_random_cups(results) logged_user = User.get_by_username(get_jwt_identity()) logged_customer = Customer.get_by_user_id(logged_user.id) nif = logged_customer.nif if not Customer_Dwelling_Contract.get_by_nif_and_contract_number( nif, contract_number): customer_dwelling_contract = Customer_Dwelling_Contract( nif=nif, cups=cups, contract_number=contract_number) try: customer_dwelling_contract.save() except IntegrityError: pass return { "message": "La factura se ha guardado con éxito", "type": "success" }, 200