def post(self): name = self.get_argument('name', '').encode('utf-8') contact = self.get_argument('contact', '').encode('utf-8') content = self.get_argument('content', '').encode('utf-8') if name and contact and content: send_email(redis=self.application.redis, subject='%s 寻求合作 (来自 视惠官网)' % name, to_list='*****@*****.**', html='<p>联系方式: %s</p><p>留言: %s</p>' % (contact, content)) self.write('{}')
def main_loop(): redis = common.redis_client() logging.info('----- emay sms send consumer starts -----') while common.running(): # 查余额 emay = EMay('getBalance') response = emay.sync_fetch(serial_no=options.emay_serial_no, key=options.emay_key) emay.parse_response(response) if float(emay.message.findtext('.//return')) < 10.0: send_email(redis=redis, subject='亿美余额不足10元提醒', to_list='*****@*****.**', html='亿美短信通道余额不足 10 元') message_raw = redis.brpoplpush(options.queue_coupon_send_emay, options.queue_coupon_send_processing) logging.info('get sms task: %s' % message_raw) task = json.loads(message_raw, object_hook=json_hook) mobile = task.mobile content = task.sms if isinstance(task.sms, unicode) else task.sms.decode('utf-8') content = content[:-5] + u',退订回复TD【一百券】' sms_id = task.sms_id if 'sms_id' in task else '' # 检查手机号码长度 if len(mobile) != 11: logging.error( 'coupon sms send consumer error: mobile number %s is not valid' % mobile) continue emay = EMay('sendSMS') response = emay.sync_fetch( serial_no=options.emay_serial_no, key=options.emay_key, send_time='', mobiles=mobile, sms_content=content.encode('utf-8'), add_serial='', src_charset='utf-8', sms_priority='5', sms_id=sms_id, ) emay.parse_response(response) if emay.is_ok(): redis.lrem(options.queue_coupon_send_processing, 0, message_raw) logging.info('re-send sms successfully: %s' % content) else: logging.error('re-send sms failed, emay response error: %s', emay.message.findtext('.//return')) logging.info('----- coupon sms sender consumer shut down -----')
def post(self): self.set_header('Content-Type', 'application/xml; charset=UTF-8') logging.info('jingdong api. push_order %s', self.request.body) request = JdToUs(self.request.body) request.set_key(options.jingdong_fx_vender_key, options.jingdong_fx_secret_key) request.parse() logging.info('jingdong api. push_order decrypted %s', ElementTree.tostring(request.message, encoding='utf-8', method='xml')) # 获得JD TEAM ID jd_team_id = request.message.findtext('JdTeamId') jd_order_id = request.message.findtext('JdOrderId') goods_id = self.db.get('select goods_id from goods_property where name="jd_team_id" and value=%s', jd_team_id).goods_id # 没找到对应我们的商品ID, 发邮件 if not goods_id: logging.error('jd push order failed: can not find internal goods_id for jd_team_id=%s', jd_team_id) send_email(redis=self.redis, subject='京东分销订单接收失败', to_list='*****@*****.**', html='京东分销订单接收失败, 没有对应内部商品, 京东商品id=%s,订单id=%s' % (jd_team_id, jd_order_id)) return self.write(request.response('push_order', 200, 'ok')) jd_coupons = [{'coupon_sn': c.findtext('CouponId'), 'coupon_pwd': c.findtext('CouponPwd')} for c in request.message.findall('Coupons/Coupon')] # 没找到券号,密码 if not jd_coupons: logging.error('jd push order failed: can not find valid coupons for jd_team_id=%s', jd_team_id) return self.write(request.response('push_order', 200, 'no coupons found in request')) count = request.message.findtext('Count') try: # 插入导入券 values = ','.join(['(%s, %s, %s, 0, NOW())'] * int(count)) self.db.execute('insert into coupon_imported (goods_id, coupon_sn, coupon_pwd, used, created_at) ' 'values %s' % values, *list(itertools.chain(*[(goods_id, jd_coupon['coupon_sn'], jd_coupon['coupon_pwd']) for jd_coupon in jd_coupons]))) except Exception: logging.error('jd push order failed: insert into coupon_imported failed for jd_order_id=%s', jd_order_id) send_email(redis=self.redis, subject='京东分销订单接收失败', to_list='*****@*****.**', html='京东分销订单接收失败, 数据库插入导入券失败, 京东商品id=%s,订单id=%s' % (jd_team_id, jd_order_id)) return self.write(request.response('push_order', 200, 'ok')) # 更新库存 self.db.execute('update goods set stock=stock+%s where goods.id=%s', int(count), goods_id) logging.info('jd push order successfully received, jd_order_id: %s', jd_order_id) return self.write(request.response('push_order', 200, 'ok'))
def main_loop(): redis = common.redis_client() logging.info('----- emay sms send consumer starts -----') while common.running(): # 查余额 emay = EMay('getBalance') response = emay.sync_fetch( serial_no=options.emay_serial_no, key=options.emay_key ) emay.parse_response(response) if float(emay.message.findtext('.//return')) < 10.0: send_email(redis=redis, subject='亿美余额不足10元提醒', to_list='*****@*****.**', html='亿美短信通道余额不足 10 元') message_raw = redis.brpoplpush(options.queue_coupon_send_emay, options.queue_coupon_send_processing) logging.info('get sms task: %s' % message_raw) task = json.loads(message_raw, object_hook=json_hook) mobile = task.mobile content = task.sms if isinstance(task.sms, unicode) else task.sms.decode('utf-8') content = content[:-5] + u',退订回复TD【一百券】' sms_id = task.sms_id if 'sms_id' in task else '' # 检查手机号码长度 if len(mobile) != 11: logging.error('coupon sms send consumer error: mobile number %s is not valid' % mobile) continue emay = EMay('sendSMS') response = emay.sync_fetch( serial_no=options.emay_serial_no, key=options.emay_key, send_time='', mobiles=mobile, sms_content=content.encode('utf-8'), add_serial='', src_charset='utf-8', sms_priority='5', sms_id=sms_id, ) emay.parse_response(response) if emay.is_ok(): redis.lrem(options.queue_coupon_send_processing, 0, message_raw) logging.info('re-send sms successfully: %s' % content) else: logging.error('re-send sms failed, emay response error: %s', emay.message.findtext('.//return')) logging.info('----- coupon sms sender consumer shut down -----')
def cancel(self, params, order): """ 退款 """ if not order: logging.info('taobao order cancel failed. order not found') return self.write('{"code":504}') refund_num = params.cancel_num coupons = self.db.query('select ic.* from item_coupon ic, item i ' 'where ic.item_id=i.id and i.status=1 and i.order_id=%s limit %s', order.order_id, int(refund_num)) for coupon in coupons: result = refund_coupon(self.db, coupon.sn, 'system', '淘宝接口退款') if not result.ok: logging.error('taobao refund failed internally for coupon sn %s: %s', coupon.sn, result.msg) send_email(redis=self.redis, subject='淘宝接口退款失败', to_list='*****@*****.**', html='淘宝订单退款失败coupon_sn: ' % coupon.sn) logging.info('taobao coupon cancel end') self.write('{"code":200}')
def do_check(rdb, partner, client, req_params): resp = '' try: resp = client.sync_fetch(**req_params) logging.info('%s browser verify check response: %s', partner, resp) client.parse_response(resp) client.is_ok() logging.info('%s browser verify check ok.', partner) except Exception: t = StringIO() traceback.print_exc(file=t) logging.info('%s browser verify check failed. %s', partner, t.getvalue()) send_email(redis=rdb, subject='检查%s验证接口失败' % partner, to_list='*****@*****.**', html='<p>%s browser verify check failed.</p> ' '<p>response: </p> <pre>%s</pre> ' '<p>exception:</p> <pre>%s</pre>' % (partner, resp, t.getvalue()))
def cancel(self, params, order): """ 退款 """ if not order: logging.info('taobao order cancel failed. order not found') return self.write('{"code":504}') refund_num = params.cancel_num coupons = self.db.query( 'select ic.* from item_coupon ic, item i ' 'where ic.item_id=i.id and i.status=1 and i.order_id=%s limit %s', order.order_id, int(refund_num)) for coupon in coupons: result = refund_coupon(self.db, coupon.sn, 'system', '淘宝接口退款') if not result.ok: logging.error( 'taobao refund failed internally for coupon sn %s: %s', coupon.sn, result.msg) send_email(redis=self.redis, subject='淘宝接口退款失败', to_list='*****@*****.**', html='淘宝订单退款失败coupon_sn: ' % coupon.sn) logging.info('taobao coupon cancel end') self.write('{"code":200}')
email_list = {} for item in stock_list: if item.email not in email_list.keys(): email_list[item.email] = [] email_list[item.email].append(item) template = """<p> 亲,有<strong>{{len(goods_list)}}</strong>个货物库存不足,请注意! </p> <table cellpadding='1' cellspacing='0' border='1' bordercolor='#000000'> <tr> <th>商品名</th> <th>库存</th> </tr> {% for goods in goods_list %} <tr> <td>{{ goods.short_name }}</td> <td>{{ goods.stock }}</td> </tr> {% end %} </table>""" now = datetime.datetime.now().hour if 18 >= now >= 9: for email, content in email_list.iteritems(): html = Template(template).generate(goods_list=content) send_email(redis=redis, subject='库存不足提醒', to_list=email + ',' + options.expiring_contract_receivers, html=html)
def post(self): notify_data = unquote_plus(self.get_argument("notify_data").encode("utf-8")) notify_data_xml = ET.fromstring(notify_data) status_set = { "WAIT_BUYER_PAY": 0, "TRADE_CLOSED": 1, "TRADE_SUCCESS": 2, "TRADE_PENDING": 3, "TRADE_FINISHED": 4, } order_id = notify_data_xml.findtext("out_trade_no") trade_status = notify_data_xml.findtext("trade_status") status = status_set.get(trade_status, -1) if status in [2, 4]: shipping = self.db.get( "select oi.shipping_info_id, oi.goods_id, o.distributor_shop_id, s.sales_id, g.*, " "o.id oid, oi.id oiid, o.payment, o.order_no, o.mobile, oi.num " "from orders o, order_item oi, goods g, supplier s " "where o.id = oi.order_id and oi.goods_id = g.id and g.supplier_id = s.id " "and o.status = 0 and o.id = %s", order_id, ) if shipping: self.db.execute("update orders set paid_at = NOW(), status = 1 where id = %s", order_id) if shipping.shipping_info_id: self.db.execute( "update order_shipping_info set paid_at = NOW() where id = %s", shipping.shipping_info_id ) item_ids = [] for i in range(shipping.num): item_id = self.db.execute( "insert into item(status, goods_name, goods_id, distr_id, distr_shop_id, " "sp_id, sales_id, order_id, order_item_id, order_no, face_value, payment, " "sales_price, purchase_price, created_at) " "values(1, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW())", shipping.short_name, shipping.goods_id, options.distributor_id_weixin, shipping.distributor_shop_id, shipping.supplier_id, shipping.sales_id, shipping.oid, shipping.oiid, shipping.order_no, shipping.face_value, shipping.payment, shipping.sales_price, shipping.purchase_price, ) item_ids.append(item_id) # 如果是电子券,生成item_coupon 并发货 if shipping.type == "E": # 导入券,获得导入的券号,密码 if shipping.generate_type == "IMPORT": coupon_imported = self.db.query( "select * from coupon_imported where goods_id=%s and used=0 " "limit %s", shipping.goods_id, shipping.num, ) # 导入券库存不足,直接返回 if len(coupon_imported) < shipping.num: send_email( redis=self.redis, subject="weixin coupon generation failed:out of stock for imported coupon", to_list="*****@*****.**", html="order id=%s and goods id=%s" % (shipping.oid, shipping.goods_id), ) logging.error("imported goods id=%s out of stock" % shipping.goods_id) self.write("success") return imported_ids = [c.id for c in coupon_imported] self.db.execute( "update coupon_imported set used=1 where id in (%s)" % ",".join(["%s"] * len(imported_ids)), *imported_ids ) coupon_sns = [c.coupon_sn for c in coupon_imported] coupon_pwds = [c.coupon_pwd for c in coupon_imported] # 生成电子券 for i in range(int(shipping.num)): if shipping.generate_type == "IMPORT": coupon_sn = coupon_sns[i] coupon_pwd = coupon_pwds[i] else: coupon_pwd = "" while True: coupon_sn = "".join([random.choice(string.digits) for z in range(10)]) # 没有重复,停止 if not self.db.get("select id from item_coupon where sn=%s", coupon_sn): break item_coupon_field = { "mobile": shipping.mobile, "sn": coupon_sn, "pwd": coupon_pwd, "distr_sn": None, "distr_pwd": None, "sms_sent_count": 0, "expire_at": shipping.expire_at, "item_id": item_ids.pop(), } self.db.execute( "insert into item_coupon(%s) values (%s)" % (",".join(item_coupon_field.keys()), ",".join(["%s"] * len(item_coupon_field))), *item_coupon_field.values() ) # 发送电子券 all_order_items = self.db.query("select * from order_item where order_id=%s", order_id) for item in all_order_items: CouponSMSMessage(self.db, self.redis, order_item=item).remark("微商城发送券号短信").send() # 删除redis对应的值 self.redis.delete("o:alipay:%s" % order_id) logging.info("order: %s, paid success", order_id) else: logging.info("order: %s, can not find order", order_id) else: logging.info("order: %s, paid failed. status: %s", order_id, trade_status) self.write("success")
login_params = urllib.urlencode({ 'emailOrMobile': params.emailOrMobile, 'password': params.password, 'isAutoLogin': '******', }) login_headers = {'Content-type': 'application/x-www-form-urlencoded', 'Accept': 'text/plain'} login_conn = httplib.HTTPConnection('y.nuomi.com') login_conn.request('POST', '/login/loginto', login_params, login_headers) login_resp = login_conn.getresponse() login_cookie = login_resp.getheader('set-cookie') login_cookie = ';'.join(filter(lambda v: v.strip().split('=')[0] in ('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: params = json.loads(shop.meituan_params, object_hook=json_obj_hook) login_params = urllib.urlencode({
email_list = {} for item in stock_list: if item.email not in email_list.keys(): email_list[item.email] = [] email_list[item.email].append(item) template = """<p> 亲,有<strong>{{len(goods_list)}}</strong>个货物库存不足,请注意! </p> <table cellpadding='1' cellspacing='0' border='1' bordercolor='#000000'> <tr> <th>商品名</th> <th>库存</th> </tr> {% for goods in goods_list %} <tr> <td>{{ goods.short_name }}</td> <td>{{ goods.stock }}</td> </tr> {% end %} </table>""" now = datetime.datetime.now().hour if 18 >= now >= 9: for email, content in email_list.iteritems(): html = Template(template).generate(goods_list=content) send_email(redis=redis, subject='库存不足提醒', to_list=email + ',' + options.expiring_contract_receivers, html=html)
login_conn = httplib.HTTPConnection('y.nuomi.com') login_conn.request('POST', '/login/loginto', login_params, login_headers) login_resp = login_conn.getresponse() login_cookie = login_resp.getheader('set-cookie') login_cookie = ';'.join( filter( lambda v: v.strip().split('=')[0] in ('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--------')
def post(self): notify_data = unquote_plus( self.get_argument('notify_data').encode('utf-8')) notify_data_xml = ET.fromstring(notify_data) status_set = { 'WAIT_BUYER_PAY': 0, 'TRADE_CLOSED': 1, 'TRADE_SUCCESS': 2, 'TRADE_PENDING': 3, 'TRADE_FINISHED': 4 } order_id = notify_data_xml.findtext('out_trade_no') trade_status = notify_data_xml.findtext('trade_status') status = status_set.get(trade_status, -1) if status in [2, 4]: shipping = self.db.get( 'select oi.shipping_info_id, oi.goods_id, o.distributor_shop_id, s.sales_id, g.*, ' 'o.id oid, oi.id oiid, o.payment, o.order_no, o.mobile, oi.num ' 'from orders o, order_item oi, goods g, supplier s ' 'where o.id = oi.order_id and oi.goods_id = g.id and g.supplier_id = s.id ' 'and o.status = 0 and o.id = %s', order_id) if shipping: self.db.execute( 'update orders set paid_at = NOW(), status = 1 where id = %s', order_id) if shipping.shipping_info_id: self.db.execute( 'update order_shipping_info set paid_at = NOW() where id = %s', shipping.shipping_info_id) item_ids = [] for i in range(shipping.num): item_id = self.db.execute( 'insert into item(status, goods_name, goods_id, distr_id, distr_shop_id, ' 'sp_id, sales_id, order_id, order_item_id, order_no, face_value, payment, ' 'sales_price, purchase_price, created_at) ' 'values(1, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, NOW())', shipping.short_name, shipping.goods_id, options.distributor_id_weixin, shipping.distributor_shop_id, shipping.supplier_id, shipping.sales_id, shipping.oid, shipping.oiid, shipping.order_no, shipping.face_value, shipping.payment, shipping.sales_price, shipping.purchase_price) item_ids.append(item_id) # 如果是电子券,生成item_coupon 并发货 if shipping.type == 'E': # 导入券,获得导入的券号,密码 if shipping.generate_type == 'IMPORT': coupon_imported = self.db.query( 'select * from coupon_imported where goods_id=%s and used=0 ' 'limit %s', shipping.goods_id, shipping.num) # 导入券库存不足,直接返回 if len(coupon_imported) < shipping.num: send_email( redis=self.redis, subject= 'weixin coupon generation failed:out of stock for imported coupon', to_list='*****@*****.**', html='order id=%s and goods id=%s' % (shipping.oid, shipping.goods_id)) logging.error('imported goods id=%s out of stock' % shipping.goods_id) self.write('success') return imported_ids = [c.id for c in coupon_imported] self.db.execute( 'update coupon_imported set used=1 where id in (%s)' % ','.join(['%s'] * len(imported_ids)), *imported_ids) coupon_sns = [c.coupon_sn for c in coupon_imported] coupon_pwds = [c.coupon_pwd for c in coupon_imported] # 生成电子券 for i in range(int(shipping.num)): if shipping.generate_type == 'IMPORT': coupon_sn = coupon_sns[i] coupon_pwd = coupon_pwds[i] else: coupon_pwd = '' while True: coupon_sn = ''.join([ random.choice(string.digits) for z in range(10) ]) # 没有重复,停止 if not self.db.get( 'select id from item_coupon where sn=%s', coupon_sn): break item_coupon_field = { 'mobile': shipping.mobile, 'sn': coupon_sn, 'pwd': coupon_pwd, 'distr_sn': None, 'distr_pwd': None, 'sms_sent_count': 0, 'expire_at': shipping.expire_at, 'item_id': item_ids.pop() } self.db.execute( 'insert into item_coupon(%s) values (%s)' % (','.join(item_coupon_field.keys()), ','.join( ['%s'] * len(item_coupon_field))), *item_coupon_field.values()) # 发送电子券 all_order_items = self.db.query( 'select * from order_item where order_id=%s', order_id) for item in all_order_items: CouponSMSMessage( self.db, self.redis, order_item=item).remark('微商城发送券号短信').send() # 删除redis对应的值 self.redis.delete('o:alipay:%s' % order_id) logging.info('order: %s, paid success', order_id) else: logging.info('order: %s, can not find order', order_id) else: logging.info('order: %s, paid failed. status: %s', order_id, trade_status) self.write('success')
port=options.redis_port, db=options.redis_db) # 查询将要过期的合同 expiring_contract_list = db.query( 'select sc.expire_at, sp.name sp_name, sp.short_name sp_short_name, sp.id sp_id, op.name sales_name ' 'from contract sc, supplier sp, operator op ' 'where sc.uid=sp.id and sc.type=1 and sp.sales_id=op.id and sc.deleted=0 and sc.expire_at>%s and sc.expire_at<%s', datetime.now(), datetime.now() + timedelta(days=10)) db.close() logging.info('expiring contract count: %s', len(expiring_contract_list)) # 如果没有要提醒的内容,退出 if not expiring_contract_list: import sys sys.exit() # 构建邮件内容 template = """<p> 亲,有<strong>{{len(contract_list)}}</strong>个商户合同在10天内到期(或已经过期),请注意! </p> <table cellpadding='1' cellspacing='0' border='1' bordercolor='#000000'> <tr> <th>销售专员</th> <th>商户</th> <th>商户简称</th> <th>到期时间</th> <th>操作</th> </tr> {% for contract in contract_list %} <tr> <td>{{contract.sales_name}}</td> <td>{{contract.sp_name}}</td> <td>{{contract.sp_short_name}}</td> <td>{{contract.expire_at}}</td> <td><a href='http://{{options.operate_domain}}/supplier/{{contract.sp_id}}/contract'>点击查看</a></td> </tr> {% end %} </table>""" # 发送邮件 html = Template(template).generate(contract_list=expiring_contract_list, options=options) send_email(redis=redis, subject='合同到期提醒', to_list=options.expiring_contract_receivers, html=html)