deal02_yang.py
11.8 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
import logging
import time
from datetime import datetime
from decimal import Decimal
from itertools import groupby
from dateutil.relativedelta import *
from my_utils.MysqlUtility import MySQL
logger = logging.getLogger("deal_equity_data")
logger.setLevel(logging.INFO)
fileHandler = logging.FileHandler("import.log")
fileHandler.setLevel(logging.INFO)
formatter = logging.Formatter("%(asctime)s - %(name)s - %(levelname)s - %(message)s")
cnslhandler = logging.StreamHandler()
cnslhandler.setLevel(logging.INFO)
cnslhandler.setFormatter(formatter)
logger.addHandler(cnslhandler)
# saas_shen_db_cfg = {
# "host": "192.168.3.190",
# "port": 3306,
# "user": "dev_user",
# "passwd": "df234fl",
# "db": "pinpoint",
# "charset": "utf8",
# }
saas_shen_db_cfg = {
"host": "192.168.3.222",
"port": 3306,
"user": "biz_audit",
"passwd": "hqVIs6jF",
"db": "saas_shen_ft",
"charset": "utf8",
}
def create_table():
bizConn = MySQL(saas_shen_db_cfg)
drop_table_sql = f"""
DROP TABLE temp_job_info_ft_02;
"""
bizConn.query(drop_table_sql)
create_table_sql = f"""
CREATE TABLE `temp_job_info_ft_02` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键',
`job_id` int(11) DEFAULT NULL COMMENT '订单ID',
`service_date` datetime DEFAULT NULL COMMENT '服务日期',
`shouru_price` decimal(12,2) DEFAULT NULL COMMENT '收入金额',
`chengben_price` decimal(12,2) DEFAULT NULL COMMENT '成本金额',
PRIMARY KEY (`id`),
KEY `idx_job_id` (`job_id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8 COMMENT='基础表';
"""
bizConn.query(create_table_sql)
def deal_equity_data():
bizConn = MySQL(saas_shen_db_cfg)
sql = """
SELECT `job_id`, `业务日期`, `收入`, `成本金额`, `分摊期限` FROM ds_job_info_23041302;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for row in result:
start_time = time.time()
logger.info(row)
job_id = row[0]
业务日期 = row[1]
收入 = paddnum_price(row[2])
成本金额 = paddnum_price(row[3])
分摊期限 = row[4]
分摊收入 = 收入 / 分摊期限
分摊收入 = Decimal(分摊收入).quantize(Decimal("0.00"))
分摊成本 = 成本金额 / 分摊期限
分摊成本 = Decimal(分摊成本).quantize(Decimal("0.00"))
values = buildApportionment(job_id, 业务日期, 分摊期限, 分摊收入, 分摊成本)
sql01 = f"""
INSERT INTO temp_job_info_ft_02 (job_id,service_date,shouru_price,chengben_price) VALUES {values};
"""
write_sql(sql01)
bizConn.update(sql01)
end_time = time.time()
print("程序运行时间:%s毫秒" % ((end_time - start_time) * 1000))
def buildApportionment(job_id, 业务日期, 分摊期限, 分摊收入, 分摊成本):
# 将业务日期开始时间设置为 1号 方便比较
业务日期 = 业务日期.replace(day=1)
sb = StringBuilder()
# 计算分摊的最后日期
分摊最后日期 = add_one_month(业务日期, 分摊期限)
print("分摊最后日期==", 分摊最后日期)
for i in range(181):
start_time = datetime.strptime("2013-01-01", "%Y-%m-%d")
# 添加一个月的日期
calculate_time = add_one_month(start_time, i)
if 业务日期 <= calculate_time < 分摊最后日期:
# sb.append(f'`{calculate_time.date()}收入` = {分摊收入}, ')
# sb.append(f'`{calculate_time.date()}成本` = {分摊成本}, ')
sb.append(f"({job_id},'{calculate_time.date()}', {分摊收入},{分摊成本}),")
return str(sb)[0 : len(str(sb)) - 1]
def add_one_month(date, i):
# Add one month to the date using timedelta
next_month = date + relativedelta(months=+i)
# print(next_month)
new_date = next_month.replace(day=1)
return new_date
def export_csv(fileName):
bizConn = MySQL(saas_shen_db_cfg)
fileHandle = open(file=fileName, mode="w", encoding="utf-8")
monthList = []
for i in range(184):
start_time = datetime.strptime("2013-01-01", "%Y-%m-%d")
# 添加一个月的日期
monthList.append(add_one_month(start_time, i).date())
headName = "job_id,主体,创建人,单据类型,单据编号,业务日期,财务日期,供应商,分类,客户,客户分类,渠道,业务类型,`业务类型-旧`,物料编码,物料名称,广汇安装单独条码,产品分类二级,设备类型,终端设备分类二级,产品类型,属性一,属性二,财务数量,计价数量,含税单价,单价,`税率(%)`,不含税金额,税额,价税合计,收入,成本金额,地区,匹配索引,分摊期限,产品分类一级"
for month in monthList:
headName += f",{month}收入,{month}成本"
headName += "\n"
fileHandle.write(headName)
sql = f"""
SELECT job_id,主体,创建人,单据类型,单据编号,业务日期,财务日期,供应商,分类,客户,客户分类,渠道,业务类型,`业务类型-旧`,物料编码,物料名称,
广汇安装单独条码,产品分类二级,设备类型,终端设备分类二级,产品类型,属性一,属性二,财务数量,计价数量,含税单价,单价,`税率(%)`,不含税金额,税额,
价税合计,收入,成本金额,地区,匹配索引,分摊期限,产品分类一级 FROM ds_job_info_23041302 WHERE LEFT(`业务日期`,4) = '2017' ;
"""
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
for index in range(int(len(result) / 5000) + 1):
split = result[5000 * index : 5000 * (index + 1)]
my_write_func(fileHandle, split, monthList)
# 关闭流
fileHandle.close()
def my_write_func(fileHandle, result, monthList):
my_job_id_list = {i[0] for i in result}
my_big_map = build_my_big_map(my_job_id_list)
for row in result:
logger.info(row)
lineValue = f"{row[0]},{row[1]},{row[2]},{row[3]},{row[4]},{row[5]},{row[6]},{row[7]},{row[8]},{row[9]},{row[10]},{row[11]},{row[12]},{row[13]},{row[14]},{row[15]},{row[16]},{row[17]},{row[18]},{row[19]},{row[20]},{row[21]},{row[22]},{row[23]},{row[24]},{row[25]},{row[26]},{row[27]},{row[28]},{row[29]},{row[30]},{row[31]},{row[32]},{row[33]},{row[34]},{row[35]},{row[36]}"
my_map = my_big_map.get(row[0])
if my_map is None:
my_map = {}
logger.info(my_map)
for month in monthList:
# logger.info("order_id" + str(row[0]) + ";year" + str(month))
# sql = f'''
# SELECT id,job_id,service_date,shouru_price,chengben_price FROM temp_job_info_ft_02 tjif WHERE tjif.job_id = {row[0]} AND tjif.service_date = '{month}';
# '''
# logger.info(sql)
# if not bizConn.query(sql):
# logger.error("deal_equity_data fail, sql=%s", sql)
# return
# result = bizConn.fetchAllRows()
result = my_map.get(
datetime.strptime(month.strftime("%Y-%m-%d"), "%Y-%m-%d")
)
# logger.info(result)
if result is None:
logger.debug(row)
lineValue += f",0,0"
else:
lineValue += f",{paddnum_price(result[3])},{paddnum_price(result[4])}"
# for row01 in result:
# logger.info(row01)
# lineValue += f",{paddnum_price(row01[3])},{paddnum_price(row01[4])}"
# 写入一行数据
lineValue += "\n"
logger.debug(lineValue)
fileHandle.write(lineValue)
def get_job_id(job_info_data):
return job_info_data[1]
def build_my_map(job_id_key):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
SELECT id,job_id,service_date,shouru_price,chengben_price FROM temp_job_info_ft_02 tjif WHERE tjif.job_id = {job_id_key} ;
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_map = {i[2]: i for i in result}
return my_map
def build_my_big_map(job_id_list):
bizConn = MySQL(saas_shen_db_cfg)
print(", ".join(str(x) for x in job_id_list))
sql = f"""
SELECT id,job_id,service_date,shouru_price,chengben_price FROM temp_job_info_ft_02 tjif WHERE tjif.job_id in ({', '.join(str(x) for x in job_id_list)}) ;
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
for job_id, group_list in my_dic:
my_big_map[job_id] = {i[2]: i for i in group_list}
return my_big_map
def write_sql(sql):
logger.info(sql)
with open("/sql11.txt", "a+", encoding="utf8") as fw:
fw.write(sql.strip())
fw.write("\n")
def paddnum_price(num):
return num if num is not None else 0
class StringBuilder:
def __init__(self):
self.strings = []
def append(self, string):
self.strings.append(string)
def __str__(self):
return "".join(self.strings)
def getMonthDataBigMap(ft_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
SELECT id,device_id,apportionment_date,apportionment_price FROM {ft_table};
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_month_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
# print("my_dic:", my_dic)
for job_id, group_list in my_dic:
my_month_big_map[job_id] = {i[2].strftime("%Y-%m-%d"): i for i in group_list}
print("my_month_big_map:", my_month_big_map)
return my_month_big_map
def getYearDataBigMap(zj_table):
bizConn = MySQL(saas_shen_db_cfg)
sql = f"""
SELECT id,device_id,order_year,qichu_num,qichu_unit_price,qichu_total_price,zengjia_num,zengjia_unit_price,zengjia_total_price,jianshao_num,jianshao_unit_price,jianshao_total_price
FROM {zj_table} tddz where device_id in (1500126,1179634);
"""
logger.info(sql)
if not bizConn.query(sql):
logger.error("deal_equity_data fail, sql=%s", sql)
return
result = bizConn.fetchAllRows()
my_year_big_map = {}
my_dic = [(key, list(group)) for key, group in groupby(result, key=get_job_id)]
print("my_dic:", my_dic)
for job_id, group_list in my_dic:
my_year_big_map[job_id] = {i[2]: i for i in group_list}
print("my_year_big_map:", my_year_big_map)
return my_year_big_map
if __name__ == "__main__":
# 创建表结构
# create_table()
# 执行脚本
# deal_equity_data()
# 导出表格
# export_csv("ds_job_info_23041302_2017_yang01.csv")
# my_map = build_my_map(61308)
# print('my_map', my_map)
# print(my_map[datetime.strptime('2017-01-01', '%Y-%m-%d')])
# start_time = datetime.strptime('2029-01-01', '%Y-%m-%d')
# # 添加一个月的日期
# date = add_one_month(start_time, 0).date()
# print(my_map.get(datetime.strptime(date.strftime("%Y-%m-%d"), '%Y-%m-%d')))
# big_map = build_my_big_map([1, 2, 3])
# print('big_map', big_map)
# my_map = big_map.get(1)
# start_time = datetime.strptime('2017-05-01', '%Y-%m-%d')
# # 添加一个月的日期
# date = add_one_month(start_time, 0).date()
# print(my_map.get(datetime.strptime(date.strftime("%Y-%m-%d"), '%Y-%m-%d')))
# getMonthDataBigMap("temp_dj_device_details_20230620_settle_hw_record_ft")
getYearDataBigMap("temp_dj_device_details_20230620_settle_hw_record_zj")