Beispiel #1
0
    def post(self):
        parser = reqparse.RequestParser()

        parser.add_argument(name="username", type=str, location="json")
        parser.add_argument(name="userid", type=str, location="json")
        parser.add_argument(name="food_name", type=str, location="json")
        parser.add_argument(name="orderdate", type=str, location="json")
        parser.add_argument(name="rate", type=float, location="json")
        parser.add_argument(name="food_number", type=int, location="json")

        body = parser.parse_args()

        username = body.username
        userid = body.userid
        food_name = body.food_name
        orderdate = body.orderdate
        rate = body.rate
        food_number = body.food_number

        order = Order(username=username,
                      userid=userid,
                      food_name=food_name,
                      orderdate=orderdate,
                      rate=rate,
                      food_number=food_number)
        order.save()

        return mlab.item2json(order)
Beispiel #2
0
def test_insert_order():
    order = Order()
    order_to_db = {
        'customer_id': 1,
        'store_id': 1,
    }
    assert isinstance(order.insert_order(order_to_db), int)
Beispiel #3
0
def test_get_order_by_order_id():
    order = Order()
    order_info = order.get_order_by_order_id(1)
    assert 'order_id' in order_info and 'customer_id' in order_info and 'store_id' in order_info and \
           'order_date' in order_info and 'customer_name' in order_info and 'customer_phone_number' in order_info and \
           'customer_mail' in order_info and 'customer_street' in order_info and 'customer_city' in order_info and \
           'customer_state' in order_info and 'customer_zip_code' in order_info and 'products' in order_info
Beispiel #4
0
def create_orders():
    user = g.current_user
    data = request.get_json()

    items = []
    goods = Goods.query.filter(Goods.id.in_(data['goods_id'])).all()
    owner_id = goods[0].user_id if len(goods) != 0 else None
    if owner_id is None:
        return {'errmsg': '请选择商品!', 'errcode': 400}, 400
    for res in goods:
        if res.user_id != owner_id:
            return {'errmsg': '一次只能提交同一商家的商品', 'errcode': 400}, 400
        if res.sale == 1:
            return {
                'errmsg': '商品 ' + res.name + ' 已被购买, 下次手快点哦',
                'errcode': 400
            }, 400
        items.append(Item(goods_id=res.id))
    if owner_id == user.id:
        return {'errmsg': '不可购买自己发布的商品', 'errcode': 400}, 400

    try:
        address = user.addresses.filter_by(id=data['address_id']).first()
        order = Order(user=user, owner_id=owner_id, address=address)
        order.items = items
        # 更新goods为已售出
        for val in goods:
            val.sale = 1
        db.session.add(order)
        db.session.commit()
        return {'errmsg': '下单成功, 请期待您的宝贝~', 'errcode': 200}, 200
    except:
        return {'errmsg': '数据出错, 请确认数据'}
Beispiel #5
0
    def post(self):

        #parser.add_argument(name="id", type= int, location="json")
        #parser.add_argument(name="count", type=int, location="json")

        body = parser.parse_args()
        items = body["items"]
        user_id = body.user_id
        total_spend = 0
        order_item = []
        print("body:", body)
        print("items:", items)
        print("user_id:", user_id)
        for item in items:
            print("item type:", type(item))
            print("item:", item)
            good_id = item["id"]
            count = item["count"]
            good = Good.objects().with_id(good_id)
            price = good.price
            print("good_id:", good_id, ";count: ", count, "price: ", price)
            total_spend += price * count
            singleOrder = SingleOrder(good=good, count=count)
            order_item.append(singleOrder)
        customer = Customer.objects().with_id(user_id)
        #print(mlab.item2json(order_item[0]))
        #print("order_item0:",mlab.item2json(order_item[0]),"order_item1:",order_item[1])

        order = Order(items=order_item,
                      customer=customer,
                      totalspend=total_spend)
        order.save()
        add_order = Order.objects().with_id(order.id)
        return mlab.item2json(add_order)
