Beispiel #1
0
    def moveStock(self, lista, carro, id_bodega, order_id):

        for l in lista:

            if len(carro) > 0:
                cart = Cart()
                cart.id = l["id"]
                cart.Remove()

                kardex = Kardex()

                producto = Product()
                response = producto.InitById(l["product_id"])

                if "success" in response:

                    kardex.product_sku = producto.sku
                    kardex.cellar_identifier = id_bodega
                    kardex.operation_type = Kardex.OPERATION_MOV_OUT
                    kardex.sell_price = l['price']
                    kardex.order_id = order_id

                    _s = Size()
                    _s.name = l["size"]
                    res_name = _s.initByName()

                    if "success" in res_name:
                        kardex.size_id = _s.id
                    elif debugMode:
                        print res_name["error"]

                    kardex.date = str(
                        datetime.now(
                            pytz.timezone('Chile/Continental')).isoformat())
                    kardex.user = "******"
                    kardex.units = l["quantity"]
                    kardex.price = producto.price

                    kardex.Insert()

                    c = Cellar()
                    res_reservation = c.GetReservationCellar()

                    reservation_cellar = shipping_cellar

                    if "success" in res_reservation:
                        reservation_cellar = res_reservation["success"]
                    elif debugMode:
                        print res_reservation["error"]

                    kardex.cellar_identifier = reservation_cellar
                    kardex.operation_type = Kardex.OPERATION_MOV_IN

                    res_kardex = kardex.Insert()

                    if debugMode and "error" in res_kardex:
                        print res_kardex["error"]

                elif debugMode:
                    print response["error"]
Beispiel #2
0
    def post(self):

        post_office_id = self.get_argument("post_office_id", "")
        shipping_type = self.get_argument("shipping_type", 1)

        if self.current_user:

            # print self.current_user

            user_id = self.current_user["id"]

            cart = Cart()
            cart.user_id = user_id

            lista = cart.GetCartByUserId()

            if len(lista) <= 0:
                self.render("beauty_error.html",
                            message="Carro est&aacute; vac&iacute;o")

            suma = 0

            for l in lista:
                suma += l["subtotal"]

            costo_despacho = int(self.get_argument("shipping_price", 0))

            self.render("store/checkout-5.html",
                        data=lista,
                        suma=suma,
                        costo_despacho=costo_despacho,
                        post_office_id=post_office_id,
                        shipping_type=shipping_type)
        else:
            self.redirect("/auth/login")
Beispiel #3
0
    def post(self):

        cart_id = self.get_argument("cart_id", "")
        quantity = self.get_argument("quantity", "")

        cart = Cart()
        response = cart.UpdateCartQuantity(cart_id, quantity)

        self.write(json_util.dumps(response))
Beispiel #4
0
    def post(self):

        email = self.get_argument("email", "")
        password = self.get_argument("password", "")
        ajax = self.get_argument("ajax", "false")
        user_id = self.get_argument("user_id", "")

        # print "user_id {}".format(user_id)

        if email == "":
            self.write("debe ingresar el email")
        elif password == "":
            self.write("debe ingresar la contraseña")
        else:
            user = User()
            user.email = email
            user.password = password

            response_obj = user.Login(user.email, user.password)

            if "success" in response_obj:

                self.set_secure_cookie("user_giani",
                                       response_obj["success"],
                                       expires_days=None)

                current_user_id = json_util.loads(
                    response_obj["success"])["id"]

                if user_id != current_user_id:

                    cart = Cart()

                    cart.MoveTempToLoggedUser(user_id, current_user_id)

                # if "error" in response:
                #     rtn_obj = {"status":"error","message":"Usuario y contraseña no coinciden, error:{}".format(response["error"])}
                #     self.write( json_util.dumps(rtn_obj) )
                #     return

                rtn_obj = {
                    "status": "ok",
                    "next": self.next,
                    "user_id": current_user_id
                }
                self.write(json_util.dumps(rtn_obj))

                if ajax == "false":
                    self.redirect(self.next)

            else:
                rtn_obj = {
                    "status": "error",
                    "message": "Error:{}".format(response_obj["error"])
                }
                self.write(json_util.dumps(rtn_obj))
Beispiel #5
0
    def get(self):

        user_id = self.get_argument("user_id", "")
        ajax = int(self.get_argument("ajax", 1))

        if user_id != "":

            cart = Cart()
            cart.user_id = user_id
            lista = cart.GetCartByUserId()

            res_update_cart_price = cart.updatePrice(lista, self.current_user)

            cart2 = Cart()
            cart2.user_id = user_id
            lista = cart2.GetCartByUserId()

            suma = 0
            for l in lista:
                suma += l["subtotal"]

            if ajax:
                self.render("store/carro_ajax.html",
                            data=lista,
                            suma=suma,
                            url_bodega=url_bodega)
            else:
                self.render("store/cart.html", data=lista, suma=suma)
        else:

            self.write("error")
