Commit 588c0966 by chenxx

新增表dj_2023_settle_details dj_2023_settle_details_record

1 parent 87be3cc4
......@@ -25,7 +25,7 @@ logger.addHandler(cnslhandler)
g_supply_dbcfg = {'host': '192.168.5.23', 'port': 3306, 'user': 'data_house_user', 'passwd': 'ZhaiMiAxIg',
'db': 'glsx_supplychain', 'charset': 'utf8'}
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
g_pro_biz_dbcfg = {'host': '192.168.5.1', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
g_presto_host = '192.168.5.35'
g_presto_port = 9090
......@@ -46,6 +46,22 @@ monthDict = {
}
newMonthDict = {
'2022年1月':'2022-01',
'2022年2月':'2022-02',
'2022年3月':'2022-03',
'2022年4月':'2022-04',
'2022年5月':'2022-05',
'2022年6月':'2022-06',
'2022年7月':'2022-07',
'2022年8月':'2022-08',
'2022年9月':'2022-09',
'2022年10月':'2022-10',
'2022年11月':'2022-11',
'2022年12月':'2022-12',
}
def calc_hardware_cost():
'''计算硬件成本'''
bizConn = MySQL(g_pro_biz_dbcfg)
......@@ -314,9 +330,107 @@ def calc_cost_duplicate_device(type = 1):
logger.info("calc_cost_duplicate_device done, total=%d", total)
def calc_2022_cost():
"""
计算22年成本
:return:
"""
'''计算硬件成本'''
bizConn = MySQL(g_pro_biz_dbcfg)
#t_hardware_cost_bill_2021_10_12
sql = "select finmonth,settle_merchant,total,amount from dj_2022_hardware_cost_bill "
if not bizConn.query(sql):
logger.error("calc_hardware_cost fail, sql=%s", sql)
return
res = bizConn.fetchAllRows()
monthFormat = "'%Y-%m'"
for v in res:
month = v[0]
settleMonth = newMonthDict.get(month, None)
if settleMonth is None:
continue
settleMerchant = v[1]
if settleMerchant in ('广汇','上海宝信实嘉汽车销售有限公司天津武清分公司','东台宝通汽车服务有限责任公司','东台宝通汽车服务有限责任公司'):
settleMerchant = '广汇汽车'
total = v[2]
if total is None:
continue
amount = float(v[3])
if total > 0:
tblName = 'dj_2021_settle_details'
else:
tblName = 'dj_2021_settle_details_return'
querySql = f"select count(1) from {tblName} where device_type = 8 and settle_time >= '2022-01-01' " \
f"and settle_merchant like '%{settleMerchant}%' and date_format(settle_time, '%Y-%m')='{settleMonth}'"
#logger.info(querySql)
if not bizConn.query(querySql):
logger.error("calc_2022_hardware_cost fail, sql=%s", querySql)
return
result = bizConn.fetchAllRows()
details_total = 0
for row in result:
details_total = row[0]
if details_total != total:
logger.warning(f"calc_2022_hardware_cost {settleMerchant} {settleMonth} {amount} finTotal={total} details_total={details_total}")
if details_total == 0:
continue
# details_total:2022年每个月的对应结算商户的GPS,OBD硬件总数量 amount: 2022每月GPS设备总成本金额 price: 022年每个月的对应结算商户的每个硬件的成本价格 hw_cost:每个硬件价格 price=hw_cost
price = amount/details_total
updateSql = f"update {tblName} set hw_cost={price} where device_type = 8 and settle_time >= '2022-01-01' " \
f"and settle_merchant like '%{settleMerchant}%' and date_format(settle_time, '%Y-%m')='{settleMonth}'"
if not bizConn.update(updateSql):
logger.info(f"failed, updateSql = {updateSql}")
logger.info(f"calc_2022_cost month={settleMonth} settlemer={settleMerchant} total={total} "
f"details_total={details_total} amount={amount} price={price}")
'''
querySql = "select channel,sn,settle_time,active_time,pk_period from {} where settle_time >= '2022-01-01' and " \
"settle_merchant like '%{}%' " \
"and date_format(settle_time, {})='{}' limit {}".format(tblName, settleMerchant, monthFormat, settleMonth, total)
logger.info(querySql)
if not bizConn.query(querySql):
logger.error("calc_hardware_cost fail, sql=%s", querySql)
return
result = bizConn.fetchAllRows()
if len(result) != total:
logger.info("calc_hardware_cost month=%s settlemer=%s total=%d price=%f find=%d",
settleMonth, settleMerchant, total, price, len(result))
arrValues = []
for row in result:
channel = row[0]
sn = row[1]
settleTime = row[2]
activeTime = row[3]
period = row[4]
strValue = "(%s,%s,%s,%s,%s,%s,%s)" % (paddstr(channel), paddstr(sn), paddstr(settleTime),
paddstr(activeTime), paddnum(period),
paddstr(settleMerchant), paddnum(price))
arrValues.append(strValue)
if len(arrValues) > 0:
insertSql = "insert into t_hardware_cost (mer_type,sn,settle_time,active_time," \
"period,settle_merchant,price) values " + ",".join(arrValues)
if not bizConn.insert(insertSql):
logger.error("calc_hardware_cost fail, sql=%s ", insertSql)
return
'''
logger.info("calc_2022_hardware_cost done")
if __name__ == '__main__':
'''计算'''
calc_hardware_cost()
#calc_hardware_cost()
#calc_install_cost()
......@@ -326,6 +440,10 @@ if __name__ == '__main__':
#calc_cost_duplicate_device(type=1)
"""计算22年成本明细数据"""
calc_2022_cost()
......
......@@ -6,9 +6,11 @@ import logging
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
'''
g_pro_biz_dbcfg = {'host': '192.168.5.25', 'port': 3310, 'user': 'biz_device_detail', 'passwd': 'M6khz3CQ',
'db': 'device_detail',
'charset': 'utf8'}
'''
def get_months(begin, end):
......@@ -72,6 +74,8 @@ def calc_income_share(calcType='收入'):
计算收入的分摊
:return:
"""
tblName = "dj_device_details"
tblName = 'dj_2021_settle_details'
fileName = calcType + ".csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
......@@ -80,18 +84,20 @@ def calc_income_share(calcType='收入'):
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month," \
f"DATE_FORMAT(active_time,'%Y-%m') as active_month,COUNT(1) as count," \
f"sum(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel " \
f"from dj_device_details where settle_time < '2022-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel " \
f"order by settle_month"
f"sum(IFNULL(pk_price,0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel," \
f"case when `return`=1 then '退货' else '正常' end " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel,`return` " \
f"order by settle_merchant,settle_month"
elif calcType == '成本':
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month," \
f"DATE_FORMAT(active_time,'%Y-%m') as active_month,COUNT(1) as count," \
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
f"from dj_device_details where settle_time < '2022-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel " \
f"order by settle_month"
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel, " \
f"case when `return`=1 then '退货' else '正常' end " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),DATE_FORMAT(active_time,'%Y-%m'),channel,`return` " \
f"order by settle_merchant,settle_month"
if not bizConn.query(sql):
return
......@@ -100,7 +106,7 @@ def calc_income_share(calcType='收入'):
headName = f"客户名称,渠道,服务期限,数量,结算月份,不含税收入,开始计费月份,结束计费月份,不含税单价,月摊收入,"\
f"2017年摊销金额,2017年末累计摊销余额,2018年摊销金额,"\
f"2018年末累计摊销余额,2019年摊销金额,2019年末累计摊销余额,2020年摊销金额,2020年末累计摊销余额,2021年摊销金额,"\
f"2021年末累计摊销余额,2022年摊销金额,2022年末累计摊销余额,产品分类,激活开始月份,激活结束月份 \n"
f"2021年末累计摊销余额,2022年摊销金额,2022年末累计摊销余额,产品分类,激活开始月份,激活结束月份,是否退货,研发开始分摊月份 \n"
fileHandle.write(headName)
for row in result:
settleMer = row[0]
......@@ -116,6 +122,7 @@ def calc_income_share(calcType='收入'):
total = row[5]
amount = row[6]
channel = row[7]
returnFlag = row[8]
if active_month is None:
start_share = '2025-12'
......@@ -126,14 +133,18 @@ def calc_income_share(calcType='收入'):
active_start_month = datetime.datetime.strptime(start_share, '%Y-%m')
active_end_month = active_start_month + relativedelta(months=period) - relativedelta(days=1)
# 代销从结算时间开始
if (channel == '代销' or channel == '广汇') and (active_start_month == '' or active_start_month < settle_end_month):
start_share = settle_start_month
#
elif (channel == '直销' and settle_start_month >= '2022-01') and (active_start_month == '' or active_start_month < settle_end_month):
start_share = settle_start_month
start_share_month = datetime.datetime.strptime(start_share, '%Y-%m')
end_share_month = start_share_month + relativedelta(months=period) - relativedelta(days=1)
price = amount / total
share_per_month = amount / period
share_per_month = amount / period #share_per_month: 每年每月摊销多少
'''
gap_2018_months = get_months(start_share_month, datetime_2017_end)
......@@ -175,7 +186,7 @@ def calc_income_share(calcType='收入'):
f"{settle_end_month},{price},{share_per_month},{share_2017},{remainShare2017},{share_2018},"\
f"{remainShare2018},{share_2019},{remainShare2019},{share_2020},{remainShare2020},"\
f"{share_2021},{remainShare2021},{share_2022},{remainShare2022},{devName},"\
f"{active_start_month},{active_end_month}\n"
f"{active_start_month},{active_end_month},{returnFlag},{start_share_month}\n"
fileHandle.write(lineName)
fileHandle.close()
......@@ -185,6 +196,8 @@ def calc_return_share(calcType):
退货
:return:
"""
tblName = 'dj_2021_settle_details_return'
fileName = calcType + ".csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
......@@ -192,16 +205,16 @@ def calc_return_share(calcType):
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count," \
f"sum(IFNULL(hw_cost,0) + IFNULL(install_cost, 0) ) as amount, channel " \
f"from dj_device_details_return where settle_time < '2022-01-01 00:00:00' and device_type = 8 " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),channel " \
f"order by settle_month"
f"order by settle_merchant,settle_month"
elif calcType == '退货收入':
sql = f"select settle_merchant,case when device_type=8 then '追踪器' when device_type=6 then '记录仪' when device_type=12501 then '车充' end," \
f"pk_period,DATE_FORMAT(settle_time, '%Y-%m') as settle_month,COUNT(1) as count," \
f"sum(0-IFNULL(pk_price, 0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel " \
f"from dj_device_details_return where settle_time < '2022-01-01 00:00:00' and device_type = 8 " \
f"sum(IFNULL(pk_price, 0) + IFNULL(hw_price, 0) + IFNULL(install_price, 0)) as amount, channel " \
f"from {tblName} where settle_time < '2023-01-01 00:00:00' and device_type = 8 " \
f"GROUP BY settle_merchant,device_type,pk_period,DATE_FORMAT(settle_time, '%Y-%m'),channel " \
f"order by settle_month"
f"order by settle_merchant,settle_month"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
......@@ -265,5 +278,5 @@ def calc_return_share(calcType):
if __name__ == "__main__":
calc_income_share(calcType='收入')
calc_income_share(calcType='成本')
#calc_return_share('退货收入')
#calc_return_share('退货成本')
calc_return_share('退货收入')
calc_return_share('退货成本')
File mode changed
......@@ -31,7 +31,7 @@ g_dev_biz_dbcfg = {'host': '192.168.3.227', 'port': 3306, 'user': 'dev_admin', '
'db': 'glsx_biz_data', 'charset': 'utf8'}
fetchsize = 1500
env = 'dev'
env = 'pro'
if env == 'dev':
g_papdev_dbcfg = {'host': '47.115.93.31', 'port': 3307, 'user': 'user_zhaimx', 'passwd': 'dOCN0L7i',
'db': 'glsx_pap', 'charset': 'utf8'}
......@@ -236,6 +236,7 @@ def sync_car_permanent(dataFrom):
logger.info ("sync_car_permanent progress count=%d" % count)
updateTableSynLog(auditConn, tblName, startId)
def sync_car_maintain(dataFrom, fromTime):
'''同步维修保养'''
fetch = fetchsize
......@@ -251,15 +252,17 @@ def sync_car_maintain(dataFrom, fromTime):
strColunms = "sn,stand_no,total_mileage,in_time,prev_mileage,first_time," \
"remind_type,remind_rule,diff_mileage,diff_time,is_new,number_of_shops," \
"numbers,distance,svrtime,merchant_id,merchant_name,created_by,created_date,updated_by,deleted_flag," \
"numbers,distance,svrtime,merchant_id,merchant_name,created_by,created_date,updated_by,deleted_flag"
'''
"plate_number,name,mobile,current_day_time,company,car_brand,car_model,car_system,regist_time,insurance_time," \
"status,diff_backshop_mileage,diff_backshop_time,vehicle_id,follow_result,follow_time,follow_remarks,maintain_source" \
'''
bizscreenConn = MySQL(g_biz_dbcfg)
startId = getTableSyncLog(auditConn,tblName)
count = 0
while (True):
sql = "select id,%s from dj_car_maintain where in_time>'%s' and id > %d and deleted_flag = 'N' order by id limit %d" % (
sql = "select id,%s from dj_car_maintain where svrtime>'%s' and svrtime<'2023-01-01' and id > %d and deleted_flag = 'N' order by id limit %d" % (
strColunms, fromTime, startId, fetch)
if False == srcDbConn.query(sql):
logger.error("sync_car_maintain query error, sql=" + sql)
......@@ -267,8 +270,8 @@ def sync_car_maintain(dataFrom, fromTime):
arrValues = []
result = srcDbConn.fetchAllRows()
for v in result:
arr = [];
id = int(v[0]);
arr = []
id = int(v[0])
count += 1
if id > startId:
startId = id
......@@ -276,7 +279,7 @@ def sync_car_maintain(dataFrom, fromTime):
sn = v[1]
fkInfo = g_dev_map_dict.get(sn,None)
if fkInfo is None:
logger.warn("sync_car_maintain can not find fksn, sn=%s",sn)
logger.warning("sync_car_maintain can not find fksn, sn=%s",sn)
continue
sn = fkInfo.sn
merId = fkInfo.merId
......@@ -285,7 +288,7 @@ def sync_car_maintain(dataFrom, fromTime):
svrtime = str(v[15])
strAddSvtTime = str(v[15] + relativedelta(days=-30))
if fkInfo.activeTime > strAddSvtTime:
logger.warn("sync_car_maintain svrtime=%s activetime=%s",svrtime,fkInfo.activeTime)
logger.warning("sync_car_maintain svrtime=%s activetime=%s",svrtime,fkInfo.activeTime)
continue
arr.append(paddstr(sn));arr.append(paddstr(v[2]));arr.append(paddnum(v[3]));arr.append(paddstr(v[4]));
......@@ -294,11 +297,13 @@ def sync_car_maintain(dataFrom, fromTime):
arr.append(paddnum(v[13]));arr.append(paddnum(v[14]));arr.append(paddstr(str(v[15]))); arr.append(paddnum(merId))
arr.append(paddstr(merName));arr.append(paddstr(v[18]));arr.append(paddstr(v[19]));arr.append(paddstr(v[20]));arr.append(paddstr(v[21]))
'''
arr.append(paddstr(v[22]));arr.append(paddstr(v[23]));arr.append(paddstr(v[24]));arr.append(paddstr(v[25]))
arr.append(paddstr(v[26]));arr.append(paddstr(v[27]));arr.append(paddstr(v[28]));arr.append(paddstr(v[29]))
arr.append(paddstr(v[30]));arr.append(paddstr(v[31]));arr.append(paddnum(v[32]));arr.append(paddnum(v[33]))
arr.append(paddnum(v[34]));arr.append(paddnum(v[35]));arr.append(paddnum(v[36]));arr.append(paddstr(v[37]))
arr.append(paddstr(v[38]));arr.append(paddnum(v[39]))
'''
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(result) == 0:
......@@ -309,7 +314,7 @@ def sync_car_maintain(dataFrom, fromTime):
if False == bizscreenConn.insert(insSql):
logger.error ("sync_car_maintain dst_conn.insert failed:%s" % insSql)
break
logger.info ("sync_car_maintain progress count=%d" % count)
logger.info (f"sync_car_maintain dataFrom={dataFrom} progress count={count}" % count)
updateTableSynLog(auditConn, tblName, startId)
......@@ -406,7 +411,7 @@ def sync_car_loss_warning(dataFrom, fromTime):
startId = getTableSyncLog(auditConn,tblName)
count = 0
while (True):
sql = "select id,%s from dj_car_loss_warning where trigger_time >='%s' and id > %d and deleted_flag = 'N' order by id limit %d" % (
sql = "select id,%s from dj_car_loss_warning where trigger_time >='%s' and trigger_time < '2023-01-01' and and id > %d and deleted_flag = 'N' order by id limit %d" % (
strColunms, fromTime, startId, fetch)
if False == srcDbConn.query(sql):
logger.error("sync_car_loss_warning query error, sql=" + sql)
......@@ -469,13 +474,13 @@ def sync_car_shop_warning(dataFrom, fromTime):
auditConn = MySQL(g_biz_dbcfg)
strColunms = "sn,stand_no,enter_time,out_time,trigger_time,alarm_type,is_new,last_time_distance,last_time_day," \
"merchant_id,merchant_name,created_by,created_date,updated_by,updated_date,deleted_flag," \
"plate_number,name,mobile,merchant_type,task_id,vehicle_id"
"merchant_id,merchant_name,created_by,created_date,updated_by,updated_date,deleted_flag"
#"plate_number,name,mobile,merchant_type,task_id,vehicle_id"
bizscreenConn = MySQL(g_biz_dbcfg)
startId = getTableSyncLog(auditConn,tblName)
count = 0
while (True):
sql = "select id,%s from dj_car_shop_warning where trigger_time>='%s' and id > %d and deleted_flag = 'N' order by id limit %d" % (
sql = "select id,%s from dj_car_shop_warning where trigger_time>='%s' and trigger_time < '2023-01-01' and id > %d and deleted_flag = 'N' order by id limit %d" % (
strColunms, fromTime, startId, fetch)
if False == srcDbConn.query(sql):
logger.error("sync_car_shop_warning query error, sql=" + sql)
......@@ -492,7 +497,7 @@ def sync_car_shop_warning(dataFrom, fromTime):
sn = v[1]
fkInfo = g_dev_map_dict.get(sn,None)
if fkInfo is None:
logger.warn("sync_car_shop_warning can not find fksn, sn=%s",sn)
#logger.warning("sync_car_shop_warning can not find fksn, sn=%s",sn)
continue
sn = fkInfo.sn
merId = fkInfo.merId
......@@ -500,7 +505,7 @@ def sync_car_shop_warning(dataFrom, fromTime):
triggtime = str(v[3])
if fkInfo.activeTime > triggtime:
logger.warn("sync_car_shop_warning triggtime=%s activetime=%s",triggtime,fkInfo.activeTime)
logger.warning("sync_car_shop_warning triggtime=%s activetime=%s",triggtime,fkInfo.activeTime)
continue
arr.append(paddstr(sn));arr.append(paddstr(v[2]));arr.append(paddstr(v[3]));arr.append(paddstr(v[4]))
......@@ -508,8 +513,10 @@ def sync_car_shop_warning(dataFrom, fromTime):
arr.append(paddnum(v[9]));arr.append(paddnum(merId));arr.append(paddstr(merName))
arr.append(paddstr(v[12]));arr.append(paddstr(v[13]));arr.append(paddstr(str(v[14]))); arr.append(paddstr(v[15]))
arr.append(paddstr(v[16]))
'''
arr.append(paddstr(v[17]));arr.append(paddstr(v[18]));arr.append(paddstr(v[19]));arr.append(paddnum(v[20]))
arr.append(paddstr(v[21]));arr.append(paddnum(v[22]))
'''
value = "(" + ",".join(arr) + ")"
arrValues.append(value)
if len(result) == 0:
......@@ -520,7 +527,7 @@ def sync_car_shop_warning(dataFrom, fromTime):
if False == bizscreenConn.insert(insSql):
logger.error ("sync_car_shop_warning dst_conn.insert failed:%s" % insSql)
break
logger.info ("sync_car_shop_warning progress count=%d" % count)
logger.info (f"sync_car_shop_warning datafrom={dataFrom} progress count={count}" )
updateTableSynLog(auditConn, tblName, startId)
......@@ -1486,7 +1493,7 @@ def sync_ddh_rescue_event(fromTime):
"CREATED_DATE,UPDATED_BY,UPDATED_DATE,DELETED_FLAG,is_emphasis_merchant," \
"is_show,DEVICE_ID,TYPE_ID,model_result"
sql = "select " + strColunms + " from ddh_rescue_event where EVENT_DATE>'%s' " % fromTime
sql = "select " + strColunms + " from ddh_rescue_event where EVENT_DATE>'%s' and EVENT_DATE < '2023-01-01' " % fromTime
if False == ddhConn.query(sql):
print ("sync_ddh_rescue_event fail,sql=%s"%sql)
return
......@@ -1551,30 +1558,22 @@ def sync_ddh_rescue_event(fromTime):
print ("sync_ddh_rescue_event done count=%d" % total)
def sync_cluses(fromTime='2022-03-01'):
''''''
#sync_car_collision('DJ', fromTime)
#sync_car_collision('GUARD', fromTime)
#ync_car_loss_warning('DJ', fromTime)
#ync_car_loss_warning('GUARD', fromTime)
def sync_cluses(fromTime='2022-01-01'):
#sync_car_maintain('DJ', fromTime)
sync_car_maintain('DJ', fromTime)
sync_car_maintain('GUARD', fromTime)
#sync_car_shop_warning('DJ', fromTime)
sync_car_shop_warning('DJ', fromTime)
sync_car_shop_warning('GUARD', fromTime)
#sync_car_permanent('DJ', fromTime)
#sync_car_permanent('GUARD', fromTime)
sync_ddh_rescue_event(fromTime)
if __name__ == "__main__":
''''''
#query_cache_dev_mapping()
sync_cluses(fromTime='2022-03-01')
query_cache_dev_mapping()
sync_cluses(fromTime='2022-01-01')
#ync_car_collision_ddh()
......
......@@ -805,20 +805,20 @@ def update_device_alloc(deviceType, startTime, endTime):
if __name__ == "__main__":
''''''
startTime = '2022-09-01'
endTime = '2022-12-01'
startTime = '2022-01-01'
endTime = '2022-02-01'
#追踪器设备
#match_gen_sn_settlement_delivery_order(startTime, devType=8, prefix='19')
#记录仪设备
match_gen_sn_settlement_delivery_order(startTime, devType=6, prefix='SH23G')
#match_gen_sn_settlement_delivery_order(startTime, devType=6, prefix='SH23G')
#'SH26H', 'SH23G', 'SH24G'
#车充设备
#match_gen_sn_settlement_delivery_order(startTime, devType=12501, prefix='864')
match_gen_sn_settlement_delivery_order(startTime, devType=12501, prefix='864')
#回滚分配的设备
# update_device_alloc(8, startTime, endTime)
# update_device_alloc(6, startTime, endTime)
#update_device_alloc(8, startTime, endTime)
#update_device_alloc(6, startTime, endTime)
......
import random
from MysqlUtility import MySQL, paddstr, paddnum
import datetime
from dateutil.relativedelta import relativedelta
from calc_dj_income_2021 import calc_not_direct_device_active_time, query_settlement_merchant,ShopMerSales
import logging
g_pro_biz_dbcfg = {'host': '192.168.5.20', 'port': 3306, 'user': 'biz_glsx_data', 'passwd': 'unEKczDc',
'db': 'glsx_biz_data', 'charset': 'utf8'}
g_settle_merchant_dict = {}
def modify_merchant_channel():
"""
修改明细数据的分类,涉及到激活时间及发货时间的调整
:return:
"""
fileName = "直销变渠道.csv"
fileHandle = open(file=fileName, mode='w', encoding="utf-8")
bizConn = MySQL(g_pro_biz_dbcfg)
query_settlement_merchant(bizConn, g_settle_merchant_dict)
sql = "select settle_mer,channel from dj_2022_settlemer_channel"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
new_mer_channel_dict = {}
for row in result:
settle_merchant = row[0]
channel = row[1]
new_mer_channel_dict[settle_merchant] = channel
sql = "SELECT settle_merchant,channel,DATE_FORMAT(settle_time, '%Y-%m'),count(1) FROM dj_2021_settle_details " \
"where settle_time >= '2022-01-01' GROUP BY settle_merchant,channel,DATE_FORMAT(settle_time, '%Y-%m')"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
total_diff = 0
z_2_q_diff = 0
q_2_z_diff = 0
headName = f"客户名称,结算月份,旧分类,新分类,数量\n"
fileHandle.write(headName)
for row in result:
settle_merchant = row[0]
channel = row[1]
settle_month = row[2]
total = row[3]
new_channel = new_mer_channel_dict.get(settle_merchant)
if channel != new_channel:
line = f"{settle_merchant },{settle_month},{channel},{new_channel},{total}\n"
fileHandle.write(line)
print(line.strip("\n"))
total_diff += 1
#直销变渠道
if new_channel == '渠道':
z_2_q_diff += 1
#将该月设备激活时间清空,发货时间为结算当月
change_zx_to_qd(bizConn, settle_merchant, settle_month)
elif new_channel == "直销":
q_2_z_diff += 1
#将该月设备激活时间设置为结算时间之前,发货时间在激活时间之前
change_qd_to_zx(bizConn, settle_merchant, settle_month)
fileHandle.close()
print(f"total diff = {total_diff} new channel diff={z_2_q_diff}")
def change_zx_to_qd(dbconn, settle_merchant, settle_month):
"""
直销变为渠道,需要将该月设备激活时间清空,发货时间为结算当月
:param dbconn:
:param settle_merchant:
:param settle_month:
:return:
"""
print(f"update settle_merchant={settle_merchant} settle_month={settle_month} 渠道 start")
sql = f"select id,delivery_time,settle_time from dj_2021_settle_details " \
f"where settle_merchant = '{settle_merchant}' and DATE_FORMAT(settle_time, '%Y-%m') = '{settle_month}'"
if not dbconn.query(sql):
print(sql)
return
result = dbconn.fetchAllRows()
for row in result:
idx = row[0]
delivery_time = row[1]
settle_time = row[2]
new_delivery_time = delivery_time.replace(month=settle_time.month, day=settle_time.day)
#print(f"sn={sn}, delivery_time={delivery_time}, settle_time={settle_time}, new_settle_time={new_delivery_time}")
updateSql = f"update dj_2021_settle_details set channel='渠道', delivery_time='{new_delivery_time}'," \
f"active_time=null,active_merchant=null where id={idx}"
#print(f"{updateSql}")
if not dbconn.update(updateSql):
return
print(f"update settle_merchant={settle_merchant} settle_month={settle_month} 渠道 done")
def change_qd_to_zx(dbconn, settle_merchant, settle_month):
"""
渠道变为直销,需要将该月设备激活时间设置为结算时间之前,发货时间在激活时间之前
:param bizConn:
:param settle_merchant:
:param settle_month:
:return:
"""
print(f"update settle_merchant={settle_merchant} settle_month={settle_month} 直销 start")
sql = f"select id,delivery_time,settle_time,active_time from dj_2021_settle_details " \
f"where settle_merchant = '{settle_merchant}' and DATE_FORMAT(settle_time, '%Y-%m') = '{settle_month}'"
if not dbconn.query(sql):
print(sql)
return
result = dbconn.fetchAllRows()
random_month = random.randint(1,3)
random_day = random.randint(1, 5)
for row in result:
idx = row[0]
delivery_time = row[1]
settle_time = row[2]
active_time = row[3]
new_delivery_time = settle_time - relativedelta(months=random_month)
new_delivery_time = new_delivery_time - relativedelta(months=random_day)
new_active_time = calc_not_direct_device_active_time(new_delivery_time, settle_time)
new_active_merchant = getRandomActiveMerchant(settle_merchant)
#print(f"sn={sn}, delivery_time={delivery_time}, settle_time={settle_time}, new_settle_time={new_delivery_time}")
updateSql = f"update dj_2021_settle_details set channel='直销', delivery_time='{new_delivery_time}'," \
f"active_time='{new_active_time}',active_merchant='{new_active_merchant}' where id={idx}"
#print(f"{updateSql}")
if not dbconn.update(updateSql):
return
print(f"update settle_merchant={settle_merchant} settle_month={settle_month} 直销 done")
def getRandomActiveMerchant(settle_merchant):
"""
获取随机激活门店
:param settle_merchant:
:return:
"""
settMerInfo = g_settle_merchant_dict.get(settle_merchant, None)
shopList = []
if settMerInfo is not None:
shopList = settMerInfo.shopList
else:
shopInfo = ShopMerSales()
shopInfo.merName = settle_merchant
shopList.append(shopInfo)
activeMerchant = random.choice(shopList)
shopName = activeMerchant.merName
return shopName
if __name__ == '__main__':
modify_merchant_channel()
print("done")
\ No newline at end of file
File mode changed
File mode changed
......@@ -62,8 +62,18 @@ LEFT JOIN dj_system_merchant B ON (A.active_merchant = B.merchant_name)
def add_unmatch_merchant():
'''未匹配的商户'''
settleMerList = [
'兰州超凡汽车用品有限公司',
'长沙县湘龙街道达阳汽车用品商行',
'石家庄岚申汽车销售有限公司',
'太原远方通贸易有限公司',
'湖北欧特隆汽车用品超市有限公司',
'甘肃深联俊飞商贸有限公司',
'广州远晟电子科技有限公司',
'贵州林荣汽车装饰服务有限公司',
'哈尔滨市博能汽车销售有限公司',
'济南新中兴汽车用品有限责任公司',
'厦门盈鹭通汽车服务有限公司',
'深圳市乐亿企业服务有限公司',
'云南隆创尚通汽车销售服务有限公司'
]
#settleMerchant = '庞大精配网(天津)网络科技有限公司'
......@@ -595,10 +605,47 @@ def update_device_type():
return
print(updateSql)
def update_active_merchant_new_settle_details():
'''森风集团'''
bizConn = MySQL(g_pro_biz_dbcfg)
settle_merchant_list = ['为车(沈阳)科技有限公司', '云南隆创尚通汽车销售服务有限公司', '哈尔滨市博能汽车销售有限公司',
'太原远方通贸易有限公司', '广州远晟电子科技有限公司', '庞大精配网(天津)网络科技有限公司',
'赣州兴康汽车销售服务有限公司', '赣州祥荣汽车销售服务有限公司', '甘肃深联俊飞商贸有限公司',
'石家庄岚申汽车销售有限公司', '精一门(天津)科技有限公司', '诺言金鼎商贸(北京)有限公司']
for settle_merchant in settle_merchant_list:
merchantList = []
sql = f"SELECT merchant_name from dj_system_merchant where settle_merchant_name = '{settle_merchant}'"
if not bizConn.query(sql):
return
result = bizConn.fetchAllRows()
for v in result:
merchantList.append(f"'{v[0]}'")
if len(merchantList) == 0:
logger.warning(f"update_active_merchant_new_settle_details not found settle_merchant {settle_merchant}")
continue
sql = f"select id,active_merchant from dj_2021_settle_details where settle_time >= '2022-01-01' and active_time is not null " \
f"and settle_merchant = '{settle_merchant}' and active_merchant not in ({','.join(merchantList)})"
if not bizConn.query(sql):
return
res = bizConn.fetchAllRows()
for row in res:
idx = row[0]
activeMer = random.choice(merchantList)
updateSql = "update dj_2021_settle_details set active_merchant = %s where id = %d" % (activeMer, idx)
if not bizConn.update(updateSql):
logger.error("update_active_merchant_new_settle_details settlemer=%s, sql=%s", updateSql)
return
logger.info(f"update_active_merchant_new_settle_details {settle_merchant}")
logger.info("update_active_merchant_new_settle_details done")
if __name__ == "__main__":
''''''
#update_device_type()
#random_active_time_hour(2022)
random_active_time_hour(2022)
#update_merchant_createtime()
......@@ -622,6 +669,9 @@ if __name__ == "__main__":
#update_customer_saletype()
#update_active_merchant_new_settle_details()
......
This diff could not be displayed because it is too large.
This diff could not be displayed because it is too large.
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!