Beispiel #6
0
 def post(self):
     #Post trên server sẽ lấy đủ đơn hàng, post trên local sẽ thiếu đơn hàng
     body = parser.parse_args()
     items = body["items"]
     user_id = body.user_id
     total_spend = 0
     order_item = []
     dumps = json.dumps(items)
     ldumps = re.findall(r"[\w']+", dumps)
     print(len(items))
     for i in range(0, len(items) + 1):
         try:
             good_id = ldumps[4 * i + 1][1:-1]
             count = int(ldumps[4 * i + 3])
             good = Good.objects().with_id(good_id)
             price = good.price
             total_spend += price * count
             singleOrder = SingleOrder(good=good, count=count)
             order_item.append(singleOrder)
         except:
             print("Index error")
     print("order_item:", mlab.list2json(order_item))
     customer = Customer.objects().with_id(user_id)
     order = Order(items=order_item,
                   customer=customer,
                   totalspend=total_spend)
     order.save()
     add_order = Order.objects().with_id(order.id)
     return mlab.item2json(add_order)
Beispiel #7
0
    def get(self):
        try:
            order = Order()
            json = request.json

            ans = []
            if json is not None and 'order_id' in json:
                ans = order.get_order_by_order_id(json['order_id'])
                # inventory.modify_stock()
            return {'success': True, 'products': ans}
        except Exception as e:
            return {'success': False, 'Error': str(e)}
Beispiel #8
0
def test():
    from model.order import Order
    from model.goods import Goods
    test = Goods()
    test.num = 10
    test.name = '香肠'
    test.count = 2
    test.unit_price = 2.5
    test.total_price = 23.2

    test2 = Goods()
    test2.num = 4
    test2.name = '火腿'
    test2.count = 3
    test2.unit_price = 3.4
    test2.total_price = 3.2

    order1 = Order()
    order1.num = '23456234234'
    order1.tel = '12234235345'
    order1.dorm_num = 'E1-228'
    order1.total_price = '234.4'
    order1.goods_list = [test, test2]

    print order1.to_show()
Beispiel #9
0
    def test_check_order_exists(self):

        order_id = 400
        order = Order()
        response = order.InitById(order_id)

        existe = None

        if "success" in response:
            if order_id == order.id:
                existe = True
        else:
            existe = False

        self.assertEqual(existe, True)
	def __init__(self, parent = None):
		super(OldReceiptDialog, self).__init__(parent)
		self.resize(800, 300)
		self.setModal(True)
		self.setWindowTitle('Sold Product')
		self.verticalLayout = QtWidgets.QVBoxLayout(self)
		self.verticalLayout.setContentsMargins(8, 4, 8, 2)
		self.verticalLayout.setSpacing(0)
		self.soldListViewWidget = SoldOrderListWidget(self)

		orderListDatabase = self.databaseService().query(Order).limit(2000).all()
		orderList = []
		for databaseOrder in orderListDatabase:
			order = Order.fromDatabase(databaseOrder)
			model = SoldProductModel()
			model.setOrder(order)
			model.setReadOnly(True)
			orderList.append(model)

		self.soldListViewWidget.setModel(orderList)

		global currentIndex
		currentIndex = len(orderList) - 1

		self.soldListViewWidget.setCurrentProductIndex(currentIndex)
		self.verticalLayout.addWidget(self.soldListViewWidget)

		self.__updateHeaderSizes()

		self.soldListViewWidget.currentIndexChanged.connect(self.__updateHeaderSizes)
		self.soldListViewWidget.soldProductLabelView.horizontalHeader().sectionResized.connect(self.__saveHeaderSizes)
Beispiel #11
0
def AddOrder(input: AddOrderInput, orderRepository: OrderRepository):
    if input.isValid() == False:
        raise Exception('Invalid input.')

    items: List[OrderItemLine] = []

    for itemLine in input.items:
        items.append(
            OrderItemLine.create(
                OrderItem.create(
                    itemId=itemLine.item.itemId,
                    variant=OrderItemVariant.create(
                        price=Price.create(
                            amount=itemLine.item.variant.price.amount,
                            currency=itemLine.item.variant.price.currency,
                            isTaxable=itemLine.item.variant.price.isTaxable
                        )
                    )
                ),
                quantity=itemLine.quantity
            )
        )

    order: Order = Order.create(id=str(uuid.uuid4()), items=items)

    return orderRepository.add(order=order)