Beispiel #6
0
    def test_move_order_ok(self):

        cart = Cart()
        cart.product_id = 129
        cart.quantity = 1
        cart.subtotal = 34950
        cart.user_id = 733
        cart.size = '37'
        cart.price = 34950
        cart.Save()
        order = Order()
        order.voucher = ''
        order.type = 1
        order.subtotal = 34950
        order.shipping = 2490
        order.tax = 0
        order.total = 37440
        order.items_quantity = 1
        order.products_quantity = 1
        order.user_id = 733
        order.billing_id = 69
        order.shipping_id = 69
        order.payment_type = 2
        order.Save()

        order_detail = OrderDetail()
        order_detail.order_id = order.id
        order_detail.quantity = 1
        order_detail.product_id = 129
        order_detail.subtotal = 34950
        order_detail.size = '37'
        order_detail.price = 34950
        order_detail.Save()

        od = order_detail.ListByOrderId(order.id, 0, 0)

        ExitoHandler.moveStock(od, 733)

        query = '''\
                select * from "Kardex" 
                where cellar_id = 5 
                and product_sku = 'GDF-PV14-Lile-C9' 
                and size_id = 3 
                order by date desc limit 1'''
        kardex = BaseModel.execute_query(query)

        if len(kardex) > 0:
            self.assertEqual(kardex[0]["balance_units"], 3)

            query = '''\
                select * from "Kardex" 
                where cellar_id = 12 
                and product_sku = 'GDF-PV14-Lile-C9' 
                and size_id = 3 
                order by date desc limit 1'''
        kardex = BaseModel.execute_query(query)

        if len(kardex) > 0:
            self.assertEqual(kardex[0]["balance_units"], 2)
Beispiel #7
0
    def get(self):

        cart = Cart()
        cart.id = self.get_argument("cart_id", "")
        if cart.id == "":
            self.write("No existe el item a eliminar")
        else:
            response_obj = cart.Remove()
            if "success" in response_obj:
                self.write("ok")
            else:
                self.write(response_obj["error"])
Beispiel #8
0
class Customer:

    customers = []

    def __init__(self, name):
        self.name = name
        self.cart = Cart()

        Customer.customers.append(self)

    def add_item(self, thing):
        self.cart.add_item(thing)

    def remove_item(self, thing):
        self.cart.remove_item(thing)
Beispiel #9
0
    def post(self):

        if self.current_user:

            shipping_type = self.get_argument("shipping_type", 1)
            costo_despacho = int(self.get_argument("shipping_price", 0))
            post_office_id = self.get_argument("post_office_id", "")

            user_id = self.current_user["id"]

            cart = Cart()
            cart.user_id = user_id

            lista = cart.GetCartByUserId()

            if len(lista) <= 0:
                self.render("beauty_error.html",
                            message="Carro est&aacute; vac&iacute;o")

            suma = 0

            for l in lista:
                c = Cart()
                c.InitById(l["id"])
                c.shipping_type = shipping_type
                c.Edit()
                suma += l["subtotal"]

            if self.current_user['type_id'] != User().getUserTypeID(
                    UserType.EMPRESA):
                self.render("store/checkout-4.html",
                            data=lista,
                            suma=suma,
                            costo_despacho=costo_despacho,
                            pytz=pytz,
                            post_office_id=post_office_id,
                            shipping_type=shipping_type)
            else:
                self.render("wholesaler/checkout-5.html",
                            data=lista,
                            suma=suma,
                            iva=iva,
                            pytz=pytz)
        else:
            self.redirect("/auth/login")
Beispiel #10
0
    def post(self):

        # obtener id de la bodega web
        id_bodega = cellar_id
        cellar = Cellar()
        res_cellar = cellar.GetWebCellar()
        if "success" in res_cellar:
            id_bodega = res_cellar["success"]

        # obtener carro del usuario logueado
        cart = Cart()
        cart.user_id = self.current_user["id"]

        lista = cart.GetCartByUserId()

        final_name = self.saveVoucher()

        order = Order()

        if len(lista) > 0:

            response_obj = self.saveOrder(lista, order, final_name)

            # si se guardo el pedido de forma exitosa
            if "success" in response_obj:

                self.saveOrderDetail(lista, order)
                self.notifyEmails(lista, order, self.current_user)

                cart = Cart()
                cart.user_id = self.current_user["id"]

                carro = cart.GetCartByUserId()
                self.moveStock(lista, carro, id_bodega, order.id)

                self.render("store/success.html",
                            webpay="no",
                            detalle=lista,
                            order=order)
            else:
                self.render("beauty_error.html",
                            message="{}".format(response_obj["error"]))
        else:
            self.render("beauty_error.html",
                        message="Carro se encuentra vacío")
