Beispiel #1
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"
def process_order(request):
    print "placing order"

    try:
        phone_number = request.POST.get("phone_number")
        user_name = request.POST.get("userName")
        email = request.POST.get("email")
        app_version = request.POST.get("app_version")
        device_id = request.POST.get("device_id")
        app_id = request.POST.get("app_id")
        bring_change_of = int(request.POST.get("bring_change_of", "0"))
        address_str = request.POST.get("address")
        landmark = request.POST.get("landmark")
        location_show = request.POST.get("location_show")
        location_id = request.POST.get("location_id")
        api_key = request.POST.get("api_key")
        products = request.POST.get("products")
        tomorrow = request.POST.get("tomorrow")
        delivery_time = request.POST.get("delivery_time")
        # print request
        coupon_id = int(request.POST.get("coupon_id", "0"))

        coupon = None

        print "coupon"
        print phone_number
        user = User.objects.get(username=phone_number)
        if user:
            user.email = email
            user.first_name = user_name.title()
            user.save()
            user_profile = user.userprofile
            user_profile.app_version = app_version
            user_profile.app_id = app_id
            user_profile.device_id = device_id
            user_profile.save()
            if user.api_key.key != api_key:
                print "api key is not valid"
                data = simplejson.dumps({"status": "Not Valid Request"})
                return HttpResponse(data, content_type="application/json", status=403)
        else:
            print "User not found"
            data = simplejson.dumps({"status": "Not Valid Request"})
            return HttpResponse(data, content_type="application/json", status=403)

        print "user obj created"
        print coupon_id

        if coupon_id > 0:
            coupon = Coupon.objects.get(pk=coupon_id)
            coupon.used_count += 1
            coupon.save()
            print coupon
            prev_order = Order.objects.filter(coupon_applied=coupon, user=user)
            print user
            if prev_order:
                if prev_order[0].status != 1:
                    print "coupon invalidation1"
                    coupon = None
            print coupon
        print "check for coupon"
        location = Location.objects.get(pk=location_id)
        address = Address.objects.filter(user=user, address=address_str, landmark=landmark)
        if address:
            address = address[0]
            address.location = location
            address.save()
        else:
            address = Address(
                user=user, address=address_str, landmark=landmark, location_show=location_show, location=location
            )
            address.save()
        print "address done"

        # print products
        products = products.split(",")
        product_ids = map(lambda x: x.split("::")[0], products)
        product_qns = map(lambda x: x.split("::")[1], products)
        print product_ids
        print product_qns
        order = Order(user=user, total_amount=0, address=address, status=3)
        if tomorrow == "1":
            print delivery_time
            if dt.datetime.now().hour > 20:
                order.delivery_time = dt.datetime.strptime(
                    str((dt.datetime.now() + dt.timedelta(days=1)).date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
            else:
                order.delivery_time = dt.datetime.strptime(
                    str(dt.datetime.now().date()) + " " + delivery_time, "%Y-%m-%d %I:%M %p"
                )
        else:
            order.delivery_time = dt.datetime.now() + dt.timedelta(hours=1)
        if bring_change_of:
            order.change_requested = bring_change_of
        order.save()
        invoice = Invoice(order=order, product_json="")
        invoice.save()
        print "order obj saved"
        total_amount = 0
        index = 0

        ordered_services = {}
        products_json = []
        for p_id in product_ids:
            prd = StoreProductMapping.objects.get(pk=p_id)
            products_json.append(
                {
                    "spid": prd.id,
                    "pid": prd.product.product.id,
                    "name": prd.product.product.name,
                    "price": prd.price,
                    "discount": prd.discount,
                    "qn": product_qns[index],
                    "size_id": prd.product.size.id,
                }
            )
            service = prd.product.product.category.service
            if "offer" in service.name.lower():
                OfferDeviceId(device_id=device_id).save()
                OfferProductOrderMapping(
                    device_id=device_id, order=order, offer_product=prd.offerproductmapping_set.all()[0]
                ).save()
            if str(service.id) not in ordered_services:
                ordered_services[str(service.id)] = 0
            total_amount += int(product_qns[index]) * (prd.price - prd.discount)
            ordered_services[str(service.id)] += int(product_qns[index]) * (prd.price - prd.discount)
            store = prd.store
            cart = Cart.objects.filter(order=order, store=store)
            if cart:
                cart = cart[0]
            else:
                cart = Cart(order=order, store=store)
                cart.save()

            OrderedProduct(product=prd, cart=cart, quantity=product_qns[index]).save()
            index += 1
        products_json = simplejson.dumps(products_json)
        invoice.product_json = products_json
        invoice.save()

        service_amount_ordered = []
        for key in ordered_services:
            service_amount_ordered.append(str(key) + ":" + str(ordered_services[key]))
        service_amount_ordered = ";;".join(service_amount_ordered)
        print total_amount

        final_amount = total_amount

        if coupon:
            if total_amount >= coupon.min_total:
                order.coupon_applied = coupon
                print "found coupon"
                print coupon.code
                print coupon
                print user
                print location_id
                print int(app_version)
                print final_amount
                print service_amount_ordered
                discount = verify_coupon(
                    coupon, user, location_id, int(app_version), final_amount, service_amount_ordered
                )["discount"]
                print "discount" + str(discount)
                final_amount -= discount

        print "passed coupon part"

        delivery_charges = {}
        for key in ordered_services:
            service = Service.objects.get(pk=key)
            lsm = LocationServiceMapping.objects.filter(service=service, location=location)
            if lsm:
                lsm = lsm[0]
                stl = StoreTimingInLocation.objects.filter(store__is_active=True, is_active=True, lsm=lsm)
                print "done"
                if stl:
                    stl = stl[0]
                    if key not in delivery_charges:
                        delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": stl.delivery_min_amount}
                    if ordered_services[key] < stl.delivery_min_amount:
                        final_amount += -stl.delivery_charges
                        total_amount += stl.delivery_charges
                        delivery_charges[key]["delivery_charges"] = stl.delivery_charges
                else:
                    delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}
            else:
                delivery_charges[key] = {"delivery_charges": 0, "delivery_amount_min": 0}

        print "passed delivery part"

        order.total_amount = total_amount
        order.final_amount = final_amount
        order.delivery_charges = simplejson.dumps(delivery_charges)
        order.save()
        OrderActivity(order=order, user=order.user, actions=0, comment=" ").save()

        data = simplejson.dumps({"status": "done"})
        return HttpResponse(data, content_type="application/json", status=201)
    except Exception as process_order_function_error:
        print "process_order: " + str(process_order_function_error)
        data = simplejson.dumps({"status": "Server Error"})
        send_mail(
            "Order placing Error " + str(process_order_function_error),
            str(request) + "\n\n\n" + str(simplejson.dumps(request.POST)),
            "*****@*****.**",
            ["*****@*****.**"],
            fail_silently=False,
        )
        return HttpResponse(data, content_type="application/json", status=500)
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