Beispiel #12
0
    def __search(self):
        nameText = self.lineEdit.text()
        sdate = self.startCalenderLineEdit.date().toPython()
        startDate = datetime.datetime.combine(sdate,
                                              datetime.datetime.min.time())

        eDate = self.stopCalenderLineEdit.date().toPython()
        stopDate = datetime.datetime.combine(eDate,
                                             datetime.datetime.max.time())

        limit = self.limitSpinbox.value()
        query = self.databaseService().query(Order)
        if nameText:
            query = query.join(DatabaseSoldProduct).filter(
                DatabaseSoldProduct.product_name.like(f'%{nameText}%'))
        if self.stopCalenderLineEdit.isEnabled():
            query = query.filter(DatabaseOrder.created_date <= stopDate)
        if self.startCalenderLineEdit.isEnabled():
            query = query.filter(startDate <= DatabaseOrder.created_date)
        query = query.order_by(desc(DatabaseOrder.created_date)).limit(limit)

        orderList = []
        for databaseOrder in query:
            order = Order.fromDatabase(databaseOrder)
            orderList.append(order)

        self.orderModel.setOrderList(orderList)
Beispiel #13
0
    def get_order(self, order_id, *args, **kwargs):
        """
            Download an order by its ID.

            :param order_id: The identifier ("gamekey") that uniquely identifies the order
            :param list args: (optional) Extra positional args to pass to the request
            :param dict kwargs: (optional) Extra keyword args to pass to the request
            :return: The :py:class:`Order` requested
            :rtype: Order
            :raises RequestException: if the connection failed
            :raises HumbleAuthenticationException: if not logged in
            :raises HumbleResponseException: if the response was invalid
        """
        url = HumbleApi.ORDER_URL.format(order_id=order_id)

        response = self._request("GET", url, *args, **kwargs)
        """ order response might be 404 with no body if not found """

        if response.status_code == requests.codes.not_found:
            raise HumbleResponseException("Order not found",
                                          request=response.request,
                                          response=response)

        data = self.__parse_data(response)

        # The helper function should be sufficient to catch any other errors
        if self.__authenticated_response_helper(response, data):
            return Order(data)
Beispiel #14
0
    def verifyOrderState(order_id):

        order = Order()
        init_by_id = order.InitById(order_id)

        if "success" in init_by_id:
            if int(order.state) == Order.ESTADO_PENDIENTE:
                ExitoHandler.sendError(
                    "pedido {} esta pendiente de pago".format(order_id))
                return None
            else:
                return order
        else:
            ExitoHandler.sendError("error al inicializar pedido {}, {}".format(
                order_id, init_by_id["error"]))
            return None
Beispiel #15
0
def _sell_all_stock(order_book_id, amount, style):
    env = Environment.get_instance()
    order = Order.__from_create__(env.calendar_dt, env.trading_dt,
                                  order_book_id, amount, SIDE.SELL, style,
                                  None)
    if env.can_submit_order(order):
        env.broker.submit_order(order)
    return order
def fx_order(fx_user, fx_inventory):
    return Order(user_id=fx_user.user_id,
                 item_id=fx_inventory.item_id,
                 item_qty=fake.random_int(1, 100),
                 date=utcnow(),
                 deliver_phone=fake.phone_number(),
                 deliver_address=fake.address(),
                 total_price=fake.random_int(100, 1000000))
Beispiel #17
0
 def start_order(self):
     name = self.ui.login_inputs()
     town, street, number = self.ui.adress_inputs()
     customer = Customer(name)
     email = Email(name)
     adress = Adress(town, street, number)
     payment = Payment()
     self.order = Order(customer, email, payment, adress)
     self.add_to_cart()    