def create_cart():
    cart = Cart(status="shopping", items=[], total_amount=0).save()
    return cart.id
Beispiel #12
0
    def post(self):

        TBK_TIPO_TRANSACCION = self.get_argument("TBK_TIPO_TRANSACCION", "")
        TBK_MONTO = self.get_argument("TBK_MONTO", "")
        TBK_ID_SESION = self.get_argument("TBK_ID_SESION", "")
        TBK_URL_EXITO = self.get_argument("TBK_URL_EXITO", "")
        TBK_URL_FRACASO = self.get_argument("TBK_URL_FRACASO", "")

        payment_type = self.get_argument("payment_type", 2)
        costo_despacho = int(self.get_argument("shipping_price", 0))
        iva = int(self.get_argument("tax", 0))

        user_id = self.current_user["id"]

        order = Order()

        cart = Cart()
        cart.user_id = user_id

        lista = cart.GetCartByUserId()

        if len(lista) > 0:

            subtotal = 0
            cantidad_items = 0
            cantidad_productos = 0
            id_facturacion = 0
            id_despacho = 0
            total = 0
            info_despacho = ''
            info_facturacion = ''

            for l in lista:
                c = Cart()
                c.InitById(l["id"])
                c.payment_type = payment_type
                c.Edit()
                subtotal += l["subtotal"]
                cantidad_items += l["quantity"]
                cantidad_productos += 1
                id_facturacion = l["billing_id"]
                id_despacho = l["shipping_id"]
                total += l["subtotal"]
                info_despacho = l['shipping_info']
                info_facturacion = l['billing_info']

            order.date = datetime.now(
                pytz.timezone('Chile/Continental')).isoformat()
            order.type = Order.TIPO_WEB
            order.subtotal = subtotal
            order.shipping = costo_despacho
            order.tax = iva
            order.total = total + costo_despacho + iva
            order.items_quantity = cantidad_items
            order.products_quantity = cantidad_productos
            order.user_id = user_id
            order.billing_id = id_facturacion
            order.shipping_id = id_despacho
            order.payment_type = payment_type
            order.voucher = ""
            order.state = Order.ESTADO_PENDIENTE
            order.shipping_info = info_despacho
            order.billing_info = info_facturacion

            response_obj = order.Save()

            if "success" in response_obj:

                for l in lista:

                    detail = OrderDetail()
                    detail.order_id = order.id
                    detail.quantity = l["quantity"]
                    detail.subtotal = l["subtotal"]
                    detail.product_id = l["product_id"]
                    detail.size = l["size"]
                    detail.price = l["price"]
                    detail.Save()

                    # res_obj = detail.Save()
                    # if "error" in res_obj:
                    #     print "{}".format(res_obj["error"])

            # else:

            #     self.write(response_obj["error"])
            #     return

        if os.name != "nt":
            myPath = "{}webpay/dato{}.log" \
                .format(project_path, TBK_ID_SESION)
        else:
            myPath = "C:\Users\YiChun\Documents\giani\webpay\dato{}.log" \
                .format(TBK_ID_SESION)

        f = open(myPath, "w+")
        linea = "{};{}".format(TBK_MONTO, order.id)
        f.write(linea)
        f.close()

        data = {
            "TBK_TIPO_TRANSACCION": TBK_TIPO_TRANSACCION,
            "TBK_MONTO": TBK_MONTO,
            "TBK_ORDEN_COMPRA": order.id,
            "TBK_ID_SESION": TBK_ID_SESION,
            "TBK_URL_EXITO": TBK_URL_EXITO,
            "TBK_URL_FRACASO": TBK_URL_FRACASO,
            "shipping": costo_despacho,
            "subtotal": subtotal
        }

        # self.write(json_util.dumps(data))
        user_id = self.current_user["id"]
        cart = Cart()
        cart.user_id = user_id
        lista = cart.GetCartByUserId()

        self.render("transbank.html", data=data, lista=lista)
