Commit 3ed58533 by 孙龙

init

parents
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-01-03 17:40:18
# @Author : yc ()
# @Link :
# @Version : $Id$
from core.base import *
from core.lib.rbmq import Rbmq
from core.lib.dbhelper import DbHelper
from core.lib.request import Request
from core.lib.hprose import Hprose
from core.lib.redis import Redis
from sync.conf.base import BaseConf
from core.func.common import *
import time, json, traceback
config = {}
class erp2web_service(base):
'''erp服务端接口'''
def __init__(self, data=None):
super().__init__(data)
global config
config = {
'ErpConf' : BaseConf,
'RedisConf' : self.RedisConf,
}
self.db = DbHelper(self.DbConf.ichunt)
self.rbmq = Rbmq(self.RbmqConf.business)
hprose = Hprose(BaseConf.erp_service_listen, BaseConf.erp_service_port, BaseConf.erp_service_debug)
hprose.setBefore(before).publish(self, ('createOrder', 'shipping', 'billPay', 'auth', 'synOrderCustomer', 'createPurchase')).server()
self.start()
def auth(self, data = ''):
'''登录'''
arr = json.loads(data)
user = arr['user']
pwd = arr['pwd']
if global_auth(user, pwd) == False:
return apiReturn(1, '校验失败')
return apiReturn(0, '登录成功')
def createOrder(self, data):
'''创建订单及明细(同订单会运行多次)'''
arr = json.loads(data)
sale_uid = 0
user_id = 0
order_sn = arr['FNUMBER']
try:
order_id = self.db.table('order').getField({'order_sn' : order_sn}, 'order_id')
self.db.startTrans()
if order_id == None:
#创建订单
datas = {
'order_sn' : order_sn,
'order_type' : BaseConf.erp_order_source[arr['SOURCE']],
'order_pay_type' : 1,
'user_id' : user_id,
'order_amount' : round(float(arr['FTOTALAMOUNT']), 2),
'currency' : BaseConf.erp_currency[arr['CURRENCY']],
'delivery_place' : BaseConf.erp_delivery[arr['CURRENCY']],
'order_shipping_type' : BaseConf.erp_shipping_type[arr['DELIVERTYPE']],
'status' : BaseConf.erp_order_status[arr['BASESTATUS']],
'create_time' : int(time.mktime(time.strptime(arr['BIZDATE'], '%Y-%m-%d'))) if 'BIZDATE' in arr.keys() and arr['BIZDATE'] != '' else 0,
'confirm_time' : int(time.mktime(time.strptime(arr['AUDITTIME'], '%Y-%m-%d %H:%M:%S'))) if 'AUDITTIME' in arr.keys() and arr['AUDITTIME'] != '' else 0,
'pay_time' : int(time.mktime(time.strptime(arr['PAYMENTDATE'], '%Y-%m-%d %H:%M:%S'))) if 'PAYMENTDATE' in arr.keys() and arr['PAYMENTDATE'] != '' else 0,
'finish_time' : int(time.mktime(time.strptime(arr['COMPLETEDATE'], '%Y-%m-%d %H:%M:%S'))) if 'COMPLETEDATE' in arr.keys() and arr['COMPLETEDATE'] != '' else 0,
'sale_id' : sale_uid,
}
#补充完成时间
if datas['status'] == '10':
if datas['finish_time'] == 0 and datas['pay_time'] == 0 and datas['confirm_time'] == 0:
datas['finish_time'] = datas['create_time']
datas['confirm_time'] = 0
datas['pay_time'] = 0
elif datas['finish_time'] == 0 and datas['pay_time'] == 0:
datas['finish_time'] = datas['confirm_time']
datas['pay_time'] = 0
elif datas['finish_time']:
datas['finish_time'] = datas['pay_time']
#补充预付款
if datas['order_pay_type'] == 2:
datas['advance_amount'] = round(float(datas['order_amount']) * 0.3, 2)
#金额生成
price = {
'1' : [datas['order_amount'], datas['create_time']]# 货款
}
if int(datas['status']) > 4:
price['-1'] = [-1 * float(datas['order_amount']), datas['pay_time']]# 付款
res = self.db.table('order').insert(datas)
if res == None:
self.db.rollback()
self.elkReport('生成订单,添加失败:%s\r%s' % (order_sn, data))
return apiReturn(1, '添加失败')
order_id = str(res)
#金额处理
for i in price.keys():
datas = {
'order_id' : order_id,
'order_sn' : datas['order_sn'],
'price' : price[i][0],
'price_type' : i,
'currency' : datas['currency'],
'create_time' : price[i][1]
}
res = self.db.table('order_price').insert(datas)
if res == None:
self.db.rollback()
self.elkReport('生成订单,添加金额失败:%s\r%s' % (order_sn, data))
return apiReturn(1, '添加金额失败', price)
else:
order_id = str(order_id)
if order_id == '0':
self.db.rollback()
self.elkReport('生成订单,订单ID为空,单号:%s\r%s' % (order_sn, data))
return apiReturn(1, '添加订单失败')
#创建订单明细
rec_id = self.db.table('order_items').getField({'erp_rec_id' : arr['ENTRYID'], 'status' : 1}, 'rec_id')
if rec_id == None:
datas = {
'order_id' : order_id,
'user_id' : user_id,
'erp_rec_id' : arr['ENTRYID'],
'goods_name' : arr['MATERIAL'],
'brand_name' : arr['FMODEL'],
'goods_price' : arr['FTAXPRICE'],
'goods_number' : arr['FQTY'],
}
rec_id = self.db.table('order_items').insert(datas)
if rec_id == None:
self.db.rollback()
self.elkReport('生成订单,添加明细失败:%s\r%s' % (order_sn, data))
return apiReturn(1, '添加明细失败')
#创建附加表
temp_id = self.db.table('order_extend').getField({'order_id' : order_id}, 'temp_id')
if temp_id == None:
datas = {
'order_id' : order_id,
'client_ip' : '0.0.0.0',
'erp_com_name' : arr['CUSTOMER'],
}
res = self.db.table('order_extend').insert(datas)
if None == res:
self.db.rollback()
self.elkReport('添加订单附加表失败:%s\r%s' % (order_sn, data))
return apiReturn(1, '添加附加表失败')
self.db.commit()
except Exception as e:
self.elkReport('生成订单程序异常:%s\r%s' % (order_sn, data))
raise e
return apiReturn(0, '创建成功', order_id)
def shipping(self, data):
'''同步发货'''
arr = json.loads(data);
shipping_name = arr['CARRIER']
order_sn = arr['NUMBER']
try:
info = self.db.table('order').where({'order_sn' : order_sn}).find()
if None == info:
self.elkReport('发货操作,无相关单据:%s\r%s' % (order_sn, data))
return apiReturn(1, '无相关单据')
send = True
#未付款发货 改账期
if info['status'] <= 2:
self.db.table('order').where({'order_sn':order_sn}).update({'status' : 2,'order_pay_type' : 3})
#账期付款
request = Request()
post_data = apitoken(self.CommonConf.api_auth_key, 3)
post_data['order_sn'] = order_sn
res = request.postUrl(self.CommonConf.api_url + '/pay/billpay', post_data)
try:
bill_arr = json.loads(res)
if bill_arr['err_code'] != 0:
self.elkReport('订单%s账期付款失败' % order_sn)
return apiReturn(bill_arr['err_code'], bill_arr['err_msg'])
except Exception as e:
self.db.table('order').where({'order_sn':order_sn}).update({'status' : info['status']})
#获取快递公司ID
if shipping_name not in ['', '自提', '送货']:
shipping_id = self.db.table('shipping').getField({'shipping_name' : shipping_name}, 'shipping_id')
if None == shipping_id:
self.elkReport('发货操作,无效快递公司:%s\r%s' % (order_sn, data))
return apiReturn(1, '无效快递公司');
else:
shipping_id = 0;
datas = {
'order_id' : info['order_id'],
'erp_removal_id' : arr['SALELSSUEID'],
'order_shipping_type' : BaseConf.erp_shipping_type[arr['DELIVERTYPE']],
'shipping_no' : arr['LOGISTICSNUMBER'],
'shipping_id' : shipping_id,
'shipping_type' : 1,
'status' : 1,
}
#检查是否已存在物流单号
order_shipping_id = self.db.table('order_shipping').getField({'order_id' : datas['order_id'], 'erp_removal_id' : datas['erp_removal_id']}, 'order_shipping_id')
self.db.startTrans()
if None != order_shipping_id:#已存在
#清空旧发货明细
res = self.db.table('order_shipping_items').where({'order_shipping_id' : order_shipping_id}).delete()
if None == res:
self.db.rollback()
self.elkReport('发货操作,清空旧发货明细失败:%s\r%s' % (order_sn, data))
return apiReturn(1, '清空旧发货明细失败')
res = self.db.table('order_shipping').where({'order_shipping_id' : order_shipping_id}).update(datas)
if None == res:
self.db.rollback()
self.elkReport('发货操作,保存发货主信息失败:%s\r%s' % (order_sn, data))
return apiReturn(1, '保存发货主信息失败')
else:
res = self.db.table('order_shipping').insert(datas)
if None == res:
self.db.rollback()
self.elkReport('发货操作,添加发货主信息失败:%s\r%s' % (order_sn, data))
return apiReturn(1, '添加发货主信息失败')
order_shipping_id = res
#发货明细
list = [];
for i in arr['ENTRYS']:
if 'ENTRYID' in i.keys():#分录ID
item = self.db.table('order_items').where({'erp_rec_id': i['ENTRYID']}).field('order_id,rec_id,goods_id,goods_name').find()
if None == item:#过渡
item = self.db.table('order_items').where({'order_id': info['order_id'] ,'erp_rec_id': i['MATERIALID']}).field('order_id,rec_id,goods_id,goods_name').find()
else:#skuid
item = self.db.table('order_items').where({'order_id': info['order_id'], 'erp_rec_id': i['MATERIALID']}).field('order_id,rec_id,goods_id,goods_name').find()
if None == item:
self.db.rollback()
self.elkReport('找不到ERPID明细,添加发货明细失败:%s' % i['ENTRYID'])
return apiReturn(1, '找不到ERPID明细,添加发货明细失败')
datas = {
'order_shipping_id' : order_shipping_id,
'order_id' : info['order_id'],
'rec_id' : item['rec_id'],
'goods_id' : item['goods_id'],
'goods_name' : item['goods_name'],
'num' : i['FQTY'],
}
res = self.db.table('order_shipping_items').insert(datas)
if None == res:
self.db.rollback()
self.elkReport('发货操作,添加发货明细失败:%s\r%s' % (order_sn, data))
return apiReturn(1, '添加发货明细失败')
stock = self.db.table('order_items').where({'order_id' : info['order_id'], 'status' : 1}).sum('goods_number')
send_stock = self.db.table('order_shipping_items').where({'order_id' : info['order_id']}).sum('num')
if stock <= send_stock:
#全部发货
status = 8
else:
#部分发货
status = 7
if True == send:#已收款可发货
if 'BIZDATE' in arr.keys():
shipping_time = int(time.mktime(time.strptime(arr['BIZDATE'], '%Y-%m-%d')))
else:
shipping_time = int(time.time())
res = self.db.table('order').where({'order_id' : info['order_id']}).update({'status' : status, 'shipping_time' : shipping_time})
if None == res:
self.db.rollback()
self.elkReport('发货操作,修改订单状态失败:%s\r%s' % (order_sn, data))
return apiReturn(1, '修改订单状态失败')
if status == 8 and info['order_shipping_type'] == 1 and int(time.time()) - shipping_time < 86400:#快递配送 并且 发货时间小于1天可以发消息提醒
is_sendmsg = self.db.table('user_main').getField({'user_id' : info['user_id']}, 'is_sendmsg')
if is_sendmsg != -1:
wechat = {
'delivername' : {'value' : shipping_name},
'ordername' : {'value' : arr['LOGISTICSNUMBER']}
}
msg = {
'order_id' : info['order_id'],
'order_sn' : order_sn,
}
#发货通知
self.sendMsg('order-confirm-send', info['user_id'], msg, wechat)
# with open('./log/tmp/1.log', 'a+') as f:
# log = {
# 'time': time.strftime('%Y-%m-%d %H:%M:%S'),
# 'id':info['user_id'],
# 'msg' : msg,
# 'wechat' : wechat,
# 'data' : data,
# }
# f.write('%s\n' % json.dumps(log))
self.db.commit()
except Exception as e:
self.elkReport('修改订单程序异常:%s\r%s' % (order_sn, data))
raise e
return apiReturn(0, '同步发货成功', str(order_shipping_id))
def billPay(self, data):
'''订单账单付款'''
arr = json.loads(data)
order_sn = arr['JKNUMBER']
request = Request()
post_data = apitoken(self.CommonConf.api_auth_key, 3)
post_data['order_sn'] = order_sn
res = request.postUrl(self.CommonConf.api_url + '/pay/billpay', post_data)
try:
arr = json.loads(res)
if arr['err_code'] != 0:
self.elkReport('订单%s账期付款失败:\r%s' % (order_sn, data))
return apiReturn(arr['err_code'], arr['err_msg'])
except Exception as e:
self.elkReport('订单%s账期付款请求失败:\r%s' % (order_sn, data))
return (1, '账期付款失败')
# def refundOrder(self, data):
# '''订单退款'''
# arr = json.loads(data)
# post_data = {
# 'order_sn' : '',
# 'money' : '',
# }
# post_data, get_data = unifyReqestData(self.CommonConf.api_auth_key, post_data)
# request = Request()
# res = request.postUrl(self.CommonConf.api_url + '/order/intraface/refundorder?%s' % get_data, post_data)
# try:
# arr = json.loads(res)
# print(arr)
# except Exception as e:
# raise e
def synOrderCustomer(self, data):
'''补充旧订单ERP客户名'''
arr = json.loads(data)
order_sn = arr['FNUMBER']
erp_com_name = arr['CUSTOMER']
items = arr['items']
order_id = self.db.table('order').getField({'order_sn' : order_sn}, 'order_id')
if None == order_id:
print(data)
return apiReturn(1, '%s未获取有效订单号' % order_sn)
datas = self.db.table('order_extend').getFields({'order_id' : order_id}, 'temp_id')
if datas in [None, []]:
data = {
'order_id' : order_id,
'client_ip' : '0.0.0.0',
'erp_com_name' : erp_com_name,
}
res = self.db.table('order_extend').insert(data)
else:
res = self.db.table('order_extend').where({'temp_id' : ['in', datas]}).update({'erp_com_name' : erp_com_name})
if None == res:
return apiReturn(1, '更新数据库失败')
#修复 明细记录的 erpid 为 erp物料ID问题
for i in items:
where = {
'order_id' : order_id,
'erp_rec_id' : i['MATERIALID'],
'goods_number' : i['NUMBER'],
}
save = {
'erp_rec_id' : i['ITEMSID'],
}
res = self.db.table('order_items').where(where).update(save)
if res in [None, 0]:
print(order_id, i['MATERIALID'], items)
return apiReturn(0, '成功', str(order_id))
def createPurchase(self, data):
'''创建ERP采购单'''
print(data)
arr = json.loads(data)
where = {
'pur_entry_id' : arr['purEntryId'],
}
purchase_id = self.db.table('erp_purchase').getField(where, 'purchase_id')
if None == purchase_id:
add = {
'sale_order_no' : arr['saleOrderNo'],
'pur_entry_id' : arr['purEntryId'],
'pur_order_no' : arr['purOrderNo'],
'supplier_name' : arr['supplierName'],
'supplier_code' : arr['supplierCode'],
'pur_material_mode' : arr['purMaterialMode'],
'pur_material_name' : arr['purMaterialName'],
'pur_qty' : arr['purQty'],
'source_type' : arr['sourceType'],
'sale_man' : arr['Saleman'],
'pur_entry_seq' : arr['purEntrySeq'],
'pur_order_bizdate' : int(time.mktime(time.strptime(arr['purOrderBizDate'], '%Y-%m-%d'))),
}
purchase_id = self.db.table('erp_purchase').insert(add)
return apiReturn(0, '', purchase_id)
def apiReturn(err_code = 0, err_msg = '', data = None):
'''格式返回'''
res = {'err_code' : err_code, 'err_msg' : err_msg}
if data != None:
res['data'] = data
else:
res['data'] = ''
print(res)
return json.dumps(res)
def global_auth(user, pwd):
'''全局登录3小时'''
res = check(user, pwd)
if res == False:
return False
redis = Redis(config['RedisConf'].ichunt)
redis.set(config['ErpConf'].erp_redis_auth_key, user, 3600*3);
return True
def check(user, pwd):
'''校验登录'''
client = config['ErpConf'].erp_client[user] if user in config['ErpConf'].erp_client.keys() else None
if client != pwd:
return False
return True
def before(name, args, byref, context):
arg = {}
if len(args) > 0:
arg = json.loads(args[0])
user = arg['user'] if 'user' in arg.keys() else None
pwd = arg['pwd'] if 'pwd' in arg.keys() else None
#没有校验登录
if user == None or pwd == None:
#是否已全局登录
redis = Redis(config['RedisConf'].ichunt)
if redis.get(config['ErpConf'].erp_redis_auth_key) == None:
raise Exception('login error')
elif check(user, pwd) == False:
raise Exception('login error')
if __name__ == '__main__':
pass
#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Date : 2018-01-03 17:40:18
# @Author : yc ()
# @Link :
# @Version : Id
from core.base import *
from core.lib.rbmq import Rbmq
from core.lib.request import Request
from core.lib.exceptions import EmptyException
from core.func.common import *
from sync.conf.base import BaseConf
from suds.client import Client
import time, json, traceback
class web2erp_track(base):
'''跟踪订单明细的采购轨迹'''
def __init__(self, data=None):
super().__init__(data)
self.needupdate_url = self.CommonConf.order_api_url + '/order/track/needupdate'
self.create_url = self.CommonConf.order_api_url + '/order/track/create'
self.audit_url = self.CommonConf.order_api_url + '/order/getrecaudit'
self.request = Request()
self.rbmq = Rbmq(self.RbmqConf.business)
self.client = Client(self.CommonConf.erp_wsdl_order)
self.start()
def start(self):
'''开启轮询'''
while True:
if self._global.extend == 'publish':
#生产
try:
self.publish()
except EmptyException as e:
pass
except Exception as e:
self.elkReport('订单明细轨迹推送任务失败')
else:
#消费
#队列监听为即时
self.rbmq.listen(BaseConf.erp_follow_queue, self.consume, self.consume_fail)
time.sleep(60)
def publish(self):
'''生产'''
if self.rbmq.queue(BaseConf.erp_follow_queue).len() <= 0:
datas = self.request.postUrl(self.needupdate_url, {'order_goods_type' : 1})
if None == datas:
raise EmptyException()
arr = json.loads(datas)
for data in arr['data']:
self.rbmq.queue(BaseConf.erp_follow_queue).publish(data)
print(len(arr['data']))
def consume(self, body):
'''消费 eg:{"rec_id": 3052, "erp_rec_id": "0", "order_id": 2492, "order_goods_type": 1, "max_type": null}'''
print(body)
body_arr = json.loads(body)
post = []
#读取最新的路径
max_type = 1 if None == body_arr['max_type'] else int(body_arr['max_type']) + 1
if max_type == 1:
#查订单审核数据
res = self.request.postUrl(self.audit_url, {'rec_id' : body_arr['rec_id']})
if None == res:
raise Exception('rec_id %s,请求查询审核接口失败' % (body_arr['rec_id'], ))
audit_arr = json.loads(res)
if audit_arr['errcode'] != 0:
raise Exception(audit_arr['errmsg'])
#记录审核数据
post.append({
'rec_id' : body_arr['rec_id'],
'order_id' : body_arr['order_id'],
'order_goods_type' : body_arr['order_goods_type'],
'track_type' : 1,
'track_num' : audit_arr['data']['goods_number'],
'create_name' : audit_arr['data']['sale_name'],
'create_time' : audit_arr['data']['confirm_time'],
'relevance_sn' : audit_arr['data']['order_sn'],
})
#ERP查询轨迹
data = {
'ORDERENTRYID' : body_arr['erp_rec_id']
}
# arr = eval("[{'NUMBER': 'LQJ-SZ201907290001', 'BIZDATE': '2019-07-29 00:00:00', 'SEQ': '2', 'CREATOR': '龙桥均', 'QTY': '10000'}, {'NUMBER': 'PUI2019019507', 'BIZDATE': '2019-07-29 13:21:16', 'SEQ': '10', 'CREATOR': '龙桥均', 'QTY': '10000', 'LOGISTICSNUMBER':'x2222222', 'CARRIER':'顺丰'}]")
try:
res = self.client.service.getPTorderStatus(json.dumps(data))
except Exception as e:
res = None
if res == None:
raise Exception('rec_id %s,获取ERP轨迹失败:请求失败' % (body_arr['rec_id'], ))
arr = json.loads(res)
for items in arr:
#只更新接下来的轨迹
if max_type <= int(items['SEQ']):
post.append({
'rec_id' : body_arr['rec_id'],
'order_id' : body_arr['order_id'],
'order_goods_type' : body_arr['order_goods_type'],
'track_type' : items['SEQ'],
'track_num' : items['QTY'] if 'QTY' in items.keys() else 0,
'create_name' : items['CREATOR'] if 'CREATOR' in items.keys() else '',
'create_time' : int(time.mktime(time.strptime(items['BIZDATE'], '%Y-%m-%d %H:%M:%S'))) if 'BIZDATE' in items.keys() and items['BIZDATE'] not in ['', None] else 0,
'relevance_sn' : items['NUMBER'] if 'NUMBER' in items.keys() else '',
'shipping_name' : items['CARRIER'] if 'CARRIER' in items.keys() else '',
'shipping_no' : items['LOGISTICSNUMBER'] if 'LOGISTICSNUMBER' in items.keys() else '',
})
if post == []:#没有可添加数据
return
res = self.request.postUrl(self.create_url, {'data': post})
if None == res:
raise Exception('rec_id %s,创建轨迹失败:请求失败%s' % (body_arr['rec_id'], self.request._error))
arr = json.loads(res)
if arr['errcode'] not in [0, 102029]:#相同类型
raise Exception('rec_id %s,创建轨迹失败:code=%s msg=%s' % (body_arr['rec_id'], arr['errcode'], arr['errmsg']))
def consume_fail(self, body, res, msg):
'''消费失败通知'''
self.elkReport('订单明细轨迹消费任务失败', False)
if __name__ == '__main__':
pass
++ "a/\346\226\260\345\273\272\346\226\207\346\234\254\346\226\207\346\241\243.txt"
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or sign in to comment