Beispiel #18
0
def createOrder():
    result = {"order": None, "details": []}
    body = dict(request.get_json())

    #Mapping all units to products
    units_map = {}
    for product in body["products"]:
        units_map[product["id"]] = product["units"]

    #Getting all eligible for customer products and the total of units they amount
    products = [
        Product(**product)
        for product in ProductRepo.getEligibleProductsForCustomer(**body)
    ]
    considered_units = set([product.getId() for product in products])
    total_units = sum([
        product["units"] if product["id"] in considered_units else 0
        for product in body["products"]
    ])

    if total_units <= VALUES.MAX_ORDER_UNITS and total_units > 0:
        total_price = sum([
            product.getPrice() * units_map[product.getId()]
            for product in products
        ])
        create = OrderRepo.createOrder(body["customer_id"], products,
                                       body["delivery_address"], total_price)
        rows, order_id = create["rows"], create["lastid"]
        if rows > 0:
            order = Order(**OrderRepo.getOrder(order_id))
            for product in products:
                create = OrderRepo.createOrderDetail(
                    order.getId(), product.getId(),
                    product.getProductDescription(), product.getPrice(),
                    units_map[product.getId()])
                rows, order_detail_id = create["rows"], create["lastid"]
                if rows > 0:
                    result["details"].append(
                        OrderDetail(order_detail_id, order_id, product.getId(),
                                    units_map[product.getId()]).__dict__)
            result["order"] = order.__dict__
    else:
        raise Exception(MESSAGES.ABOVE_MAX_UNIT(total_units))
    return result
Beispiel #19
0
 def create_orders(self):
     # 泊松分布获取生成订单个数,传入参数
     param = 50
     order_count = Poisson(param).get_num()
     # 获取今天0点的时间
     timestamp = day
     now = day
     # 获取4S点分布以及每个4S点的订单个数
     destination_data = get_destination(order_count)
     default_car_num = 1
     # 自动获取组id
     group = OrderGroupId().id
     # 生成订单
     for destination in destination_data:
         car_num = destination_data[destination]
         for i in range(car_num):
             order = Order(self.b_id, timestamp, now, destination,
                           default_car_num, group)
             order.set_delay_time()
             self.new_orders.add(order)
Beispiel #20
0
    def post(self):
        try:
            order = Order()
            order_product = OrderProduct()
            json = request.json
            inventory = Inventory()
            order_to_db = {
                'customer_id': json['customer_id'],
                'store_id': json['store_id'],
            }
            order_id = order.insert_order(order_to_db)
            for product in json['products']:

                store_inventory = inventory.get_product_availability_in_specific_store(product['product_id'], json['store_id'])
                if product['quantity'] > store_inventory[0]['quantity']:
                    return {'success': False, 'Error': 'product unavailable '+product['product_id']}
                product['order_id'] = order_id
                order_product.insert_order_product(product)
                inventory.modify_stock(json['store_id'], product['product_id'], int(product['quantity'])*-1)
            return {'success': True, 'product': json}
        except Exception as e:
            return {'success': False, 'Error': str(e)}
Beispiel #21
0
    def set_state(self, state):
        self._open_orders = []
        self._delayed_orders = []

        value = jsonpickle.loads(state.decode('utf-8'))
        for v in value['open_orders']:
            o = Order()
            o.set_state(v)
            account = self._env.get_account(o.order_book_id)
            self._open_orders.append((account, o))
        for v in value['delayed_orders']:
            o = Order()
            o.set_state(v)
            account = self._env.get_account(o.order_book_id)
            self._delayed_orders.append((account, o))
Beispiel #22
0
    def post(self):
        parser = reqparse.RequestParser()
        parser.add_argument('name', type=str, help='name')
        parser.add_argument('phone', type=str, help='phone')
        parser.add_argument('address', type=str, help='address')
        parser.add_argument('email', type=str, help='email')
        parser.add_argument('bankAccount', type=str, help='bank account')
        parser.add_argument('itemList',
                            type=list,
                            help='item list',
                            location="json")
        args = parser.parse_args()
        print(args)

        with app.app_context():
            order = Order(args['name'], args['address'], args['phone'],
                          args['email'], args['bankAccount'])
            order.save_to_db()
            for pid in args['itemList']:
                ohp = OrderHasProduct(order.data['id'], pid, 1)
                ohp.save_to_db()

            return order.id
