clean_budget_achievement.py
11.6 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
# -*- coding: utf-8 -*-
"""预算达成数据清洗脚本(第一步:结算数据汇总表 → biz_budget_achieve 前 7 个维度字段)。
处理链路:
data_process_task(筛选:data_table_type + month + is_deleted=0 + status=PROCESSING)
→ 取任务主键 id
→ data_process_file(task_id + form_type='结算数据汇总表' + is_deleted=0)
→ 按 file_url 下载 OSS 上的 Excel
→ 解析并按维度分组
→ 写入 biz_budget_achieve
本期写入字段(维度 7 个 + 金额 6 个,共 13 个):
task_id、stat_month、is_multi_category、traffic_name、business_type、
entity、brand、park_store、service_provider、
order_count、gmv、revenue、cost_gmv、
cost_gmv_ratio_current、cost_gmv_ratio_previous
说明:
- 金额指标按「业务类型+主体+流量方+品牌+园区店+服务商」维度累计汇总;
- cost_gmv_ratio_current = 成本(GMV口径)/GMV*100(保留 2 位);
- cost_gmv_ratio_previous = 上月同维度比值,取自 biz_budget_achieve 中上一统计月的数据,
若上月数据尚未处理则写 NULL,待上月跑完后重跑本脚本即可自动回填。
用法:
python clean_budget_achievement.py --data-table-type budget_achievement --month 2026-06
python clean_budget_achievement.py -t budget_achievement -m 2026-06 --dry-run
"""
import argparse
import os
import re
import sys
import tempfile
import traceback
from datetime import datetime
from urllib.parse import urlparse
import pymysql
import requests
from config import Config
from parsers import SettlementSummaryParser
# 数据源表单类型:结算数据汇总表
FORM_TYPE_SETTLEMENT = '结算数据汇总表'
# 目标表
TARGET_TABLE = 'biz_budget_achieve'
# 任务状态:处理中
TASK_STATUS_PROCESSING = 'PROCESSING'
# 附件清洗状态:1 待清洗 / 2 清洗中 / 3 清洗完成
CLEAN_PENDING, CLEAN_RUNNING, CLEAN_DONE = 1, 2, 3
MONTH_PATTERN = re.compile(r'^\d{4}-(0[1-9]|1[0-2])$')
def log(msg):
print(f'[{datetime.now():%Y-%m-%d %H:%M:%S}] {msg}', flush=True)
# ---------------- 数据库 ----------------
def get_conn():
"""按 config.Config(.env / .env.{APP_ENV})建立 MySQL 连接。"""
return pymysql.connect(
host=Config.MYSQL_HOST,
port=Config.MYSQL_PORT,
user=Config.MYSQL_USER,
password=Config.MYSQL_PASSWORD,
database=Config.MYSQL_DB,
charset='utf8mb4',
autocommit=False,
connect_timeout=10,
cursorclass=pymysql.cursors.DictCursor,
)
def query_tasks(conn, data_table_type, month):
"""筛选任务单据:数据表类型 + 月份 + 未删除 + 处理中。"""
sql = (
'SELECT id, data_table_type, month, status '
'FROM data_process_task '
'WHERE data_table_type = %s AND month = %s AND is_deleted = 0 AND status = %s '
'ORDER BY id'
)
with conn.cursor() as cur:
cur.execute(sql, (data_table_type, month, TASK_STATUS_PROCESSING))
return cur.fetchall()
def query_settlement_files(conn, task_id):
"""查询任务下未删除的「结算数据汇总表」附件(按 id 倒序,最新在前)。"""
sql = (
'SELECT id, task_id, form_type, file_name, file_url, clean_status '
'FROM data_process_file '
'WHERE task_id = %s AND form_type = %s AND is_deleted = 0 '
'ORDER BY id DESC'
)
with conn.cursor() as cur:
cur.execute(sql, (task_id, FORM_TYPE_SETTLEMENT))
return cur.fetchall()
def update_clean_status(conn, file_id, status):
"""更新附件清洗状态。"""
with conn.cursor() as cur:
cur.execute('UPDATE data_process_file SET clean_status = %s WHERE id = %s', (status, file_id))
conn.commit()
def prev_month_str(month):
"""'YYYY-MM' → 上一统计月字符串(如 2026-01 → 2025-12)。"""
year, mon = month.split('-')
year, mon = int(year), int(mon)
if mon == 1:
year, mon = year - 1, 12
else:
mon -= 1
return f'{year:04d}-{mon:02d}'
def query_previous_month_metrics(conn, prev_month):
"""查询上一统计月 biz_budget_achieve 中各维度组的成本(GMV口径)与 GMV 累计值。
用于计算 cost_gmv_ratio_previous(上月占比)。按 6 维度聚合,
返回 dict:key=(traffic_name, business_type, entity, brand, park_store, service_provider),
value={'cost_gmv':float, 'gmv':float}。
若上月数据尚未处理(查无记录),返回空 dict,对应比值写 None。
"""
sql = (
'SELECT traffic_name, business_type, entity, brand, park_store, service_provider, '
'SUM(cost_gmv) AS cost_gmv, SUM(gmv) AS gmv '
'FROM biz_budget_achieve '
'WHERE stat_month = %s '
'GROUP BY traffic_name, business_type, entity, brand, park_store, service_provider'
)
result = {}
with conn.cursor() as cur:
cur.execute(sql, (prev_month,))
for r in cur.fetchall():
key = (r['traffic_name'], r['business_type'], r['entity'],
r['brand'], r['park_store'], r['service_provider'])
result[key] = {
'cost_gmv': float(r['cost_gmv'] or 0),
'gmv': float(r['gmv'] or 0),
}
return result
def save_budget_rows(conn, task_id, stat_month, rows):
"""写入预算达成数据表:同一任务重跑先清空旧数据,再批量插入(单事务)。
写入字段:维度 7 个 + 金额 6 个(order_count/gmv/revenue/cost_gmv/
cost_gmv_ratio_current/cost_gmv_ratio_previous)。
"""
insert_sql = (
f'INSERT INTO {TARGET_TABLE} '
'(task_id, stat_month, is_multi_category, traffic_name, business_type, '
' entity, brand, park_store, service_provider, '
' order_count, gmv, revenue, cost_gmv, '
' cost_gmv_ratio_current, cost_gmv_ratio_previous) '
'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
)
params = [
(
task_id,
stat_month,
r['is_multi_category'],
r['traffic_name'] or None,
r['business_type'] or None,
r['entity'] or None,
r['brand'] or None,
r['park_store'] or None,
r['service_provider'] or None,
r['order_count'],
r['gmv'],
r['revenue'],
r['cost_gmv'],
r['cost_gmv_ratio_current'],
r['cost_gmv_ratio_previous'],
)
for r in rows
]
try:
with conn.cursor() as cur:
cur.execute(f'DELETE FROM {TARGET_TABLE} WHERE task_id = %s AND stat_month = %s',
(task_id, stat_month))
deleted = cur.rowcount
cur.executemany(insert_sql, params)
conn.commit()
return deleted, len(params)
except Exception:
conn.rollback()
raise
# ---------------- 文件下载 ----------------
def download_file(file_url, dest_dir):
"""下载 OSS 文件到本地临时目录,返回本地路径。"""
name = os.path.basename(urlparse(file_url).path) or 'settlement.xlsx'
local_path = os.path.join(dest_dir, name)
with requests.get(file_url, stream=True, timeout=120) as resp:
resp.raise_for_status()
with open(local_path, 'wb') as f:
for chunk in resp.iter_content(chunk_size=1024 * 256):
if chunk:
f.write(chunk)
size = os.path.getsize(local_path)
log(f' 文件已下载:{name}({size / 1024 / 1024:.2f} MB)')
return local_path
# ---------------- 主流程 ----------------
def process_task(conn, task, dry_run=False):
"""处理单个任务:下载附件 → 解析 → 写库。返回写入行数。"""
task_id, stat_month = task['id'], task['month']
log(f'处理任务 #{task_id}({task["data_table_type"]} / {stat_month})')
files = query_settlement_files(conn, task_id)
if not files:
log(f' 跳过:未找到未删除的「{FORM_TYPE_SETTLEMENT}」附件')
return 0
if len(files) > 1:
log(f' 注意:存在 {len(files)} 个未删除的「{FORM_TYPE_SETTLEMENT}」附件,取最新一个(id={files[0]["id"]})')
file_row = files[0]
log(f' 附件 #{file_row["id"]}:{file_row["file_name"]}')
# 上月数据(用于计算 cost_gmv_ratio_previous),写库阶段才查库
prev_month = prev_month_str(stat_month)
prev_metrics = query_previous_month_metrics(conn, prev_month) if not dry_run else {}
if not dry_run:
log(f' 上月统计月 {prev_month}:命中维度组 {len(prev_metrics)} 个'
f'(缺失则该组上月占比写 NULL)')
if not dry_run:
update_clean_status(conn, file_row['id'], CLEAN_RUNNING)
try:
with tempfile.TemporaryDirectory(prefix='budget_') as tmp:
local_path = download_file(file_row['file_url'], tmp)
parser = SettlementSummaryParser(local_path)
records = parser.parse()
rows = parser.generate_budget_metrics(prev_metrics=prev_metrics)
log(f' 解析明细 {len(records)} 行 → 分组后 {len(rows)} 行'
f'(多品类 {sum(1 for r in rows if r["is_multi_category"] == "是")} 行)')
if dry_run:
log(' dry-run:不写库,样例前 3 行:')
for r in rows[:3]:
log(f' {r}')
return len(rows)
deleted, inserted = save_budget_rows(conn, task_id, stat_month, rows)
log(f' 写入 {TARGET_TABLE}:清理旧数据 {deleted} 行,新增 {inserted} 行'
f'(含金额指标 6 列,本月占比非空 {sum(1 for r in rows if r["cost_gmv_ratio_current"] is not None)} 行)')
update_clean_status(conn, file_row['id'], CLEAN_DONE)
return inserted
except Exception:
if not dry_run:
update_clean_status(conn, file_row['id'], CLEAN_PENDING) # 失败回退为待清洗
raise
def main():
ap = argparse.ArgumentParser(description='预算达成数据清洗:结算数据汇总表 → biz_budget_achieve')
ap.add_argument('-t', '--data-table-type', required=True,
help='数据表类型编码,对应 data_process_task.data_table_type,如 budget_achievement')
ap.add_argument('-m', '--month', required=True,
help='所属月份,对应 data_process_task.month,格式 YYYY-MM,如 2026-06')
ap.add_argument('--dry-run', action='store_true', help='只解析不写库,用于校验数据')
args = ap.parse_args()
if not MONTH_PATTERN.match(args.month):
log(f'月份格式错误:{args.month},应为 YYYY-MM')
return 2
log(f'开始清洗:data_table_type={args.data_table_type},month={args.month}'
f'{"(dry-run)" if args.dry_run else ""}')
log(f'数据库:{Config.MYSQL_USER}@{Config.MYSQL_HOST}:{Config.MYSQL_PORT}/{Config.MYSQL_DB}')
conn = get_conn()
total, failed = 0, 0
try:
tasks = query_tasks(conn, args.data_table_type, args.month)
if not tasks:
log(f'没有符合条件的任务(状态={TASK_STATUS_PROCESSING}、未删除),流程结束')
return 0
log(f'命中任务 {len(tasks)} 个:{[t["id"] for t in tasks]}')
for task in tasks:
try:
total += process_task(conn, task, dry_run=args.dry_run)
except Exception as e:
failed += 1
log(f' 任务 #{task["id"]} 处理失败:{e}')
traceback.print_exc()
finally:
conn.close()
log(f'清洗结束:累计 {total} 行,失败任务 {failed} 个')
return 1 if failed else 0
if __name__ == '__main__':
sys.exit(main())