Beispiel #13
0
    def moveStock(order_detail, user_id):
        try:
            id_bodega = cellar_id
            id_bodega_reserva = shipping_cellar

            cellar = Cellar()
            res_cellar = cellar.GetWebCellar()

            if "success" in res_cellar:
                id_bodega = res_cellar["success"]
            else:
                ExitoHandler.sendError("obtener id de bodega web {}".format(
                    res_cellar["error"]))

            res_reservation_cellar = cellar.GetReservationCellar()

            if "success" in res_reservation_cellar:
                id_bodega_reserva = res_reservation_cellar["success"]
            else:
                ExitoHandler.sendError(
                    "obtener id de bodega reserva {}".format(
                        res_reservation_cellar["error"]))

            cart = Cart()
            cart.user_id = user_id

            carro = cart.GetCartByUserId()

            if len(carro) > 0:

                res_remove_cart = cart.RemoveByUserId()

                if "error" in res_remove_cart:
                    ExitoHandler.sendError("vaciar carro {}".format(
                        res_remove_cart["error"]))

            for l in order_detail:

                if not l['moved']:

                    kardex = Kardex()

                    producto = Product()
                    response = producto.InitById(l["product_id"])

                    if "success" in response:

                        kardex.product_sku = producto.sku
                        kardex.cellar_identifier = id_bodega
                        kardex.operation_type = Kardex.OPERATION_MOV_OUT

                        _s = Size()
                        _s.name = l["size"]
                        res_name = _s.initByName()

                        if "success" in res_name:
                            kardex.size_id = _s.id
                        else:
                            ExitoHandler.sendError(
                                "obtener size_id para product_id {}, {}".
                                format(l["product_id"], res_name["error"]))

                        kardex.date = datetime.now(
                            pytz.timezone('Chile/Continental')).isoformat()
                        kardex.user = "******"
                        kardex.units = l["quantity"]

                        res_kardex = kardex.Insert()

                        if "error" in res_kardex:
                            ExitoHandler.sendError(
                                "sacar de bodega web product_id {}, {}".format(
                                    l["product_id"], res_kardex["error"]))
                        else:
                            kardex.cellar_identifier = id_bodega_reserva
                            kardex.operation_type = Kardex.OPERATION_MOV_IN

                            res_kardex = kardex.Insert()

                            product = Product()
                            product.updateSold(producto.sku)

                            if "error" in res_kardex:
                                ExitoHandler.sendError(
                                    "move a bodega reserva product_id {}, {}".
                                    format(l["product_id"],
                                           res_kardex["error"]))
                            else:
                                od = OrderDetail()
                                res_moved = od.MarkAsMoved(l['id'])
                                if "error" in res_moved:
                                    ExitoHandler.sendError(
                                        "mark as moved id {}".format(l['id']),
                                        res_moved["error"])

                    else:
                        ExitoHandler.sendError(
                            "initizalizar producto {}, {}".format(
                                l["product_id"], res_remove_cart["error"]))
        except Exception, e:
            ExitoHandler.sendError("mover stock {}".format(str(e)))
            pass
Beispiel #14
0
    def _save_user_profile(self, user):

        if not user:
            raise tornado.web.HTTPError(500, "Facebook authentication failed.")

        user_id = self.get_argument("user_id", "")

        usr = User()

        usr.name = user["name"]
        usr.email = user["email"]
        usr.user_type = UserType.VISITA

        if user_id != "":
            usr.id = user_id

        response = usr.Exist(user["email"])

        if "success" in response:
            if not response["success"]:
                res = usr.Save()
                RegistrationEmail(usr.name, usr.email)
                if "error" in res:
                    print res["error"]

        else:
            self.render("auth/fail.html", message=response["error"])

        response_obj = usr.InitByEmail(user["email"])

        # print response_obj

        if "success" in response_obj:

            current_user_id = json_util.loads(response_obj["success"])["id"]

            # print "user_id: {} current_user_id: {}".format(str(user_id),str(current_user_id))

            if user_id != "":

                if str(user_id) != str(current_user_id):

                    cart = Cart()

                    response = cart.MoveTempToLoggedUser(
                        user_id, current_user_id)

                    # if "error" in response:
                    #     print "Error moving cart detail: {}".format(response["error"])

            self.set_secure_cookie("user_giani",
                                   response_obj["success"],
                                   expires_days=0.02)

            _u = User()

            _u.updateLastView(
                current_user_id,
                datetime.now(pytz.timezone('Chile/Continental')).isoformat())

            self.redirect(self.next)

        else:

            self.render("auth/fail.html", message=response_obj["error"])

        # else:

        #     self.write(response_obj["error"])

        # conn = psycopg2.connect(conn_string)

        # cursor = conn.cursor(cursor_factory=psycopg2.extras.DictCursor)

        # # self.write(user)

        # # return

        # cursor.execute("select * from \"user\" where email = %(email)s",{"email":user["email"]})

        # data = cursor.fetchone()

        # _user = {}

        # if data:
        #     _user["id"] = data["id"]
        #     _user["name"] = data["name"]
        #     _user["email"] = data["email"]
        #     _user["type"] = data["type"]
        #     _user["profile"] = data["profile"]

        #     print "ya existe"
        #     self.write("el usuario con el email ya existe")
        # else:

        #     parameters = {"email":user["email"],"name":user["name"],"type":"facebook"}

        #     try:
        #         cursor.execute("insert into \"user\" (email, name, type) values (%(email)s,%(name)s,%(type)s)",parameters)
        #         conn.commit()

        #         try:
        #             cursor.execute("select * from \"user\" where email = %(email)s",{"email":user["email"]})
        #             data = cursor.fetchone()
        #             if data:
        #                 _user["id"] = data["id"]
        #                 _user["name"] = data["name"]
        #                 _user["email"] = data["email"]
        #                 _user["type"] = data["type"]
        #                 self.write("usuario creado correctamente")
        #         except Exception, e:
        #             self.write(str(e))
        #     except Exception,e:
        #         self.write(str(e))

        # self.set_secure_cookie("user_giani", json_util.dumps(_user, sort_keys=True, indent=4, default=json_util.default))
        # self.redirect("/")

        pass