Beispiel #23
0
def getOrder(orderId):
    import common
    import re
    from bs4 import BeautifulSoup
    from model.order import Order
    from model.goods import Goods

    orderId = str(orderId)
    cookie_id = cookie_ship.getCookie()
    req = urllib2.Request(common.ORDER_URL + orderId)
    req.add_header('Cookie', '_FSESSIONID=' + cookie_id)
    res_data = urllib2.urlopen(req)
    html = res_data.read()

    soup = BeautifulSoup(html)
    xndian_order = Order()
    # 订单号
    order_num_list = soup.find_all('span', class_='g_stress')
    xndian_order.num = deal_str(order_num_list[0].string)

    # 总价
    xndian_order.total_price = deal_str(order_num_list[1].string)

    # 电话号 寝室号
    order_tel_list = soup.find_all('td', class_='propItemValue')

    xndian_order.tel = deal_str(order_tel_list[0].string)
    xndian_order.dorm_num = deal_str(order_tel_list[1].string)

    xndian_good_list = []

    # 货物列表
    good_list = soup.find_all('table', class_='lineBody')
    for i in range(len(good_list) - 1):

        xndian_good = Goods()
        i = i + 1

        string = str(good_list[i])
        soup2 = BeautifulSoup(string)
        # 商品名
        xndian_good.name = deal_str(soup2.find_all('a')[0].string)
        # 编号
        xndian_good.num = deal_str(soup2.find_all('td')[1].string)
        # 单价
        xndian_good.unit_price = deal_str(soup2.find_all('span')[0].string)
        # 数量
        xndian_good.count = deal_str(soup2.find_all('td')[3].string)
        # 总价
        xndian_good.total_price = deal_str(soup2.find_all('td')[4].string)

        xndian_good_list.append(xndian_good)

    xndian_order.goods_list = xndian_good_list
    return xndian_order
Beispiel #24
0
 def getOrderInfo(self, orderId):
     params = {"method": "order_info"}
     params['coin_type'] = self.coinType
     params['id'] = orderId
     extra = {}
     res = send2api(params, extra)
     if res and "code" not in res:
         order_info = Order()
         order_info.order_id = res['id']
         order_info.status = res['status']
         order_info.price = float(res['order_price'])
         order_info.deal_amount = float(res['processed_amount'])
         order_info.avg_price = float(res['processed_price'])
         return order_info
     return None
Beispiel #25
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")
Beispiel #26
0
 def get_order_by_user(self, user):
     cursor = self.order_coll.find({
         "user.unionId": user
     }).sort("created_date", pymongo.DESCENDING)
     order_list = []
     if cursor is not None:
         for document in cursor:
             order_utc_time_str = document.get('created_date')
             order_east_eight_zone_time = datetime.datetime.strptime(
                 order_utc_time_str,
                 "%Y/%m/%d %H:%M:%S") + datetime.timedelta(hours=8)
             order_east_eight_zone_time_str = order_east_eight_zone_time.strftime(
                 "%Y/%m/%d %H:%M:%S")
             order = Order(
                 document.get('_id').__str__(), document.get('user'),
                 document.get('snack_list'), document.get('total_price'),
                 document.get('total_amount'),
                 order_east_eight_zone_time_str, document.get('location'))
             order_list.append(order.__dict__)
     return order_list
Beispiel #27
0
    def getOrderInfo(self, orderId):
        ORDER_INFO_RESOURCE = "/api/v1/order_info.do"
        params = {
            'api_key': APIKEY,
            'symbol': self.symbol,
            'order_id': orderId
        }
        params['sign'] = buildMySign(params, SECRETKEY)
        res = httpPost(URL, ORDER_INFO_RESOURCE, params)

        if res and res['result']:
            order_info = Order()
            order_info.order_id = res["orders"][0]["order_id"]
            order_info.price = res["orders"][0]["price"]
            order_info.avg_price = res["orders"][0]['avg_price']
            order_info.deal_amount = res["orders"][0]['deal_amount']
            order_info.status = res["orders"][0]["status"]
            return order_info
        return None
Beispiel #28
0
def listOrders():
    result = []
    args = dict(request.args)

    #Tranform date into MYSQL readable format
    parseDate = lambda val: datetime.strptime(val, "%d/%m/%Y").date()
    startDate, endDate = parseDate(args["from"]), parseDate(args["to"])

    orders = [
        Order(**order) for order in OrderRepo.getCustomerOrdersOnDateRange(
            args["customer_id"], str(startDate), str(endDate))
    ]
    for order in orders:
        order_details = [
            OrderDetail(**detail)
            for detail in OrderRepo.getOrderDetails(order.getId())
        ]
        order_products = []
        for detail in order_details:
            product = Product(**ProductRepo.getProduct(detail.getProductId()))
            order_products.append((product, detail.getQuantity()))

        #Organizing data to deliver resposne
        order_data = {
            "creation_date":
            order.getCreationDate(),
            "order_id":
            order.getId(),
            "total":
            order.getTotal(),
            "delivery_address":
            order.getDeliveryAddress(),
            "products": [{
                "name": product.getName(),
                "units": units
            } for product, units in order_products]
        }
        result.append(order_data)
    return result
