test_hm_data.py
27.2 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
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
# -*- coding: utf-8 -*-
"""
鸿蒙生态数据验证脚本
=====================
功能:根据输出模板字段,逐层验证数据来源:
1. 原始表(5.23 dj_smartcarlife)数据
2. ODS 层数据
3. DWS 层数据
用法:
python tests/test_hm_data.py --name "鸿蒙门店名称"
python tests/test_hm_data.py --id 12345
python tests/test_hm_data.py --name "门店A" --start 2025-07-01 --end 2025-07-09
python tests/test_hm_data.py --name "门店A" --all # 输出所有明细
"""
import os
import sys
import argparse
from datetime import datetime
from collections import defaultdict
import pymysql
from pymysql.cursors import DictCursor
# ==================== 数据库配置 ====================
# 原始表 (5.23 生产库 dj_smartcarlife)
SOURCE_DB = {
"host": "192.168.5.23",
"port": 3306,
"user": "user_jiangmy",
"password": "VMziLJun",
"database": "dj_smartcarlife",
"charset": "utf8mb4",
"cursorclass": DictCursor,
}
# 数仓 (data_analyze)
WAREHOUSE_DB = {
"host": "192.168.2.155",
"port": 3308,
"user": "user_jiangmy",
"password": "PYuxMTB1",
"database": "data_analyze",
"charset": "utf8mb4",
"cursorclass": DictCursor,
}
# ==================== 鸿蒙品牌定义 ====================
# 鸿蒙智行 first_brand_id = 2365
# 子品牌: 2695=问界, 2698=智界, 2741=享界, 2740=尊界, 2797=尚界
FIRST_BRAND_ID = 2365
HARMONY_BRAND_IDS = (2698, 2741, 2740, 2797)
HARMONY_BRAND_NAMES = {2695: "问界", 2698: "智界", 2741: "享界", 2740: "尊界", 2797: "尚界"}
# ==================== 辅助函数 ====================
def _fmt(val, decimals=None):
"""格式化数值,None 显示为 '-'"""
if val is None:
return "-"
if decimals is not None:
return f"{float(val):,.{decimals}f}"
if isinstance(val, float):
return f"{val:,.2f}"
return str(val)
def _pct(val, digits=2):
"""格式化为百分比"""
if val is None:
return "-"
return f"{float(val) * 100:.{digits}f}%"
def _connect(cfg, label):
"""连接数据库"""
try:
conn = pymysql.connect(**cfg)
print(f" [{label}] 连接成功: {cfg['host']}:{cfg['port']}/{cfg['database']}")
return conn
except Exception as e:
print(f" [{label}] 连接失败: {e}")
return None
# ==================== 1. 原始表查询 (5.23) ====================
def query_source_staff_daily(conn, merchant_id, start_date, end_date):
"""
原始表: dj_car_life_staff_daily_report_huawei (员工日报华为表)
粒度: 员工 + 日期 + scene + brand
聚合到门店级别
"""
sql = """
SELECT
r.merchant_id,
r.report_date,
r.scene_type,
r.first_brand_id,
r.brand_id,
r.equity_to_shop_count,
r.extended_warranty_to_shop_count,
r.real_equity_to_shop_count,
r.after_sale_equity_to_shop_count,
r.after_sale_extended_warranty_to_shop_count,
r.after_sale_real_equity_to_shop_count,
r.extended_warranty_count,
r.tire_warranty_count,
r.ax_package_count,
r.battery_extended_warranty_count,
r.battery_extended_warranty_money,
r.total_order_count,
r.total_order_money
FROM dj_car_life_staff_daily_report_huawei r
WHERE r.merchant_id = %s
AND r.report_date >= %s AND r.report_date <= %s
AND r.deleted_flag = 'N'
AND r.first_brand_id = %s
AND r.brand_id IN (2695, 2698, 2741, 2740, 2797)
AND r.scene_type = '0'
ORDER BY r.report_date
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id, start_date, end_date, FIRST_BRAND_ID))
return cur.fetchall()
def query_source_merchant_daily(conn, merchant_id, start_date, end_date):
"""原始表: dj_car_life_merchant_daily_report_huawei (门店日报华为表 - 交付数)"""
sql = """
SELECT
merchant_id,
report_date,
delivery_count,
customer_loss_count
FROM dj_car_life_merchant_daily_report_huawei
WHERE merchant_id = %s
AND report_date >= %s AND report_date <= %s
AND deleted_flag = 'N'
AND first_brand_id = %s
AND brand_id IN ( 2698, 2741, 2740, 2797)
AND scene_type = '0'
ORDER BY report_date
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id, start_date, end_date, FIRST_BRAND_ID))
return cur.fetchall()
def query_source_staff_info(conn, merchant_id):
"""原始表: dj_car_life_staff_daily_report (员工通用信息)"""
sql = """
SELECT
r.merchant_id,
r.merchant_name,
r.staff_uuid,
r.staff_name,
r.report_date,
r.on_break,
r.template_type
FROM dj_car_life_staff_daily_report r
WHERE r.merchant_id = %s
AND r.deleted_flag = 'N'
ORDER BY r.report_date
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id,))
return cur.fetchall()
def query_source_merchant(conn, merchant_id):
"""原始表: dj_car_life_service_merchant (门店主数据)"""
sql = """
SELECT
merchant_id,
merchant_name,
store_code,
province_id,
province_name,
city_id,
city_name,
region,
channel_type
FROM dj_car_life_service_merchant
WHERE merchant_id = %s AND deleted_flag = 'N'
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id,))
return cur.fetchall()
# ==================== 2. ODS 层查询 ====================
def query_ods_staff_daily(conn, merchant_id, start_date, end_date):
"""ODS: ods_staff_daily_report_huawei"""
sql = """
SELECT
merchant_id, report_date, scene_type,
first_brand_id, brand_id,
equity_to_shop_count,
extended_warranty_to_shop_count,
real_equity_to_shop_count,
after_sale_equity_to_shop_count,
after_sale_extended_warranty_to_shop_count,
after_sale_real_equity_to_shop_count,
extended_warranty_count,
tire_warranty_count,
ax_package_count,
battery_extended_warranty_count,
battery_extended_warranty_money,
total_order_count,
total_order_money
FROM ods_staff_daily_report_huawei
WHERE merchant_id = %s
AND report_date >= %s AND report_date <= %s
AND deleted_flag = 'N'
AND first_brand_id = %s
AND brand_id IN ( 2698, 2741, 2740, 2797)
AND scene_type = '0'
ORDER BY report_date
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id, start_date, end_date, FIRST_BRAND_ID))
return cur.fetchall()
def query_ods_merchant_daily(conn, merchant_id, start_date, end_date):
"""ODS: ods_merchant_daily_report_huawei"""
sql = """
SELECT
merchant_id, report_date,
delivery_count, customer_loss_count
FROM ods_merchant_daily_report_huawei
WHERE merchant_id = %s
AND report_date >= %s AND report_date <= %s
AND deleted_flag = 'N'
AND first_brand_id = %s
AND brand_id IN (2698, 2741, 2740, 2797)
AND scene_type = '0'
ORDER BY report_date
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id, start_date, end_date, FIRST_BRAND_ID))
return cur.fetchall()
def query_ods_store_config(conn, merchant_id):
"""ODS: ods_store_config"""
sql = """
SELECT
merchant_id, merchant_name, merchant_code,
province, city, channel, operation_mode,
traffic_grade, primary_brand,
area_manager, online_ops, flight_supervisor,
deploy_time
FROM ods_store_config
WHERE merchant_id = %s AND deleted_flag = 'N'
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id,))
return cur.fetchone()
def query_ods_host_plant_delivery(conn, merchant_id, start_date, end_date):
"""ODS: ods_host_plant_delivery (主机厂交付数据)"""
sql = """
SELECT
store_code, store_name, delivery_date,
delivery_count, province, enabler
FROM ods_host_plant_delivery
WHERE store_code = (SELECT store_code FROM ods_service_merchant WHERE merchant_id = %s LIMIT 1)
AND delivery_date >= %s AND delivery_date <= %s
ORDER BY delivery_date
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id, start_date, end_date))
return cur.fetchall()
# ==================== 3. DWS 层查询 ====================
def query_dws_merchant_daily(conn, merchant_id, start_date, end_date):
"""
DWS: dws_merchant_daily_wide (门店日报大宽表)
对应输出模板的产值数据
"""
sql = """
SELECT
merchant_id,
merchant_name,
report_date,
province_name,
city_name,
region,
channel_type,
area_supervision,
online_supervision,
flight_supervision,
scene_type,
first_brand_id,
brand_id,
brand_name,
delivery_count,
customer_loss_count,
total_staff,
active_staff,
on_break_staff,
sum_equity_to_shop,
sum_extended_warranty_to_shop,
sum_real_equity_to_shop,
sum_after_sale_to_shop,
sum_not_delivery,
sum_order_count,
sum_extended_warranty,
sum_tire_warranty,
sum_ax_package,
sum_battery_extended,
sum_battery_money,
sum_total_order_money,
month_deliver_target,
month_output_target
FROM dws_merchant_daily_wide
WHERE merchant_id = %s
AND report_date >= %s AND report_date <= %s
AND first_brand_id = %s
AND brand_id IN (2698, 2741, 2740, 2797)
AND scene_type = '0'
ORDER BY report_date, brand_id
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id, start_date, end_date, FIRST_BRAND_ID))
return cur.fetchall()
def query_dws_merchant_aggregate(conn, merchant_id, start_date, end_date):
"""DWS: 门店汇总(同 harmony_analysis_service 的查询方式)"""
sql = """
SELECT
m.merchant_id,
m.merchant_name,
m.province_name,
m.area_supervision,
m.flight_supervision,
m.online_supervision,
SUM(IFNULL(m.delivery_count, 0)) AS total_delivery,
SUM(IFNULL(m.sum_equity_to_shop, 0)) AS total_touch,
SUM(IFNULL(m.sum_extended_warranty, 0)) AS total_yb_orders,
SUM(IFNULL(m.sum_ax_package, 0)) AS total_axb_orders,
SUM(IFNULL(m.sum_battery_extended, 0)) AS total_battery_orders,
SUM(IFNULL(m.sum_tire_warranty, 0)) AS total_tire_orders,
SUM(IFNULL(m.sum_total_order_money, 0)) AS total_amount,
SUM(IFNULL(m.sum_real_equity_to_shop, 0)) AS total_equity_orders,
SUM(IFNULL(m.sum_battery_money, 0)) AS total_battery_money,
SUM(IFNULL(m.active_staff, 0)) AS total_active_staff,
COUNT(DISTINCT m.report_date) AS data_days
FROM dws_merchant_daily_wide m
WHERE m.merchant_id = %s
AND m.report_date >= %s AND m.report_date <= %s
AND m.first_brand_id = %s
AND m.brand_id IN (2698, 2741, 2740, 2797)
AND m.scene_type = '0'
GROUP BY m.merchant_id, m.merchant_name, m.province_name,
m.area_supervision, m.flight_supervision, m.online_supervision
"""
with conn.cursor() as cur:
cur.execute(sql, (merchant_id, start_date, end_date, FIRST_BRAND_ID))
return cur.fetchall()
# ==================== 门店名称 → merchant_id 查询 ====================
def find_merchant_by_name(conn, name):
"""根据门店名称查找 merchant_id"""
sql = """
SELECT merchant_id, merchant_name, store_code, province_name
FROM ods_service_merchant
WHERE merchant_name LIKE %s AND deleted_flag = 'N'
LIMIT 20
"""
with conn.cursor() as cur:
cur.execute(sql, (f"%{name}%",))
return cur.fetchall()
# ==================== 格式化输出 ====================
def print_separator(title, char="="):
print(f"\n{char * 70}")
print(f" {title}")
print(f"{char * 70}")
def print_table(headers, rows, col_widths=None):
"""简单表格打印"""
if not rows:
print(" (无数据)")
return
if col_widths is None:
col_widths = [max(len(str(r.get(h, ""))) if isinstance(r, dict) else len(str(r[i] if isinstance(r, (list, tuple)) else "")) for r in [dict(zip(headers, headers))] + rows) + 2 for i, h in enumerate(headers)]
col_widths = [max(w, len(h) + 2) for w, h in zip(col_widths, headers)]
# 打印表头
header_line = " " + "".join(f"{h:<{w}}" for h, w in zip(headers, col_widths))
print(header_line)
print(" " + "-" * (sum(col_widths)))
# 打印数据
for row in rows:
if isinstance(row, dict):
vals = [str(row.get(h, "")) for h in headers]
else:
vals = [str(v) for v in row]
print(" " + "".join(f"{v:<{w}}" for v, w in zip(vals, col_widths)))
def print_source_data(source_rows, merchant_rows, label):
"""打印原始表(5.23)数据"""
print_separator(f"[1] 原始表 (5.23 dj_smartcarlife) - {label}", "-")
if merchant_rows:
print("\n 📍 门店主数据 (dj_car_life_service_merchant):")
print_table(
["merchant_id", "merchant_name", "store_code", "province_name"],
merchant_rows
)
if source_rows:
print(f"\n 📋 员工日报华为表 (dj_car_life_staff_daily_report_huawei) - 共 {len(source_rows)} 条:")
headers = [
"report_date", "scene_type", "first_brand_id", "brand_id",
"equity_to_shop_count", "extended_warranty_count",
"ax_package_count", "battery_extended_warranty_count",
"tire_warranty_count", "total_order_count", "total_order_money"
]
print_table(headers, source_rows)
print_summary(source_rows, "原始表(5.23)")
def print_ods_data(ods_rows, ods_merchant_rows, store_config, host_delivery_rows, label):
"""打印ODS层数据"""
print_separator(f"[2] ODS 层 (data_analyze) - {label}", "-")
if store_config:
print("\n 📍 门店配置 (ods_store_config):")
for k, v in store_config.items():
print(f" {k}: {v}")
if ods_merchant_rows:
print(f"\n 📋 ODS 门店日报 (ods_merchant_daily_report_huawei) - 共 {len(ods_merchant_rows)} 条:")
headers = ["report_date", "delivery_count", "customer_loss_count"]
print_table(headers, ods_merchant_rows)
if host_delivery_rows:
print(f"\n 📋 主机厂交付 (ods_host_plant_delivery) - 共 {len(host_delivery_rows)} 条:")
headers = ["delivery_date", "store_code", "store_name", "delivery_count", "province"]
print_table(headers, host_delivery_rows)
if ods_rows:
print(f"\n 📋 ODS 员工日报 (ods_staff_daily_report_huawei) - 共 {len(ods_rows)} 条:")
headers = [
"report_date", "scene_type", "brand_id",
"equity_to_shop_count", "extended_warranty_count",
"ax_package_count", "battery_extended_warranty_count",
"tire_warranty_count", "total_order_count", "total_order_money"
]
print_table(headers, ods_rows)
print_summary(ods_rows, "ODS")
def print_dws_data(dws_rows, dws_agg_rows, label):
"""打印DWS层数据"""
print_separator(f"[3] DWS 层 (data_analyze) - {label}", "-")
if dws_agg_rows:
print("\n 📊 DWS 汇总 (门店聚合,对应输出模板产值数据):")
for row in dws_agg_rows:
print(f" merchant_id : {row['merchant_id']}")
print(f" merchant_name : {row['merchant_name']}")
print(f" province_name : {row['province_name']}")
print(f" area_supervision : {row['area_supervision']}")
print(f" flight_supervision : {row['flight_supervision']}")
print(f" online_supervision : {row['online_supervision']}")
print(f" data_days : {row['data_days']} 天")
print(f" ─────────────────────────────")
print(f" total_delivery : {_fmt(row['total_delivery'])}")
print(f" total_touch : {_fmt(row['total_touch'])}")
print(f" total_yb_orders : {_fmt(row['total_yb_orders'])} (整车延保)")
print(f" total_axb_orders : {_fmt(row['total_axb_orders'])} (安心包)")
print(f" total_battery_orders: {_fmt(row['total_battery_orders'])} (电池延保)")
print(f" total_tire_orders : {_fmt(row['total_tire_orders'])} (轮胎险)")
print(f" total_equity_orders: {_fmt(row['total_equity_orders'])} (广联权益)")
print(f" total_amount : {_fmt(row['total_amount'])} (累计成交金额)")
print(f" total_battery_money: {_fmt(row['total_battery_money'])} (电池延保金额)")
print(f" ─────────────────────────────")
# 计算渗透率
d = row['total_delivery'] or 0
t = row['total_touch'] or 0
if d > 0:
print(f" 触客率 : {_pct(t / d)} (触客/交付)")
if t > 0:
print(f" 延保渗透率 : {_pct(row['total_yb_orders'] / t)} (延保/触客)")
print(f" 安心包渗透率 : {_pct(row['total_axb_orders'] / t)} (安心包/触客)")
print(f" 电池延保渗透率 : {_pct(row['total_battery_orders'] / t)} (电池/触客)")
print(f" 轮胎险渗透率 : {_pct(row['total_tire_orders'] / t)} (轮胎/触客)")
if d > 0:
print(f" 售前交付成交率 : {_pct(row['total_yb_orders'] / d)} (延保/交付)")
if dws_rows:
print(f"\n 📋 DWS 明细 (dws_merchant_daily_wide) - 共 {len(dws_rows)} 条:")
headers = [
"report_date", "brand_id",
"delivery_count", "sum_equity_to_shop",
"sum_extended_warranty", "sum_ax_package",
"sum_battery_extended", "sum_tire_warranty",
"sum_total_order_money"
]
print_table(headers, dws_rows)
def print_summary(rows, label):
"""打印汇总统计"""
if not rows:
return
agg = defaultdict(float)
for r in rows:
agg["delivery_count"] += float(r.get("delivery_count", 0) or 0)
agg["equity_to_shop_count"] += float(r.get("equity_to_shop_count", 0) or 0)
agg["extended_warranty_count"] += float(r.get("extended_warranty_count", 0) or 0)
agg["ax_package_count"] += float(r.get("ax_package_count", 0) or 0)
agg["battery_extended_warranty_count"] += float(r.get("battery_extended_warranty_count", 0) or 0)
agg["tire_warranty_count"] += float(r.get("tire_warranty_count", 0) or 0)
agg["total_order_money"] += float(r.get("total_order_money", 0) or 0)
agg["total_order_count"] += float(r.get("total_order_count", 0) or 0)
agg["days"] = len(set(r["report_date"] for r in rows if "report_date" in r))
print(f"\n 📊 {label} 汇总 (共 {agg['days']:.0f} 天):")
print(f" equity_to_shop_count (触客数) : {agg['equity_to_shop_count']:,.0f}")
print(f" extended_warranty_count (整车延保) : {agg['extended_warranty_count']:,.0f}")
print(f" ax_package_count (安心包) : {agg['ax_package_count']:,.0f}")
print(f" battery_extended_warranty_count (电池) : {agg['battery_extended_warranty_count']:,.0f}")
print(f" tire_warranty_count (轮胎险) : {agg['tire_warranty_count']:,.0f}")
print(f" total_order_count (总成交) : {agg['total_order_count']:,.0f}")
print(f" total_order_money (总金额) : {agg['total_order_money']:,.2f}")
# ==================== 主流程 ====================
def main():
parser = argparse.ArgumentParser(
description="鸿蒙生态数据验证 - 逐层查询原始表/ODS/DWS",
formatter_class=argparse.RawDescriptionHelpFormatter,
epilog="""
示例:
python tests/test_hm_data.py --name "鸿蒙门店"
python tests/test_hm_data.py --id 12345
python tests/test_hm_data.py --name "门店A" --start 2025-07-01 --end 2025-07-09
python tests/test_hm_data.py --name "门店A" --all
"""
)
parser.add_argument("--name", type=str, help="门店名称(模糊匹配)")
parser.add_argument("--id", type=int, help="门店 merchant_id")
parser.add_argument("--start", type=str, default=None, help="开始日期 YYYY-MM-DD(默认本月1号)")
parser.add_argument("--end", type=str, default=None, help="结束日期 YYYY-MM-DD(默认今天)")
parser.add_argument("--all", action="store_true", help="输出所有明细数据")
parser.add_argument("--skip-source", action="store_true", help="跳过原始表(5.23)查询")
parser.add_argument("--skip-ods", action="store_true", help="跳过ODS层查询")
parser.add_argument("--skip-dws", action="store_true", help="跳过DWS层查询")
args = parser.parse_args()
# 默认日期:本月1号 ~ 今天
today = datetime.now()
start_date = args.start or today.replace(day=1).strftime("%Y-%m-%d")
end_date = args.end or today.strftime("%Y-%m-%d")
print("=" * 70)
print(" 鸿蒙生态数据验证")
print("=" * 70)
print(f" 查询周期: {start_date} ~ {end_date}")
print(f" 鸿蒙品牌: {', '.join(f'{k}({v})' for k, v in HARMONY_BRAND_NAMES.items())}")
# 步骤0: 解析 merchant_id
wh_conn = _connect(WAREHOUSE_DB, "数仓")
if not wh_conn:
print("❌ 无法连接数仓数据库,退出")
return
merchant_id = args.id
merchant_name = args.name
if not merchant_id and not merchant_name:
print("❌ 请指定 --name 或 --id 参数")
wh_conn.close()
return
# 按名称查找
if merchant_name and not merchant_id:
results = find_merchant_by_name(wh_conn, merchant_name)
if not results:
print(f"\n❌ 未找到匹配的门店: '{merchant_name}'")
wh_conn.close()
return
if len(results) == 1:
r = results[0]
merchant_id = r["merchant_id"]
print(f"\n📍 找到门店: [{r['merchant_id']}] {r['merchant_name']} ({r['province_name']})")
else:
print(f"\n📍 找到 {len(results)} 个匹配门店:")
print_table(
["merchant_id", "merchant_name", "store_code", "province_name"],
results
)
choice = input("\n请输入 merchant_id (或回车退出): ").strip()
if not choice:
wh_conn.close()
return
try:
merchant_id = int(choice)
except ValueError:
print("无效输入")
wh_conn.close()
return
print(f"\n 📌 最终查询: merchant_id = {merchant_id}")
print(f" 📌 数据周期: {start_date} ~ {end_date}")
# ========== 1. 原始表 (5.23) ==========
if not args.skip_source:
src_conn = _connect(SOURCE_DB, "原始库 5.23")
if src_conn:
try:
merchant_rows = query_source_merchant(src_conn, merchant_id)
source_staff_rows = query_source_staff_daily(src_conn, merchant_id, start_date, end_date)
source_merchant_rows = query_source_merchant_daily(src_conn, merchant_id, start_date, end_date)
# 合并交付数到 staff 行
delivery_map = {r["report_date"]: r.get("delivery_count", 0) for r in source_merchant_rows}
for r in source_staff_rows:
r["delivery_count"] = delivery_map.get(r["report_date"], 0)
print_source_data(source_staff_rows, merchant_rows, f"merchant_id={merchant_id}")
except Exception as e:
print(f" ❌ 原始表查询失败: {e}")
finally:
src_conn.close()
else:
print_separator("[1] 原始表 (5.23) - 已跳过", "-")
# ========== 2. ODS 层 ==========
if not args.skip_ods:
try:
store_config = query_ods_store_config(wh_conn, merchant_id)
ods_staff_rows = query_ods_staff_daily(wh_conn, merchant_id, start_date, end_date)
ods_merchant_rows = query_ods_merchant_daily(wh_conn, merchant_id, start_date, end_date)
host_delivery_rows = query_ods_host_plant_delivery(wh_conn, merchant_id, start_date, end_date)
# 合并交付数
delivery_map = {r["report_date"]: r.get("delivery_count", 0) for r in ods_merchant_rows}
for r in ods_staff_rows:
r["delivery_count"] = delivery_map.get(r["report_date"], 0)
print_ods_data(ods_staff_rows, ods_merchant_rows, store_config, host_delivery_rows,
f"merchant_id={merchant_id}")
except Exception as e:
print(f" ❌ ODS 查询失败: {e}")
else:
print_separator("[2] ODS 层 - 已跳过", "-")
# ========== 3. DWS 层 ==========
if not args.skip_dws:
try:
dws_rows = query_dws_merchant_daily(wh_conn, merchant_id, start_date, end_date) if args.all else []
dws_agg_rows = query_dws_merchant_aggregate(wh_conn, merchant_id, start_date, end_date)
print_dws_data(dws_rows, dws_agg_rows, f"merchant_id={merchant_id}")
except Exception as e:
print(f" ❌ DWS 查询失败: {e}")
else:
print_separator("[3] DWS 层 - 已跳过", "-")
# ========== 4. 数据对比 ==========
if not args.skip_source and not args.skip_ods and not args.skip_dws:
print_separator("[4] 数据一致性对比")
print(" (需要同时查询三层数据,可通过汇总结果对比)")
wh_conn.close()
print(f"\n{'=' * 70}")
print(" 验证完成")
print(f"{'=' * 70}")
if __name__ == "__main__":
main()