Beispiel #15
0
    def post(self):

        name = self.get_argument("name", "")
        email = self.get_argument("email", "")
        password = self.get_argument("password", "")
        re_password = self.get_argument("re-password", "")
        tos = self.get_argument("tos", "")
        ajax = self.get_argument("ajax", "false")
        user_id = int(self.get_argument("user_id", 0))

        # print tos

        if name == "":
            self.write(json_util.dumps({"error": "debe ingresar su nombre"}))
            return
        elif email == "":
            self.write(json_util.dumps({"error": "debe ingresar el email"}))
            return
        elif password == "":
            self.write(
                json_util.dumps({"error": "debe ingresar la contraseña"}))
            return
        elif password != re_password:
            self.write(
                json_util.dumps({"error": "las contraseñas no coinciden"}))
            return
        elif tos != "on":
            self.write(
                json_util.dumps(
                    {"error": "debe aceptar las condiciones de uso"}))
            return
        else:

            response = User().Exist(email)

            if "success" in response:
                if response["success"]:
                    self.write(
                        json_util.dumps({
                            "error":
                            "ya existe un usuario registrado con este email"
                        }))
                    return
            else:
                self.write(
                    json_util.dumps({
                        "error":
                        "se ha producido un error {}".format(response['error'])
                    }))
                return

            # perform login

            user = User()
            user.name = name
            user.email = email
            user.password = password
            user.user_type = UserType.CLIENTE
            user.status = User.ACEPTADO

            if user_id != 0:
                existe = User().Exist('', user_id)
                if "success" in existe:
                    if existe["success"]:
                        user.id = user_id

            user.Save()

            RegistrationEmail(user.name, user.email)

            response_obj = user.Login(user.email, user.password)

            if "success" in response_obj:

                self.set_secure_cookie("user_giani",
                                       response_obj["success"],
                                       expires_days=None)

                current_user_id = json_util.loads(
                    response_obj["success"])["id"]

                if user_id != current_user_id:

                    cart = Cart()

                    response = cart.MoveTempToLoggedUser(
                        user_id, current_user_id)

                self.write(json_util.dumps({"success": self.next}))
                return
            else:
                self.write(json_util.dumps({"error": str(response_obj)}))
                return

            # redirect is the request isn't aajx
            if ajax == "false":
                self.set_secure_cookie("user_giani",
                                       response_obj["success"],
                                       expires_days=None)
                self.write(json_util.dumps({"success": self.next}))
Beispiel #16
0
    def post(self):

        post_office_id = self.get_argument("post_office_id", "")
        shipping_type = self.get_argument("shipping_type", 1)
        cart_id = self.get_argument("cart_id", "")
        ciudad = None

        items = 0

        c = Cart()
        c.user_id = self.current_user["id"]
        detail = c.GetCartByUserId()

        for d in detail:
            items += int(d["quantity"])

        if cart_id != "":
            cart = Cart()
            res = cart.InitById(cart_id)

            if "success" in res:
                contact = Contact()
                res_contact = contact.InitById(cart.shipping_id)
                if "success" in res_contact:
                    ciudad = res_contact["success"]["city_id"]

        c = Cellar()
        res_cellar_id = c.GetWebCellar()

        web_cellar_id = cellar_id

        if "success" in res_cellar_id:
            web_cellar_id = res_cellar_id["success"]

        res_web_cellar = c.InitById(web_cellar_id)

        if "success" in res_web_cellar:
            if int(shipping_type) == 1:
                cellar_city_id = c.city_id
                shipping = Shipping()
                shipping.from_city_id = int(cellar_city_id)
                shipping.to_city_id = int(ciudad)
                res = shipping.GetGianiPrice()
            else:
                shipping = Shipping()
                shipping.post_office_id = post_office_id
                res = shipping.GetPriceByPostOfficeId()

            if "error" in res:
                self.write(
                    json_util.dumps({
                        "state": "error",
                        "message": res["error"]
                    }))
            else:
                if shipping.charge_type == 1:
                    costo_despacho = shipping.price * items
                else:
                    costo_despacho = shipping.price

                self.write(
                    json_util.dumps({
                        "state": "ok",
                        "shipping_cost": costo_despacho
                    }))
        else:
            self.write(
                json_util.dumps({
                    "state": "error",
                    "message": res_web_cellar["error"]
                }))