Beispiel #29
0
def order(id_or_ins, amount, side, position_effect, style):
    if not isinstance(style, OrderStyle):
        raise RuntimeError
    if amount <= 0:
        raise RuntimeError
    if isinstance(style, LimitOrder) and style.get_limit_price() <= 0:
        raise RQInvalidArgument(_(u"Limit order price should be positive"))

    order_book_id = assure_future_order_book_id(id_or_ins)
    env = Environment.get_instance()
    price = env.get_last_price(order_book_id)
    if np.isnan(price):
        user_system_log.warn(
            _(u"Order Creation Failed: [{order_book_id}] No market data").
            format(order_book_id=order_book_id))
        return

    amount = int(amount)

    r_order = Order.__from_create__(env.calendar_dt, env.trading_dt,
                                    order_book_id, amount, side, style,
                                    position_effect)

    if np.isnan(price) or price == 0:
        user_system_log.warn(
            _(u"Order Creation Failed: [{order_book_id}] No market data").
            format(order_book_id=order_book_id))
        r_order.mark_rejected(
            _(u"Order Creation Failed: [{order_book_id}] No market data").
            format(order_book_id=order_book_id))
        return r_order

    if r_order.type == ORDER_TYPE.MARKET:
        r_order.set_frozen_price(price)

    if env.can_submit_order(r_order):
        env.broker.submit_order(r_order)
    return r_order
