def get(self): orderitems = [] user = self.current_user try: order = Order.get(uid=user.id, status=0) for orderitem in OrderItem.select().where( OrderItem.oid == order.id).dicts(): try: orderitem['shop'] = Shop.get(id=orderitem['sid']) if orderitem['said'] > 0: orderitem['shopattr'] = ShopAttr.get( id=orderitem['said']) orderitems.append(orderitem) except: pass except: order = Order() ashops = Shop.select().where((Shop.cid == 2) & (Shop.status != 9)) self.render("shop/order.html", orderitems=orderitems, order=order, ashops=ashops)
def insert_user(user_json): #print "INSERT USER" #print user_json user_string = json.loads(user_json) userAddress = Address(number = user_string["number"], street = user_string["street"], postalCode = user_string["postalCode"], city = user_string["city"], province = user_string["province"]) #print "pizzaId: " + user_string["pizzaId"] userOrder = Order(qty = int(user_string["quantity"]), size = int(user_string["pizzaSize"]), pizza_type = int(user_string["pizzaId"])) userAddress.put() userOrder.put() user = User(name = user_string["name"], phoneNumber = user_string["phoneNumber"], email = user_string["email"], addressId = userAddress.key(), orderId = userOrder.key()) user.put() return user.key();
def post(self): notify = Notify_pub() xml = self.request.body notify.saveData(xml) if not notify.checkSign: notify.setParameter("return_code", "FAIL") notify.setReturnParameter("return_msg", "签名失败") print "签名失败" else: result = notify.getData() print "result:" print result if result["return_code"] == "FAIL": notify.setReturnParameter("return_code", "FAIL") notify.setReturnParameter("return_msg", "通信错误") print "通信错误" elif result["result_code"] == "FAIL": notify.setReturnParameter("return_code", "FAIL") notify.setReturnParameter("return_msg", result["err_code_des"]) else: notify.setReturnParameter("return_code", "SUCCESS") out_trade_no = result["out_trade_no"] time_end = result["time_end"] print "支付成功:" + out_trade_no print "交易时间:" + time_end print "更改订单状态" Order.update(status = 1).where(Order.status == 0 and Order.wxid == out_trade_no).execute() #支付成功订单状态改为1 return self.write(notify.returnXml())
def post(self): notify = Notify_pub() xml = self.request.body notify.saveData(xml) if not notify.checkSign: notify.setParameter("return_code", "FAIL") notify.setReturnParameter("return_msg", "签名失败") print "签名失败" else: result = notify.getData() print "result:" print result if result["return_code"] == "FAIL": notify.setReturnParameter("return_code", "FAIL") notify.setReturnParameter("return_msg", "通信错误") print "通信错误" elif result["result_code"] == "FAIL": notify.setReturnParameter("return_code", "FAIL") notify.setReturnParameter("return_msg", result["err_code_des"]) else: notify.setReturnParameter("return_code", "SUCCESS") out_trade_no = result["out_trade_no"] time_end = result["time_end"] print "支付成功:" + out_trade_no print "交易时间:" + time_end print "更改订单状态" Order.update(status=1).where( Order.status == 0 and Order.wxid == out_trade_no).execute() #支付成功订单状态改为1 return self.write(notify.returnXml())
def accept_order(self, order: Order): if order.get_id() in self.orders: self.remove_order(order.get_id()) th = WorkingThread(self, order) self.working_threads.append(th) th.start() self.orders[order.get_id()] = order
def add_order(self): s = Session() ord = Order() ord.manager_id = self.parent.user.id ord.device = unicode(self.ui.device.text()) ord.description = unicode(self.ui.description) ord.client_id = s.query(Client).filter_by(id=unicode(self.ui.client.itemText(self.ui.client.currentIndex())).split()[0]).one().id s.add(ord) s.commit() s.close() self.close()
def get(self): user = self.get_current_user() status = self.get_argument("status", None) ft = (Order.uid == user.id) if status: ft = ft & (Order.status == status) page = int(self.get_argument("page", 1)) pagesize = self.settings['admin_pagesize'] oq = Order.select().where(ft) total = oq.count() orders = [] for order in oq.paginate(page, pagesize).dicts(): order['orderitems'] = [] for orderitem in OrderItem.select().where( OrderItem.oid == order['id']).dicts(): try: orderitem['shop'] = Shop.get(id=orderitem['sid']) if orderitem['said'] > 0: orderitem['shopattr'] = ShopAttr.get( id=orderitem['said']) except: break order['orderitems'].append(orderitem) if order['orderitems']: orders.append(order) else: Order.delete().where(Order.id == order['id']).execute() try: user = User.get(id=user.id) if user.order > 0: user.order = user.order - 1 user.save() self.session['user'] = user self.session.save() except: pass self.render('user/order.html', orders=orders, total=total, page=page, pagesize=pagesize)
def reject_order(order_event): status = 'REJECTED' try: order = Order(order_event['order_id']) order.update(actions=[ Order.order_status.set(status) # Order.cause.set(order_event['error']['Error']) ]) return except UpdateError as e: error_message = 'update_order Error: {}'.format(vars(e)) logging.exception(error_message) raise ErrorOrderUpdate(error_message)
def submit_order(): headers = request.headers if headers['Authorization'] != os.getenv("WEBHOOK_PSWD"): return "" data = request.json data['order_id'] = data['id'] del data['id'] del data['status'] order = Order(**data) order.save() return jsonify({"success": True})
def get(self): user = self.get_current_user() status = self.get_argument("status", None) ft = (Order.uid == user.id) if status: ft = ft & (Order.status == status) page = int(self.get_argument("page", 1)) pagesize = self.settings['admin_pagesize'] oq = Order.select().where(ft) total = oq.count() orders = [] for order in oq.paginate(page, pagesize).dicts(): order['orderitems'] = [] for orderitem in OrderItem.select().where(OrderItem.oid == order['id']).dicts(): try: orderitem['shop'] = Shop.get(id = orderitem['sid']) if orderitem['said'] > 0: orderitem['shopattr'] = ShopAttr.get(id = orderitem['said']) except: break order['orderitems'].append(orderitem) if order['orderitems']: orders.append(order) else: Order.delete().where(Order.id == order['id']).execute() try: user = User.get(id = user.id) if user.order > 0: user.order = user.order - 1 user.save() self.session['user'] = user self.session.save() except: pass self.render('user/order.html', orders = orders, total = total, page = page, pagesize = pagesize)
def approve_order(order_event): status = 'APPROVED' try: order = Order(order_event['order_id']) order.update( actions=[ Order.order_status.set(status) ] ) return except UpdateError as e: error_message = 'update_order Error: {}'.format(vars(e)) logging.exception(error_message) raise ErrorOrderUpdate(error_message)
def booking(id): apartment = Apartment.query.filter_by(id=id).first() if request.method == 'POST': daterange = request.values.get('daterange') if daterange: l = daterange.split('-') checkin = datetime.strptime(l[0].strip(), '%m/%d/%Y').date() checkout = datetime.strptime(l[1].strip(), '%m/%d/%Y').date() if not apartment.checkbooking(checkin, checkout): booking = Order(user_id=current_user.id, apartment_id=id, checkin_date=checkin, checkout_date=checkout) db.session.add(booking) db.session.commit() flash('This booking ordered.', 'success') return redirect(url_for('apartment', id=id)) else: flash('This apartment is booked in this daterange', 'info') else: flash('Booking date not selected.', 'warning') return render_template('booking.html', data=apartment)
def create_order(): global order_counter parser = reqparse.RequestParser() parser.add_argument('coffee_id', type=int, required=True) parser.add_argument('additions', type=str, action='append') args = parser.parse_args() coffee_id = args.get("coffee_id") additions = args.get("additions") for row in coffee_db: if int(row.coffee_id) == int(coffee_id): coffee = row break else: return jsonify(coffee_id=False), 404 order_counter += 1 new = Order(order_counter, coffee_id, coffee.coffee_name, coffee.cost, 'open', additions) order_db.append(new) return jsonify({ 'data': new.__dict__, 'payment': { 'link': url_for('create_payment', order_id=order_counter), 'method': 'POST' } }), 201
def get(self, oid): orderitems = [] price = 0.0 credit = 0.0 order = None try: order = Order.get(id = oid) print order.id for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts(): try: orderitem['shop'] = Shop.get(id = orderitem['sid']) _oiprice = orderitem['shop'].price if orderitem['said'] > 0: orderitem['shopattr'] = ShopAttr.get(id = orderitem['said']) if orderitem['shop'].cid == 1: _oicredit = orderitem['shopattr'].price credit = credit + _oicredit * orderitem['num'] _oiprice = orderitem['shopattr'].price else: _oiprice = orderitem['shopattr'].price else: _oiprice = float(_oiprice) orderitems.append(orderitem) price = price + float(_oiprice) * orderitem['num'] except: pass print price except: pass self.render("/responsive/user_confirmorder.html", order = order, credit = credit, orderitems = orderitems)
def get(self, oid): try: order = Order.get(id = oid) except: pass self.render("admin/changeorder.html", order = order)
def test_job_transmission(self): self.awake_single() # campaignをセット campaign = Campaign(author="cxxx0", requirement=Requirement(values=["zero", "random"], trigger={"timer": 1}), trigger={"timer": 5}, place="All", purpose="test_purpose", destination="mongodb://localhost:27017/") clients["cxxx0"].post('/commander/campaigns', data=json.dumps(campaign.to_dict()), content_type='application/json') time.sleep(1.5) # heartbeatを待つ; 0.7 + 0.4 + alpha # missionを確認 mission = Mission(author="lxxx0", requirement=Requirement(values=["zero", "random"], trigger={"timer": 1}), trigger={"timer": 5}, place="All", purpose=campaign.get_id()) self.assertIn(mission, self.models["lxxx0"].missions.values()) # orderを確認 order = Order(author="sxxx0", values=["zero", "random"], trigger={"timer": 1}, purpose=mission.get_id()) self.assertIn(order, self.models["sxxx0"].orders.values())
def get(self, oiid): result = {'status': False, 'msg': 0} user = self.get_current_user() if user: try: orderitem = OrderItem.get(id=oiid) order = Order.get(id=orderitem.oid) if order.uid == user.id: if OrderItem.select().where( OrderItem.oid == orderitem.oid).count() == 1: order.delete_instance() if user.order > 0: user.order = user.order - 1 user.save() self.session['user'] = user self.session.save() orderitem.delete_instance() result['status'] = True result['msg'] = 200 else: result['msg'] = 403 except Exception, ex: logging.error(ex) result['msg'] = 500
def post(self, oid, sid): result = {'status': False, 'msg': 0} user = self.get_current_user() if user: try: order = Order.get(id=oid) if order.uid == user.id: try: orderitem = OrderItem.get(OrderItem.oid == oid, OrderItem.sid == sid) except: orderitem = OrderItem() orderitem.oid = oid orderitem.sid = sid orderitem.num = orderitem.num + 1 try: orderitem.save() result['status'] = True result['msg'] = 200 except Exception, ex: logging.error(ex) result['msg'] = 500 else: result['msg'] = 403
def accept_mission(self, mission: Mission) -> Mission: # Missionの更新であれば(=IDが同じであれば)既存のものを消す if mission.get_id() in self.missions: self.remove_mission(mission.get_id()) # 部下のOrderを生成・割り当てる target_subs = [] if mission.place == "All": target_subs = list(self.subordinates.values()) for sol in target_subs: m_req = mission.requirement values = list(set(m_req.values).intersection(sol.weapons)) order = Order(author=sol.id, values=values, trigger=m_req.trigger, purpose=mission.get_id()) sol.orders.append(order) # 自身のデータ送信スレッドを生成する th = WorkingThread(self, mission) self.working_threads.append(th) th.start() self.missions[mission.get_id()] = mission return mission
def get(self): iscatched = False if self.current_user: beginvalue = time.mktime(time.strptime('2015-01-12', "%Y-%m-%d")) endvalue = time.mktime(time.strptime('2015-01-31', "%Y-%m-%d")) q = Order.select(Order.currentprice).where( (Order.user == self.current_user) & (Order.ordered >= beginvalue) & (Order.status < 5) & (Order.ordered < endvalue) & (Order.payment < 9) & (((Order.status > -1) & (Order.payment == 0)) | ( (Order.status > 0) & (Order.payment > 0)))).dicts() price = sum([n['currentprice'] for n in q]) cpcount = int(price / 50.0) activities = UserActivity.select().where( UserActivity.user == self.current_user.id) if activities.count() > 0: iscatched = True else: price = 0.0 cpcount = 0 list = ProductStandard.select(ProductStandard).join(Product). \ where((ProductStandard.id << [268,215,128,279,38,37,84,86]) & (Product.status == 1)) self.render('activity/new_year.html', user=self.current_user, price=price, cpcount=cpcount, iscatched=iscatched, list=list)
def get(self, oiid): result = {'status' : False, 'msg' : 0} user = self.get_current_user() if user: try: orderitem = OrderItem.get(id = oiid) order = Order.get(id = orderitem.oid) if order.uid == user.id: if OrderItem.select().where(OrderItem.oid == orderitem.oid).count() == 1: order.delete_instance() if user.order > 0: user.order = user.order - 1 user.save() self.session['user'] = user self.session.save() orderitem.delete_instance() result['status'] = True result['msg'] = 200 else: result['msg'] = 403 except Exception, ex: logging.error(ex) result['msg'] = 500
def post(self, oid, sid): result = {'status' : False, 'msg' : 0} user = self.get_current_user() if user: try: order = Order.get(id = oid) if order.uid == user.id: try: orderitem = OrderItem.get(OrderItem.oid == oid, OrderItem.sid == sid) except: orderitem = OrderItem() orderitem.oid = oid orderitem.sid = sid orderitem.num = orderitem.num + 1 try: orderitem.save() result['status'] = True result['msg'] = 200 except Exception, ex: logging.error(ex) result['msg'] = 500 else: result['msg'] = 403
def get(self, oid): try: order = Order.get(id=oid) except: pass self.render("admin/changeorder.html", order=order)
def make(cls, source: dict): try: return cls(source['id'], source['name'], source['place'], source['weapons'], [Order.make(o) for o in source['orders']]) except KeyError: raise TypeError
def check_order_store_quantity(store_id, oid): result = 0 items = OrderItem.select().where(OrderItem.order == oid) r = 0 if store_id: for i in items: if i.product.is_store == 1: # and i.product.store.id == int(store_id) r += 1 else: r += check_store_product_quantity(store_id, i.product_standard.id) if r == items.count(): result = 1 else: list = [] order = Order.get(Order.id == oid) store = Store.select().where(Store.status == 1) sid = 0 for s in store: ss = getDistanceAS(order.take_address.replace(' ', ''), s.id) if ss['flag'] == 1: list.append(float(ss['data'])) if float(ss['data']) < setting.PeiSongDistance: sid = s.id for i in items: if i.product.is_store == 1 and i.product.store.id == sid: r += 1 else: r += check_store_product_quantity(sid, i.product_standard.id) if r == items.count(): result = 1 return result
def createOrder(): current_user = get_jwt_identity() vir = Order(current_user) db.session.add(vir) db.session.commit() carts = Cart.query.filter_by(creator_id=current_user, removed=False).all() orders = [] for cart in carts: product = Product.query.filter_by(id=cart.product_id, shelved=True, archived=False).first() description = Description.query.filter_by(product_id=cart.product_id, active=True, removed=False).first() # 限购暂未实现 print(description.remain, cart.count) if (not product) or (not description) or (description.remain < cart.count): orders.append([False, cart.id]) continue description.remain = description.remain - cart.count order = Order(current_user) order.fill(cart.product_id, cart.count, description.price, vir.id) db.session.add(order) cart.removed = True db.session.commit() orders.append( [True, cart.id, cart.product_id, cart.count, description.price]) return jsonify(orders=orders, price=vir.cost()), 200
def get(self): orderitems = [] user = self.current_user order = None distributions = self.get_distributions() price = 0.0 credit = 0.0 try: order = Order.get(uid=user.id, status=0) try: mobile = '18014349809' sendmsg(self.settings, mobile, '新订单') except: pass for orderitem in OrderItem.select().where( OrderItem.oid == order.id).dicts(): try: orderitem['shop'] = Shop.get(id=orderitem['sid']) _oiprice = orderitem['shop'].price if orderitem['said'] > 0: orderitem['shopattr'] = ShopAttr.get( id=orderitem['said']) if orderitem['shop'].cid == 1: _oicredit = orderitem['shopattr'].price credit = credit + _oicredit * orderitem['num'] else: _oiprice = orderitem['shopattr'].price else: _oiprice = float(_oiprice) orderitems.append(orderitem) price = price + _oiprice * orderitem['num'] except: pass order.price = price order.save() except: pass if orderitems: self.render("shop/settle.html", tmday=datetime.date.today() + datetime.timedelta(days=1), order=order, orderitems=orderitems, distributions=distributions.values(), credit=credit)
def make(cls, source: dict): try: return cls( source['id'], source['name'], source['place'], source['weapons'], [Order.make(o) for o in source['orders']] ) except KeyError: raise TypeError
def save_order(order_data): order = Order(order_id=order_data.get("id"), side=order_data.get("side"), state=order_data.get("state"), price=float(order_data.get("price")), symbol=order_data.get("symbol"), amount=float(order_data.get("amount")), filled_amount=float(order_data.get("filled_amount")), fill_fees=float(order_data.get("fill_fees"))) with DBSession() as session: session.add(order)
def add_order_details(order_id, address, user_id): try: order = Order(order_id=order_id, address=address, user=user_id) db.session.add(order) db.session.commit() return True except IntegrityError: return make_response( jsonify({'response': "user name or email already exists"}), 400) except (InvalidRequestError, OperationalError): raise InvalidUsageError('sql connection or syntax is improper', 500)
def post(self): result = {'status': False, 'msg': 0} user = self.get_current_user() if user: sid = int(self.get_argument("sid", 0)) said = int(self.get_argument("said", 0)) num = int(self.get_argument("num", 1)) #判断商品是否下架 if sid > 0 and said > 0 and num > 0: try: Shop.get(id=sid) ShopAttr.get(id=said) #判断是否有未使用的订单或生成新订单 try: try: order = Order.get(uid=user.id, status=0) except: order = Order() order.uid = user.id order.mobile = user.mobile order.ordered = int(time.time()) try: order.save() except Exception, ex: logging.error(ex) try: orderitem = OrderItem.get(oid=order.id, sid=sid, said=said) except: orderitem = OrderItem() orderitem.oid = order.id orderitem.sid = sid orderitem.said = said orderitem.num = orderitem.num + num orderitem.save() result['status'] = True result['msg'] = 200 except Exception, ex: logging.error(ex) result['msg'] = 500 except:
def create_order(self, rq_user_id, products): session = self.Session() try: user = session.query(User).get(rq_user_id) if user is None: raise Exception('Unable to find user with id = %s' % rq_user_id) order_line_list = [] user_order = Order(user_id=rq_user_id, order_total=0) for prod_def in products: db_product = session.query(Product).get(prod_def['productId']) if db_product is None: raise Exception('Product not found with ProductID: %s' % prod_def['productId']) order_line = OrderLine(product=db_product, order=user_order, quantity=prod_def['quantity']) order_line_list.append(order_line) user_order.order_total = user_order.order_total + db_product.price * prod_def[ 'quantity'] session.add(user_order) session.add_all(order_line_list) session.commit() the_order = session.query(Order).get(user_order.order_id) return the_order.to_json() except Exception as e: logging.error('*** Exception in create_order: %s' % e) traceback.print_exc() session.rollback() raise finally: session.close()
def insert_order(self, order_dict): order = Order(id=order_dict.get('id'), reqId=order_dict.get('reqId'), createTime=datetime.now(), updateTime=None, status=order_dict.get('status'), total=order_dict.get('total'), payWay=order_dict.get('pay_way')) session = self.get_session() session.add(order) session.commit() session.close()
def order_item(order_event): logger.info('order_item: {}'.format(order_event)) try: order = Order(order_event['order_id'], order_date=order_event['order_date'], customer_id=order_event['customer_id'], items=order_event['items'], order_status='APPROVED_PENDING') return order except Exception as e: logging.error('Error: order_item: {}'.format(vars(e))) raise e
def buy(): if request.method == 'POST' and request.form['name']: order = Order( # goods = request.form['goods'], name=request.form['name'], phone=request.form['phone'], pay_method=request.form['payment'], del_method=request.form['delivery'], ) order.save() # huey = Goods.get(Goods.id == 2) # cs1 = Order.get(Order.id == 2) # huey.orders.add(cs1) # id_goods = request.form['goods'].split() for id in id_goods: huey = Goods.get(Goods.id == id) huey.orders.add(Order.get(Order.id == order.id)) return redirect(url_for('goods_list'))
def create_order(): if request.method == "POST": params = request.json latitude = request.json["latitude"] longitude = request.json["longitude"] user_id = request.json["user_id"] text = request.json["text"] location_text = "" new_order = Order( latitude=latitude, longitude=longitude, text=text, location_text=location_text, user_id=user_id ) g.db.add(new_order) g.db.flush() g.socketio.emit("order", new_order.serialize(), namespace="/update") return resource_created(new_order) else: return invalid_method()
def get_order(): if db.is_closed(): db.connect() order = Order.get_or_none(Order.is_processing == False) if not order: return order.is_processing = True order.save() if not db.is_closed(): db.close() return order
def neworder(self, session_id, json_order): distributor = self._get_distributor(session_id) if not distributor: return json_error("NotLoggedIn") order_dict = json.loads(json_order) product_id = order_dict["product_id"] amount = order_dict["amount"] try: product = self.session.query(Product).filter(Product.product_id == product_id).one() except: return json_error("ProductNonExistant") order = Order(datetime.now(), amount) order.distributor_id = distributor.dist_id order.product_id = product.product_id self.session.add(order) try: self.session.commit() except: self.session.rollback() return json_error("ProductNotAdded") #product_order = Product_Order(product_id=product.product_id, order_id=order.order_id) #self.session.add(product_order) #try: #self.session.commit() #except: #self.session.rollback() #return json_error("ProductNotAdded") return json_neworder(order.order_id)
def new_order(customer_id, product_list): order = Order(customer_id) db.session.add(order) db.session.commit( ) # order id has to be generated first to add products in order for product in product_list: link = product.get('link') description = product.get('description') quantity = product.get('quantity') new_product(order.id, link, description, quantity)
def get(self): orderitems = [] user = self.current_user order = None distributions = self.get_distributions() price = 0.0 credit = 0.0 try: order = Order.get(uid = user.id, status = 0) try: mobile = '18014349809' sendmsg(self.settings, mobile, '新订单') except: pass for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts(): try: orderitem['shop'] = Shop.get(id = orderitem['sid']) _oiprice = orderitem['shop'].price if orderitem['said'] > 0: orderitem['shopattr'] = ShopAttr.get(id = orderitem['said']) if orderitem['shop'].cid == 1: _oicredit = orderitem['shopattr'].price credit = credit + _oicredit * orderitem['num'] else: _oiprice = orderitem['shopattr'].price else: _oiprice = float(_oiprice) orderitems.append(orderitem) price = price + _oiprice * orderitem['num'] except: pass order.price = price order.save() except: pass if orderitems: self.render("shop/settle.html", tmday = datetime.date.today() + datetime.timedelta(days=1), order = order, orderitems = orderitems, distributions = distributions.values(), credit = credit)
def add_order(amazon_fresh_order_id, delivery_date, delivery_day_of_week, delivery_time, user_gmail, line_items_one_order): """Adds information for one order to database""" order = Order.query.filter_by( amazon_fresh_order_id=amazon_fresh_order_id).first() if order: print "Order # %s already in database" % amazon_fresh_order_id else: order = Order(amazon_fresh_order_id=amazon_fresh_order_id, delivery_date=delivery_date, delivery_day_of_week=delivery_day_of_week, delivery_time=delivery_time, user_gmail=user_gmail) db.session.add(order) print "Order # %s added to database" % amazon_fresh_order_id for line_item_info in line_items_one_order: # line_item_info is a list of info for one line item ex [1, 5.50, "description"] quantity, unit_price_cents, description = line_item_info description_key = "" for char in description: if char.isalpha(): description_key += char description_key = description_key.lower() item = Item.query.filter_by( description_key=description_key).first() if item: print "General item description '%s' already in database." % ( description) else: add_item(description, description_key) print "General item description '%s' added to database." % ( description) item = Item.query.filter_by( description_key=description_key).first() add_line_item(amazon_fresh_order_id, item.item_id, unit_price_cents, quantity) print "Line item '%s', added to database for order # %s" % ( description, amazon_fresh_order_id) db.session.commit()
def post(self): result = {'status' : False, 'msg' : 0} user = self.get_current_user() if user: sid = int(self.get_argument("sid", 0)) said = int(self.get_argument("said", 0)) num = int(self.get_argument("num", 1)) #判断商品是否下架 if sid > 0 and said > 0 and num > 0: try: Shop.get(id = sid) ShopAttr.get(id = said) #判断是否有未使用的订单或生成新订单 try: try: order = Order.get(uid = user.id, status = 0) except: order = Order() order.uid = user.id order.mobile = user.mobile order.ordered = int(time.time()) try: order.save() except Exception, ex: logging.error(ex) try: orderitem = OrderItem.get(oid = order.id, sid = sid, said = said) except: orderitem = OrderItem() orderitem.oid = order.id orderitem.sid = sid orderitem.said = said orderitem.num = orderitem.num + num orderitem.save() result['status'] = True result['msg'] = 200 except Exception, ex: logging.error(ex) result['msg'] = 500 except:
def post(self): alipay = Alipay(**self.settings) params = {} ks = list(self.request.arguments.keys()) for k in ks: params[k] = self.get_argument(k) if alipay.notify_verify(params): tn = self.get_argument("out_trade_no", None) trade_no = self.get_argument("trade_no", None) trade_status = self.get_argument("trade_status", None) logging.info("notify:%s - %s - %s" % (tn, trade_no, trade_status)) oid = int(tn.split('-')[1].replace('S', '')) try: order = Order.get(id = oid) if order.status == 0: order.status = 1 order.save() user = User.get(id = order.uid) user.credit = user.credit + int(order.price) user.save() log = CreditLog() log.uid = order.uid log.mobile = user.mobile log.ctype = 0 log.affect = int(order.price) log.log = '成功下单 - %s' % tn log.save() except Exception as ex: logging.error(ex) if trade_status == 'WAIT_SELLER_SEND_GOODS': alipay.send_goods_confirm_by_platform(trade_no) self.write("success") else: self.write("fail")
def get(self): alipay = Alipay(**self.settings) params = {} ks = list(self.request.arguments.keys()) for k in ks: params[k] = self.get_argument(k) if alipay.notify_verify(params): tn = self.get_argument("out_trade_no", None) trade_no = self.get_argument("trade_no", None) trade_status = self.get_argument("trade_status", None) logging.info("return:%s - %s - %s" % (tn, trade_no, trade_status)) oid = int(tn.split('-')[1].replace('S', '')) try: order = Order.get(id = oid) order.status = 1 order.save() user = User.get(id = order.uid) user.credit = user.credit + int(order.price) user.save() log = CreditLog() log.uid = order.uid log.mobile = user.mobile log.ctype = 0 log.affect = int(order.price) log.log = '成功下单 - %s' % tn log.save() self.session['user'] = user self.session.save() alipay.send_goods_confirm_by_platform(trade_no) self.flash("支付成功") except Exception as ex: logging.error(ex) else: self.flash("支付失败") self.redirect("/pay")
def get(self): orderitems = [] user = self.current_user try: order = Order.get(uid = user.id, status = 0) for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts(): try: orderitem['shop'] = Shop.get(id = orderitem['sid']) if orderitem['said'] > 0: orderitem['shopattr'] = ShopAttr.get(id = orderitem['said']) orderitems.append(orderitem) except: pass except: order = Order() ashops = Shop.select().where((Shop.cid == 2) & (Shop.status != 9)) self.render("shop/order.html", orderitems = orderitems, order = order, ashops = ashops)
def get(self): status = self.get_argument("status", None) ft = (Order.status >= 0) if status: ft = ft & (Order.status == status) page = int(self.get_argument("page", 1)) pagesize = self.settings['admin_pagesize'] oq = Order.select().where(ft) total = oq.count() orders = [] for order in oq.paginate(page, pagesize).order_by(Order.ordered.desc()).dicts(): order['orderitems'] = [] try: order['ua'] = UserAddr.get(id = order['uaid']) except: order['ua'] = UserAddr() try: order['distr'] = Distribution.get(id = order['distrid']) except: order['distr'] = Distribution() for orderitem in OrderItem.select().where(OrderItem.oid == order['id']).dicts(): try: orderitem['shop'] = Shop.get(id = orderitem['sid']) if orderitem['said'] > 0: orderitem['shopattr'] = ShopAttr.get(id = orderitem['said']) order['orderitems'].append(orderitem) except: orderitem['shop'] = Shop() if order['orderitems']: orders.append(order) self.render('admin/order.html', orders = orders, total = total, page = page, pagesize = pagesize)
def get(self): orderitems = [] user = self.current_user order = None distributions = self.get_distributions() price = 0.0 credit = 0.0 try: order = Order.get(uid = user.id, status = 0) print order.id ''' try: mobile = '18014349809' sendmsg(self.settings, mobile, '新订单') except: pass ''' for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts(): try: orderitem['shop'] = Shop.get(id = orderitem['sid']) _oiprice = orderitem['shop'].price if orderitem['said'] > 0: orderitem['shopattr'] = ShopAttr.get(id = orderitem['said']) if orderitem['shop'].cid == 1: _oicredit = orderitem['shopattr'].price credit = credit + _oicredit * orderitem['num'] _oiprice = orderitem['shopattr'].price else: _oiprice = orderitem['shopattr'].price else: _oiprice = float(_oiprice) orderitems.append(orderitem) price = price + float(_oiprice) * orderitem['num'] except: pass print price price_pay = str(int(price*100)) print 'price_pay:' + price_pay openid = user.openid print 'wx_pay:'+ openid jsApi = JsApi_pub() unifiedOrder = UnifiedOrder_pub() unifiedOrder.setParameter("openid",openid) #商品描述 unifiedOrder.setParameter("body","菜市优品购物") #商品描述 timeStamp = time.time() print timeStamp out_trade_no = "{0}{1}".format(WxPayConf_pub.APPID, int(timeStamp*100)) unifiedOrder.setParameter("out_trade_no", out_trade_no) #商户订单号 print 'out_trade_no:' + out_trade_no Order.update(wxid = out_trade_no).where(Order.id == order.id).execute() unifiedOrder.setParameter("total_fee", price_pay) #总金额 print WxPayConf_pub.NOTIFY_URL unifiedOrder.setParameter("notify_url", WxPayConf_pub.NOTIFY_URL) #通知地址 unifiedOrder.setParameter("trade_type", "JSAPI") #交易类型 prepay_id = unifiedOrder.getPrepayId() jsApi.setPrepayId(prepay_id) jsApiParameters = jsApi.getParameters() print jsApiParameters appid = json.loads(jsApiParameters).get("appId") timestamp = json.loads(jsApiParameters).get("timeStamp") noncestr = json.loads(jsApiParameters).get("nonceStr") package = json.loads(jsApiParameters).get("package") signtype = json.loads(jsApiParameters).get("signType") paysign = json.loads(jsApiParameters).get("paySign") print appid + timestamp + noncestr + package + signtype +paysign if orderitems: self.render("/responsive/wxpay.html", tmday = datetime.date.today() + datetime.timedelta(days=1), order = order, orderitems = orderitems, distributions = distributions.values(), credit = credit, appid = appid, timestamp = timestamp, noncestr = noncestr, package = package, signtype = signtype, paysign = paysign) except: pass
def post(self): order = None user = self.get_current_user() try: order = Order.get(uid = user.id, status = 0) mobile = self.get_argument("mobile", user.mobile) uaid = self.get_argument("uaid", None) distrid = self.get_argument("distrid", None) day = self.get_argument("day", datetime.date.today() + datetime.timedelta(days=1)) hour = int(self.get_argument("hour", 10)) payment = self.get_argument("payment", 0) message = self.get_argument("message", "") isinvoice = self.get_argument("isinvoice", 0) invoicesub = self.get_argument("invoicesub", 0) invoicename = self.get_argument("invoicename", "") invoicecontent = self.get_argument("payment", 1) shippingprice = self.get_argument("shippingprice", 0.0) if uaid and distrid: try: distrib = Distribution.get(id = distrid) shippingprice = distrib.price except: pass order.mobile = mobile order.uaid = uaid order.distrid = distrid order.distribbed = "%s %d:00:00" % (str(day), hour) order.payment = payment order.message = message order.isinvoice = isinvoice if isinvoice: order.invoicesub = invoicesub order.invoicename = invoicename order.invoicecontent = invoicecontent order.shippingprice = shippingprice order.save() body = "" for orderitem in OrderItem.select().where(OrderItem.oid == order.id).dicts(): try: shop = Shop.get(id = orderitem['sid']) sname = "" if orderitem['said'] > 0: shopattr = ShopAttr.get(id = orderitem['said']) if shop.cid == 1: credits = shopattr.price * orderitem['num'] if credits > user.credit: OrderItem.delete().where(OrderItem.id == orderitem['id']).execute() else: user = User.get(id = user.id) user.credit = user.credit - credits user.save() clog = CreditLog() clog.uid = user.id clog.mobile = user.mobile clog.ctype = 1 clog.affect = int(credits) clog.log = u"购买" + shop.name clog.save() self.session['user'] = user self.session.save() sname = shopattr.name #body = body + shop.name + " " + sname + " " + str(orderitem['num']) + "个\n" body = body + shop.name + " " + sname + " " + str(orderitem['num']) except Exception, ex: logging.error(ex) tn = "U%d-S%d" % (user.id, order.id) if int(payment) == 1: self.redirect("/alipay/topay?tn=%s&body=%s&price=%f" % (tn, body, order.price)) else: self.flash(u"请选择地址和收货方式") self.redirect("/user/orders") else:
def post(self, oid): #status = int(self.get_argument("status", 0)) Order.update(status = 3).where(Order.id == oid).execute() self.flash("修改成功") self.redirect("/user/orders")