Beispiel #17
0
    def get(self):

        product = Product()
        cart = Cart()
        cart.product_id = self.get_argument("product_id", "")
        cart.quantity = int(self.get_argument("quantity", 0))

        if cart.quantity > 0:

            if cart.product_id != "":

                response_obj = product.InitById(cart.product_id)

                if "success" in response_obj:

                    if product.promotion_price != 0:
                        subtotal = int(product.promotion_price) * cart.quantity
                        cart.price = product.promotion_price
                    else:
                        subtotal = int(product.sell_price) * cart.quantity
                        cart.price = product.sell_price

                    if self.current_user:
                        if self.current_user["type_id"] == 4:
                            subtotal = int(product.bulk_price) * cart.quantity
                            cart.price = product.bulk_price

                    size_id = self.get_argument("size", "")

                    size = Size()
                    size.id = size_id
                    res_name = size.initById()

                    if "error" in res_name:
                        self.write(res_name["error"])
                    else:
                        cart.size = size.name

                    cart.date = datetime.now(
                        pytz.timezone('Chile/Continental')).isoformat()
                    cart.subtotal = subtotal
                    cart.user_id = self.get_argument("user_id", -1)

                    if self.current_user:
                        cart.user_id = self.current_user["id"]

                    response_obj = cart.Save()

                    product.updateAdded(product.sku)

                    if "success" in response_obj:
                        self.write("ok")
                    else:
                        self.write(response_obj["error"])
                else:
                    self.write(response_obj["error"])
            else:
                self.write("Product ID is empty")
        else:
            self.write("ok")
Beispiel #18
0
    def get(self):

        if self.current_user:

            cart = Cart()
            cart.user_id = self.current_user["id"]

            lista = cart.GetCartByUserId()

            cellar = Cellar()
            res_web_cellar = cellar.GetWebCellar()

            if self.current_user["type_id"] == User().getUserTypeID(
                    UserType.EMPRESA):
                total_quantity = 0
                for item in lista:
                    total_quantity += item["quantity"]
                if total_quantity < 15:
                    self.write(
                        json_util.dumps(
                            {"error": "La cantidad mínima es de 15 pares"}))
                    return

            if "success" in res_web_cellar:
                web_cellar_id = res_web_cellar["success"]

                k = Kardex()
                res_checkstock = k.checkStock(lista, web_cellar_id)

                if "error" in res_checkstock:
                    self.write(json_util.dumps(res_checkstock))
                else:
                    res_update_cart_price = cart.updatePrice(
                        lista, self.current_user)
                    if res_update_cart_price["success"] > 0:
                        self.write(
                            json_util.dumps({
                                "alert":
                                "Alerta! El precio de algunos productos han sido actualizados"
                            }))
                    else:
                        self.write(json_util.dumps(res_update_cart_price))

            else:

                self.write(json_util.dumps(res_web_cellar))

        else:

            user_id = self.get_argument("user_id", 0)

            cart = Cart()
            cart.user_id = user_id

            lista = cart.GetCartByUserId()

            cellar = Cellar()
            res_web_cellar = cellar.GetWebCellar()

            if "success" in res_web_cellar:
                web_cellar_id = res_web_cellar["success"]

                k = Kardex()
                res_checkstock = k.checkStock(lista, web_cellar_id)

                if "error" in res_checkstock:
                    self.write(json_util.dumps(res_checkstock))
                else:
                    res_update_cart_price = cart.updatePrice(
                        lista, self.current_user)
                    if res_update_cart_price["success"] > 0:
                        self.write(
                            json_util.dumps({
                                "alert":
                                "Alerta! El precio de algunos productos han sido actualizados"
                            }))
                    else:
                        self.write(json_util.dumps(res_update_cart_price))

            else:

                self.write(json_util.dumps(res_web_cellar))
