def post(self): self.set_header("Content-Type", "application/json; charset=UTF-8") if (not self.request.files) or (not "imgFile" in self.request.files): return img_file = self.request.files["imgFile"][0] o_filename = img_file["filename"] shop_id = self.get_argument("shop_id", "13") distributor_shop = self.db.get( "select taobao_api_info, taobao_nick from distributor_shop where id = %s", shop_id ) app_info = json.loads(distributor_shop.taobao_api_info, object_hook=json_hook) try: request = Taobao("taobao.picture.upload") request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) request.add_file("img", o_filename, img_file["body"]) response = yield request(picture_category_id="0", image_input_title=o_filename.encode("utf-8")) request.parse_response(response.body) if request.is_ok(): self.write({"error": 0, "url": request.message.picture.picture_path}) else: err_msg = request.error.sub_msg if "sub_msg" in request.error else request.error.msg self.write(json_dumps({"error": err_msg})) except IOError: self.write(json_dumps({"error": "没有找到图片文件"})) return
def post(self): # 解密58请求参数 params = get_params(self.get_argument('param')) logging.info('wuba order query request : %s', json_dumps(params)) try: # 获得参数 coupon_ids = params.ticketIds except AttributeError: logging.info('wuba request failed: wrong params') return self.write('{"status":"10201", "msg": "参数错误"}') # 查询每个券号 tickets = [] for coupon_id in coupon_ids: coupon = self.db.get('select * from item i, item_coupon c where i.id=c.item_id and c.id=%s', coupon_id.encode('utf-8')) if not coupon: # 券不存在,跳过 continue else: distributor_order = self.db.get('select * from distributor_order where order_id=%s', coupon.order_id) if not distributor_order: # 分销订单不存在,跳过 continue else: message = json.loads(distributor_order.message, object_hook=json_hook) # 检查状态 if coupon.status == const.status.BUY: status = 0 elif coupon.status == const.status.USED: status = 1 elif coupon.expire_at < datetime.now(): status = 9 elif coupon.status == const.status.REFUND: status = 10 # 生成返回信息 ticket = { "ticketIdThirdpart": int(coupon_id), "orderIdThirdpart": int(coupon.order_no), "groupbuyIdThirdpart": int(message.groupbuyIdThirdpart), "ticketId58": "", "orderId58": int(distributor_order.order_no), "groupbuyId58": int(message.groupbuyId), "ticketCode": str(coupon.sn), "orderPrice": float(message.prodPrice), "status": status, "createtime": str(coupon.created_at), "endtime": str(coupon.expire_at), } tickets.append(ticket) if not tickets: logging.info('wuba request failed: can not find coupon') return self.write('{"status":"10202", "msg": "券号不存在"}') else: logging.info('wuba request success: %s coupon(s) found' % len(tickets)) result_json = {'status': '10000', 'msg': 'ok', 'data': encrypt(str(tickets), options.wuba_secret_key)} # '2a6f8f2c') return self.write(json_dumps(result_json))
def post(self): self.set_header('Content-Type', 'application/json; charset=UTF-8') coupon_sn = self.get_argument('coupon') if not coupon_sn: return self.write(json_dumps({'error': '请输入券号'})) coupon = self.db.get('select i.sp_id, i.goods_id, i.goods_name as gsname, i.sales_price, c.expire_at, i.status,' ' c.id from item i, item_coupon c where c.sn = %s and i.id=c.item_id', coupon_sn) if not coupon: return self.write(json_dumps({'error': '券号不存在,请检查输入'})) if coupon.expire_at < datetime.now(): return self.write(json_dumps({'error': '券号已过期', 'coupon': coupon})) if coupon.status != const.status.BUY: return self.write(json_dumps({'error': '券已使用或已退款', 'coupon': coupon})) # 查找可验证店铺 all_shops = self.db.get('select all_shop from goods where id=%s', coupon.goods_id).all_shop if all_shops == '1': # 所有店铺 shops = self.db.query('select s.id, s.name, s.supplier_name as spname from supplier_shop s ' 'where supplier_id=%s', coupon.sp_id) else: # 指定店铺 shop_ids = self.db.query('select supplier_shop_id from goods_supplier_shop ' 'where goods_id=%s', coupon.goods_id) ids = ','.join([str(item.supplier_shop_id) for item in shop_ids]) shops = self.db.query('select s.id, s.name, s.supplier_name as spname from supplier_shop s ' 'where s.id in (' + ids + ')') self.write(json_dumps({'coupon': coupon, 'shops': shops}))
def post(self): self.set_header('Content-Type', 'application/json; charset=UTF-8') sp_id = self.current_user.supplier_id cate_name = self.get_argument('name', '').encode('utf-8') # 检查是否重复 exist = self.db.query('select * from member_category where sp_id=%s and name=%s and deleted=0', sp_id, cate_name) # 重复组名,返回 if exist: self.write(json_dumps({'ok': False, 'error': '分组名称已经存在'})) return # 更新微信分组 if self.current_user.sp_props.wx_type == 'service' and self.current_user.sp_props.wx_verified == '1': body = json_dumps({"group": {"name": cate_name}}) wx = Weixin(db=self.db, sp_id=sp_id, method='groups/create', body=body) wx.set_app_info(self.current_user.sp_props.app_id, self.current_user.sp_props.app_secret) res = yield wx.fetch() wx.parse_response(res.body) if wx.is_ok(): # 更新本地数据库 last_id = self.db.execute('insert into member_category (sp_id, name, deleted, wx_grp_id) ' 'values (%s, %s, 0, %s)', sp_id, cate_name, wx.message.group.id) self.write(json_dumps({'ok': True, 'cate_id': last_id, 'cate_name': cate_name})) else: logging.error('wx error: %s' % wx.error) self.write(json_dumps({'ok': False, 'error': '添加失败,%s' % wx.error})) else: # 更新本地数据库 last_id = self.db.execute('insert into member_category (sp_id, name, deleted) ' 'values (%s, %s, 0)', sp_id, cate_name) self.write(json_dumps({'ok': True, 'cate_id': last_id, 'cate_name': cate_name}))
def post(self): num_iid = self.get_argument("num_iid").encode("utf-8") arg_img_url = self.get_argument("img_url") shop_id = self.get_argument("shop_id") distributor_shop = self.db.get( "select taobao_api_info, taobao_nick from distributor_shop where id = %s", shop_id ) app_info = json.loads(distributor_shop.taobao_api_info, object_hook=json_hook) img_path = os.path.join(options.upload_img_path, arg_img_url[1:]) try: fo = open(img_path, "rb") except IOError: self.write(json_dumps({"error": "没有找到图片文件"})) return request = Taobao("taobao.item.img.upload") request.set_app_info(app_info.app_key, app_info.app_secret_key) request.set_session(app_info.session) request.add_file("image", fo.name, fo.read()) fo.close() response = yield request(num_iid=num_iid, is_major="true") request.parse_response(response.body) if request.is_ok(): self.write(json_dumps({"success": "图片上传成功"})) else: err_msg = request.error.sub_msg if "sub_msg" in request.error else request.error.msg self.write(json_dumps({"error": err_msg}))
def post(self): form = Form(self.request.arguments, add_schema) goods_info, shops, properties, img = get_goods_info(self.db, form.id.value) if goods_info.supplier_id != self.current_user.supplier_id: raise HTTPError(403) if goods_info.status not in ['PREPARE', 'REJECT']: raise HTTPError(403) # 为了下面的 validate 成功 这里必须填入数据 form.arguments.update({'generate_type': EmptyDict({'value': goods_info.generate_type})}) img_paths = dict() for key in self.request.arguments: if key.startswith('var_img_path_'): v = self.request.arguments[key][0] if v: img_paths[key[key.rindex('_')+1:]] = v form.img_paths['value'] = json_dumps(img_paths) if not form.validate(): form.properties.value = properties form.shops['value'] = shops form.img_paths['value'] = img_paths supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0', self.current_user.supplier_id) logging.error(json_dumps(form.errors)) self.render('goods/add.html', form=form, error='', action='edit', supplier_shops=supplier_shops, img_url=img_url) fields = ('type', 'generate_type', 'expire_at', 'category_id', 'name', 'short_name', 'sms_name', 'face_value', 'sales_price', 'purchase_price', 'stock', 'virtual_sales_count', 'img_path', 'detail', 'tips', 'supplier_intro', 'all_shop', 'on_sale_at', 'off_sale_at', 'img_paths', 'postage') update_sql = 'update goods set %s where id=%%s' % ','.join([field + '=%s' for field in fields]) form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None params = [form.arguments[field]['value'] for field in fields] params.append(form.id.value) self.db.execute(update_sql, *params) self.db.execute('insert into journal(created_at, type, created_by, message, iid) ' 'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '商户修改了商品', form.id.value) # 批量更新商品属性 self.db.execute('delete from goods_property where goods_id=%s and name in ("gift_card", "hidden", "ktv")', form.id.value) if form.properties.value: insert_properties(self.db, form.properties.value, form.id.value) # 批量更新关联门店 self.db.execute('delete from goods_supplier_shop where goods_id=%s', form.id.value) if not form.all_shop.value: if form.shops.value: insert_shops(self.db, form.shops.value, form.id.value) self.redirect(self.reverse_url('goods.list'))
def get(self): sp_id = self.current_user.supplier_id # 获得所有模块 added_blocks = self.db.query('select * from wx_mem_block where sp_id=%s and deleted=0', sp_id) # 获得自定义模块的name,用来除重 blocks = [b.name for b in added_blocks if b.is_default != '1'] self.render('wx/member/block_edit.html', added_blocks=added_blocks, desc=json_dumps(desc), blocks=json_dumps(blocks), extend_block_name=json_dumps(extend_block_name), json_loads=json.loads)
def post(self): form = Form(self.request.arguments, add_schema) img_paths = dict() for key in self.request.arguments: if key.startswith('var_img_path_'): v = self.request.arguments[key][0] if v: img_paths[key[key.rindex('_')+1:]] = v if not form.validate(): supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0', self.current_user.supplier_id) form.img_paths['value'] = img_paths logging.error(json_dumps(form.errors)) return self.render('wx/mall/goods_add.html', form=form, error='error', action='add', supplier_shops=supplier_shops, img_url=img_url) # 获取微信商品手续费 commission = self.db.get('select value from supplier_property where sp_id=%s and name="wx_commission"', self.current_user.supplier_id) if not commission: rate = Decimal((100 - options.wx_min_commission)/100.0) else: rate = Decimal((100 - int(commission.value))/100.0) # 更新结算价 form.arguments['purchase_price']['value'] = form.arguments['sales_price']['value'] * rate fields = ('type', 'generate_type', 'expire_at', 'category_id', 'short_name', 'sms_name', 'max_buy', 'on_sale_at', 'off_sale_at', 'face_value', 'sales_price', 'purchase_price', 'stock', 'img_path', 'all_shop', 'detail', 'postage') goods_sql = """ insert into goods(%s, supplier_id, created_by, img_paths, created_at, status, name) values (%s, %%s, %%s, %%s, NOW(), "PREPARE", "")""" % (','.join(fields), ','.join(['%s']*len(fields))) form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None form.on_sale_at['value'] = form.on_sale_at.value if form.off_sale_at.value else None form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None params = [form.arguments[field]['value'] for field in fields] params.extend([self.current_user.supplier_id, self.current_user.name, json_dumps(img_paths)]) goods_id = self.db.execute_lastrowid(goods_sql, * params) self.db.execute('insert into journal(created_at, type, created_by, message, iid) ' 'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '商户新增了微商城商品', goods_id) # 批量插入关联的门店 if not form.all_shop.value: if form.shops.value: insert_shops(self.db, form.shops.value, goods_id) # 插入微信商品特有属性 self.db.execute('insert into goods_property (goods_id, name, value) values ' '(%s, "is_wx_goods", %s)', goods_id, "1") self.db.execute('insert into goods_property (goods_id, name, value) values ' '(%s, "is_wx_on_sale", %s)', goods_id, "0") self.redirect(self.reverse_url('wx.goods.list'))
def post(self): form = Form(self.request.arguments, add_schema) img_paths = dict() for key in self.request.arguments: if key.startswith('var_img_path_'): v = self.request.arguments[key][0] if v: img_paths[key[key.rindex('_')+1:]] = v form.img_paths['value'] = json_dumps(img_paths) if not form.validate(): supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0', form.supplier_id.value) distributors = self.db.query('select * from distributor_shop where deleted = 0') all_sku = self.db.query('select * from sku where deleted=0 and supplier_id=%s', form.supplier_id.value) form.img_paths['value'] = img_paths logging.error(json_dumps(form.errors)) return self.render('goods/add.html', form=form, error='error', action='add', img_url=img_url, supplier_shops=supplier_shops, all_sku=all_sku, distributors=distributors) fields = ('type', 'generate_type', 'expire_at', 'category_id', 'name', 'short_name', 'sms_name', 'img_paths', 'face_value', 'sales_price', 'purchase_price', 'stock', 'virtual_sales_count', 'img_path', 'all_shop', 'detail', 'tips', 'supplier_intro', 'created_by', 'supplier_id', 'on_sale_at', 'off_sale_at') goods_sql = 'insert into goods(%s, created_at, status) values (%s ,NOW(), "ON_SALE")' % ( ','.join(fields), ','.join(['%s']*len(fields))) form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None form.arguments['created_by'] = EmptyDict({'value': self.current_user.name}) params = [form.arguments[field]['value'] for field in fields] goods_id = self.db.execute_lastrowid(goods_sql, * params) self.db.execute('insert into journal(created_at, type, created_by, message, iid) ' 'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '新增了商品', goods_id) # 批量插入商品属性 if form.properties.value: insert_properties(self.db, form.properties.value, goods_id) # 批量插入关联的门店 if not form.all_shop.value: if form.shops.value: insert_shops(self.db, form.shops.value, goods_id) # 批量插入SKU信息 if form.skus.value: insert_skus(self.db, form.skus.value, goods_id) # 批量插入分销店铺佣金 if form.ratios.value: insert_ratios(self.db, form.ratios.value, goods_id) self.redirect(self.reverse_url('goods.show_list'))
def post(self): self.set_header('Content-Type', 'application/json; charset=UTF-8') coupon_sn = self.get_argument('coupon', '') shop_id = self.get_argument('shop', '') # 检查请求的参数 if not coupon_sn or not shop_id: self.write(json_dumps({'error': '请输入正确参数'})) return # 检查电子券 coupon = self.db.get('select * from item i, item_coupon c where c.sn=%s and i.id=c.item_id', coupon_sn) if not coupon: self.write(json_dumps({'error': '券号不存在'})) return # 查找可验证店铺 all_shops = self.db.get('select all_shop from goods where id=%s', coupon.goods_id).all_shop if all_shops == '1': # 所有店铺 shops = self.db.query('select s.id, s.name, s.supplier_name as spname from supplier_shop s ' 'where supplier_id=%s', coupon.sp_id) else: # 指定店铺 shop_ids = self.db.query('select supplier_shop_id from goods_supplier_shop ' 'where goods_id=%s', coupon.goods_id) ids = ','.join([str(item.supplier_shop_id) for item in shop_ids]) shops = self.db.query('select s.id, s.name, s.supplier_name as spname from supplier_shop s ' 'where s.id in (' + ids + ')') if int(shop_id) not in [i.id for i in shops]: self.write({'ok': False, 'msg': '验证门店错误'}) return # 本地检测 check_result = local_check(self.db, coupon_sn, shop_id) if not check_result.ok: self.write(json_dumps({'error': check_result.msg})) return # 合作伙伴API验证 api_result = yield partner_api_verify(self.db, coupon_sn) if not api_result.ok: ok, msg = (False, api_result.msg) else: # 本地验证 verify_result = local_verify(self.db, coupon_sn, shop_id, self.get_current_user().name) ok, msg = (verify_result.ok, verify_result.msg) if not ok: self.write(json_dumps({'error': '错误,原因:%s' % msg})) else: # 发送验证确认短信 shop_name = self.db.get('select name from supplier_shop where id=%s', shop_id).name CouponConsumedMessage(self.redis, [coupon.sn], shop_name, coupon.mobile).send() self.write(json_dumps({'ok': '验证成功'}))
def post(self): self.set_header("Content-Type", "application/json; charset=UTF-8") coupon_sn = self.get_argument("coupon", "") if not coupon_sn: return self.write(json_dumps({"error": "请输入券号"})) coupon = self.db.get("""select * from item i, item_coupon c where i.id=c.item_id and c.sn=%s""", coupon_sn) if not coupon: return self.write(json_dumps({"error": "券号不存在"})) return self.write(json_dumps({"coupon": coupon}))
def post(self): if (not self.request.files) or (not 'imgFile' in self.request.files): return self.write(json_dumps({'error': 1, 'message': u'请选择文件'})) img_file = self.request.files['imgFile'][0] o_filename = img_file['filename'] # 选择上传根目录 root = self.get_argument('root', '') if root: upload_root = options['upload_img_path_%s' % root] else: upload_root = options.upload_img_path # 生成文件名 random_id = int(datetime.now().strftime('%Y%m%d%H%M%S%f')[:19]) random_id += random.randint(0, 99) extension = os.path.splitext(o_filename)[1] file_name = '%s%s' % (random_id, extension) # 算出目录 first_dir = random_id >> 20 second_dir = (~(first_dir << 10)) & (random_id >> 10) third_dir = (~((random_id >> 10) << 10)) & random_id first_dir %= 1000 three_level_path = os.path.join(str(first_dir), str(second_dir), str(third_dir)) file_dir = os.path.join(upload_root, three_level_path) # 如果目录不存在,创建之 if not os.path.exists(file_dir): try: os.makedirs(file_dir) except OSError: return self.write(json_dumps({'error': 1, 'message': u'创建目录失败'})) # 保存文件 try: with open(os.path.join(file_dir, file_name), 'w') as f: f.write(img_file['body']) except IOError: return self.write(json_dumps({'error': 1, 'message': u'保存文件失败'})) # 文件名上加认证信息、水印信息 masks = ['nw'] if self.get_argument('source', ''): masks.append(self.get_argument('source')) if root == 'contract': url = contract_url(os.path.join('/', three_level_path, file_name)) else: url = img_url(os.path.join('/', three_level_path, file_name), *masks) self.write(json_dumps({'error': 0, 'url': url}))
def post(self): page_number = self.get_argument('page_number') max_id = self.get_argument('max_id') category = self.get_argument('category', '') begin = int(page_number) * 10 + 1 sql = """select g.id, g.face_value, g.sales_price, g.img_path, g.short_name from goods g left join goods_category gc on g.category_id = gc.id where g.off_sale_at > NOW() and g.deleted = 0 and g.id <= %s and g.id not in (select goods_id from goods_property where name = 'hidden' and value = 1) and g.id in (select goods_id from goods_distributor_shop where distributor_goods_id <> '' and deleted = 0 and distributor_shop_id in (%s, %s, %s, %s)) """ params = [max_id, options.shop_id_tmall, options.shop_id_taobao, options.shop_id_jingdong, options.shop_id_yihaodian] if category != '': sql += 'and gc.parent_id = %s ' params.append(category) sql += 'order by g.sales_count desc limit %s, 10 ' params.append(begin) goods_list = self.db.query(sql, *params) for goods in goods_list: goods['img_path'] = img_url(goods.img_path) self.set_header('Content-Type', 'application/json; charset=UTF-8') self.write(json_dumps(goods_list))
def get(self): shop_id = self.get_argument('shop_id') product_id = self.get_argument('product_id') product_name = self.get_argument('product_name') shop = self.db.get('select name from supplier_shop where id = %s', shop_id) taobao_sku_list = build_taobao_sku(self.db, shop_id, product_id) title = shop.name + '-' + product_name.encode('utf-8') app_info = json.loads(self.db.get('select taobao_api_info from distributor_shop where id = %s', options.shop_id_taobao).taobao_api_info, object_hook=json_hook) attribute_request = Taobao('taobao.itemprops.get') attribute_request.set_app_info(app_info.app_key, app_info.app_secret_key) attribute_request.set_session(app_info.session) response = yield attribute_request(cid=50644003, fields='pid,name,must,multi,prop_values,is_input_prop,features') attribute_request.parse_response(response.body) if attribute_request.is_ok() and 'item_props' in attribute_request.message: if 'item_prop' in attribute_request.message.item_props: attributes = attribute_request.message.item_props.item_prop else: attributes = [] else: attributes = [] self.render('ktv/manage/publish.html', taobao_sku_list=taobao_sku_list, title=title, shop_id=shop_id, product_id=product_id, attributes=json_dumps(attributes))
def yihaodian_order_listener(db, redis): """ 定时从一号店获得新生成的订单, 筛选未处理订单,并放入订单处理队列 :type db:torndb.Connection :type redis:redis.StrictRedis """ # 生产环境运行 # if not options.app_mode == 'prod': # logging.info("yihaodian order listener quit: not in prod mode") # return end_time = datetime.now() + timedelta(minutes=10) # 当前时间往后10分钟 start_time = end_time - timedelta(days=14) # 初始时间推前14天,因为一号店api支持的最大跨度是15天 end = end_time.strftime('%Y-%m-%d %H:%M:%S') start = start_time.strftime('%Y-%m-%d %H:%M:%S') # 获得一号店订单列表 orders = fetch_yihaodian_order(start, end) if orders: # 查询已经存在的订单 result = db.query('select order_no from distributor_order where distributor_shop_id=%s and order_no in (' + ','.join(['%s']*len(orders)) + ')', options.shop_id_yihaodian, *orders) exist_orders = [row['order_no'] for row in result] # 插入不存在的订单 for order in orders: if not exist_orders or exist_orders and order not in exist_orders: distributor_order_id = db.execute('insert into distributor_order (order_no, created_at, message, ' 'distributor_shop_id) values (%s, now(), "", %s)', order, options.shop_id_yihaodian) logging.info('insert new distributor order_no: %s', order) # 推进 redis 处理队列 redis.lpush(options.queue_distributor_order, json_dumps({'distributor_order_id': distributor_order_id, 'distributor': 'YHD', 'retry': 0}))
def post(self): """根据日期查询可体现金额""" end_date = datetime.date.today().strftime('%Y-%m-%d') if self.current_user.separate_account == '1': # account_sequence 中的哪些账户算入可提现账户 seq_account_ids = [self.db.get('select account_id from supplier_shop where id=%s', self.current_user.shop_id).account_id] else: # account_sequence 中的哪些账户算入可提现账户 accounts = self.db.query('select account_id from supplier_shop where supplier_id=%s', self.current_user.supplier_id) seq_account_ids = [i.account_id for i in accounts] # 钱款统计截止至当天凌晨 withdraw_amount = self.db.get( 'select sum(amount) amount from account_sequence ' 'where status=1 and created_at<%%s and account_id in (%s)' % ','.join(['%s']*len(seq_account_ids)), end_date, *seq_account_ids).amount # 判断最大可提现金额 max_amount = withdraw_amount remark = '' if 'max_withdraw' in self.current_user.sp_props: max_withdraw = Decimal(self.current_user.sp_props.max_withdraw) if max_withdraw < withdraw_amount: max_amount = max_withdraw remark = u'如有疑问,请联系销售' return self.write(json_dumps({'amount': withdraw_amount, 'end_date': end_date, 'max_amount': max_amount, 'remark': remark}, decimal_fmt=float))
def post(self): goods_id = self.get_argument("id", "") start_arg = self.get_argument("start", "") end_arg = self.get_argument("end", "") data = [] categories, start, end = generate_duration(start_arg, end_arg) goods = self.db.get("select id, short_name from goods where id=%s and deleted=0", goods_id) # 查不到商品,返回 if not goods: data.append({"name": "商品不存在", "data": format_chart_data([], start, categories)}) goods_amount = self.db.query( "select cast(i.created_at as DATE) as archive_date, sum(payment) as amount from " "item i where goods_id=%s and cast(i.created_at as DATE)>=%s " "and cast(i.created_at as DATE)<=%s " "group by archive_date order by archive_date asc", goods_id, start, end, ) # 如果有销售数据 if goods_amount: # 补全时间轴 sales_data = format_chart_data(goods_amount, start, categories) # 添加到返回的数据列表上 data.append({"name": goods.short_name, "data": sales_data}) # 没有数据,返回空数据 if not data: data.append({"name": "无数据", "data": format_chart_data([], start, categories)}) self.write(json_dumps(data, decimal_fmt=float))
def get(self): message_count = self.db.get('select count(1) c from notification where user_type = 0 and (uid = 0 or uid = %s) ' 'and id > %s', self.current_user.supplier_id, self.current_user.max_message_id) self.set_header('Content-Type', 'application/json; charset=UTF-8') self.write(json_dumps({'count': message_count.c}))
def post(self): sp_id = self.current_user.supplier_id cate_id = self.get_argument('cate_id', '') # 查出默认的分组ID default_cate_id = self.db.get('select id from member_category where sp_id=%s and name="未分组"', sp_id).id # 微信服务器分组放到0 if self.current_user.sp_props.wx_type == 'service' and self.current_user.sp_props.wx_verified == '1': members = self.db.query('select wx_id from member where sp_id=%s and category_id=%s', sp_id, cate_id) app_id = self.current_user.sp_props.app_id app_secret = self.current_user.sp_props.app_secret for mem in members: body = {"openid": mem.wx_id, "to_groupid": 0} wx = Weixin(db=self.db, sp_id=sp_id, method='groups/members/update', body=json_dumps(body)) wx.set_app_info(app_id, app_secret) res = yield wx.fetch() wx.parse_response(res.body) if not wx.is_ok(): logging.error('wx error: %s' % wx.error) # 把要删除组的会员合并入默认分组 self.db.execute('update member set category_id=%s where sp_id=%s and category_id=%s', default_cate_id, sp_id, cate_id) # 删除分组 self.db.execute('update member_category set deleted=1 where id=%s', cate_id) # 返回 self.set_header('Content-Type', 'application/json; charset=UTF-8') self.write(json_dumps({'ok': True}))
def post(self): sp_id = self.current_user.supplier_id self.db.execute('delete from supplier_property where sp_id=%s and name="wx_mem_cover"', sp_id) self.db.execute('insert into supplier_property(sp_id, name, value) values (%s, "wx_mem_cover", %s)', sp_id, json_dumps({'pic': self.get_argument('pic'), 'title': self.get_argument('title'), 'desc': self.get_argument('desc')})) self.redirect(self.reverse_url('wx.mem_cover'))
def post(self): categories = self.db.query('select id, name, parent_id from goods_category') parents = dict([(c.id, {'id': c.id, 'name': c.name, 'children': []}) for c in categories if not c.parent_id]) for category in categories: if category.parent_id: parents[category.parent_id]['children'].append({'id': category.id, 'name': category.name}) self.set_header('Content-Type', 'application/json; charset=UTF-8') self.write(json_dumps(parents.values()))
def send(self, params, order): """ 发码通知 """ if not order: shop = self.db.get('select id from distributor_shop where deleted =0 and ' 'taobao_seller_id=%s', params.taobao_sid) distributor_order_id = self.db.execute( 'insert into distributor_order(order_no, message, distributor_shop_id, created_at) ' 'values (%s, %s, %s, NOW())', params.order_id, json_dumps(params), shop.id) self.redis.lpush(options.queue_distributor_order, json_dumps({'distributor_order_id': distributor_order_id, 'distributor': 'TB', 'retry': 0})) else: self.redis.lpush(options.queue_distributor_order, json_dumps({'distributor_order_id': order.id, 'distributor': 'TB', 'retry': 0})) logging.info('taobao coupon send end') self.write('{"code":200}')
def post(self): user = self.get_current_user() start_arg = self.get_argument('start', '') end_arg = self.get_argument('end', '') total = self.get_argument('total', '') # 用来分辨是销售人员查询个人,还是查询所有 data = [] extend_sql = '' categories, start, end = generate_duration(start_arg, end_arg) # 没有total, 需查询销售人员关联的商户 if not total: related_suppliers = self.db.query('select id from supplier where sales_id=%s', user.id) ids = ','.join([str(item.id) for item in related_suppliers]) # 没有关联商户,返回空数据 if not ids: data.append({'name': '无数据', 'data': format_chart_data([], start, categories)}) self.write(json_dumps(data, decimal_fmt=float)) return extend_sql = ' and sp_id in (' + ids + ') ' # 该销售人员旗下所有商户的所有商品在分销商中的销售的数据按日归档 sql = 'select cast(i.created_at as DATE) as archive_date, sum(payment) as amount, distr_shop_id from item i ' \ 'where cast(i.created_at as DATE)>=%s and cast(i.created_at as DATE)<=%s ' \ + extend_sql + 'group by archive_date, distr_shop_id order by archive_date, distr_shop_id asc ' account_sequence = self.db.query(sql, start, end) # 获得所有分销渠道信息 account_info = self.db.query('select id, name from distributor_shop where deleted = 0') data = [] # 生成有销售数据的分销渠道的系列, 按分销渠道,一个个查 for item in account_info: temp_list = [] for sequence in account_sequence: if sequence.distr_shop_id == item.id: temp_list.append(sequence) if temp_list: # 将有销售数据的分销渠道生成数据 data.append({'name': item.name, 'data': format_chart_data(temp_list, start, categories)}) # 没有数据,返回空数据 if not data: data.append({'name': '无数据', 'data': format_chart_data([], start, categories)}) self.write(json_dumps(data, decimal_fmt=float))
def post(self): supplier_id = self.get_argument("supplier_id", "") data = [] # supplier id 不存在 if not supplier_id: data.append({"error": "没有该商户数据", "name": "没有该商户数据", "data": ""}) return prepayment = self.db.get( "select sum(amount) as amount from external_money where uid=%s and type=1 " "and deleted=0 and source<2", supplier_id, ) if not prepayment: data.append({"error": "没有该商户数据", "name": "没有该商户数据", "data": ""}) return total = prepayment.amount start = self.db.get( "select cast(created_at as DATE) as start from external_money where uid=%s and type=1 " "and deleted=0 and source<2 order by created_at asc limit 1", supplier_id, ).start end = datetime.now().date() duration = (end - start).days + 1 categories = [(start + timedelta(days=i)).strftime("%Y-%m-%d") for i in range(duration)] usage = self.db.query( "select sum(i.purchase_price) as amount, cast(i.created_at as DATE) as archive_date from item i " "where sp_id=%s and cast(i.created_at as DATE)>=%s and cast(i.created_at as DATE)<=%s " "group by cast(i.created_at as DATE) order by cast(i.created_at as DATE) asc", supplier_id, start, end, ) if usage: result = [] length = len(usage) index = 0 current_day = start for i in range(len(categories)): if index < length and current_day == usage[index].archive_date: total = total - usage[index].amount result.append(total) index += 1 else: result.append(total) current_day += timedelta(days=1) data.append({"name": "预付款剩余", "data": [[categories[i], result[i]] for i in range(len(categories))]}) else: data.append({"name": "预付款剩余", "data": [[cate, total] for cate in categories]}) self.write(json_dumps(data, decimal_fmt=float))
def post(self): """推送商品""" arg = lambda k: self.get_argument(k).encode('utf-8') goods_id = self.get_argument('goods_id') dg = alloc_distributor_goods(self.db, goods_id, options.shop_id_wuba) params = dict([(name, self.get_argument(name).encode('utf-8')) for name in self.request.arguments]) params.pop("goods_id") params.pop("_xsrf") params['groupbuyId'] = dg.goods_link_id prod_model_json = dict(prodmodcatename=arg('prodName'), prodprice=arg('prodPrice'), groupprice=arg('groupPrice'), prodcode='', count=arg('saleMaxNum')) cityIds = self.request.arguments['cityIds'] ids = [] for cityId in cityIds: ids.append(int(cityId)) params['cityIds'] = str(ids) if options.app_mode == 'dev': params['prodImg'] = 'http://www.itlearner.com/google_commonweal_ad/images/sun/300px.jpg' params['prodModelJson'] = '{%s}' % json_dumps(prod_model_json) #商家信息参数 shop_ids = list(arg('shop_ids').split(",")) # 将团购信息参数中的特定key值转移出来,构建商家信息参数 partner_keys = {"partnerId", "title", "shortTitle", "telephone", "webUrl", "busline", "mapImg", "mapServiceId", "mapUrl", "latitude", "longitude", "address", "circleId"} partners = [] for shop_id in shop_ids: partner = {} for key in partner_keys: partner[key] = params.pop(key + "_" + shop_id) partners.append(partner) request_params = {'groupbuyInfo': params, 'partners': partners} wb = Wuba('addgroupbuy') response = yield wb.fetch(**request_params) wb.parse_response(response.body) if wb.is_ok(): off_sale_at = datetime.strptime(params['endTime'], '%Y-%m-%d %H:%M:%S') expire_at = ceiling(datetime.strptime(params['deadline'], '%Y-%m-%d %H:%M:%S'), today=True) self.db.execute('update goods_distributor_shop set status="PENDING", created_by=%s, created_at=NOW(), ' 'offsale_at = %s, expire_at = %s, distributor_goods_id = %s ' 'where goods_id=%s and distributor_shop_id=%s and goods_link_id=%s', self.current_user.name, off_sale_at, expire_at, wb.message.data.groupbuyId58, goods_id, options.shop_id_wuba, dg.goods_link_id) self.render('goods/distributor/wuba/result.html', ok=True, title='上传成功', explain='<a href="http://t.58.com/sh/%s" target="_blank">去58查看商品</a><br/><a href="/goods/distributor?shop=wb">' '继续上传58商品</a>' % wb.message.data.groupbuyId58) else: self.render('goods/distributor/wuba/result.html', ok=False, title='上传出错', explain=wb.message.msg)
def post(self): user = self.get_current_user() supplier_id = self.get_argument('id', '') start_arg = self.get_argument('start', '') end_arg = self.get_argument('end', '') total = self.get_argument('total', '') # 用来分辨是销售人员查询个人,还是查询所有 data = [] categories, start, end = generate_duration(start_arg, end_arg) # 没有total, 需查询销售人员关联的商户 if not total: # 查询商家 supplier = self.db.get('select short_name, id from supplier where sales_id=%s and deleted=0 ' 'and id=%s', user.id, supplier_id) else: supplier = self.db.get('select short_name, id from supplier where id=%s and deleted=0', supplier_id) # 商家不存在 if not supplier: data.append({'name': '商家不存在或者您不是该商家的关联销售人员', 'data': format_chart_data([], start, categories)}) self.write(json_dumps(data, decimal_fmt=float)) return # 对商家,根据日期统计销售 sales_amount = self.db.query('select cast(i.created_at as DATE) as archive_date, sum(payment) as amount ' 'from item i where sp_id=%s ' 'and cast(i.created_at as DATE)>=%s and cast(i.created_at as DATE)<=%s ' 'group by archive_date order by archive_date asc', supplier_id, start, end) # 如果有销售数据 if sales_amount: # 补全时间轴 sales_data = format_chart_data(sales_amount, start, categories) # 添加到返回的数据列表上 data.append({'name': supplier.short_name, 'data': sales_data}) # 没有数据,返回空数据 if not data: data.append({'name': '无数据', 'data': format_chart_data([], start, categories)}) self.write(json_dumps(data, decimal_fmt=float))
def get(self): msg_type = self.get_argument('msg_type') if msg_type == '0': msgs = self.db.query('select id, title name from wx_app_msg where deleted = 0 and sp_id = %s', self.current_user.supplier_id) elif msg_type == '1': msgs = self.db.query('select id, name from wx_app_msg_gp where deleted = 0 and sp_id = %s', self.current_user.supplier_id) else: msgs = [] self.set_header('Content-Type', 'application/json; charset=UTF-8') self.write(json_dumps(msgs))
def before_request(self): params = {'appid': options.wuba_app_id, 'f': 'json', 'v': '1.0', 'sn': '1'} if self.method in get_methods: self._fields['m'] = self.method self._fields.update(params) return json_message = json_dumps(self._fields) params['m'] = self.method if 'request' in encrypt_info[self.method]: params['param'] = encrypt(json_message, options.wuba_secret_key) else: params['param'] = json_message self._fields = params
def post(self): sql = 'select id, short_name,name from supplier where deleted = 0' result = [] for supplier in self.db.query(sql): result.append({ 'id': supplier.id, 'value': pinyin.get_pinyin(supplier.short_name.decode('utf-8'), '').encode('utf-8'), 'label': supplier.short_name, 'full_name': supplier.name, 'alias': [ ''.join([pinyin.get_initials(s).lower().encode('utf-8') for s in supplier.short_name.decode('utf-8')]), supplier.short_name, ] }) self.set_header('Content-Type', 'application/json; charset=UTF-8') self.write(json_dumps(result))
def post(self): level = self.get_argument("dict") level_list = [obj for obj in level.split(",") if obj] level_dict = dict([(item.split("-")[0], item.split("-")[1]) for item in level_list]) self.db.execute( 'delete from supplier_property where name = "wx_level" and sp_id = %s', self.current_user.supplier_id ) self.db.execute( "insert into supplier_property(sp_id, name, value) values(%s, %s, %s)", self.current_user.supplier_id, "wx_level", json_dumps(level_dict), ) self.redirect(self.reverse_url("wx.member.level"))
def post(self): if not self.request.files: self.render('real/import_shipping.html', error=1, message='', success_list=[], failure_list=[]) #读取文件 order_shipping_file = self.request.files['order_shipping_file'][0] try: book = open_workbook(file_contents=order_shipping_file['body']) sheet = book.sheet_by_index(0) except: message = u"打开%s发生错误,请重新选择上传文件" % (order_shipping_file['filename']) self.render('real/order_shipping.html', error=1, message=message, success_list=[], failure_list=[]) #flag_import用于判定是否重复导入发货单 flag_import = 0 success_list = set([]) failure_list = set([]) taobao_list = set([]) taobao_map = {} taobao_failure = [] rows = [sheet.row_values(i) for i in range(1, sheet.nrows)] for row in rows: order_no = row[1] express_company = row[12] express_number = guess_express(str(row[13])) if not (express_company or express_number): failure_list.add(order_no) continue express_company_id = self.db.get( 'select id from express_company where code = %s', express_company) if not express_company_id: failure_list.add(order_no) continue #只有待打包的才可以上传 real_items = self.db.query( """ select ri.id,oi.goods_id,oi.shipping_info_id,ri.distr_id,ri.goods_name, oi.order_id,(select g.name from goods g,sku s,sku_goods sg where g.id = sg.goods_id and s.id=sg.sku_id and g.id = oi.goods_id) name,ri.sp_id, osi.express_number, osi.express_company_id,ri.payment,ri.purchase_price,ri.distr_shop_id from order_item oi,item ri,orders o,order_shipping_info osi where ri.order_item_id = oi.id and o.id=oi.order_id and ri.order_id =o.id and oi.shipping_info_id = osi.id and ri.status = %s and o.order_no = %s and oi.goods_id=%s order by o.id """, const.status.WAIT_TO_SEND, order_no, row[0]) if real_items: flag_import += 1 # 查找商户及门店的账户 supplier_shop_account_id = self.db.get( 'select ss.account_id from supplier s,supplier_shop ss ' 'where s.id=ss.supplier_id and s.deleted =0 and s.id=%s limit 1', real_items[0].sp_id).account_id #记录资金 for item in real_items: #把每个real_item状态更新为已发货 self.db.execute( 'update item set status =%s, used_at = NOW() where status = %s ' 'and id = %s', const.status.USED, const.status.WAIT_TO_SEND, item.id) self.db.execute( 'insert into account_sequence(type, account_id, item_id,amount,created_at,remark,' 'trade_type,trade_id) values (%s, %s, %s, %s, NOW(),%s,1,%s)', const.seq.USED, supplier_shop_account_id, item.id, item.purchase_price, u'实物发货,备注:%s,订单号:%s' % (item.goods_name.decode('utf-8'), order_no), item.order_id) #更新运物流信息 self.db.execute( 'update order_shipping_info set express_company_id = %s, express_number = %s ' 'where id = %s', express_company_id.id, express_number, real_items[0].shipping_info_id) # 记录订单日志 self.db.execute( 'insert into journal (created_at, type, created_by, message, iid)' 'values (NOW(), 1, %s, %s, %s)', "%s" % self.current_user.name, "实物发货成功, 本次发货数量%s个" % len(real_items), real_items[0].order_id) #分销商为taobao时自动发货 if real_items[0]['distr_shop_id']== options.shop_id_taobao \ or real_items[0]['distr_shop_id'] == options.shop_id_tmall: taobao_list.add(real_items[0].order_id) taobao_map[str(real_items[0].order_id)] = [ real_items[0]['distr_shop_id'], express_number, express_company ] #更新运费todo success_list.add(order_no) #取得淘宝订单中的所有外部单号 if taobao_list: outer_list = self.db.query( 'select o.id, d.order_no from orders o left join distributor_order d on ' 'o.distributor_order_id = d.id where o.id in (%s)' % ','.join(['%s'] * len(taobao_list)), *taobao_list) for i in outer_list: taobao_map[str(i.id)].append(i.order_no) #taobao自动发货的都加入进队列 for taobao_item in taobao_list: params = { 'tid': int(taobao_map[str(taobao_item)][3]), 'out_sid': int(taobao_map[str(taobao_item)][1]), 'company_code': taobao_map[str(taobao_item)][2], } #此处循环取得队列中的信息,先进行取状态。若状态为WAIT_SELLER_SEND_GOODS,则加入队列 app_info = json.loads(self.db.get( 'select taobao_api_info from distributor_shop where id = %s', int(taobao_map[str(taobao_item)][0])).taobao_api_info, object_hook=json_hook) status = yield order_status(params['tid'], app_info) logging.info('status:%s', status.ok) if status.ok: params.update({'retry': 0}) self.redis.lpush(options.queue_taobao_express, json_dumps(params)) else: taobao_failure.append(taobao_map[str(taobao_item)][3]) #如果订单多个item 只退了其中一个 则,我们这边不知道更新哪一个real_item # if status.status == 'REFUND': # self.db.execute('update real_item set status = "RETURNED" where order_id = %s', taobao_item) # logging.info('order has returned. order %s', taobao_item) # else: logging.info('order need not send. order %s', taobao_item) if not flag_import: if not len(failure_list): message = u"%s已经导入,请勿重复导入" % (order_shipping_file['filename']) self.render('real/order_shipping.html', error=1, message=message, success_list=[], failure_list=[]) else: message = u"%s已经导入成功" % (order_shipping_file['filename']) self.render('real/order_shipping.html', error=2, message=message, success_list=success_list, failure_list=failure_list, taobao_failure=taobao_failure) message = u"%s已经导入成功" % (order_shipping_file['filename']) self.render('real/order_shipping.html', error=2, message=message, success_list=success_list, failure_list=failure_list, taobao_failure=taobao_failure)
def post(self): form = Form(self.request.arguments, add_schema) goods_info, shops, properties = get_goods_info(self.db, form.id.value) # 为了下面的 validate 成功 这里必须填入数据 form.arguments.update({'type': EmptyDict({'value': goods_info.type}), 'generate_type': EmptyDict({'value': goods_info.generate_type})}) img_paths = dict() for key in self.request.arguments: if key.startswith('var_img_path_'): v = self.request.arguments[key][0] if v: img_paths[key[key.rindex('_')+1:]] = v form.img_paths['value'] = json_dumps(img_paths) if not form.validate(): form.properties.value = ['%s-%s' % (item.name, item.value) for item in properties] form.shops['value'] = shops supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0', form.supplier_id.value) all_sku = self.db.query('select * from sku where deleted=0 and supplier_id=%s', form.supplier_id.value) distributors = self.db.query('select * from distributor_shop where deleted = 0') form.img_paths['value'] = img_paths logging.error(json_dumps(form.errors)) self.render('goods/add.html', form=form, error='', action='edit', img_url=img_url, supplier_shops=supplier_shops, all_sku=all_sku, distributors=distributors) return fields = ('expire_at', 'category_id', 'name', 'short_name', 'sms_name', 'face_value', 'sales_price', 'stock', 'virtual_sales_count', 'img_path', 'detail', 'tips', 'supplier_intro', 'all_shop', 'on_sale_at', 'off_sale_at', 'purchase_price', 'img_paths') update_sql = 'update goods set %s, created_at = NOW(), created_by = %%s where id=%%s' % \ ','.join([field + '=%s' for field in fields]) form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None params = [form.arguments[field]['value'] for field in fields] params.append(self.current_user.name) params.append(form.id.value) #将更新前的旧数据插入goods_copy商品 insert_fields = ('supplier_id', 'face_value', 'purchase_price', 'sales_price', 'sales_count', 'stock', 'virtual_sales_count', 'code', 'all_shop', 'name', 'short_name', 'sms_name', 'category_id', 'img_path', 'created_at', 'expire_at', 'detail', 'tips', 'supplier_intro', 'status', 'created_by', 'deleted', 'type', 'generate_type', 'supplier_goods_id', 'on_sale_at', 'off_sale_at', 'img_paths') change_fields = ','.join([field for field in insert_fields]) insert_id = self.db.execute('insert into goods_copy({0}) select {0} from goods ' 'where id = %s'.format(change_fields), form.id.value) self.db.execute('update goods_copy set goods_id = %s where id = %s', form.id.value, insert_id) #更新goods表 self.db.execute(update_sql, *params) self.db.execute('insert into journal(created_at, type, created_by, message, iid) ' 'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '修改了商品', form.id.value) # 批量更新商品属性 self.db.execute('delete from goods_property where goods_id=%s and name in ' '("gift_card", "hidden", "ktv", "jd_team_id")', form.id.value) if form.properties.value: insert_properties(self.db, form.properties.value, form.id.value) # 批量更新关联门店 self.db.execute('delete from goods_supplier_shop where goods_id=%s', form.id.value) if not form.all_shop.value: if form.shops.value: insert_shops(self.db, form.shops.value, form.id.value) # 批量更新SKU self.db.execute('delete from sku_goods where goods_id=%s', form.id.value) if form.skus.value: insert_skus(self.db, form.skus.value, form.id.value) # 批量更新分销店铺佣金 self.db.execute('delete from goods_distributor_commission where goods_id=%s', form.id.value) if form.ratios.value: insert_ratios(self.db, form.ratios.value, form.id.value) self.redirect(self.reverse_url('goods.show_list'))
('lbc_tuan_user_key', 'tuan_user_ticket_key', 'JSESSIONID'), [p.split(',')[-1] for p in login_cookie.split(';')])) login_conn.close() if not login_cookie: logging.error( 'nuomi update cookie failed: login fail, supplier_shop_id=%s', shop.id) send_email(redis=redis, subject='糯米更新cookie失败提醒', to_list='*****@*****.**', html='supplier_shop id: %s' % shop.id) continue params['cookie'] = login_cookie try: db.execute('update supplier_shop set nuomi_params=%s where id=%s', json_dumps(params), shop.id) except Exception: send_email( redis=redis, subject='糯米更新cookie失败提醒', to_list='*****@*****.**', html='insert cookie into database failed, supplier_shop id: %s' % shop.id) logging.info('--------end update nuomi cookie--------') shops = db.query( 'select id, meituan_params from supplier_shop where deleted=0 and meituan_params is not null' ) logging.info('--------start update meituan cookie--------') for shop in shops:
def process_wb_order(self, order_list, existed_orders, unbind_goods, success_orders): """处理58团的订单""" distributor_shop_id = options.shop_id_wuba for order in order_list: wb_order_no = order['distr_order_no'] logging.info("Process OrderNO: %s", wb_order_no) #拆分58团购导入的实体券. separate_order_list = separate_wuba_order(order) if not separate_order_list: logging.info("excel数据格式有问题。外部订单: %s", wb_order_no) continue #判断是不是已经导入过的外部订单 distributor_order = self.db.get( 'select * from distributor_order where distributor_shop_id=%s and ' 'order_no=%s', distributor_shop_id, wb_order_no) if distributor_order: existed_orders.append(wb_order_no.encode('utf-8')) continue else: #创建外部订单过程 order_message = json_dumps(order) distributor_order_id = self.db.execute( 'insert into distributor_order(order_no, message, distributor_shop_id, created_at) ' 'values (%s, %s, %s, NOW())', wb_order_no, order_message, options.shop_id_wuba) #开始创建一百券订单 #订单总额 order_amount = order['sales_price'] # 生成订单 while True: order_no = '%s%s' % (random.choice('123456789'), ''.join( [random.choice(string.digits) for i in range(7)])) # 没有重复,停止 if not self.db.get('select id from orders where order_no=%s', order_no): break order_id = self.db.execute( 'insert into orders(distributor_shop_id, order_no, distributor_order_id,' 'total_fee, payment,mobile, paid_at, status, created_at) values(%s, %s, %s, %s, %s, %s, %s, 1, NOW())', distributor_shop_id, order_no, distributor_order_id, order_amount, order_amount, order['phone'], order['paid_at']) #更新外部订单中的一百券订单Id self.db.execute( 'update distributor_order set order_id =%s where id =%s', order_id, distributor_order_id) #创建实物订单物流信息 order_shipping_info_id = self.db.execute( 'insert into order_shipping_info(address, created_at, express_info, paid_at, ' 'receiver, phone, remarks, zip_code, distr_order_no) ' 'values(%s, NOW(), %s, %s, %s, %s, %s, %s, %s)', order['address'], order['express_info'], order['paid_at'], order['receiver'], order['phone'], order['remarks'], order['zip_code'], order['distr_order_no']) amount = 0 for wuba_order in separate_order_list: # 找到关联的商品 goods_info = self.db.get( 'select g.* from goods g, goods_distributor_shop gds ' 'where g.id = gds.goods_id and distributor_shop_id=%s and ' 'distributor_goods_id=%s', distributor_shop_id, wuba_order['goods_no']) if not goods_info: unbind_goods.add(wuba_order['goods_no']) logging.info("58未映射商品NO:%s", wuba_order['goods_no'].encode('utf-8')) #删除未映射已产生的订单关联信息 self.db.execute( 'delete from order_shipping_info where id = %s', order_shipping_info_id) self.db.execute('delete from orders where id = %s', order_id) self.db.execute('delete from distributor_order where id = %s', distributor_order_id) continue # 生成 订单项 count = wuba_order['buy_num'] order_item_id = self.db.execute( 'insert into order_item(distributor_shop_id, goods_id, num, order_id, sales_price, ' 'shipping_info_id, distributor_goods_no) values (%s, %s, %s, %s, %s,%s,%s)', distributor_shop_id, goods_info.id, count, order_id, goods_info.sales_price, order_shipping_info_id, wuba_order['goods_no']) # 查找销售人员,商户的账户 supplier = self.db.get('select s.* from supplier s where s.id=%s', goods_info.supplier_id) # 放入消息表,以便通知商户发货 url = '/shipping/show' self.db.execute( 'insert into notification(content, created_at, type, url, uid, user_type,title) ' 'values(%s, NOW(), 1, %s, %s, 0,%s)', '有物品%s需要发货' % goods_info.short_name, url, goods_info.supplier_id, u'发货通知') #取得商品佣金比例 goods_commission = self.db.get( 'select ratio from goods_distributor_commission ' 'where goods_id=%s and distr_shop_id=%s', goods_info.id, distributor_shop_id) commission = goods_commission.ratio * goods_info.sales_price * Decimal( '0.01') if goods_commission else 0 #生成item for i in range(int(count)): create_item(self, distributor_shop_id, options.distributor_id_wuba, goods_info, order_id, order_item_id, order_no, supplier.sales_id, commission) #根据一百券商品计算订单总金额 amount += goods_info.sales_price * int(count) #成功的订单 success_orders.add(str(wb_order_no)) if amount > 0 and amount != order_amount: logging.info('58订单总金额和一百券不一致,外部订单号:%s', wb_order_no) # 记录订单日志 self.db.execute( 'insert into journal (created_at, type, created_by, message, iid)' 'values (NOW(), 1, %s, %s, %s)', "%s" % self.current_user.name, "生成新订单", order_id)
def post(self): form = Form(self.request.arguments, add_schema) goods_info, shops, properties, img = get_goods_info(self.db, form.id.value) if goods_info.supplier_id != self.current_user.supplier_id: raise HTTPError(403) # 为了下面的 validate 成功 这里必须填入数据 form.arguments.update({'generate_type': EmptyDict({'value': goods_info.generate_type})}) img_paths = dict() for key in self.request.arguments: if key.startswith('var_img_path_'): v = self.request.arguments[key][0] if v: img_paths[key[key.rindex('_')+1:]] = v form.img_paths['value'] = json_dumps(img_paths) if not form.validate(): form.properties.value = properties form.shops['value'] = shops form.img_paths['value'] = img_paths supplier_shops = self.db.query('select ss.* from supplier_shop ss where ss.supplier_id=%s and ss.deleted=0', self.current_user.supplier_id) logging.error(json_dumps(form.errors)) self.render('wx/mall/goods_add.html', form=form, error='', action='edit', supplier_shops=supplier_shops, img_url=img_url) # 获取微信商品手续费 commission = self.db.get('select value from supplier_property where sp_id=%s and name="wx_commission"', self.current_user.supplier_id) if not commission: rate = Decimal((100 - options.wx_min_commission)/100.0) else: rate = Decimal((100 - int(commission.value))/100.0) # 更新结算价 form.arguments['purchase_price']['value'] = form.arguments['sales_price']['value'] * rate fields = ('type', 'generate_type', 'expire_at', 'category_id', 'short_name', 'sms_name', 'max_buy', 'on_sale_at', 'off_sale_at', 'face_value', 'sales_price', 'purchase_price', 'stock', 'img_path', 'all_shop', 'detail', 'postage') update_sql = 'update goods set %s where id=%%s' % ','.join([field + '=%s' for field in fields]) form.expire_at['value'] = ceiling(form.expire_at.value, today=True) if form.expire_at.value else None form.on_sale_at['value'] = form.on_sale_at.value if form.off_sale_at.value else None form.off_sale_at['value'] = ceiling(form.off_sale_at.value, today=True) if form.off_sale_at.value else None params = [form.arguments[field]['value'] for field in fields] params.append(form.id.value) self.db.execute(update_sql, *params) self.db.execute('insert into journal(created_at, type, created_by, message, iid) ' 'values(NOW(), 3, %s, %s, %s)', self.current_user.name, '商户修改了微商城商品', form.id.value) # 批量更新关联门店 self.db.execute('delete from goods_supplier_shop where goods_id=%s', form.id.value) if not form.all_shop.value: if form.shops.value: insert_shops(self.db, form.shops.value, form.id.value) self.redirect(self.reverse_url('wx.goods.list'))
def post(self): self.set_header('Content-Type', 'application/json; charset=UTF-8') coupon_list = [ i.strip() for i in self.get_argument('coupons', '').split(',') if i.strip() ] if len(coupon_list) == 0: self.write({'ok': False, 'msg': u'请输入券号'}) return shop_id = self.get_argument('shop_id', 0) #这一步是检查该操作员是否有权限验证券 all_shops = self.db.query( 'select ss.* from supplier_shop ss, supplier_user su where ss.supplier_id=%s and ' 'ss.deleted=0 and su.id=%s and su.supplier_id=ss.supplier_id and ' ' (su.shop_id=0 or ss.id=su.shop_id)', self.current_user.supplier_id, self.current_user.id) if int(shop_id) not in [i.id for i in all_shops]: self.write({'ok': False, 'msg': u'对不起,您无权执行此操作'}) return is_our_coupon = False coupon_length = 0 messages = PropDict() # 用来存不同的手机号对应的券号 #检测长度是否相同、是否是我们的券 for coupon_sn in coupon_list: coupon = self.db.get( 'select id, sn, mobile from item_coupon where sn=%s', coupon_sn) if coupon: is_our_coupon = True if coupon_length == 0: coupon_length = len(coupon_sn) elif coupon_length != len(coupon_sn): coupon_length = -1 if coupon_length == -1: self.write({'ok': False, 'msg': u'券号长度必须一致'}) return result_list = [] if is_our_coupon: # 我们自己的券 for coupon_sn in coupon_list: # 本地检测 check_result = local_check(self.db, coupon_sn, shop_id) if not check_result.ok: ok, msg = (False, check_result.msg) else: # 合作伙伴API验证 api_result = yield partner_api_verify(self.db, coupon_sn) if not api_result.ok: ok, msg = (False, api_result.msg) else: # 本地验证 verify_result = local_verify(self.db, coupon_sn, shop_id, self.current_user.name) ok, msg = (verify_result.ok, verify_result.msg) # 验证通过,记录需要发送确认短信的券 if ok: if messages.get(str(check_result.coupon.mobile)): # 手机号已存在,添加券号到对应手机号 messages.get(str( check_result.coupon.mobile)).append( str(coupon_sn)) else: # 手机号不存在,新建K-V对 messages.update({ str(check_result.coupon.mobile): [str(coupon_sn)] }) result_list.append({ 'coupon_sn': coupon_sn, 'ok': ok, 'msg': msg }) else: mobile = self.get_argument('mobile', '') # 检查手机号合法性 mobile_ptn = re.compile('^1[\d+]{10}$') if not re.match(mobile_ptn, mobile): # 不合法手机号,不记录 mobile = '' # 尝试外部验证 results = yield partner_browser_verify(self.db, coupon_list, shop_id) for result in results: if result.ok: goods_info = self.db.get( 'select g.* from goods g where id=%s', result.goods_id) verify_infos = { 'goods_id': result.goods_id, 'shop_id': shop_id } #创建分销订单 distributor_order_id = self.db.execute( 'insert into distributor_order(order_no, message, distributor_shop_id, created_at) ' 'values (%s, %s, %s, NOW())', result.coupon_sn, json_dumps(verify_infos), result.distributor_shop_id) order_id, order_no = new_distributor_order( self.db, result.distributor_shop_id, goods_info.sales_price, goods_info.sales_price, mobile) #记录订单信息 new_order = new_distributor_item( db=self.db, order_id=order_id, order_no=order_no, sales_price=None, count=1, goods_info=goods_info, mobile=mobile, distributor_shop_id=result.distributor_shop_id, distributor_goods_id='', distributor_coupons=[{ 'coupon_sn': result.coupon_sn, 'coupon_pwd': result.coupon_pwd or '' }], use_distributor_coupon=True) if new_order.ok: #更新分销订单id self.db.execute( 'update orders set distributor_order_id=%s where id = %s', distributor_order_id, order_id) #更新订单id self.db.execute( 'update distributor_order set order_id=%s where id=%s', order_id, distributor_order_id) #更新该券验证的门店 self.db.execute( 'update item set sp_shop_id = %s where order_id=%s', shop_id, order_id) self.redis.lpush( options.queue_coupon_local_verify, json_dumps({ 'coupon': result.coupon_sn, 'shop_id': shop_id, 'retry': 0, 'used_at': datetime.now() })) result_list.append({ 'coupon_sn': result.coupon_sn, 'coupon_pwd': result.coupon_pwd or '', 'ok': result.ok, 'msg': result.msg }) # 如果有合法券号,发送确认短信 if messages: shop_name = self.db.get( 'select name from supplier_shop where id=%s', shop_id).name for mobile, coupon_sns in messages.items(): CouponConsumedMessage(self.redis, coupon_sns, shop_name, mobile).send() self.write({'ok': True, 'result': result_list})
def process_partner_order(self, partner, order_list, tb_auto_import, existed_orders, unbind_goods, success_orders): """ 处理渠道的订单数据信息""" ###################处理京东,一号店,淘宝 渠道订单################### order_bool = 0 order_id = 0 shipping_id = 0 # 分销店铺 distributor = { 'tb': options.shop_id_taobao, 'tm': options.shop_id_tmall, 'jd': options.shop_id_jingdong, 'yhd': options.shop_id_yihaodian } # 分销商 distr_id = { 'tb': options.distributor_id_taobao, 'tm': options.distributor_id_taobao, 'jd': options.distributor_id_jingdong, 'yhd': options.distributor_id_yihaodian, } distributor_shop = distributor[partner] distributor_id = distr_id[partner] logging.info('processing %s order start...', partner) for order in order_list: amount = 0 if not tb_auto_import: if partner == 'jd': filename = self.request.files['order_file'][0]['filename'] order['goods_no'] = filename.split('.')[0] order['sales_price'] = str( Decimal(order['total_fee']) / Decimal(order['buy_num'])) order['zip_code'] = '000000' order['express_info'] = '' goods = self.db.get( 'select goods_id from goods_distributor_shop where ' 'distributor_goods_id = %s and distributor_shop_id = %s limit 1', order['goods_no'], distributor_shop) else: goods = self.db.get( 'select goods_id from goods_distributor_shop where ' 'goods_link_id = %s and distributor_shop_id = %s limit 1', order['goods_no'], distributor_shop) if not goods: unbind_goods.add(str(order['goods_no'])) continue goods_id = goods.goods_id goods_info = self.db.get('select * from goods where id = %s ', goods_id) #如果是float,转为如2013-08-22 17:23:00格式 if isinstance(order['paid_at'], float): order['paid_at'] = excel_time_translation(order['paid_at']) distr_order_no = order['distr_order_no'] if isinstance(distr_order_no, float): distr_order_no = str(int(distr_order_no)) #第一次循环,判断distributor_order是否已存在 distributor_order = self.db.get( 'select * from distributor_order where order_no = %s limit 1', distr_order_no) if distributor_order: #如果第一次插入时发现是淘宝自动导入且存在外部订单号。默认为已导入,返回 if tb_auto_import and not order_bool: logging.info('distributor order %s has exist', distr_order_no) existed_orders.append(str(distr_order_no)) #如果已经存在了,则不再导入 return else: distributor_order_id = distributor_order.id order_existed = self.db.get( 'select id from orders where distributor_order_id = %s', distributor_order_id) order_id = order_existed.id if order_existed else 0 if not order_id: #删除没创建订单成功的外部订单 self.db.execute( 'delete from distributor_order where id = %s', distributor_order_id) continue if not order_bool: existed_orders.append(str(distr_order_no)) continue shipping_id = self.db.get( 'select id from order_shipping_info where distr_order_no = %s ' 'limit 1', distr_order_no)['id'] else: # 生成一百券订单 while True: order_no = '%s%s' % (random.choice('123456789'), ''.join( [random.choice(string.digits) for i in range(7)])) # 没有重复,停止 if not self.db.get('select id from orders where order_no=%s', order_no): break order_id = self.db.execute( 'insert into orders(distributor_shop_id, created_at, order_no, mobile, status, paid_at) ' 'values(%s, NOW(), %s, %s, 1, NOW())', distributor_shop, order_no, order['phone']) distributor_order_id = self.db.execute( 'insert into distributor_order(order_no, created_at, message, ' 'distributor_shop_id, order_id) values(%s, NOW(), %s, %s, %s)', order['distr_order_no'], json_dumps(order), distributor_shop, order_id) self.db.execute( 'update orders set distributor_order_id = %s where id = %s', distributor_order_id, order_id) shipping_id = self.db.execute( 'insert into order_shipping_info(address, created_at, express_info, ' 'paid_at, receiver, phone, remarks, zip_code, distr_order_no) ' 'values(%s, NOW(), %s, %s, %s, %s, %s, %s, %s)', order['address'], order['express_info'], order['paid_at'], order['receiver'], order['phone'], order['remarks'], order['zip_code'], order['distr_order_no']) order_bool = 1 order_item = self.db.get( 'select * from order_item where distributor_shop_id = %s and goods_id = %s and ' 'shipping_info_id = %s and distributor_goods_no = %s limit 1', distributor[partner], goods_id, shipping_id, order['goods_no']) if order_item: continue order_item_id = self.db.execute( 'insert into order_item(distributor_shop_id, goods_id, num, order_id,sales_price,' 'shipping_info_id, distributor_goods_no) values(%s, %s,%s, %s,%s, %s, %s)', distributor_shop, goods_id, order['buy_num'], order_id, order['sales_price'], shipping_id, order['goods_no']) sales_price = float(order['sales_price']) * float(order['buy_num']) amount += sales_price self.db.execute( 'update orders set payment = %s, total_fee = %s where id = %s', amount, amount, order_id) supplier = self.db.get('select s.* from supplier s where s.id=%s', goods_info.supplier_id) # 放入消息表,以便通知商户发货 url = '/shipping/show' self.db.execute( 'insert into notification(content, created_at, type, url, uid, user_type,title) ' 'values(%s, NOW(), 1, %s, %s, 0,%s)', '有物品%s需要发货' % goods_info.short_name, url, goods_info.supplier_id, u'发货通知') #取得商品佣金比例 goods_commission = self.db.get( 'select ratio from goods_distributor_commission ' 'where goods_id=%s and distr_shop_id=%s', goods_info.id, distributor_shop) commission = goods_commission.ratio * goods_info.sales_price * Decimal( '0.01') if goods_commission else 0 #生成real_item for i in range(int(order['buy_num'])): create_item(self, distributor_shop, distributor_id, goods_info, order_id, order_item_id, order_no, supplier.sales_id, commission) success_orders.add(str(distr_order_no)) # 记录订单日志 self.db.execute( 'insert into journal (created_at, type, created_by, message, iid)' 'values (NOW(), 1, %s, %s, %s)', "分销商id:%s" % distributor_shop, "生成新订单", order_id)