Пример #1
0
def get_profile_data():
    logged_user = User.get_by_username(get_jwt_identity())
    logged_customer = Customer.get_by_user_id(logged_user.id)
    return {
        "name": logged_customer.name,
        "surname": logged_customer.surname,
        "email": logged_customer.email
    }
Пример #2
0
def delete_account():
    logged_user = User.get_by_username(get_jwt_identity())
    logged_customer = Customer.get_by_user_id(logged_user.id)
    customers_dwellings_contracts = Customer_Dwelling_Contract.get_by_nif(
        logged_customer.nif)
    for customer_dwelling_contract in customers_dwellings_contracts:
        contract_number = customer_dwelling_contract.contract_number
        Contract.get_by_contract_number(contract_number).delete()
    logged_user.delete()
    return "", 200
Пример #3
0
def delete_user():
    form = DeleteUserForm()
    user = User.get_by_username(current_user.username)
    if form.validate_on_submit():
        if request.method == 'POST':
            db.session.delete(user)
            db.session.commit()
            flash(f'Deleted {user.username}', 'warning')
            return redirect(url_for('main.home'))
    flash('Wrong password', 'danger')
    return redirect(url_for('user.user', username=current_user.username))
Пример #4
0
def change_password():
    # if current_user != User.get_by_username(username):

    form = ChangePasswordForm()
    if form.validate_on_submit():
        user = User.get_by_username(current_user.username)
        if user.check_password(form.old_password.data):
            user.password = form.new_password.data
            db.session.commit()
            flash(f"Password successfully changed.", 'success')
            return redirect(url_for('user.user', username=current_user.username))
        else:
            flash(f"Current password is incorrect.", 'danger')
    return render_template('change_password.html', form=form)
Пример #5
0
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)
Пример #6
0
def get_invoices_data():
    logged_user = User.get_by_username(get_jwt_identity())
    logged_customer = Customer.get_by_user_id(logged_user.id)
    customers_dwellings_contracts = Customer_Dwelling_Contract.get_by_nif(
        logged_customer.nif)
    data = []
    for customer_dwelling_contract in customers_dwellings_contracts:
        contract_number = customer_dwelling_contract.contract_number
        contract = Contract.get_by_contract_number(contract_number).to_dict()
        dwelling = Dwelling.get_by_cups(customer_dwelling_contract.cups)
        contract["address"] = dwelling.address
        invoices = __get_invoices(contract_number)
        contract = {"contract_data": contract, "invoices": invoices}
        data.append(contract)
    return jsonify(data)
Пример #7
0
 def test_customer_sign_up_correctly(self):
     with self.app.app_context():
         res = self.client.post("/api/auth/signup-customer",
                                json={
                                    "username": "******",
                                    "password": "******",
                                    "passwordconfirmation": "12341234",
                                    "name": "Juan",
                                    "surname": "Garrido",
                                    "nif": "12345678A",
                                    "email": "*****@*****.**"
                                })
         user = User.get_by_username("test1")
         customer = Customer.get_by_nif("12345678A")
         self.assertEqual(200, res.status_code)
         self.assertEqual("test1", user.username)
         self.assertEqual("12345678A", customer.nif)
Пример #8
0
def delete_invoice(invoice_number):
    invoice = Invoice.get_by_invoice_number(invoice_number)
    invoice.delete()
    contract = Contract.get_by_contract_number(invoice.contract_number)
    invoices = __get_invoices(contract.contract_number)
    if len(invoices) == 0:
        logged_user = User.get_by_username(get_jwt_identity())
        logged_customer = Customer.get_by_user_id(logged_user.id)
        nif = logged_customer.nif
        cus_dwe_con = Customer_Dwelling_Contract \
         .get_by_nif_and_contract_number(
          nif,
          invoice.contract_number
         )
        cus_dwe_con.delete()
        contract.delete()
    return "", 200
Пример #9
0
def login():
    if current_user.is_authenticated:
        return redirect(page_not_found("e"))

    form = LoginForm()

    if form.validate_on_submit():
        user = User.get_by_username(form.username.data)
        if user is None or not user.check_password(form.password.data):
            flash("Invalid username or password", 'danger')
            return redirect(url_for("auth.login"))

        login_user(user, remember=form.remember_me.data)
        flash(f'You are logged in!', 'success')
        return redirect(request.args.get('next') or url_for('main.home'))

    random_image = f"shop_{randint(1, 5)}.webp"

    return render_template('login.html', form=form, random=random_image)