Beispiel #19
0
    def get(self):

        if self.current_user:
            user_id = self.current_user["id"]
            nombre = self.get_argument("name", self.current_user["name"])
            apellido = self.get_argument("lastname",
                                         self.current_user["lastname"])
            email = self.get_argument("email", self.current_user["email"])
            direccion = self.get_argument("address", "")
            ciudad = self.get_argument("city_id", "")
            codigo_postal = self.get_argument("zip_code", "")
            informacion_adicional = self.get_argument("additional_info", "")
            telefono = self.get_argument("telephone", "")
            id_contacto = self.get_argument("contact_id", "")
            comuna = self.get_argument("town", "")
            rut = self.get_argument("rut", "")
            shipping_type = self.get_argument("shipping_type", "")
            post_office_id = self.get_argument("post_office_id", "")

            shipping_type_id = 1

            cart = Cart()
            cart.user_id = user_id

            lista = cart.GetCartByUserId()

            if len(lista) <= 0:
                self.render("beauty_error.html",
                            message="Carro est&aacute; vac&iacute;o")

            contact = Contact()

            contact.name = nombre
            contact.lastname = apellido
            contact.telephone = telefono
            contact.email = email
            contact.address = direccion
            if shipping_type == "chilexpress":
                po = PostOffice()
                po.InitById(post_office_id)
                post_office_name = po.name
                contact.address = "Oficina {}".format(post_office_name)
            contact.city = ciudad
            contact.zip_code = codigo_postal
            contact.user_id = user_id
            contact.additional_info = informacion_adicional
            contact.town = comuna
            contact.rut = rut

            operacion = ""

            if id_contacto != "":
                contact.id = id_contacto
                response_obj = contact.Edit()
                operacion = "editar"
            else:
                response_obj = contact.Save()
                operacion = "guardar"

            if "error" in response_obj:
                self.render("beauty_error.html",
                            message="Error al {} contacto {}".format(
                                operacion, response_obj["error"]))
            else:

                items = 0
                suma = 0

                for l in lista:
                    c = Cart()
                    response_obj = c.InitById(l["id"])

                    if "success" in response_obj:
                        c.shipping_id = contact.id
                        c.shipping_info = contact.additional_info
                        c.Edit()
                    else:
                        print response_obj["error"]

                    suma += l["subtotal"]
                    items += l["quantity"]

                contactos = []
                cities = []

                response_obj = contact.ListByUserId(user_id)

                city = City()
                res_city = city.List()

                if "success" in response_obj:
                    contactos = json_util.loads(response_obj["success"])

                if "success" in res_city:
                    cities = res_city["success"]

                c = Cellar()
                res_cellar_id = c.GetWebCellar()

                web_cellar_id = cellar_id

                if "success" in res_cellar_id:
                    web_cellar_id = res_cellar_id["success"]

                res_web_cellar = c.InitById(web_cellar_id)

                if "success" in res_web_cellar:
                    if shipping_type != "chilexpress":
                        cellar_city_id = c.city_id

                        shipping = Shipping()
                        shipping.from_city_id = int(cellar_city_id)
                        shipping.to_city_id = int(ciudad)
                        res = shipping.GetGianiPrice()
                        if "error" in res:
                            self.render(
                                "beauty_error.html",
                                message="Error al calcular costo de despacho, {}"
                                .format(res["error"]))
                    else:
                        shipping_type_id = 2
                        shipping = Shipping()
                        shipping.post_office_id = post_office_id
                        res = shipping.GetPriceByPostOfficeId()

                    if "error" in res:
                        self.render(
                            "beauty_error.html",
                            message=
                            "Error al calcular costo de despacho de Chilexpress, {}"
                            .format(res["error"]))
                    else:
                        if shipping.charge_type == 1:
                            costo_despacho = shipping.price * items
                        else:
                            costo_despacho = shipping.price

                        self.render("store/checkout-2.html",
                                    contactos=contactos,
                                    data=lista,
                                    suma=suma,
                                    selected_address=direccion,
                                    cities=cities,
                                    costo_despacho=costo_despacho,
                                    shipping_type=shipping_type_id,
                                    post_office_id=post_office_id)
        else:

            self.redirect("/auth/login")
Beispiel #20
0
    def __init__(self, name):
        self.name = name
        self.cart = Cart()

        Customer.customers.append(self)
