Beispiel #1
0
def submit(request):
    contractname = request.POST['contractname']
    a = request.POST['a']
    b = request.POST['b']
    c = request.POST['c']
    d = request.POST['d']
    e = request.POST['e']
    f = request.POST['f']
    g = request.POST['g']
    h = request.POST['h']
    i = request.POST['i']
    j = request.POST['j']
    k = request.POST['k']
    l = request.POST['l']
    m = request.POST['m']
    n = request.POST['n']
    o = request.POST['o']

    time_format = time.strftime('%Y-%m-%d_%H%M%S', time.localtime(time.time()))

    file = open('LCR_' + time_format + '.txt', 'wt')
    file.write('Letter of Credit' + '\n'
               '1.Advising bank:' + a + '\n'
               '2.Credit No.:' + b + '\n'
               '3.Beneficiary:' + c + '\n'
               '4.Applicant:' + d + '\n'
               '5.L/C Amount and Tolerance:' + e + '\n'
               '6.Type:' + f + '\n'
               '7.Partial shipment:' + g + '\n'
               '8.Transshipment:' + h + '\n'
               '9.Trnasport mode:' + i + '\n'
               '10.Loading(shipment from):' + j + '\n'
               '11.Discharging(shipment to):' + k + '\n'
               '12.Latest shipment date:' + l + '\n'
               '13.All banking charges:' + m + '\n'
               '14.Confirmation:' + n + '\n'
               '15.T/T reimbursement:' + o + '\n')
    file.close()

    file = open('LCR_' + time_format + '.txt', 'rb')
    data = file.read()

    # hasher = hashlib.md5()
    # with open('myfile.jpg', 'rb') as afile:
    #     buf = afile.read()
    #     hasher.update(buf)
    # print(hasher.hexdigest())

    # a = 'MD5 : ' + hashlib.md5(data).hexdigest()
    # b = 'SHA-1 : ' + hashlib.sha1(data).hexdigest()
    hash = 'SHA-256 : ' + hashlib.sha256(data).hexdigest()
    file.close()

    # 데이터 저장
    contract = Contract(contractname=contractname,
                        sha256=hash,
                        filename='LCR_' + time_format + '.txt')

    # 로그인한 사용자 정보를 Contract에 같이 저장
    user_id = request.session['user_id']
    member = Member.objects.get(user_id=user_id)
    contract.owner = member

    contract.save()

    return redirect('ing')
Beispiel #2
0
def process_bill():
    if request.method == "POST":

        file = request.files["inputFile"]

        if not file.filename:
            flash("No se ha seleccionado ningún archivo")
            return redirect(url_for("customer.upload_bill"))

        if file and __allowed_file(file.filename):

            # 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)

            # return results

            # 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:
                    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:
                            flash(
                                "No se encuentra la comercializadora ni existe cif en la factura"
                            )
                            return redirect(url_for("customer.my_bills"))
                    else:
                        flash(
                            "No se encuentra el nombre de la comercializadora en la factura"
                        )
                        return redirect(url_for("customer.my_bills"))

                    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:
                flash("No se encuentra el número de referencia del contrato")
                return redirect(url_for("customer.my_bills"))

            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:
                flash("Esta factura ya está registrada")
                return redirect(url_for("customer.my_bills"))

            cups = __get_first_value(results["Datos del contrato"]["CUPS"])

            if cups and not Dwelling.get_by_cups(cups):
                __create_dwelling_with_cups(results, cups)
            else:
                cups = __create_dwelling_with_random_cups(results)

            customer_dwelling_contract = Customer_Dwelling_Contract(
                nif=Customer.get_by_user_id(current_user.id).nif,
                cups=cups,
                contract_number=contract_number)
            customer_dwelling_contract.save()

            flash("La factura se ha guardado con éxito")
            return redirect(
                url_for("customer.show_bill",
                        invoice_number=invoice.invoice_number))

        else:
            flash(
                "Los tipos de fichero permitidos son txt, pdf, png, jpg, jpeg, gif"
            )
            return redirect(url_for("customer.upload_bill"))

    return "Error POST"
Beispiel #3
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