Пример #10
0
 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)
Пример #11
0
def update_profile():
    if not request.is_json:
        return "Missing JSON in request", 400
    data = request.get_json()
    errors = {}
    if data['password'] or data['passwordconfirmation']:
        if data["password"] != data["passwordconfirmation"]:
            errors["passwordconfirmation"] = ["Las contraseñas no coinciden"]
        errors.update(validateUser(data))
    errors.update(validateCustomer(data))
    if errors:
        return errors, 422
    user = User.get_by_username(get_jwt_identity())
    customer = Customer.get_by_user_id(user.id)
    if data['password']:
        user.set_password(data['password'])
    user.save()
    customer.name = data['name']
    customer.surname = data['surname']
    customer.email = data['email']
    customer.save()
    return "", 200
Пример #12
0
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
Пример #13
0
def get_offers_notifications_count():
    logged_user = User.get_by_username(get_jwt_identity())
    logged_customer = Customer.get_by_user_id(logged_user.id)
    return str(len(Offer_Notification.get_all_by_nif(logged_customer.nif)))
Пример #14
0
def get_consumption_data():
    contract_invoices = {}
    logged_user = User.get_by_username(get_jwt_identity())
    if logged_user.user_type == 1:
        logged_customer = Customer.get_by_user_id(logged_user.id)
        customers_dwellings_contracts = Customer_Dwelling_Contract.get_by_nif(
            logged_customer.nif)
        contracts = []
        for customer_dwelling_contract in customers_dwellings_contracts:
            contracts.append(
                Contract.get_by_contract_number(
                    customer_dwelling_contract.contract_number))
        for contract in contracts:
            invoices = Invoice.get_by_contract_number(contract.contract_number)
            for invoice in invoices:
                year = int(invoice.init_date.strftime("%Y"))
                total_amount_list = [0 for _ in range(12)]
                consumed_energy_list = [0 for _ in range(12)]
                contracted_power_amount_list = [0 for _ in range(12)]
                consumed_energy_amount_list = [0 for _ in range(12)]
                tax_amount_list = [0 for _ in range(12)]
                if year in contract_invoices:
                    total_amount_list = contract_invoices[year][
                        "total_amount_list"]
                    consumed_energy_list = contract_invoices[year][
                        "consumed_energy_list"]
                    contracted_power_amount_list = contract_invoices[year][
                        "contracted_power_amount_list"]
                    consumed_energy_amount_list = contract_invoices[year][
                        "consumed_energy_amount_list"]
                    tax_amount_list = contract_invoices[year][
                        "tax_amount_list"]
                month = int(invoice.init_date.strftime("%m")) - 1

                if invoice.total_amount:
                    total_amount_list[month] = round(invoice.total_amount, 2)
                else:
                    total_amount_list[month] = 0

                if invoice.consumed_energy:
                    consumed_energy_list[month] = invoice.consumed_energy
                else:
                    consumed_energy_list[month] = 0

                if invoice.contracted_power_amount:
                    contracted_power_amount_list[month] = round(
                        invoice.contracted_power_amount, 2)
                else:
                    contracted_power_amount_list[month] = 0

                if invoice.consumed_energy_amount:
                    consumed_energy_amount_list[month] = round(
                        invoice.consumed_energy_amount, 2)
                else:
                    consumed_energy_amount_list[month] = 0

                if invoice.tax_amount:
                    tax_amount_list[month] = round(invoice.tax_amount, 2)
                else:
                    tax_amount_list[month] = 0
                contract_invoices[year] = {
                    "total_amount_list": total_amount_list,
                    "consumed_energy_list": consumed_energy_list,
                    "contracted_power_amount_list":
                    contracted_power_amount_list,
                    "consumed_energy_amount_list": consumed_energy_amount_list,
                    "tax_amount_list": tax_amount_list
                }
    else:
        return "No tienes permiso", 403
    return contract_invoices