Beispiel #21
0
    def get(self):

        if self.current_user:

            user_id = self.current_user["id"]

            contact = Contact()
            response_obj = contact.ListByUserId(user_id)

            contactos = []
            cities = []

            if "success" in response_obj:
                contactos = json_util.loads(response_obj["success"])
            # else:
            #     self.render("beauty_error.html",message="Error al obtener la lista de contactos:{}".format(response_obj["error"]))
            #     return

            # use globals default to avoid exception
            web_cellar_id = cellar_id

            c = Cellar()
            res_cellar_id = c.GetWebCellar()

            if "success" in res_cellar_id:
                web_cellar_id = res_cellar_id["success"]

            cart = Cart()
            cart.user_id = user_id
            lista = cart.GetCartByUserId()

            suma = 0

            for l in lista:
                suma += l["subtotal"]

            res_web_cellar = c.InitById(web_cellar_id)

            if "success" in res_web_cellar:
                cellar_city_id = c.city_id

            city = City()
            city.from_city_id = cellar_city_id
            res_city = city.ListByFromCityId()
            # print res_city

            post_office_list = []

            po = PostOffice()
            res_po = po.ListOnlyWithShippingCost()

            if "success" in res_po:
                post_office_list = res_po["success"]

            if suma > 0:
                if "success" in res_city:
                    cities = res_city["success"]

                self.render("store/checkout-1.html",
                            contactos=contactos,
                            data=lista,
                            suma=suma,
                            cities=cities,
                            post_office_list=post_office_list)
            else:
                self.render("beauty_error.html",
                            message="Carro est&aacute; vac&iacute;o")

        else:
            self.redirect("/auth/login")
Beispiel #22
0
    def post(self):

        if self.current_user:

            costo_despacho = int(self.get_argument("shipping_price", 0))
            user_id = self.current_user["id"]
            nombre = self.get_argument("name", self.current_user["name"])
            apellido = self.get_argument("lastname",
                                         self.current_user["lastname"])
            email = self.get_argument("email", self.current_user["email"])
            direccion = self.get_argument("address", "")
            ciudad = self.get_argument("city_id", "")
            codigo_postal = self.get_argument("zip_code", "")
            informacion_adicional = self.get_argument("additional_info", "")
            telefono = self.get_argument("telephone", "")
            id_contacto = self.get_argument("contact_id", "")
            misma_direccion = self.get_argument("same_address", "")
            comuna = self.get_argument("town", "")
            rut = self.get_argument("rut", "")
            shipping_type = self.get_argument("shipping_type", 1)
            post_office_id = self.get_argument("post_office_id", "")

            cart = Cart()
            cart.user_id = user_id

            lista = cart.GetCartByUserId()

            if len(lista) <= 0:
                self.render("beauty_error.html",
                            message="Carro est&aacute; vac&iacute;o")

            if misma_direccion != "on":

                contact = Contact()

                contact.name = nombre
                contact.lastname = apellido
                contact.telephone = telefono
                contact.email = email
                contact.address = direccion
                contact.city = ciudad
                contact.zip_code = codigo_postal
                contact.user_id = user_id
                contact.additional_info = informacion_adicional
                contact.town = comuna
                contact.rut = rut

                operacion = ""

                if id_contacto != "":
                    contact.id = id_contacto
                    response_obj = contact.Edit()
                    operacion = "editar"
                else:
                    response_obj = contact.Save()
                    operacion = "guardar"

                if "error" in response_obj:
                    self.render("beauty_error.html",
                                message="Error al {} contacto {}".format(
                                    operacion, response_obj["error"]))
                else:
                    suma = 0

                    for l in lista:
                        c = Cart()
                        c.InitById(l["id"])
                        c.billing_id = contact.id
                        c.billing_info = contact.additional_info
                        c.Edit()
                        suma += l["subtotal"]

                    # self.render("store/checkout-2.html",contactos=contactos,data=lista,suma=suma,selected_address=direccion)
                    if self.current_user['type_id'] == User().getUserTypeID(
                            UserType.EMPRESA):
                        self.render("wholesaler/checkout-4.html",
                                    data=lista,
                                    suma=suma,
                                    iva=iva)
                    else:
                        self.render("store/checkout-3.html",
                                    data=lista,
                                    suma=suma,
                                    costo_despacho=costo_despacho,
                                    shipping_type=shipping_type,
                                    post_office_id=post_office_id)
            else:

                contact = Contact()
                cart = Cart()
                cart.user_id = user_id

                lista = cart.GetCartByUserId()

                billing_info = ''
                suma = 0

                try:
                    billing_info = contact.getAdditionalInfo(
                        c.shipping_id)['success']
                except:
                    pass

                for l in lista:
                    c = Cart()
                    c.InitById(l["id"])
                    c.billing_info = billing_info
                    c.billing_id = c.shipping_id
                    c.Edit()
                    suma += l["subtotal"]

                if self.current_user['type_id'] == User().getUserTypeID(
                        UserType.EMPRESA):
                    self.render("wholesaler/checkout-4.html",
                                data=lista,
                                suma=suma,
                                iva=iva)
                else:
                    self.render("store/checkout-3.html",
                                data=lista,
                                suma=suma,
                                costo_despacho=costo_despacho,
                                shipping_type=shipping_type,
                                post_office_id=post_office_id)

        else:

            self.redirect("/auth/login")