Beispiel #30
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 #31
0
    def post(self):

        username = ''

        TBK_RESPUESTA = self.get_argument("TBK_RESPUESTA")
        TBK_ORDEN_COMPRA = self.get_argument("TBK_ORDEN_COMPRA")
        TBK_MONTO = self.get_argument("TBK_MONTO")
        TBK_ID_SESION = self.get_argument("TBK_ID_SESION")

        myPath = "{}webpay/dato{}.log".format(project_path, TBK_ID_SESION)

        filename_txt = "{}webpay/MAC01Normal{}.txt".format(
            project_path, TBK_ID_SESION)

        cmdline = "{}cgi-bin/tbk_check_mac.cgi {}".format(
            cgi_path, filename_txt)

        acepta = False

        if TBK_RESPUESTA == "0":
            acepta = True
        else:
            order = Order()
            init_by_id = order.InitById(TBK_ORDEN_COMPRA)
            if "success" in init_by_id:
                order.state = Order.ESTADO_RECHAZADO_WP
                save_order = order.Edit()

        try:
            f = open(myPath, "r")

            linea = ""

            for l in f:
                if l.strip() != "":
                    linea = l

            f.close()

            detalle = linea.split(";")

            # print "linea:{}".format(linea)

            if len(detalle) > 0:
                monto = detalle[0]
                ordenCompra = detalle[1]

            f = open(filename_txt, "wt")

            f.write("{}={}&".format("TBK_ORDEN_COMPRA",
                                    self.get_argument("TBK_ORDEN_COMPRA")))
            f.write("{}={}&".format("TBK_TIPO_TRANSACCION",
                                    self.get_argument("TBK_TIPO_TRANSACCION")))
            f.write("{}={}&".format("TBK_RESPUESTA",
                                    self.get_argument("TBK_RESPUESTA")))
            f.write("{}={}&".format("TBK_MONTO",
                                    self.get_argument("TBK_MONTO")))
            f.write("{}={}&".format(
                "TBK_CODIGO_AUTORIZACION",
                self.get_argument("TBK_CODIGO_AUTORIZACION")))
            f.write("{}={}&".format(
                "TBK_FINAL_NUMERO_TARJETA",
                self.get_argument("TBK_FINAL_NUMERO_TARJETA")))
            f.write("{}={}&".format("TBK_FECHA_CONTABLE",
                                    self.get_argument("TBK_FECHA_CONTABLE")))
            f.write("{}={}&".format(
                "TBK_FECHA_TRANSACCION",
                self.get_argument("TBK_FECHA_TRANSACCION")))
            f.write("{}={}&".format("TBK_HORA_TRANSACCION",
                                    self.get_argument("TBK_HORA_TRANSACCION")))
            f.write("{}={}&".format("TBK_ID_SESION",
                                    self.get_argument("TBK_ID_SESION")))
            f.write("{}={}&".format("TBK_ID_TRANSACCION",
                                    self.get_argument("TBK_ID_TRANSACCION")))
            f.write("{}={}&".format("TBK_TIPO_PAGO",
                                    self.get_argument("TBK_TIPO_PAGO")))
            f.write("{}={}&".format("TBK_NUMERO_CUOTAS",
                                    self.get_argument("TBK_NUMERO_CUOTAS")))
            f.write("{}={}&".format("TBK_VCI", self.get_argument("TBK_VCI")))
            f.write("{}={}&".format("TBK_MAC", self.get_argument("TBK_MAC")))

            f.close()

            if (TBK_MONTO == monto and TBK_ORDEN_COMPRA == ordenCompra
                    and acepta):
                acepta = True
            else:
                acepta = False

        except:
            self.write("RECHAZADO")
            return

        if acepta:

            resultado = os.popen(cmdline).read()

            # print "RESULTADO:-----{}----".format(resultado.strip())
            if resultado.strip() == "CORRECTO":
                acepta = True
            else:
                acepta = False

        if acepta:

            order = Order()
            init_by_id = order.InitById(TBK_ORDEN_COMPRA)

            detail = OrderDetail()
            lista = detail.ListByOrderId(TBK_ORDEN_COMPRA)

            if "success" in init_by_id:

                user = User()
                usuario = user.InitById(order.user_id)

                user_email = ''

                if "error" not in usuario:
                    username = usuario['name']
                    user_email = usuario["email"]

                # rechaza si orden no esta pendiente
                if order.state != Order.ESTADO_PENDIENTE:
                    acepta = False
                # si esta pendiente actualizar a pagado
                elif order.state == Order.ESTADO_PENDIENTE:
                    order.state = Order.ESTADO_CONFIRMADO
                    save_order = order.Edit()
                    # rechaza si no puede actualizar la orden
                    if "error" in save_order:
                        acepta = False

                    webpay = Webpay()
                    webpay.order_id = order.id
                    webpay.tbk_orden_compra = self.get_argument(
                        "TBK_ORDEN_COMPRA")
                    webpay.tbk_tipo_transaccion = self.get_argument(
                        "TBK_TIPO_TRANSACCION")
                    webpay.tbk_monto = self.get_argument("TBK_MONTO")
                    webpay.tbk_codigo_autorizacion = self.get_argument(
                        "TBK_CODIGO_AUTORIZACION")
                    webpay.tbk_final_numero_tarjeta = self.get_argument(
                        "TBK_FINAL_NUMERO_TARJETA")
                    webpay.tbk_fecha_contable = self.get_argument(
                        "TBK_FECHA_CONTABLE")
                    webpay.tbk_fecha_transaccion = self.get_argument(
                        "TBK_FECHA_TRANSACCION")
                    webpay.tbk_hora_transaccion = self.get_argument(
                        "TBK_HORA_TRANSACCION")
                    webpay.tbk_id_sesion = self.get_argument("TBK_ID_SESION")
                    webpay.tbk_id_transaccion = self.get_argument(
                        "TBK_ID_TRANSACCION")
                    webpay.tbk_tipo_pago = self.get_argument("TBK_TIPO_PAGO")
                    webpay.tbk_numero_cuotas = self.get_argument(
                        "TBK_NUMERO_CUOTAS")
                    res = webpay.Save()

                    if "error" in res:
                        print res["error"]
                    else:
                        try:
                            self.moveStock(lista, order.user_id)
                        except Exception, e:
                            ExitoHandler.sendError(
                                'error moviendo stock, {}'.format(
                                    TBK_ORDEN_COMPRA))
                        if username != '':
                            try:
                                subject = "Giani Da Firenze - Procesando Compra Nº {}".format(
                                    TBK_ORDEN_COMPRA)
                                mandrill_client = mandrill.Mandrill(
                                    mailchimp_api_key)
                                mandrill_client.templates.update(
                                    processing_order_template, subject=subject)
                                info = mandrill_client.templates.info(
                                    processing_order_template)

                                template_content = [{
                                    "name": "",
                                    "content": info["code"]
                                }]
                                merge_vars = [{
                                    "name": "name",
                                    "content": username
                                }, {
                                    "name": "order_id",
                                    "content": TBK_ORDEN_COMPRA
                                }, {
                                    "name": "company",
                                    "content": "Giani Da Firenze"
                                }, {
                                    "name": "current_year",
                                    "content": 2015
                                }, {
                                    "name":
                                    "list_address_html",
                                    "content":
                                    '*****@*****.**'
                                }, {
                                    "name": "user_email",
                                    "content": user_email
                                }]

                                html = mandrill_client.templates.render(
                                    processing_order_template,
                                    template_content, merge_vars)
                                sg = sendgrid.SendGridClient(
                                    sendgrid_user, sendgrid_pass)
                                mensaje = sendgrid.Mail()
                                mensaje.set_from("{nombre} <{mail}>".format(
                                    nombre=info["from_name"],
                                    mail=info["from_email"]))
                                mensaje.add_to([
                                    '*****@*****.**',
                                    '*****@*****.**'
                                ])
                                mensaje.set_subject(info["subject"])
                                mensaje.set_html(html["html"])
                                status, msg = sg.send(mensaje)
                            except Exception, e:
                                print 'enviando correo procesamiento, {}'.format(
                                    str(e))
                                ExitoHandler.sendError(
                                    'enviando correo procesamiento, {}'.format(
                                        str(e)))
def __get_order_list(account_id, order_array):
    order_list = []
    order_dict = dict()
    for order_info in order_array:
        order_db = Order()
        order_db.sys_id = getattr(order_info, 'm_strOrderSysID', '')
        # sys_id为空表示交易未到达交易所即被打回
        if order_db.sys_id == '':
            continue

        order_db.account = account_id
        order_db.symbol = getattr(order_info, 'm_strInstrumentID', '')

        # 48:买,49:卖
        order_db.direction = getattr(order_info, 'm_nDirection', '')

        # 0:开仓  1:平仓  3:平今  4:平昨
        order_db.trade_type = getattr(order_info, 'm_eOffsetFlag', '')

        # 全部成交:'0' 部分成交还在队列中:'1',部分成交不在队列中:'2',未成交还在队列中:'3',
        # 未成交不在队列中:'4',撤单:'5',未知:'a',尚未触发:'b',已触发:'c'
        order_db.status = getattr(order_info, 'EEntrustStatus', '')

        # 已经提交:'0',撤单已经提交:'1',修改已经提交:'2',已经接受:'3',报单已经被拒绝:'4',撤单已经被拒绝:'5',改单已经被拒绝:'6'
        order_db.submit_status = getattr(order_info, 'EEntrustSubmitStatus',
                                         '')

        trading_day = getattr(order_info, 'm_strInsertDate', '')
        insert_time = getattr(order_info, 'm_strInsertTime', '')
        if (trading_day != '') and (insert_time != ''):
            insert_time_str = '%s-%s-%s %s' % (trading_day[0:4],
                                               trading_day[4:6],
                                               trading_day[6:8], insert_time)
            if insert_time > now_datetime_str:
                insert_time_str = '%s %s' % (last_trading_day, insert_time)
        else:
            insert_time_str = '%s 00:00:00' % (now_date_str, )
        order_db.insert_time = insert_time_str

        qty = getattr(order_info, 'm_nTotalVolume', '')
        if order_db.direction == '0':
            order_db.qty = qty
        elif order_db.direction == '1':
            order_db.qty = 0 - int(qty)
        order_db.price = getattr(order_info, 'm_dAveragePrice', '')
        order_db.ex_qty = getattr(order_info, 'm_nTradedVolume', '')
        order_list.append(order_db)
        order_dict[order_db.sys_id] = order_db
    return order_list, order_dict