Commit b905a7d1 by 叶立庆

Merge remote-tracking branch 'origin/v1.1'

# Conflicts:
#	.workbuddy/memory/MEMORY.md
#	data-process/.gitignore
2 parents 7c523de5 f8aa2c2b
Showing 78 changed files with 13403 additions and 134 deletions
/data-process/backend_avita11.log
/data-process/backend_avita.log
/data-process/backend_avita2.log
/data-process/backend_avita3.log
/data-process/backend_avita4.log
/data-process/backend_avita5.log
/data-process/backend_avita6.log
/data-process/backend_avita7.log
/data-process/backend_avita8.log
/data-process/backend_avita9.log
/data-process/backend_avita10.log
/data-process/*.log
# VSCode Local History 插件
.history/
# IDE
.idea/
# 2026-09-04 工作日志
## 项目现状盘点:三类数据表完成度(只做分析,未改代码)
### 架构现状(相对 8 月记忆的重大变化)
- `config.DATA_TABLE_TYPES` 现有 4 类:`budget_achievement`(预算达成数据, 7表单)、`store_effect_earnings`(店效人效及盈利测算, 11表单, need_period)、`output_value`(产值达成表, 2表单=SAAS门店预算分解表+关系表, need_period)、`future_expansion`(占位)。
- 新增模块(原记忆未覆盖):`report_utils.py`(40KB 公共解析库)、`earnings_report_processor.py`(延保)、`equity_processor.py`(权益)、`light_reform_inshop_processor.py`(轻改店中店)、`light_reform_park_processor.py`(轻改园区店)、`indicator_client.py`(指标系统 API)、`_init_brand_config.py`、`_test_newtypes.py`;`scheduler.py` 新增 `NewReportScheduler` 基类 + 4 个子类调度器(按 OUTPUT_CATEGORY 分类扫描 store_effect_earnings)。
- 模型新增:`DataProcessSubtask`(4 类输出独立状态机)、`LuxuryBrandConfig`、`ReportExtendedWarranty`、`ReportEquityService`、`ReportLightReformInshop`、`ReportLightReformPark`。
- 模板:`exporttemplete/红黄门店盈利测算 延保权益.xlsx`(延保/权益 2 sheet)、`红黄门店盈利测算 轻改 .xlsx`(店中店汇总/四分位/园区店汇总/主机厂×2/品类×6)。
### 完成度判定(依据 DB 实测,非估算)
1. **预算达成数据 ≈90%**:7 类表单解析全实现(结算汇总/市场费/人力/外施/房租水电/装修/耗材),clean+processor 双流水线可跑。任务:2026-01/02/05/06 COMPLETED,03/08/10 FAILED。
2. **店效人效及盈利测算 ≈55%**:4 处理器+4 ORM+4 调度器已就位,10/11 表单有解析函数;但 **4 张报告表行数均为 0、data_process_subtask 0 行、luxury_brand_config 0 行**(即从未真正产出数据,任务 26/29 的 COMPLETED 来自页面 mock 接口 `/api/tasks/<id>/complete`)。阻塞点:各处理器「业务系统 SQL」Step 全是 `biz_sql_data = {}` 占位(产值/成本类字段恒为 0);`二手车收购与销售台账` 无解析函数;豪华品牌表未初始化。
3. **产值达成表 ≈10%**:仅在 config 注册 + 页面可建单/上传附件;**无处理器、无 ORM 输出表、无 Excel 模板、无调度器**。DB 中 5 个任务:20/23/24/25 PROCESSING(永远不会被扫描,因 4 个调度器只扫 store_effect_earnings,而 process_all 只认 budget_achievement),28 FAILED(error=`not enough values to unpack (expected 4, got 3)`,推测是手动 `/api/tasks/<id>/process` 把产值任务塞进预算达成流水线所致——`process_task` 未按 data_table_type 校验,仅 `process_all` 用 `SUPPORTED_PROCESS_TYPES` 过滤)。
### 可复用的解析资产(产值达成表可直接复用)
- `report_utils.parse_saas_base`(sheet1, biz_type 过滤 2.3/2.1)、`parse_saas_base_sheet2`(店中店)、`parse_saas_base_sheet2_exclude`(园区店)、`parse_region_map`(关系表)、`parse_delivery_table`(主机厂交车)、`parse_inshop_delivery_touch`/`parse_park_delivery_touch`、`parse_commerce_policy_inshop`/`_park`、`parse_labor_cost`、`parse_budget_achieve_excel`、`fetch_prev_month_budget_detail`、`fetch_indicator_data`(A075成交/A036产值/A084触客…)、`is_luxury_brand`、子任务状态机 helpers。
- 产值达成口径现只存在于轻改园区店表:`output_progress = 合计总产值 / est_output_value(预算目标)`,且 est 分摊逻辑仍是 `pass # TODO`。
### 产值达成表开工缺口(4 项)
① 输出口径与 Excel 模板(需求说明书 V1.0.0 只覆盖第一期预算达成,未定义产值达成表);② 独立处理器 + ORM 输出表 + 调度器注册;③ 实际产值来源(业务 SQL 未接 / 或指标 API A036);④ `process_task` 增加 data_table_type 校验,避免非预算任务误跑。
## 产值达成表 output_value 处理器落地(本回合,已改代码)
- 按用户提供的《产值达成表.xlsx》《关系表.xlsx》《8月SAAS+门店预算分解0806终版》三表反推映射:A列业务类型定 sheet(2.1+2.3→权益延保sheet1 / 1.1→轻改sheet2);C列=SAAS「区域运营」;B列=关系表「E区域经理→D大区经理」;E/F按门店去重;H/K=预估产值(纠偏)按存量/新增汇总。G/I/L 接口列暂落 NULL。
- 新增 `report_utils.parse_saas_achieve_details` / `parse_operator_relation`(按表头名定位,兼容月份表名变化);新增 `models.SaasBusinessAchievement`(对应结果表 A~O + task_id/周期);新增 `output_value_processor.OutputValueProcessor`(scan_output_value→process→_process_output_value,按 task_id 先删后 flush 后插,幂等);新增 `scheduler.OutputValueScheduler` 并注册进 `app.ALL_SCHEDULERS`。
- 验证:`py_compile` + 导入全过;用真实文件跑解析+聚合——权益延保 28 / 轻改 7 区域运营,**关系表匹配率 100%**;DB 冒烟写入 35 行并正确回读(哨兵 `/` 归一为 NULL),虚拟 task 数据已清理。
- 缺口①仍是待办(接口列 G/I/L 未接,连带 J/M/N/O 留空)。
## process_task 增加 data_table_type 校验/路由(本回合收尾,已改代码)
- `processor.process_task` 在 task 加载后、预算流水线前插入路由分支:`output_value` → `OutputValueProcessor(app=self.app).process(task)` 并 `return`(手动单任务触发亦可正确落库,不再误跑预算流水线)。
- 其余非 `SUPPORTED_PROCESS_TYPES` 类型(`store_effect_earnings`/`future_expansion`)仍走白名单拦截抛"引擎尚未接入"。`process_all` 原函数内已按 `data_table_type=='budget_achievement'` 过滤。
- 修正了 MEMORY.md / 本日志中"process_task 不校验/类型校验未加"的过时描述(校验与路由现已落地)。
- 编译 + 导入校验通过。
## 任务完成后生成结果表 Excel(本回合新增)
- 需求:产值达成任务跑完后要输出《产值达成表》结果文件(对应结果表 A~O 列)。
- 实现:`OutputValueProcessor.generate_result_excel(task)` 读 `saas_business_achievement` → 生成「业务达成总览」sheet(标题/表头/口径说明/数据,按业务类型排序)→ `upload_file` 上传 OSS → 回写 `task.result_file_url`;`process()` 末尾自动调用(对齐 `processor.py` 步骤 f/h 范式)。
- 端到端验证(真实三表,虚拟 task):35 行正确生成,A~O 列映射正确,H 金额 `#,##0.00`、E 整数 `#,##0`、G/I/L/J/M/N/O 接口列**真正留空(None)**。
- 关键坑修复:`saas_business_achievement` 的 DECIMAL 列带 DB 默认 `0.00`,`bulk_save_objects` 省略 None 列会落 `0`(误读为"已接入");改用 `db.session.add_all(rows)` 显式存 NULL。已记入 MEMORY.md。
- 待办:结果表模板其余 sheet(精品业务达成、1.1省份维度透视)依赖接口数据,暂未生成;G/I/L 接口接入后重跑即自动补数。
## 结果表第1行标题与「时间进度」修正(最新)
- 标题改为:`{month}月SAAS+业务各区域预算达成率-运营(截止"{period_end}")`,合并 `A1:M1` 居中(原 `(运营视角)` 文本废弃)。
- 「时间进度」列 O1 不再是字面公式,而是真实计算结果:`所属周期天数 / 统计月总天数 × 100%`,`round(…,2)` 保留 2 位小数,`number_format='0.00"%"'`。周期取 `task.period_start/period_end`(页面「所属周期」)。
- 端到端验证:部分周期 8/1~8/15 → O1=48.39%(15/31×100),整月 → 100.00%。
## 结果表布局对齐《产值达成表》模板(最新)
- 表头改为模板口径:A业务类型 / B+C合并=区域运营 / D线上运营 / E~O指标。**大区经理列已按用户最新口径移除**(B、C 均为区域运营,B:C 合并)。
- 第 3 行「口径说明」已删除(行3留空)。
- 每个业务类型明细后加小计行(`2.1+2.3小计`、`1.1小计`),末行加 `合计`;统计列:E/F/H/K 求和,J/M/O 由汇总值重算(rate 列用 `_aggregate` + `_safe_rate_pct`,×100 与数据行一致)。
- 模板末两行**静态保留**:`二手车`(M列, N=1863790, O==N/5600000 用 `0.00%` 格式)/ `总合计`(M列, N==N合计+N二手车, O==N/138000000 `0.00%`),公式引用合计行以便后续自动更新;此两行常量(1863790/5600000/138000000)照搬模板。
- 验证:小计求和正确(490+52=542 等),B2:C2 与每行 B:C 合并,行3空,二手车/总合计公式保留。
- 注意:模板比率列原生格式 `0.00%`(分数×100),我的数据行用 `0.00"%"`(×100 存储),两者单元格各自格式独立;二手车/总合计行刻意用模板 `0.00%` 以正确显示 33.28%/1.35%。
## 结果表布局再修正(最新 4 项反馈,已改代码并验证)
1. 行3「口径说明」整行删除 → 明细从行4上移为**行3**开始(`cur=3`、冻结 `A3`),无空行。
2. 数据行 B/C **不再合并**:去掉逐行 `merge_cells(B:C)`,B、C 各自独立单元格(均写区域运营)。仅表头 `B2:C2` 保留合并。
3. 小计/合计标签占 **A:B 合并**:`2.1+2.3小计`、`1.1小计`、`合计` 各加 `merge_cells(A:B)`(列C留空)。
4. 二手车/总合计 **后续单元格留空**:去掉 N(GMV 常数/公式)与 O(公式),仅保留 M 列标签。
- 验证(mock 3 行数据实际生成并 reopen 检查):merged = `A1:M1` / `B2:C2` / `A5:B5`(2.1+2.3小计) / `A7:B7`(1.1小计) / `A8:B8`(合计);行3 首条数据、B3=C3=区域运营独立;二手车/总合计仅 M 列有值、N/O 空。py_compile 通过。
## 结果表合并与边框再修正(最新,已改代码并验证)
1. A 列按业务类型纵向合并:每个业务类型的明细行 A 列合并为一格(`A3:A5` 等),对齐原产值达成表。
2. B、C 列相同相邻「区域运营」纵向合并:新增静态方法 `_merge_same_vertical(ws,start,end,col,values,border)`,对相邻相同值做 `merge_cells` 并对合并区内逐格补 `border`(openpyxl 合并后仅顶/底可见边生效,逐格补边框才显示完整边线);B、C 均套用(两列同值)。
3. 边框补齐:小计/合计行的 C 列(列3)原无边框,现显式 `ws.cell(row,3).border=thin`;二手车/总合计行前面列 `A~L` 合并(`merge_cells(1,12)`)并逐格补边框,M 列标签带边框,N/O 留空但补边框。
- 验证(mock:2.1+2.3 含相邻华东×2 + 华北×1,1.1 华南×1,实际生成 reopen):merged = `A1:M1`/`B2:C2`/`A3:A5`(业务类型)/`A6:B6`(小计)/`A8:B8`(1.1小计)/`A9:B9`(合计)/`B3:B4`+`C3:C4`(华东纵向)/`A10:L10`(二手车)/`A11:L11`(总合计);各小计/合计 C 列、二手车/总合计 C/N/O 边框均 True。
## B 列取值修正(最新,已改代码并验证)
- 问题:`RESULT_COLUMNS` 的 B 列误写为 `region_operator`(与 C 列同值),导致 B 显示「区域运营」而非「大区经理」。
- 修正:B 列改用 `manager`(大区经理)字段;C 列保持 `region_operator`(区域运营)。表头 `B2=大区经理`、`C2=区域运营`,并**取消 B2:C2 合并**(两列含义不同,不再合并)。
- 取值链路(生产侧本就正确,仅输出错了):`_process_output_value` 中 `manager = line_map.get(region_operator, '')`,即以 C 列(区域运营) 为键查关系表 E(区域经理)→D(大区经理),存于 `SaasBusinessAchievement.manager`;结果表 B 列直接读该字段。
- 纵向合并同步:B 列(大区经理) 与 C 列(区域运营) 各自用独立序列做 `_merge_same_vertical`(相邻相同值合并)。
- 验证(mock 设 manager=华东大区/华北大区/华南大区 + 相邻华东大区×2,实际生成 reopen):B2=大区经理 C2=区域运营、B2:C2 未合并;B 列=华东大区/华北大区/华南大区,C 列=华东一区/华东二区/华北一区/华南一区;`B3:B4`(华东大区纵向) 合并、`A3:A5`(业务类型) 合并。
## B 列为空不合并(最新,已改代码并验证)
- 修正 `_merge_same_vertical`:值为 None 或空串时**不合并**,仅逐格补边框、单列处理。
- 影响:B 列(大区经理) 为空(关系表无匹配→存空串)时,相邻空行不再纵向合并。C 列同口径(空不合并)。
- 验证(mock:r3 华东大区、r4/r5 大区经理为空且相邻):`B3:B4 merged? False`;A3:A5(业务类型) 与 C 列相邻相同合并仍正常。
## git 分支挪移(产值达成表功能 main→v1.1,本轮回退 main)
- 起因:产值达成表功能先前提交在 `main` 的 `cac5de2`(含全部 Excel 精细改动:B=大区经理、空不合并、_merge_same_vertical 等都在该提交内,非半成品)。
- 操作:在 `v1.1` 上 `git cherry-pick cac5de2` → 新提交 `b3b24d5`(产值达成表基础数据)。
- 唯一冲突 `report_utils.py`:v1.1 侧是嘀加 SQL 函数(fetch_biz_sql_aggregated/fuzzy_match_store),cac5de2 侧是产值解析函数(parse_saas_achieve_details/parse_operator_relation 等),两函数集无重叠 → 移除冲突标记、两边都保留,py_compile 通过。
- `main` 本地 `git branch -f main cac5de2^`(=45b68eb),**不推送**(按用户选择)。origin/main 仍含旧历史,远程未动;如需彻底撤回远程需后续 force push(用户自决)。
- 注:上一轮"指标接口改造"实际未落地——indicator_client.fetch 仍为单 `biz`、report_utils.fetch_indicator_data 仍收单 biz_code,bizs 列表改造未完成;待继续。
## 指标系统接口接入(G/I/L 列,本轮回填落地)
- 参数(用户确认):itemCodes=`A036`(产值);2.1+2.3→bizs=[1,3]、1.1→bizs=[2];均非率不×100;按 `store_name` 匹配 API `merchantName` 逐一求和;G=全部门店=I+L。
- bizs 序列化格式(用户确认):多业务线用**逗号字符串** `bizs="1,3"`(与 itemCodes 风格一致),单值走原 `biz`=2。
- 改动:
1. `indicator_client.py`:`fetch` 的 `biz` 支持 list→`payload["bizs"]=",".join(...)`;int 仍走 `"biz"`(向后兼容 light_reform 等单值调用方)。
2. `report_utils.py`:`fetch_indicator_data` 文档补 biz 可 int/list;逻辑不变。
3. `output_value_processor.py`:导入 `fetch_indicator_data`;新增 `INDICATOR_ITEM_CODES=['A036']`、`BIZS_MAP`;`_process_output_value` 在聚合前按业务类型预拉取指标(带门店匹配覆盖率日志);`_sum_indicator` 按门店名匹配 merchantName 求和(未匹配/接口空→落 NULL 而非 0);I=存量门店和、L=新增门店和、G=I+L。
- 验证(mock 数据实际生成并 reopen Excel):
- Test A:bizs=[1,3]→payload `bizs:"1,3"`;biz=2→`biz:2`。
- Test B:华东 G=16725(I 16170+L 555)、华南 G=1887;故意不返回的「北京YY店」所在华北组 G/I/L 全 NULL。
- Test C:全链路 Excel 华东 G=85000 I=80000 J%=80 L=5000 M%=25 N=85000 O%=70.83;华南 I=40000 J%=80 L=2000 M%=20 N=42000 O%=70。G/I/L 与 J/M/N/O 达成率全部按接口值正确展示。
- 待真实环境验证:本沙箱无法连通 `http://dc.glsx.com.cn/data`,需在生产跑一次真实任务确认门店名匹配率与返回编码格式(A036 是否确为非率、bizs 字符串是否被后端正确解析)。
## 指标 G/I/L 查询周期修正:整周期累计→统计周期最后一天(最新,已改代码)
- 问题:用户实测 G 列是「当前周期内全部数据」而非「当日」。例:刘冬雪+岚图汽车北京大兴分公司,单日(2026-08-31) API 返回 A036=18797,但生成表 G=580922(≈18797×31,即整月累计)。根因:`_process_output_value` Step3.5 用 `fetch_indicator_data(start_str, end_str, ...)` 拉了整周期。
- 修正:G/I/L 均为「当日」口径(G 列名即「当日新增GMV」),故 `startDate=endDate=end_str`(统计周期结束日,单日查询);条件由 `if start_str and end_str` 改为 `if end_str`。同步更新模块 docstring 与 Step3.5 注释。
- 影响:`_sum_indicator` 求和逻辑不变(仍按门店名匹配 merchantName 求和),仅入参日期范围收窄为单日 → G/I/L 取最后一天实际值。py_compile 通过。
## 指标口径二次修正:仅 G=最后一天,I/L=整周期累计(最新,已改代码)
- 用户纠正:上一条「G/I/L 均取最后一天」是错的。**只有 G 列「当日新增GMV」取最后一天单日值;I 列「存量门店实际达成」与 L 列「新店实际达成」取整周期(start_str→end_str)累计。**
- 实现:Step3.5 分别拉两份指标 map —— `indicator_period_by_biz`(整周期, 供 I/L) 与 `indicator_last_day_by_biz`(最后一天 end_str, 供 G);若 start_str 缺失则 I/L 的 period map 为空(I/L 落 NULL)。
- 聚合:`existing_actual`/`new_actual` 用 `ind_period` 按 existing_stores/new_stores 求和;`daily_new_gmv`(G) 用 `ind_last` 按 `all_stores`(存量+新增去重) 求和。**注意 G 不再等于 I+L**,与结果表列义一致(G=当日快照,N=实际达成GMV合计=I+L 整周期)。
- py_compile 通过;无遗留 `indicator_by_biz` 引用。
## G/I/L 缺数据填充 0(最新,已改代码)
- 用户要求:G/I/L 三列若未匹配到指标数据(ind_map 空 / 门店名不匹配 / 门店列表为空),结果表**填充 0 显示**,不再留空。
- 改动:`_sum_indicator` 不再返回 None,未匹配一律返回 `Decimal('0')`(覆盖 ind_map 空、列表空、均不匹配三种情形);聚合处去掉 `if ... else None` 守卫,`existing_actual/new_actual/daily_new_gmv` 恒为 Decimal。
- 连带:J/M/N/O 达成率原 `if x is not None else None` 守卫删除,现由 G/I/L 与预算直接重算(实际 0 → 达成率 0%;预算 0 时 safe_div_pct_decimal 返回 0)。N=实际达成GMV合计=I+L(整周期)。
- 影响:DB 列现为显式 0 而非 NULL;`add_all` 写入仍安全。Excel `_write_cell` 对 0 正常显示(金额 0.00、比率 0.00%)。py_compile 通过;无遗留 `is not None` 守卫。
## 门店店效人效汇总表(第5个sheet,独立处理器,本回合落地)
- 需求(用户确认):用户做「门店店效人效汇总表」结果输出,放合并结果表**第5个sheet**;其他 4 个 sheet 由同事做(红黄门店盈利测算 轻改/延保权益)。同源数据,结果表需含三份输出合并到一个 Excel。口径:**从源数据重新计算**(不读 4 张报告表)、**整体合计不分组**(无门店明细)、**先出骨架数字待校准**(BIZ_SQL_ENABLED=false 时业务系统 SQL 字段恒为 0)。
- 新增 `store_effect_summary_processor.py`:`StoreEffectSummaryProcessor`(scan_store_effect_summary→process→_process_summary→generate_result_excel)。_process_summary 解析 SAAS 延保2.3/权益2.1/sheet2店中店1.1/sheet2_exclude园区店1.1 → 逐店计算(交车/触客/成交/产值/成本/毛利/人力/人员数)→ 累加为整体合计一行 → 先删后插 `report_store_effect_summary` 单任务一行 → 生成单 sheet「门店店效人效汇总表」(标题/表头/数据/说明) → 上传 OSS → 回写 `task.result_file_url`。
- 口径细节:延保/权益 产值=A036、成交=A075、触客=A084、交车=主机厂表;成本=市场费+营销费(商务 labor_ratio×产值)+服务费(非直营);轻改 产值=业务SQL store_output_value(0待校准)、成交=A075、交车=日报 delivery_cnt、人力=直营(headcount×3500+产值×4%);人效=产值/人员数、毛利/人员数。毛利率=safe_div_pct_decimal。
- 注册:`report_utils.ALL_OUTPUT_CATEGORIES` 已含 `'store_effect_summary'`;新增 `scheduler.StoreEffectSummaryScheduler`(OUTPUT_CATEGORY='store_effect_summary') 并加入 `app.ALL_SCHEDULERS`;`processor.process_task` 增加 `store_effect_earnings` 路由到 `StoreEffectSummaryProcessor`(手动单任务触发可正确落库,不再误跑预算流水线 / 不再被白名单拦截)。
- 修复两个运行时 bug:① 轻改分支 `delivery` 行括号不匹配(语法);② 商务预算原在 `cleanup_tmp_dir` 删除下载文件后才重解析(`file_map['预算达成数据(商务)']` 还会 KeyError),改为在 try 内 cleanup 前统一解析并加默认值,避免 use-after-cleanup。
- 验证:`py_compile` 全部通过(store_effect_summary_processor/models/report_utils/scheduler/app/processor);grep 逐项核对全部导入符号(STORE_EFFECT_EARNINGS_TYPE/BIZ_TYPE_*/INDICATOR_BIZ_MAP/INDICATOR_BIZ_MAP 键/各 parse/fetch/fuzzy_match/subtask helpers 均存在)、各 helper 返回结构(fetch_indicator_data→{merchantName:{itemCode}}、fetch_biz_sql_aggregated/fetch_park_daily_report→BIZ_SQL_ENABLED=false 返回 {}、parse_labor_cost→{store:headcount}、parse_saas_base→含 store_name/resident_type、sheet2→含 store_name/operate_type、parse_delivery_table→{store:cnt})与 ORM 列(ReportStoreEffectSummary 12 字段+task 元数据完全匹配)。**沙箱 guarded import 仅因缺 dotenv 等第三方依赖失败(环境限制,非代码问题)**;全链路真实冒烟需生产 DB+附件+OSS 凭证,沙箱不可达,待生产跑一次确认。
- 待办/风险:① 本模块为骨架,业务系统 SQL 字段需开 BIZ_SQL_ENABLED 并校准;② 同事的 延保/权益 处理器(earnings_report_processor.py:170 / equity_processor.py:172)仍引用未定义 `indicator_data`(NameError,与本模块独立、不互相依赖);③ 最终合并到一个 Excel(5 个 sheet)的拼装尚未实现(用户/MEMORY 待明确谁来合并)。
# 2026-09-07 工作日志
## 店效人效及盈利测算 模块进度盘点(分析,未改代码)
### 现状结论(基于代码实测)
- 4 处理器 + 4 ORM 报告表 + 4 子调度器 + DataProcessSubtask 状态机均已就位,调度器在 app.ALL_SCHEDULERS 注册。
- **但 4 张报告表行数均为 0**:历史上 store_effect_earnings 任务的 COMPLETED 来自页面 mock 接口,从未真实跑成功过。
- **致命 Bug**:`earnings_report_processor.py:170` 与 `equity_processor.py:172` 引用未定义的 `indicator_data`(Step2 指标系统 API 在代码里被删/漏写,仅 docstring 保留),运行时必抛 NameError → 延保/权益处理器根本跑不出数据。
- **轻改 inshop/park 处理器**:能跑(park 在 Step2 定义了 indicator_data),但**产值/成本类字段恒为 0**——依赖业务系统 SQL 的字段仍是 `biz_sql_data` TODO 占位(fetch_park_daily_report 只给交车/到店数,产值/毛利/成本无 SQL 映射)。故毛利测算失真。
- **无 Excel 结果输出**:4 个店效人效处理器都只写 DB 报告表,**不生成结果文件**(没有像 output_value_processor 那样的 generate_result_excel + result_file_url 回写)。app.py 的 /download 取 task.result_file_url,但店效人效任务从未回写该 URL → 结果表 Excel 目前不存在。仅产值达成表有 Excel 产出。
### 已完成的数据解析(按处理器)
- 延保 warranty:parse_saas_base(biz=2.3) / parse_region_map / parse_delivery_table(主机厂) / parse_budget_achieve_excel(预算达成-商务) / 指标A084触客+A075成交+A036产值+A066/A070/A086延保 / fetch_biz_sql_aggregated(嘀加)。
- 权益 equity:同结构 biz=2.1,指标 biz=3。
- 轻改店中店 inshop:parse_saas_base_sheet2(含品牌) / parse_region_map / parse_park_delivery_touch / parse_commerce_policy_park / parse_labor_cost / parse_budget_achieve_excel;fetch_park_daily_report(scene=1) 给交车/到店;产值/成本 SQL 占位。
- 轻改园区店 park:parse_saas_base_sheet2_exclude / parse_park_delivery_touch / parse_commerce_policy_park / parse_labor_cost / parse_budget_achieve_excel;fetch_indicator_data(A075)+fetch_park_daily_report;产值/成本 SQL 占位。
### 同源数据源清单(4 处理器共用)
SAAS门店预算分解表 + 关系表 + 主机厂数据表(鸿蒙/广联) + 预算达成数据(商务) + 园区店交车触客表 + 商务政策表(园区店) + 人力成本表 + 指标系统 API + 业务系统 SQL(嘀加 dj_smartcarlife)。
### 用户新需求(待澄清后实现)
- 用户负责「门店店效人效汇总表」输出,放在合并结果表的**第三个 sheet**;同事负责 sheet1=红黄门店盈利测算 轻改、sheet2=红黄门店盈利测算 延保权益。数据源同一份,结果表需包含三份表输出。
- 待澄清:①汇总表数据来源=读 4 张已算报告表 or 重算源数据;②粒度=门店级明细 / 片区聚合 / 两者;③合并导出如何组织(新建读 4 报告表生成单 xlsx 三 sheet,还是只产出 sheet3)。
## 门店店效人效汇总表 结果输出(本轮实现 + 修 bug)
### 用户反馈
- "无法生成结果表,先实现结果的输出 可以只有我的这部分的第5个sheet" → 优先让第5个sheet的单 Excel 可控产出(骨架数字待校准即可)。
### 修复 store_effect_summary_processor.py(3 处)
1. 原 `_process_summary` 在缺 SAAS 附件时 `raise Exception` → 整段中止、Excel 永不生成。**改为骨架模式**:缺附件仅 warning,base_records 为空、指标/SQL 取 0,仍走完入库+生成 Excel。
2. 原权益/延保 `ind`/`biz` 用 `A or B or {} if cond else C` 条件表达式,**运算符优先级错误**(解析为 `A or B or ({} if cond else C)`),权益门店可能误读延保指标/SQL。**改为显式 if/else**。
3. 指标/业务SQL拉取包 `_safe_indicator/_safe_sql`:失败降级为 `{}` 而非抛异常中止。
4. `generate_result_excel` 新增 `local_only=True`:本地落盘到 `outputs/store_effect_summary/`,不依赖 OSS 配置即能拿到文件。
### 新增独立生成脚本 generate_store_effect_summary.py
- `--demo --month 2026-08`:纯 openpyxl 生成骨架样例,**无需数据库/凭证**(沙箱可跑,已验证产出 xlsx)。
- `--task-id <ID>`:应用上下文读 report_store_effect_summary 行 → 处理器生成(默认 local_only 本地落盘;`--oss` 上传并回填 result_file_url)。
- 验证:py_compile 通过;demo 生成 `outputs/store_effect_summary/门店店效人效汇总表_2026-08.xlsx`,12 列、数字格式(#,##0 / #,##0.00 / 0.00"%")、标题/表头/数据/说明四行均正确。
### 待办
- 生产环境真实任务跑一次端到端(解析→入库→Excel→OSS 回填)。
- 同事 equity/warranty 处理器 `indicator_data` NameError 仍待修(合并5-sheet 前置)。
- 5-sheet 合并拼装未实现。
## 任务29 真实跑通 + 根因修复(关键)
### "无法生成结果表" 的真正根因(3 层 bug,已全部修复)
1. **SAAS 在 cleanup 之后才解析**:`_process_summary` Step1 的 `try/finally` 在解析完其他源文件后 `cleanup_tmp_dir`,而 SAAS 解析原在 Step3(cleanup 之后)→ `No such file` → 所有业务 base_records 为空 → 全 0。已把 SAAS 解析移入 Step1 try 内(cleanup 之前)。
2. **`find_header_row` 误把标题行当表头**:标题「8月SAAS+延保权益门店预算分解」含"门店"→ 被当作表头行,真实表头行(含 门店/品牌/省份/业务类型…)被当成数据 → `store_name` 误匹配标题单元格,551 条垃圾行。**已改为按"表头特征关键字命中数最多"打分选行**(HEADER_HINT_KEYWORDS,score 最高者)。
3. **`match_columns` 子串误命中**:store_name 关键词无"门店"(只有 门店名称/门店名/厅店名称/store_name),而本文件列名就是"门店";且"门店"子串会误命中"门店类型"(列序更靠前)。**已让 `match_columns` 先精确相等、再子串包含**,并向 3 个 SAAS 解析器的 store_name 关键词追加 `'门店'`。
### 附带修复
- `_process_summary` Step7 回填时引用未导入的 `DataProcessTask` → NameError。**已在模块 import 增加 `DataProcessTask`**。
- 重排 Step6/Step7:先生成 Excel(保证结果表一定产出),再 best-effort 入库/回填(失败不影响文件)。
### 任务29 真实结果(store_effect_summary_2026-10_29.xlsx)
- 门店数=498、交车数=7961(来自 主机厂/广联,真实);已上传 OSS 并回填 `task.result_file_url`。
- 仍 0 的字段(数据/周期原因,非代码 bug):
- 产值/成交/触客=0:任务周期 2026-10 是**未来月**(今天 2026-09-07),指标系统无该月数据。
- 人力成本/人员数=0:`人力成本表-密码2026.xlsx` **密码保护**读取失败,需提供未加密版。
- 鸿蒙主机厂数据表"未找到门店名列"→其交车未计入(仅广联计入);该文件列名结构异常,待单独核对。
- 本地副本:`outputs/store_effect_summary/门店店效人效汇总表_2026-10.xlsx`(用 `python generate_store_effect_summary.py --task-id 29` 生成)。
### 复跑验证命令
- 骨架/样例:`python generate_store_effect_summary.py --demo --month <月>`
- 真实任务:`python generate_store_effect_summary.py --task-id <ID>`(本地落盘)/ 加 `--oss` 上传回填
- 直接重算某任务:`StoreEffectSummaryProcessor().process(task)`(需先 `update_subtask(task_id, 'store_effect_summary', SUBTASK_PROCESSING)` 清状态)
## 「重新计算后一直显示处理中」根因与修复(本轮)
### 根因
- `/api/tasks/<id>/regenerate`(重新生成)只把主任务置 `status='PROCESSING'`、清空 result_file_url、重建子任务,然后**依赖调度器**扫描 PROCESSING 任务来跑。
- 旧 `StoreEffectSummaryProcessor.process()` 成功时仅把**子任务**置 COMPLETED,**从不把主任务 `DataProcessTask.status` 置 COMPLETED**(`report_utils.py:182-185` 注释写明"总表逻辑 finalize_all_subtasks_done() 后续统一接入"从未实现)→ 主任务永远停在 PROCESSING → UI 一直显示"处理中"。
- 旧代码还有 `is_subtask_completed` 早退:重算子任务已 COMPLETED 时直接 return,连重算都不触发、主任务更不会被收敛。
### 修复(store_effect_summary_processor.py)
1. 删除 `is_subtask_completed` 早退,改为**每次都重算**(delete-then-insert 幂等,安全)。
2. 新增 `_finalize_main_task(task_id)`:主任务为 PROCESSING 时置 `status='COMPLETED'`、清空 error_msg、兜底回填 result_file_url(用已入库汇总行重生成),并在 process() 成功路径调用。
3. 现状:任务 29 经此修复后 `status=COMPLETED`、`result_file_url` 已回填,新触发会在 60s 调度周期内收敛为完成。
- 注:调度器默认 SCHEDULER_ENABLED=true、间隔 60s;若禁用则 regenerate 后无人处理,需走 `/api/tasks/<id>/process` 手动触发(该接口路由到 StoreEffectSummaryProcessor.process,同样会 finalize)。
## 拿到正式模板:门店店效人效汇总表 = 总看板(非12列单行表)
### 重大认知纠正
- 之前实现的 12 列单行汇总表是**错误简化**。正式模板 `门店店效人效汇总表.xlsx` 含 **2 个 sheet**:
- `总看板`:约 45 个指标的双列看板(标签列 A/C/E/G/I/K,值列 B/D/F/H/J),行 3-11(门店/预算/产值/人力)+ 行 13-23(1.1/2.1/2.3/6.1 各指标 + 流失新增门店);右上 R-U 列(18-21) 是 2.1/2.3/1.1/6.1/合计 的 存量目标·新增目标·总计目标(万) 小表。
- `字段说明`:78 行,逐字段写明取数来源(权威口径)。
- 用户确认:**从源重算**(不读同事 report_* 结果表);豪华判定用 **config_brand_category**。
### 关键坑(务必记住)
1. **`is_luxury_brand()` 是坏的**:它查 `luxury_brand_config` 表 **0 行** → 所有门店恒判「非豪华」。
正确源是 **`config_brand_category`(18 条,全是豪华:AITO/鸿蒙智行/奥迪/腾势/奔驰/领克/AITO&鸿蒙/宝马mini/问界/红旗/凯迪拉克/Smart 等)**,未命中即非豪华,需**模糊匹配**(配置值可能是原始品牌名的子串或反之)。
2. **SAAS 列名含换行**:`预估产值\n(预算目标)` / `预估产值\n(纠偏)` → 匹配前必须 `norm_col`(去换行/空格/全角括号)。
3. **sheet1 无「存量/新增」列**(只有 拓店类型/门店类型红黄绿/驻店类型/品牌/业务类型);只有 **sheet2 有 `性质`∈{存量,新增}**。→ 存量/新增需按门店去重后统一归类,否则 存量+新增≠总数(曾算出 534+3≠498)。
4. **sheet1 真实表头在第 1 行(第 0 行是标题),sheet2 在第 0 行**。
5. **8月数据 纠偏值 == 预算目标值**(本月未纠偏),所以 经管预算目标 = 全国经营总预算 = 117,172,565.5 是**数据事实非bug**。
6. **二手车汇总销售台账 R2 是「合计」行必须跳过**;收购/拍卖日期是 **Excel 序列号**需转换;库存口径「拍卖日期为空且处置类型≠寄售」中**处置类型为空也算非寄售**(否则得 0)。
7. `to_decimal` 必须先用 `pd.isna` 拦 NaN,否则 `Decimal(str(nan))` = `Decimal('NaN')` 污染所有求和(曾致全部预算=NaN)。
### 新增构建器 build_store_effect_board.py
- 直接读桌面上提供的源数据文件,按模板重算并输出「总看板 + 字段说明」两个 sheet。
- 用法:`python build_store_effect_board.py --src <数据源目录> --month 2026-08 --period-start 2026-08-01 --period-end 2026-08-31`
- 已算出的真实值(2026-08):门店总数 498(豪华 278/非豪华 220)、存量 495/新增 3、直营 372(豪华 213/非豪华 159)、经营总预算 117,172,565.5(存量 117,001,365.5/新增 171,200)、1.1预算 8,197,720 / 2.1预算 6,910,275 / 2.3预算 102,064,570.5、交车 1.1=945 / 2.1=373 / 2.3=7,562、6.1产值 1,394,810 / 处置 51 / 收车 64 / 库存 51 / 交付平均车价 15,281.08。
### 人力成本表已接入(密码 2026)
- 文件是 **OLE2 加密容器**(magic `d0cf11e0`,非 zip → openpyxl 报 `BadZipFile`),需 **msoffcrypto-tool** 解密(密码 `2026`)。
- 结构:sheet `人力成本` 1196 行 × 44 列;关键列 **B=工号 / D=入驻门店 / F=岗位 / AF=检核**。
注意 **AG 也叫「检核」**,解析时列名索引要**取首次出现**(否则误用 AG=False 会全被过滤掉)。
- 口径:检核(AF)=TRUE → 过滤 岗位≠离职 → 按 **工号去重**(一人多行,按门店/业务线展开)。
- 构建器已内置 `_resolve_hr_path()`:zip 直接读;OLE2 则复用 `outputs/tmp/hr_decrypted.xlsx` 缓存,无缓存时用 msoffcrypto 解密。
(msoffcrypto 装在隔离 venv `C:/Users/66/.workbuddy/binaries/python/envs/default`,项目 python 未装;生产部署需 `pip install msoffcrypto-tool`)
- 算出的值(2026-08):直营总人数 **688**、营销人数 **526**、店均人数 **1.41**;豪华员工 **353**/营销 **290**/店均 **1.04**;非豪华员工 **177**/营销 **158**/店均 **0.72**。
- 缺口:豪华353+非豪华177=530 < 总人数688,**158 人**的「入驻门店」未匹配到 SAAS 门店(人资含非运营门店人员);营销侧 290+158=448 < 526,差 78 人。属正常口径差,需业务确认。
### 指标系统已接入(复用已有封装,但发现 API 缺陷)
- 封装位置:`indicator_client.py` 的 `IndicatorClient.fetch(start,end,biz,item_codes)`;`report_utils.fetch_indicator_data()` 是适配函数。
返回 `{merchantName: {itemCode: Decimal}}`。指标码:**A036=产值 / A075=成交 / A084=触客**。
- 业务码 `INDICATOR_BIZ_MAP`:warranty(延保2.3)=**1**、equity(权益2.1)=**3**、light_reform(轻改1.1)=**2**。
- **⚠️ 严重 API 缺陷**:传**单值 biz**(payload 键 `biz`)时 **API 会忽略该参数**,biz=1/2/3 返回完全相同(都是全业务 93,020,647.64);
必须传**列表**(payload 键 `bizs="N"`)才生效。实测可加总:
延保[1]=81,385,295.2 + 权益[3]=3,351,856.0 = [1,3]=84,737,151.2;+轻改[2]=8,283,496.44 = [1,2,3]=93,020,647.64。
→ **任何需要分业务取数的调用都必须用列表形式** `[biz]`,否则会重复计算成全业务值。(现有 store_effect_summary_processor 等若用单值也有此隐患)
- 算出的值(2026-08):全国经营总产值 **88,047,249.84**;1.1产值 6,221,030.44 / 2.1产值 2,660,748 / 2.3产值 78,108,742.8;
达成率 1.1=75.89% / 2.1=38.50% / 2.3=76.53%;成交单数 1757/1060/8228;接待数 1551/2119/13653;
店均产值 豪华 272,684.20 / 非豪华 55,641.10;人均产值 全国 167,390.21 / 豪华 261,400.72 / 非豪华 77,474.94。
- **待确认**:列名带 `(w)`(店均产值(w)/人均产值(w))是否要 **÷10000 换算成万元**?字段说明给的公式只做除法未提换算,当前按字面未换算。
- **仍为 0**:1.1/2.1/2.3 毛利率 及 毛利率(含人力)——需「毛利测算/营销成本/人力成本」,来自同事结果表口径,非指标系统。
### 仍为 0(源未接入,已在字段说明里标注)
- **指标系统 A036产值/A075成交/A084触客** 未接 → 全国经营总产值、店均产值、人均产值、1.1/2.1/2.3 产值·毛利·接待·成交 全 0。
- **系统数据**(闭店日期/商户创建/品牌归属)未接 → 流失/新增门店及其豪华拆分 全 0。
- **鸿蒙主机厂数据表** `未找到门店名列` → 交车数只统计了广联,鸿蒙未计入。
- 目标小表(存量/新增/总计目标 万)**字段说明未定义取数**,留空待填。
### (补正)130-134 段为早期记录,后续已接入
- 人力成本表、指标系统 A036/A075/A084 后续均已接入(见上「人力成本表已接入」「指标系统已接入」两段),130-134 的"未接=0"已不成立。
### (w) 万元换算已落地(用户确认)
- 用户确认:**模板列名含 `(w)` 的指标必须 ÷10000 换算成万元**。
- 实现位置:`build_store_effect_board.compute_metrics` 返回前做数据驱动后处理——遍历 `m` 所有 key,凡含 `(w)` 或 `(w)` 且值为数值,则 `Decimal(v)/10000`(quantize 1.0000)。
- 不含 (w) 的列(如「豪华车人均产值」)不换算,保持元。
- 2026-08 换算后:豪华车店均产值(w)=**27.2684 万**、非豪华车店均产值(w)=**5.5641 万**、全国人均产值(w)=**16.7390 万**、非豪华车人均产值(w)=**7.7475 万**。
### 修复:页面「重新生成」出单行 12 列(应为双列看板)
- 根因:页面 regenerate 走 `StoreEffectSummaryProcessor.process → _process_summary → generate_result_excel`,原 `generate_result_excel` 只渲染单行 12 列(RESULT_COLUMNS),与本地双列看板两套逻辑未打通。
- 已改造 `store_effect_summary_processor.py`:
1. `_process_summary` 在 `download_all_files` 的 tmp_dir 内、`cleanup_tmp_dir` **之前**,调 `from build_store_effect_board import compute_metrics; board_m = compute_metrics(tmp_dir, period_start, period_end)` 算 45 项双列看板指标。
2. `generate_result_excel(task, row, board_metrics=None, ...)`:`board_metrics` 非空时改调 `render_board(board_metrics, excel_path, month_label)` 渲染「总看板 + 字段说明」并上传 OSS;为 `None` 时回退原单行(兼容 `generate_store_effect_summary.py --task-id`)。
3. `compute_metrics` 内 `load_brand_category`/`fetch_indicator_data`/`parse_delivery_table` 均为局部 import(需 app context 的由函数内部自开),后端 import 安全;已 `py_compile` 通过。
- 注意:人力表解密复用 `outputs/tmp/hr_decrypted.xlsx` 缓存(后端若未装 msoffcrypto 也 OK);换月份/新人表需 `pip install msoffcrypto-tool` 或重建缓存。
- 验证:本地重跑 `build_store_effect_board.py` 已生成含万元换算的双列看板;页面 regenerate 需在改后**重新点一次**才会走新逻辑(旧任务点过的是旧代码)。
### 任务 32(store_effect_earnings / 2026-08)生成失败 — 根因与修复
- 现象:DB `data_process_task.id=32` 状态 FAILED,`error_msg='name '\''indicator_data'\'' is not defined'`。
- 根因 1(直接失败):`earnings_report_processor.py`(warranty) 与 `equity_processor.py`(equity) 在 Step5 直接用 `ind = indicator_data.get(...)`,但**从未定义 `indicator_data`**(对比 `light_reform_park_processor.py` Step2 有正确定义)。NameError。
- 根因 2(修完根因1 后暴露):比率列 `DECIMAL(10,6)`(上限 9999.999999)溢出。
- `marketing_fee_ratio = extract_budget_ratio(prev_labor_ratio_map, store_name, 'labor_ratio')` 直接取 Excel 原始值,可能把预算达成表的「人员工资」**绝对额列**误匹配成占比(实测值 12350.41)→ 溢出。
- `cost_ratio`/`gross_profit_rate = safe_div_pct_decimal(total_cost, store_output_value)` 当 `store_output_value` 极小(脏数据,如某店成本 -21.9 亿/产值 1.09 万、甚至 -1.19 万亿)→ 比值超界溢出。
- 根因 3(级联污染):`report_utils.promote_subtask_failure_to_main_task` 写 `error_msg` 时 `'...: ' + '; '.join(err_parts)[:500]` 先截后拼前缀 → 总长超 500 → `Data too long` → `PendingRollbackError` 把整个 session 搞废,连带其余 4 个 processor 全 FAIL。
- 修复:
1. earnings/equity 的 `_process_extended_warranty`/`_process_equity_service` Step2 补 `indicator_data = fetch_indicator_data(start_str, end_str, [INDICATOR_BIZ_MAP.get('warranty'/'equity')], codes)`,且**必须用列表形式**(防单值 biz 被 API 忽略,见上 120-123);包 try/except 回退 `{}`。
2. `report_utils.safe_div_pct_decimal` 内对结果 clamp 到 `±9999.999999` 并 `logger.warning` 揭示(num/den);新增 `clamp_ratio()` 工具,`marketing_fee_ratio = clamp_ratio(extract_budget_ratio(...))` 包裹(earnings/equity 两处)。
3. `promote_subtask_failure_to_main_task` 改为 `(前缀 + join)[:500]`(先拼后截)。
- 验证:5 个 processor(warranty/equity/inshop/park/summary)用新代码全部 OK,任务 32 主任务已手动收敛 COMPLETED,5 子任务全 COMPLETED(warranty 419 / equity 133 / inshop 32 / park 20 / summary 1 行),summary OSS 结果文件已上传。
- **⚠️ 必须重启后端/调度器进程**:后台常驻调度器加载的是旧代码(未热更新),会抢跑并把任务又置 FAILED。修复只对重启后的新进程/下次手动触发生效。用户下次点「重新生成」前须重启服务。
- 脏数据待核对:比率 clamp 警告暴露多家门店成本/产值异常巨大(负万亿级别),以及预算达成表列名匹配把「人员工资」当「占比」。clamp 仅防崩溃,这些门店比率被截断到 ±10000% 不真实,需回源核对。
### 全国经营总产值 口径更正(用户拍板)
- **原口径(错)**:`ind_sum(ind_all, all_stores, 'A036')` —— A036 指标产值**不含二手车业务**,且按 SAAS 498 门店名做匹配,结果 88,047,249.84。
- **新口径(对)**:用户明确「A036 不含二手车,全国经营总产值需含二手车 → 改用 **A0018**,不传 bizs 直接查全量总数、不做门店匹配」。
- 实现:`ind_total = fetch_indicator_data(start, end, None, ['A0018'])`(biz=None → 全量含二手车),`全国经营总产值 = Σ 所有商户 A0018`(不按门店匹配)。豪华/非豪华店均产值同步改用 A0018(按门店匹配)。1.1/2.1/2.3 产值保持 A036(它们是汽车服务业务,不含二手车,A036 正确)。
- 实测 2026-08:A0018 全量 = **97,681,597.64**(497 商户);A036 全量 = 93,020,647.64;差额 4,660,950 = 二手车+其他。全国人均产值(w) 由 16.74→**18.5706 万**。
- **关键**:A0018 必须**不传 bizs**;若传 `bizs=[1,2,3]` 会把二手车业务过滤掉(得 93.02M),与"含二手车"相悖。
### 全国直营总人数 688→666 修复(用户核对)
- 用户算出 666(人力表 AF=TRUE、岗位排除离职人员、按工号去重);我方原算 688。
- **根因**:人力表「岗位」列离职人员的值实际是 **`离职人员`**(22 条),不是裸 `离职`。原代码过滤 `r['position'] != '离职'`(精确相等)漏掉这 22 条 → 多算 22 人(688-666=22,且这 22 工号均唯一不重叠)。
- **修复**:`build_store_effect_board.py` `not_left` 改为 `if '离职' not in r['position']`(子串排除,覆盖 `离职人员`/未来变体)。
- 实测(正确环境,flask+DB 品牌分类生效):全国直营总人数=**666**、营销人数=526(不变);豪华员工 353→**344**、非豪华员工 177→**171**(离职人员按入驻门店映射分摊扣减,其余 158 人入驻门店未匹配 SAAS 门店仍属正常口径差)。
- ⚠️ 本地重建必须用 **`C:/Python314/python.exe`**(有 flask+DB)从 `data-process` 目录跑;隔离 venv(managed 3.13.12)缺 flask 会让 `load_brand_category` 失败→全店判非豪华→豪华维度全 0,会污染输出文件。
### 存量门店数量 495→433 / 新店数量 3→67 修复(用户核对)
- 用户口径:门店预算分解表 **sheet1「存量/新店」(A列)=存量** ∪ **sheet2「性质」(J列)=存量**,门店名去重 = 存量门店数量;新增同理(sheet1 存量/新店=新增 ∪ sheet2 性质=新增)。
- **根因**:`parse_saas` 解析 sheet1 时**根本没读「存量/新店」列**,硬编码 `nature=''`,并把整张 sheet1 当存量;计数器用 `总门店数 − (sheet2 新增且不在 sheet1)` → sheet1 新增(81 行/64 店)被误算成存量,且 sheet2 新增仅 3 店。
- 实测源分布:sheet1 存量/新店 = 存量 469 / 新增 81(按店去重 423/64);sheet2 性质 = 存量 49 / 新增 3。
- **修复**:①`parse_saas` sheet1 新增 `c_nat=_pick(df1,['存量/新店','存量新店'])`,写入 `nature`;②计数改为 `len(uniq(allrows, lambda r: r['nature']=='存量'))` / `=='新增'`(纯 union,不再 `总数−新增`);③`存量门店总预算`/`新增门店总预算` 改为直接对 `nature` 过滤求和(原 `总预算−新增预算` 因含空白 nature 行略有偏差)。
- 实测 2026-08:存量=**433**(旧 495)、新店=**67**(旧 3)、总门店 498 不变;存量预算 105,323,280.5 / 新增预算 11,753,285.0(合计 117,076,565.5,余 ~96k 为 nature 空白行,与实际一致)。
- ⚠️ 个别门店同时出现在「存量」与「新增」两处(union 3 店),故 存量+新增(500)≠总数(498),符合源数据。
# 2026-09-08 工作日志(店效人效汇总表)
## 1.1产值 取数口径变更
- 用户要求 `1.1产值` 改为从结果表读取:`report_light_reform_inshop` + `report_light_reform_park` 的 `total_output_value`(合计总产值) 之和,条件 **同 task_id 且 is_deleted=0**。
- 代码改动(`build_store_effect_board.py`):
- 新增 `fetch_light_reform_11_output_value(period_start, period_end)`:惰性 import `app/db/models`,`with app.app_context()` 内查;task_id 解析优先按周期(period_start>=/period_end<=)过滤,否则取最大 task_id;两表各 `func.sum(total_output_value)` 后相加。
- `compute_metrics` 中 `m['1.1产值']` 由 `ind_sum(ind_11,...,'A036')` 改为调用该函数。
- 字段说明同步更新为"轻改结果表 inshop+park 合计总产值之和"。
- 仅改 `1.1产值`;`1.1成交单数/1.1接待数` 仍走指标系统(A075/A084)。
- 实测(task_id=32, 2026-08):inshop 32行 + park 20行,`SUM(合计总产值)=0` → `1.1产值=0`。**是真实数据状态**:轻改处理器业务SQL未接入(BIZ_SQL_ENABLED=false),产值类字段恒为0;非代码bug。结果表被 populate 后看板会自动反映。
- 运行注意:本地重建须用 `C:/Python314/python.exe`(带 flask+DB)从 data-process 目录跑;`--month 2026-08`(无 period)会走"取最大 task_id"分支命中 task 32。
## 1.1毛利率 取数口径变更
- 用户要求 `1.1毛利率` =(所有"毛利测算"之和 / 1.1产值)*100%,四舍五入保留百分比后2位;"毛利测算"之和 = `report_light_reform_inshop`+`report_light_reform_park` 的 `gross_profit` 之和(同 task_id, is_deleted=0)。
- 重构:`fetch_light_reform_11_output_value` 改为通用 `fetch_light_reform_11_sum(col_attr, period_start, period_end)`(列名字符串),两表同 task_id 求和。
- `compute_metrics` 中 `m['1.1毛利率'] = pct(fetch_light_reform_11_sum('gross_profit',...), m['1.1产值'])`;pct 已 *100 并 quantize 2 位;RATE_FIELDS 含 '1.1毛利率' 配 `0.00"%"`。
- 实测(task_id=32):gross_profit inshop=-43818.64 + park=-74529.05 = **-118347.69**;total_output_value inshop=0.01(仅此极小数,本质未填充)。→ 1.1毛利率 = (-118347.69/0.01)*100 = **-1183476900.00%**。
- **此为数据状态所致非公式bug**:结果表"毛利测算"已填充而"合计总产值"≈0(业务SQL未接),分母≈0 使比率爆炸。待合计总产值真实填充后比率自然合理。字段说明已更新。
## 1.1毛利率(含人力) 取数口径变更
- 公式:`((毛利测算之和 + 营销成本 + 人力成本)/ 1.1产值) * 100%`,四舍五入保留百分比后2位。
- 毛利测算 = `inshop.gross_profit + park.gross_profit`(同 task_id, is_deleted=0)
- 营销成本 = **仅** `report_light_reform_inshop.marketing_personnel_cost`
- 人力成本 = **仅** `report_light_reform_park.personnel_cost`
- 分母 = `1.1产值`(同上合计总产值之和)
- 重构:`fetch_light_reform_11_sum` 拆出单表底层 `_lr_sum_one(which, col_attr, ...)`(which='inshop'|'park'),并新增安全包装 `fetch_light_reform_11_sum_one(which, col_attr, ...)`(失败置0)。`fetch_light_reform_11_sum` 现 = `_lr_sum_one('inshop') + _lr_sum_one('park')`。
- `compute_metrics` 中 `m['1.1毛利率(含人力)'] = pct(gp_11 + mkt_11 + hr_11, m['1.1产值'])`;该指标此前已在 RATE_FIELDS/总看板 row17/字段说明占位(原注"待接入")。
- 实测(task_id=32):marketing_personnel_cost=0.0、personnel_cost=0.0 → 当前 `1.1毛利率(含人力)` = `1.1毛利率` = -1183476900%(两成本列未填充,公式正确,待 populate 后自然分化)。字段说明已更新为完整口径。
## 1.1交车数 取数口径变更
- 用户要求 `1.1交车数` 改为从结果表读取:`report_light_reform_inshop` + `report_light_reform_park` 的 `delivery_cnt`(交车数) 之和(同 task_id, is_deleted=0)。
- 改动:`compute_metrics` 中 `m['1.1交车数']` 由 `dsum(stores_11)`(原 = 主机厂数据表按 sheet2 门店交车数之和)改为 `fetch_light_reform_11_sum('delivery_cnt', period_start, period_end)`。仅改 1.1;2.1/2.3 交车数仍走原 `dsum` 主机厂口径。字段说明同步更新。
- 实测(task_id=32):inshop 32行 delivery_cnt=0 + park 20行 delivery_cnt=887 → `1.1交车数 = 887`。`1.1触客率`/`1.1成交客单价` 分母随之变为 887(仍受 1.1接待数/产值=0 影响暂为0)。
## 1.1接待数 取数口径变更
- 用户要求 `1.1接待数` 改为从结果表读取:park.arrival_cnt(到店数) 之和 + inshop.delivery_touch_cnt(交付触客数) 之和(同 task_id, is_deleted=0)。
- 改动:`compute_metrics` 中 `m['1.1接待数']` 由 `ind_sum(ind_11, stores_11, 'A084')`(指标系统触客 A084)改为 `fetch_light_reform_11_sum_one('park','arrival_cnt',...)+fetch_light_reform_11_sum_one('inshop','delivery_touch_cnt',...)`。仅改 1.1;2.1/2.3 接待数仍走指标系统。
- 实测(task_id=32):park.arrival_cnt=693 + inshop.delivery_touch_cnt=0 → `1.1接待数 = 693`。`1.1触客率` = pct(693, 887) 现可算(此前因分子0为0);`1.1转化率` 仍受 1.1成交单数=0 影响暂为0。字段说明同步更新。
## 1.1成交单数 取数口径变更
- 用户要求 `1.1成交单数` 改为从结果表读取:park.deal_cnt(成交数) 之和 + inshop.total_deal_cnt(总成交数) 之和(同 task_id, is_deleted=0)。
- 改动:`compute_metrics` 中 `m['1.1成交单数']` 由 `ind_sum(ind_11, stores_11, 'A075')`(指标系统成交 A075)改为 `fetch_light_reform_11_sum_one('park','deal_cnt',...)+fetch_light_reform_11_sum_one('inshop','total_deal_cnt',...)`。仅改 1.1;2.1/2.3 成交单数仍走指标系统。
- 实测(task_id=32):park.deal_cnt=888 + inshop.total_deal_cnt=0 → `1.1成交单数 = 888`。`1.1转化率` = pct(888, 693) 现可算;`1.1成交客单价`=pct(1.1产值=0.01, 887)≈0(产值未填充)。字段说明同步更新。
## 2.1 全指标改从 report_equity_service 读取
- 用户要求 2.1 全部改从 `report_equity_service`(模型 `ReportEquityService`,task_id=32)读取,条件同 task_id + is_deleted=0:
- 2.1产值 = store_output_value(门店产值) 之和
- 2.1毛利率 = gross_profit(毛利测算) 之和 / 2.1产值 *100%(pct 已*100+quantize 2位)
- 2.1毛利率(含人力)= (gross_profit 之和 + marketing_fee(营销费用) 之和) / 2.1产值 *100%
- 2.1交车数 = delivery_cnt(交车) 之和
- 2.1接待数 = touch_cnt(触客) 之和
- 2.1成交单数 = deal_cnt(成交数) 之和
- 代码改动:`_lr_sum_one` 增加 'equity' 分支(import ReportEquityService,tag=权益);新增 `fetch_equity_21_sum(col_attr,...)` 安全包装。compute_metrics 中 2.1产值/交车数/接待数/成交单数/毛利率/毛利率(含人力) 全部改为 `fetch_equity_21_sum`(原走指标系统 A036/A075/A084 或主机厂 dsum)。字段说明同步更新。
- 实测(task_id=32):2.1产值=2,660,748;gross_profit=-12,408,485,764.22(脏数据!量级异常)、marketing_fee=12,411,140,704.22(脏数据!);→ 2.1毛利率≈-466353.29%(爆炸)、2.1毛利率(含人力)≈99.78%(因 gp≈-mf 抵消)。delivery_cnt=373、touch_cnt=2119、deal_cnt=1060 量级正常。**gross_profit/marketing_fee 两列源数据明显脏(与早前 cost -21.9亿同类),公式正确但比率失真,待结果表清洗。**
- 2.1 改完;2.3 仍走指标系统。
## 2.1成交客单价 公式纠错(去掉 ×100%)
- 用户指出 `2.1成交客单价` 原用 `pct()`(a/b*100)错误,应改为纯除法 `2.1产值/2.1成交单数`,四舍五入保留2位小数(不乘100%)。
- 代码改动:`build_store_effect_board.py` 新增 `div2(a,b)`(a/b quantize 2位,不做*100);第820行 `m['2.1成交客单价']` 由 `pct(...)` 改为 `div2(m['2.1产值'], m['2.1成交单数'])`;字段说明改为"2.1产值/2.1成交单数,四舍五入保留2位小数"。
- 客单价字段本就不在 `RATE_FIELDS`(单元格格式 `#,##0.00`),故只改数值、无需改格式。
- 实测(task_id=32):2.1产值=2,660,748 / 2.1成交单数=1,060 → **2,510.14**(元)。
- 提醒:`1.1成交客单价`(分母交车数)、`2.3成交客单价` 仍用 `pct()`(×100),属同样错误;用户当时只要求改 2.1,待确认是否一并改。
## 1.1 / 2.3 成交客单价 一并改正
- 用户确认把 1.1、2.3 客单价也改掉。第819、821行由 `pct(...)` 改为 `div2(...)`(分母分别用 1.1交车数 / 2.3成交单数);两条字段说明同步去掉 `*100%`。
- 现三条客单价统一走 `div2`(纯除法、2位小数、不乘100%):1.1=产值/交车数、2.1=产值/成交单数、2.3=产值/成交单数。
- 实测(task_id=32):1.1产值≈0.01→≈0.00;2.1=2510.14;2.3产值/成交单数=0→0.00(数据未填充)。
## 2.3 全指标改从 report_extended_warranty 读取
- 用户要求 2.3 全部改从 `report_extended_warranty`(模型 `ReportExtendedWarranty`,task_id=32)读取,条件同 task_id + is_deleted=0:
- 2.3产值 = store_output_value(门店产值) 之和
- 2.3毛利率 = gross_profit(毛利测算) 之和 / 2.3产值 *100%
- 2.3毛利率(含人力)= (gross_profit 之和 + marketing_fee(营销费用) 之和) / 2.3产值 *100%
- 2.3交车数 = delivery_cnt(交车) 之和
- 2.3接待数 = touch_cnt(触客) 之和
- 2.3成交单数 = deal_cnt(成交数) 之和
- 代码改动:`_lr_sum_one` 增加 'warranty' 分支(import ReportExtendedWarranty,tag='延保');新增 `fetch_extended_warranty_23_sum(col_attr,...)` 安全包装(并行于 `fetch_equity_21_sum`)。`compute_metrics` 中 2.3产值/交车数/接待数/成交单数/毛利率/毛利率(含人力) 全部改为 `fetch_extended_warranty_23_sum`(原走指标系统 A036/A075/A084 或主机厂 dsum)。字段说明同步更新(去掉"待接入,当前0")。
- 注:`ind_23`、`stores_23` 变量现仅用于已废弃的指标路径,保留无副作用。
- 实测(task_id=32):2.3产值=78,524,941;gross_profit=23,235,523.22、marketing_fee=3,022,248.73(数据干净,非2.1脏数据);→ 2.3毛利率=29.59%、2.3毛利率(含人力)=33.44%;delivery_cnt=7588、touch_cnt=13736、deal_cnt=8267;2.3成交客单价=9498.60。2.3达成率=76.94%。**至此 1.1/2.1/2.3 三条业务线全部从结果表取数,指标系统(A036/A075/A084)仅剩 全国经营总产值/店均产值 在用。**
- 至此三大业务线(1.1轻改 inshop+park、2.1权益 equity、2.3延保 warranty)取数口径全部迁移完毕。
## 本月流失门店/流失豪华/流失非豪华 接入 dj_smartcarlife
- 用户要求三项流失门店指标读取 `dj_smartcarlife.sale_close_store_record`:闭店时间字段 `close_time`,主营品牌 `main_brands`(多个逗号分隔)。DB 配置在 `config.py`(`Config.BIZ_SQL_DATABASE_URL`,用法同 `report_utils._get_biz_sql_conn` 的 create_engine 模式)。
- 代码改动(`build_store_effect_board.py`):
- 新增 `fetch_closed_stores(month_start, month_end_excl)`:create_engine(Config.BIZ_SQL_DATABASE_URL)→`SELECT close_time, main_brands FROM sale_close_store_record WHERE close_time >= :s AND close_time < :e`;DB 不可达返回 [](指标置0)。
- `compute_metrics` 签名加 `month_start=None, month_end_excl=None`;在零值循环后:若两者非空,查闭店记录,逐条按 `main_brands` 逗号拆分→`brand_category()` 归类(任一品牌=豪华→流失豪华,否则流失非豪华);`本月流失门店`=总条数、`流失豪华门店`/`流失非豪华门店` 拆分。
- `main()` 新增由 `--month`(优先) 或 `--period-start/end` 推导统计月份区间:month_start=当月1号,month_end_excl=下月1号(闭区间 [s,e));传给 compute_metrics。**注意:不能改 ps/pe(否则会破坏结果表 fetch 的"无周期→取最大task_id"逻辑),故单独用 month_start/month_end_excl 传参。**
- 字段说明三行更新为 dj_smartcarlife 口径;三项加入控制台回显。
- 验证:本沙箱无法连通 192.168.5.23(timed out),三项优雅降级为 0 并打 warning;后端有 DB 权限时自动填充。口径风险:按"行数=门店数"计(一条闭店记录=一个门店),未做 store 去重(假定该表一店一行);如后端出现一店多行需改 COUNT(DISTINCT 门店标识)。
## task 32 页面"重新生成"显示失败 → 根因=后端进程缓存旧代码
- 现象:用户在页面点 task 32「重新生成」后状态显示 FAILED。但在沙箱用 `C:/Python314/python.exe` 直接跑 `StoreEffectSummaryProcessor().process(task)` 与 `DataProcessor(app).process_task(32)` 均成功(状态→COMPLETED,结果文件已上传 OSS)。
- 根因:后端是常驻 `python app.py` 进程(原 PID 26920 监听 :5000,带 Werkzeug 调试重载)。`store_effect_summary_processor` / `build_store_effect_board` 在首次调用后被缓存进 `sys.modules`,后续调用不会按源文件 mtime 重新加载;`processor.py` 的函数体也在进程启动时载入。故我在 `build_store_effect_board.py` / `processor.py` 上的改动(含 流失门店、客单价公式、store_effect_earnings 路由到 StoreEffectSummaryProcessor)**旧后端进程完全看不到**,仍跑旧逻辑而失败。
- 修复:结束旧进程(taskkill 26920/29388),用受管 Python 后台重启 `python app.py`(cwd=data-process,自动载 .env、启 ALL_SCHEDULERS、监听 :5000)。新 PID 25352 已起,端口恢复,当前代码全部生效。task 32 现状态 COMPLETED。
- 结论/惯例:**改完 build_store_effect_board.py / store_effect_summary_processor.py / processor.py 后,必须重启后端常驻进程**才能让页面"重新生成"生效(调试重载未覆盖动态 import 的模块缓存)。下游用户点"重新生成"本质是触发后端进程内代码,不重启则永远跑旧版。
## task 33 本月流失门店=0 与数据库不符 → 根因=页面路径漏传统计月
- 现象:用户把8月数据源导入6月周期(task 33)跑出 本月流失门店=0,但自查数据库闭店数比0大。
- 根因(与 task 32 同源但不同点):`store_effect_summary_processor.py` 第230行原调用 `compute_metrics(tmp_dir, period_start, period_end)` **只传2个参数**,`month_start/month_end_excl` 默认 `None`;而 `compute_metrics` 内流失门店统计块由 `if month_start and month_end_excl:` 守卫,两者为 None 时整块跳过,`本月流失门店` 保留零值循环初值 0(查询根本没执行,不是 SQL 写错)。CLI 路径(`--month`)会传月份故正常,但页面"重新生成"走 processor 路径漏传。
- 修复:`store_effect_summary_processor.py` 调用前由 `stat_month=task.month`(回退 period_start) 推导 `[当月1号, 下月1号)` 并传给 `compute_metrics`;补 `from datetime import ...,date,timedelta`。重启后端(PID 12464)生效。
- ⚠️ 月份口径待用户确认:task 33 周期=6月→现查 **2026-06** 闭店记录。用户是把"8月数据源"塞进"6月周期",对比库时可能按8月查;若应按数据源月份(8月)取数,需改 `compute_metrics` 月份来源(一行改动),待用户确认。
- 口径补充:①总量=闭店记录行数(假定一店一行,未去重);②豪华拆分依赖 `config_brand_category` 配置表,若该表未配宝马→豪华映射,则流失豪华门店可能全为0(总量不受影响)。沙箱无法连 192.168.5.23,真实值需后端页面"重新生成"后核对。
## 本月新增门店 / 新增豪华门店 / 新增非豪华门店(3库关联,已实现)
- 口径(用户确认):按 `main_merchant_id`(门店商户号) 去重,取该门店所有 `sub_merchant_id` 行中 `MIN(created_date)` 为首建日期;首建日期落在统计月→本月新增门店。品牌判定:`main_merchant_id`→`scrm_account.platform_merchant_brand`(first_brand_id/sec_brand_id)→`cyb_os.platform_carbrand`(bid=一级/二级品牌id 得品牌名)→`brand_category()`(config_brand_category) 定豪华;first 或 sec 任一豪华即豪华门店。
- 实现:`config.py` 新增 `SCRM_DATABASE_URL`(默认假设同 dj_smartcarlife 主机 `192.168.5.23:3306` 库名 scrm_account,可 .env 覆盖) 与 `CYB_OS_DATABASE_URL`(用户给 read_cyb_os/192.168.5.5:3311/ebf6C0D6)。`build_store_effect_board.py` 新增 `fetch_new_stores(month_start,month_end_excl,exact_map,keys)`:`_engine(url_key)` 通用建连;`_in_params` 生成具名 IN 参数。compute_metrics 在流失门店块后调用,写入三指标。
- 容错设计:首建日期(dj_smartcarlife) 独立 try,**总量无论如何保留**;scrm/cyb_os 失败仅豪华拆分降级为 0/总数(不丢总量)。
- **实测(沙箱)**:dj_smartcarlife 可达 → 2026-08 首建日期命中 **42** 个门店;但 `scrm_account` 报 `Access denied for user 'read_dj_smartcarlife'@'192.168.%' to database 'scrm_account'`(即 scrm_account 与 dj_smartcarlife 同主机 192.168.5.23,但 read_dj_smartcarlife 用户无该库权限)→ 豪华拆分降级 0/42。**缺 scrm_account 连接账号(有 SELECT 权限的用户/密码)是硬阻塞**,cyb_os 已可用。
- 重启后端(PID 7648)生效。字段说明三行已更新。
# 2026-09-09 工作日志
## scrm_account 账号补齐 + 新增门店品牌归类链路打通
- 用户给出 scrm_account 只读账号:`read_scrm_account` / `TnZobW2b` / `192.168.5.1:3310` / 库名 `scrm_account`。
- `config.py` 原 `SCRM_DATABASE_URL` 默认值(误用 read_dj_smartcarlife@192.168.5.23:3306)改为正确账号串:`mysql+pymysql://read_scrm_account:TnZobW2b@192.168.5.1:3310/scrm_account?charset=utf8mb4`。
- 实测 scrm_account 可达:`platform_merchant_brand` 58万行,列 `id/merchant_id/first_brand_id/sec_brand_id/del_flag/...`。cyb_os `platform_carbrand` 列 `bid/brand/brand_code/...`,品牌名在 **`brand`** 列(非 name/brand_name)。
- 修复 `fetch_new_stores` 三处口径错误:
1. `platform_merchant_brand` 加 `del_flag=0` 过滤(表有逻辑删除列)。
2. 品牌名字段由 `name`/`brand_name` 优先改取 `brand`(否则全空→豪华归0)。
3. 一个 `merchant_id` 多行 → 按商户 **union** 所有 first/sec 品牌 id(原 `brand_map[mid]=[r1,r2]` 覆盖只留最后一行)。
- 真实结果(链路全通):2026-08 → 新增41 豪华41 非豪华0;2026-06 → 新增90 豪华85 非豪华5。
- ⚠️ 豪华占比异常高的根因 = **用户 config_brand_category 配置本身**:69 条里把 比亚迪/吉利/广汽丰田/大众/零跑/长安/奇瑞/埃安 等大量主流/自主品牌都标成"豪华"。`brand_category` 双向子串匹配工作正常,归类是按用户配置正确得出,非代码 bug。已向用户说明,是否收窄豪华定义由用户决定(改 config 表即可,无需改代码)。
- 重启后端(PID 16560)生效。新代码+配置均可经页面"重新生成"跑通。
## 关键惯例(持续有效)
- 改 `build_store_effect_board.py` / `store_effect_summary_processor.py` / `processor.py` / `config.py` 任一文件后,**必须重启后端常驻进程**才能页面"重新生成"生效(调试重载不刷新动态 import 的模块缓存)。
- 页面"重新生成"路径(`store_effect_summary_processor.py`)统计月来自 `task.month`,非 CLI 的 `--month`;两路径需各自保证传 `month_start/month_end_excl`。
# 2026-09-16 工作日志
## 新增数据表类型:阿维塔专项
- `config.DATA_TABLE_TYPES` 新增 `avita_special`:`name='阿维塔专项'`、`need_period=True`、`forms=['主机厂数据表']`。
- 附件表名「主机厂数据表」为暂定,后续可能改名(改名只改 config 该处即可,前端动态渲染 forms)。
- 处理引擎未接入:`process_task` 白名单(SUPPORTED_PROCESS_TYPES)会拦截并提示"引擎尚未接入"(与 future_expansion 一致),不会误跑预算流水线、不崩溃。
- 改动仅 config.py;前端按 DATA_TABLE_TYPES 动态渲染上传区,重启后端后上传页出现"阿维塔专项"选项。
- need_period 已按用户要求改为 False(阿维塔专项不需要所属周期项)。仍待确认:是否需重启后端(PID 13536)让前端生效。
- 澄清(用户纠正):阿维塔专项的「主机厂数据表」为独立数据表,格式不保证与现有「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,不可复用 report_utils.parse_delivery_table(鸿蒙/广联共用结构);后续接引擎时按用户实际提供的附件字段解析、写入阿维塔专属结果表。当前阶段仅配置类型+定义上传表名,解析逻辑未实现。已在 config.py 注释中标注此独立性。
## 阿维塔专项 引擎接入(task 37 实测落库)
- 用户已建两表:`avita_special_month_data`(明细,无 created_at/updated_at)/ `avita_special_month_summary_metrics`(汇总,仅 created_at)。
- 改动三处:`models.py` 加两 ORM 模型(对齐真实列,缺列会 INSERT 报 Unknown column);`avita_special_processor.py` 新建 `AvitaSpecialProcessor`(下载→解析双表头 Excel→按 task_id 先删后插→置 COMPLETED/result_file_url='');`processor.py` 的 `process_task` 在白名单**前**加 `avita_special` 路由分支。
- 源文件实测(task 37,7月样本「7月页签-字段取值说明」):2 行表头 + 8 家门店明细 + 末尾汇总段('阿维塔品牌汇总' + 售后门店数=3/售后场景开通率=0.38/售后订单数=0)。
- 解析坑:①store_name/store_short_name 是字符串列,不能走 `_to_dec` 数值转换(否则门店名全被置空);②明细表多声明的 created_at/updated_at 与实际表不符→已移除;③汇总表仅 created_at。已修正并落库成功。
- 结果:task 37 落库 COMPLETED,明细 8 行 + 汇总 1 行;汇总表 store_count/output_value/delivery_count 等源文件未提供→留空(待最终 Excel 生成或后续填充)。
- 当前无后端进程在跑(Get-Process 无 python),代码改动下次启动自动生效;前端页面"重新生成"需在后端运行新代码时才可用。
## 阿维塔专项 源文件新增门店模式/入驻时间两列(task 37 重跑)
- 用户更新源数据:月份明细新增「门店模式」(col2, 文本如服务商/直营) 与「入驻时间」(col3, Excel datetime) 两列,插入到原门店简称之后、主机厂指标之前 → 所有指标列整体右移 +2。
- `avita_special_processor.py` 改动:①`DETAIL_COL` 列索引整体右移(store_name=0/store_short_name=1/store_mode=2/entry_time=3/主机厂交付=4/延保=5/无忧=6/单车收入=7/总产值=8/广联交付=9/广联触客=10);②`_STR_COLS` 加 store_mode/entry_time,新增 `_to_date_str` 将入驻时间 datetime 格式化为 `YYYY-MM-DD` 写入 `varchar(10)`;③`_save` 由 `rec.get('store_mode'/'entry_time')` 写入(此前硬编码 None)。
- 重跑 task 37(run_avita37.py,app 上下文直接调用 AvitaSpecialProcessor):8 家门店门店模式/入驻时间全部填充成功,状态回 COMPLETED。临时脚本已清理。
- 重启后端:杀掉两个旧后端(24636/31508,监听 5000 的旧代码)后,以 `PYTHONPATH=用户site-packages` 重启(新 PID 30988,日志无报错,已加载新 avita 代码)。页面"重新生成"现在用新引擎,不会再清空这两列。
- 表列类型确认:`store_mode varchar(50)`、`entry_time varchar(10)`(均为文本,入驻时间存日期串)。
- 仍空缺:regional_operation/resident_name/广联延保成交数/广联无忧成交数 源文件未提供→留空。
## 阿维塔专项两表加 is_deleted 软删除(逻辑删除)
- 需求:avita_special_month_data 与 avita_special_month_summary_metrics 加 `is_deleted`(0正常/1已删除),后续不再物理删除,只逻辑删除(与项目偏好一致)。
- 改动三处:①`alter_avita_softdelete.py` 对两表 `ALTER TABLE ... ADD COLUMN is_deleted INT NOT NULL DEFAULT 0`(已跑,两表均加好);②`models.py` 两 ORM 模型加 `is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除(软删除)')`;③`avita_special_processor.py` 的 `_save` 由 `query.filter_by(task_id).delete()` 改为 `query.filter_by(task_id=..., is_deleted=0).update({is_deleted:1})` 逻辑删除旧行 + 新行 `is_deleted=0`(幂等),docstring 同步。
- 验证(重跑 task 37):明细 total=16(active=8 + 软删=8)、汇总 total=2(active=1 + 软删=1);门店模式/入驻时间写入无误,状态 COMPLETED。确认软删除生效、INSERT 未因新增列报错。
- 重启后端(杀 30988,新 PID 28164,日志无报错)加载新代码。临时脚本已清理。
- 注意:后续任何读这两张表的逻辑都需 `filter_by(is_deleted=0)`,否则会把历史软删行当活跃数据。
## 阿维塔专项 源文件新增驻店姓名一列(task 37 重跑)
- 用户更新源数据:月份明细再新增「驻店姓名」(col4, 文本如"创思/服务商"/"王永忠"),插入到入驻时间之后、主机厂指标之前 → 所有指标列整体右移 +1(累计右移 +3)。
- `avita_special_processor.py` 改动:①`DETAIL_COL` 列索引调整(resident_name=4,主机厂交付=5/延保=6/无忧=7/单车收入=8/总产值=9/广联交付=10/广联触客=11);②`_STR_COLS` 加 `resident_name`(字符串列勿走数值转换);③`_save` 由 `rec.get('resident_name')` 写入(此前硬编码 None);docstring 同步。
- 重跑 task 37(run_avita37.py,app 上下文):8 家门店驻店姓名全部填充成功(如 创思/服务商、王永忠、杨淑萍、林彩玲、刘秀锦),门店模式/入驻时间/数值无回退,软删除正确(active=8,历史 16 行 is_deleted=1),状态 COMPLETED。临时脚本已清理。
- 重启后端(杀 28164,新 PID 31244,日志无报错)加载新代码。页面"重新生成"现在用新引擎。
- 仍空缺:广联延保成交数/广联无忧成交数 源文件未提供→留空。
## 阿维塔专项 区域运营字段改由 dj_smartcarlife 查询(task 37 重跑)
- 需求:avita_special_month_data.regional_operation(区域运营)从 dj_smartcarlife 数据源读取,源文件无此列。
- 规则(两跳):①`select merchant_id from dj_car_life_service_merchant where merchant_name=门店名称 and deleted_flag='N'`;②用查到的 merchant_id `select director_name from dj_car_life_shop_merchant_director_config where deleted_flag='N' and merchant_id=:mid and director_type=9`,多条记录去重后 `/` 分隔。
- 改动(`avita_special_processor.py`):加 `from config import Config` + `create_engine(Config.BIZ_SQL_DATABASE_URL)` 引擎缓存 + `fetch_regional_operation(store_name)`(参数化 text 查询,模块级 `_BIZ_ENGINE` 缓存,异常不致命仅告警留空);`_save` 的 `regional_operation` 由 `None` 改为 `fetch_regional_operation(rec['store_name'])`;docstring 同步。
- 踩坑:`config` 模块无 `BIZ_SQL_DATABASE_URL` 属性(报 AttributeError),该连接串挂在 `Config` 类上 → 改用 `from config import Config` 取 `Config.BIZ_SQL_DATABASE_URL` 修复。
- 重跑 task 37(run_avita37.py):8 家门店区域运营全部填充成功(陈晓文/张爱豪/李明瑞/张浩锋/王孝樟/卓炯煜/刘淑君/李明瑞),状态从 FAILED 恢复 COMPLETED,软删除正确(active=8,历史 24 行 is_deleted=1)。临时脚本已清理。
- 重启后端(杀 31244 及幽灵 20340,新 PID 16536,日志 `Running on 5000` 无报错)加载新代码。注意 netstat 显示的 20340 是幽灵条目(PowerShell Get-Process 找不到),真实新进程为 16536。
- 仍空缺:广联延保成交数/广联无忧成交数 源文件未提供→留空。
# 2026-09-17 工作日志
- 阿维塔专项 `avita_special_processor.py`:新增 `cutoff_gl_extended_warranty_deal_count`(广联延保成交数)/ `cutoff_gl_worry_free_deal_count`(广联无忧成交数)获取逻辑,数据源 `dj.glsx.com.cn` 报表导出接口(无需鉴权)。流程:①`/queryAllExcel?filename={stat_month}` 取 通用品牌 报表 key;②`/download?key=` 取文件 url;③下载 xlsx 解析 Sheet1,延保小计行取「整车延保成交数」、权益小计行取「原厂权益成交数」,按门店名称精确匹配聚合。表头单元格含换行需 `_norm_header` 归一(如 '整车延保\n成交数'→'整车延保成交数')。代码改动:新增 import io/requests + `_GLSX_BASE`/`fetch_glsx_deal_counts`/`_norm_header`/`_cell_to_int`;`_save` 中每任务调一次 `fetch_glsx_deal_counts(stat_month)` 并按 store_name 填两列(未匹配留空+告警);从 `_INT_COLS` 移除非源文件的这两列。
- 实测(重跑 task 37):4 家门店命中通用品牌报表(昆明东杰 ext=12/worry=0、厦门奥瀚 4/0、福州大邦通商 2/0、云南万福经景 2/0);成都万友翔宇/重庆万友诚行/广州市美昌/江苏万友 4 家不在该报表→留空。状态 COMPLETED。
- 重启后端加载新代码(旧 PID 16536 终止,新 PID 31304 监听 5000,日志无报错)。改 processor 后须重启后端页面才生效。
- 临时脚本 run_avita37.py 已清理。
## 续:cutoff_gl_worry_free_deal_count 取数口径变更(11:39 重跑 task 37)
- 用户要求 `cutoff_gl_worry_free_deal_count`(广联无忧成交数)改为:A列='延保小计' 行、取「原厂权益成交数」(Z列, index25) 的值(原取自「权益小计」行)。`avita_special_processor.py` 已改:`fetch_glsx_deal_counts` 的 `延保小计` 分支同时取 `ext_c`(整车延保成交数) 与 `worry_c`(原厂权益成交数),删除 `权益小计` 分支对此字段的填充;同步更新文件头 docstring 与注释。
- 重跑 task 37 验证:2026-07 通用品牌报表中,4 家命中门店的「原厂权益成交数」列在「延保小计」行均为 0(这些门店只卖了延保、未卖权益/无忧)——故 worry_free 实际落 0;与旧逻辑(权益小计行该列也为空→0)结果一致。4 家未命中门店仍 NULL。结论:本次改口径对 task 37 数据值无变化(均为 0),但代码已按用户口径修正;若后续月份报表在延保小计行出现非零原厂权益成交数,将正确落库。
- 当前后端未运行(端口 5000 无监听、PID 31304 已不在),无需重启;下次启动将加载新代码。
## 续2:阿维塔专项结果表生成(基于用户模板)
- 用户提供最终模板 `C:\Users\66\Desktop\阿维塔7月页签-字段取值说明(模板版).xlsx`(单 sheet `7月页签-字段取值说明`,26行×27列)。结构:行1标题、行2/3表头分组、行4-11=8门店明细(A-F门店属性;G-M=6月主机厂块;N-R=截止主机厂块;S-AA=广联块含衍生指标)、行14/18段标题+行15/16与行19/20品牌汇总(6月段/7月段)。
- 已复制模板到 `data-process/exporttemplete/avita_special_report_template.xlsx` 作为生成基线。
- `avita_special_processor.py` 新增 `generate_result_excel(task)`:标题/表头/段标题的「7月」「2026-07-26」「6月」「截止7月26日」按 task.month(派生月标签/上月标签) + 真实生成日期替换(用户确认截止日期取生成时真实日期→本次 2026-09-17);明细从 `avita_special_month_data` 读真实值,衍生指标按公式:触客率 W=T/S、延保渗透率 X=O/N、无忧渗透率 Y=P/N、延保引荐转化率 Z=U/T、无忧引荐转化率 AA=V/T;品牌汇总 项目/品牌 固定=阿维塔,门店数=明细数,售后三项(门店数/开通率/订单数)取汇总表,其余聚合/环比列无源→'-';6月主机厂块无源→'-';生成后 `upload_file` 上传 OSS 并回填 `result_file_url`。`process()` 末尾调用之。
- 修复 openpyxl 陷阱:`ws.cell(r,c,value=None)` 不会清除已存在旧值(导致未命中广联报表的4家门店 U/V 残留模板示例值4/1)。新增 `_set_cell(ws,r,c,v)` 用 `ws.cell(r,c).value=v` 显式写/清空,全部单元格写入改走该helper。
- 重跑 task 37 验证通过:标题=阿维塔专项报表 ·「7月」页签 · 数据截止 2026-09-17;4家未命中门店 U/V=None(已清空);命中门店 U/V 取真实值(昆明东杰12/0、云南万福2/0);品牌汇总 项目/品牌=阿维塔、门店数=8、售后门店=3/开通率0.38/订单0。
- 结果文件:OSS `data-process/20260917/avita_special_2026-07_37.xlsx`;本地副本 `data-process/outputs/avita_special_2026-07_task37.xlsx`。
- 已知缺口(待补数据源):①6月(上月)主机厂数据块无 DB 源(仅 stat_month=2026-07);②品牌汇总聚合字段(产值/交付数/售前触客数/整车延保成交数/原厂权益成交数/各渗透率/环比)DB 无源且不等于明细简单求和(如7月段交付数模板205≠8店求和218,疑似剔除新店),暂置'-'。
- 后端当前未运行;结果表生成逻辑已在 task 37 重跑中验证(standalone 脚本直连 DB+OSS,网络正常)。
## 续3:截止日期规则修正(14:15 重跑 task 37)
- 用户明确截止日期口径:**用报表所属月**(task.month);若当前时间在报表所属月**之后**,数据截止时间取报表所属月**最后一天**(封账)。进行中(同月)则取真实生成日期。
- 代码改动:`generate_result_excel` 新增 `from calendar import monthrange`;截止日期计算改为 `today=date.today()`,若 `today > report_month_last(所属月最后一天)` 则 `cutoff_date=report_month_last` 否则 `today`。同步更新文件头 docstring 与函数 docstring。
- 重跑 task 37 验证:报表所属月 2026-07,当前 2026-09-17 > 2026-07-31 → 截止日期正确取 **2026-07-31**。标题=阿维塔专项报表 ·「7月」页签 · 数据截止 2026-07-31;N2=截止2026-07-31主机厂数据;S2=截止2026-07-31广联数据;W2=数据截止2026-07-31。OSS 与 outputs 副本已刷新。
## 续4:阿维塔专项接入定时任务自动处理(14:47 验证通过)
- 需求:阿维塔专项数据表支持定时任务自动处理(与其他类型一致:任务上传后 status='PROCESSING',由调度器轮询处理)。
- 改动三处:①`avita_special_processor.py` 新增 `scan_avita_special()`(仿 `OutputValueProcessor.scan_output_value`:扫 `data_table_type='avita_special' AND status='PROCESSING' AND is_deleted=0` 任务,逐调 `self.process(task)`,返回 `{success,failed}`,失败 `mark_task_failed`);②`scheduler.py` 新增 `AvitaSpecialScheduler(NewReportScheduler)`(`OUTPUT_CATEGORY='avita_special'`、`JOB_NAME='avita_special_scan'`,重写 `_execute_scan` 调 `AvitaSpecialProcessor(app).scan_avita_special()`);③`app.py` 在 `from scheduler import (...)` 增加 `AvitaSpecialScheduler`,实例化 `avita_special_scheduler` 并加入 `ALL_SCHEDULERS = [..., ('avita_special', avita_special_scheduler)]`。
- 启动逻辑:后端启动循环 `for name, sch in ALL_SCHEDULERS: sch.start()`(间隔 `Config.SCHEDULER_INTERVAL_SECONDS`=60s,APScheduler 未装则 threading.Timer 后备),故仅需重启后端即自动加载新调度器,每 60s 扫描 PROCESSING 的阿维塔任务自动处理。
- 验证:重置 task 37 为 PROCESSING → `scan_avita_special()` 返回 success=1/failed=0,task 37 变 COMPLETED 且 result_file_url 已回填;二次扫描 0 待处理(不重复处理)。另测 `AvitaSpecialScheduler._execute_scan()` 同样走通。
- 注意:本段改动后**须重启后端**(页面才生效);之前 app.py 的 import 编辑一度未落盘已补正。当前后端 PID 16484 已用含全部改动的新代码重新拉起。
## 续5:W列触客率公式修正(15:00 重跑 task 37)
- 用户要求:结果表 W 列触客率口径由「触客数/主机厂交付数」改为「主机厂交付数/广联触客数」,即 N/T(N=主机厂交付数 oem_delivery_count col14;T=广联触客数 cutoff_gl_visit_count col20)。
- 改动两处:①`generate_result_excel` 明细行 W 公式由 `_safe_div(t, s)`(触客/广联交付)改为 `_safe_div(n, t)`(主机厂交付/广联触客);②模板 `exporttemplete/avita_special_report_template.xlsx` 的 W3 表头由 `触客率\n(触客数/主机厂交付数)` 改为 `触客率\n(主机厂交付数/广联触客数)`(单一真源,后续生成自动带入)。
- 重跑 task 37 校验:W 值= N/T(如昆明东杰 13/15=0.867、成都万友翔宇 20/11=1.818),表头已更新。OSS 与 outputs 副本已刷新。后端已重启(PID 16484 → 25168)以加载新公式。
## 续6:品牌汇总五项聚合由明细月份求和(15:23 重跑 task 37)
- 需求:品牌汇总 产值/交付数/售前触客数/整车延保成交数/原厂权益成交数 = 明细月份(当前月)对应字段求和。
- 字段映射:D产值=Σoem_total_output;E交付数=Σoem_delivery_count(主机厂);F售前触客数=Σcutoff_gl_visit_count(广联);K整车延保成交数=Σoem_extended_warranty_deal_count(主机厂);M原厂权益成交数=Σoem_worry_free_deal_count(主机厂)。
- 仅填 7月段(行20);6月段(行16)无上月明细源→全 '-';G售前触客率/L延保渗透率/N权益渗透率/O/P/Q/R环比 未要求→留 '-'。
- 改动:`generate_result_excel` 品牌汇总块新增 total_output/delivery/visit/ext/rights 求和,行20填 D/E/F/K/M;删原 `for c in (4,5,6,7,11,12,13,14,15,16,17,18):'-'` 改为仅 (7,12,14,15,16,17,18)='-'。
- 校验:行20 D=487338 E=218 F=124 K=97 M=47,与 DB `SUM(...)` 直接求和完全一致(双方法对比通过)。后端已重启(PID 25168)加载新代码。
## 续7:汇总指标表 avita_special_month_summary_metrics 同步聚合(15:31 重跑 task 37)
- 需求:结果表品牌汇总的五项聚合须同步落库到 `avita_special_month_summary_metrics` 表(之前这五项在表中为 NULL)。
- 改动两处(avita_special_processor.py):①`_save` 在构造 `sum_obj`(AvitaSpecialMonthSummaryMetrics)前,基于已落库的 `detail_objs` 计算聚合并写入:`store_count=len(detail_objs)`、`output_value=Σoem_total_output`(round 2)、`delivery_count=Σoem_delivery_count`、`pre_sales_visit_count=Σcutoff_gl_visit_count`、`vehicle_extended_warranty_deal_count=Σoem_extended_warranty_deal_count`、`oem_rights_deal_count=Σoem_worry_free_deal_count`;其余(各渗透率/环比)仍 NULL,`after_sales_*` 保留原 summary_vals 解析值。②`generate_result_excel` 品牌汇总 7月段(行20) 改优先读 `summary` 对象(已落库的汇总表)对应列,缺值才回退到明细实时求和——实现结果表与汇总表**单一来源同步**。
- 校验:三方法对比(结果表行20 / 汇总表 / 明细SUM)全部一致:store_count=8、output_value=487338、delivery_count=218、pre_sales_visit_count=124、veh_ext=97、oem_rights=47,全 OK。
- 后端重启(PID 25168→16372,backend_avita9.log)加载新代码;`avita_special 定时任务已启动(间隔 60 秒)` 已生效。
## 续8:汇总指标表 project_name 固定为 阿维塔(15:45 重跑 task 37)
- 需求:`avita_special_month_summary_metrics` 表的 `project_name` 应为固定值「阿维塔」(原代码 `getattr(task,'data_table_type_name',None) or '阿维塔专项'` 取任务类型名,非固定)。
- 改动:`avita_special_processor.py` `_save` 中 `project_name='阿维塔'`(与 `brand='阿维塔'` 一致)。
- 验证:standalone 脚本直连 DB 重跑 task 37,`AvitaSpecialMonthSummaryMetrics` 落库后确认 `project_name=阿维塔`、`brand=阿维塔`(已回显)。后端重启(旧 PID 930 终止 → 新 PID 启动,backend_avita10.log)加载新代码;`avita_special_scan` 调度正常。临时重跑脚本 `_reproc_avita37.py` 已清理。
## 续9:品牌汇总渗透率公式 + 环比(16:03 重跑 task 37)
- 需求(用户给列位):售前触客率=售前触客数/交付数 即 F/E(col6/col5);整车延保渗透率=整车延保成交数/交付数 即 K/E(col11/col5);原厂权益渗透率=原厂权益成交数/交付数 即 M/E(col13/col5,N为结果列);环比(本月-上月)四项:售后场景开通率环比(O15)=本月I9-上月I9、售前触客率环比(P16)=本月G7-上月G7、整车延保渗透率环比(Q17)=本月L12-上月L12、原厂权益渗透率环比(R18)=本月N14-上月N14。
- 模板确认:品牌汇总 7月段表头(行19)A~R:1项目2品牌3门店数4产值5交付数6售前触客数7售前触客率8售后门店数9售后场景开通率10售后订单数11整车延保成交数12整车延保渗透率13原厂权益成交数14原厂权益渗透率15售后场景开通率环比16售前触客率环比17整车延保渗透率环比18原厂权益渗透率环比。
- 改动(avita_special_processor.py):①新增 `_safe_sub`(安全减法) + `_prev_month_str`(上月月份推导,跨年处理);②`generate_result_excel` 品牌汇总段重写:从汇总表(缺则明细)取 E交付数/F售前触客数/K整车延保成交数/M原厂权益成交数,G/L/N 按 F/E、K/E、M/E 计算;环比从 DB 查 `stat_month=上月` 的 `AvitaSpecialMonthSummaryMetrics`(按 id desc 取最新),有则填行16(上月)真实值并算 O~R=本月-上月,无则行16整行与 O~R 留空(用户确认口径「从DB取,如无则留空」)。
- 验证(重跑 task 37,DB 无 2026-06 汇总):行20 G=0.568807(124/218)、L=0.444954(97/218)、N=0.215596(47/218),与 DB 重算一致;行16 与 O~R 全空。后端重启(旧 PID 1619 → 新 PID,backend_avita11.log)加载新代码。临时重跑脚本已清理。
- 注意:当前系统仅处理 2026-07,无 6月汇总表 → 环比恒空;待后续接入 6月任务/数据后,行16 与 O~R 自动填充。
## 续10:汇总指标表遗留 7 个派生字段全部落库(17:19 重跑 task 37)
- 需求:用户指出 `avita_special_month_summary_metrics` 仍有字段未保存。`_save` 原把 7 个派生列置 NULL:`pre_sales_visit_rate`、`vehicle_extended_warranty_penetration_rate`、`oem_rights_penetration_rate`、及四项环比 `after_sales_scene_open_rate_mom`/`pre_sales_visit_rate_mom`/`vehicle_extended_warranty_penetration_rate_mom`/`oem_rights_penetration_rate_mom`。
- 改动(avita_special_processor.py `_save`):在构造 `sum_obj` 前按与结果表一致的口径计算——三项渗透率 = 分子/交付数(E):`pre_sales_visit_rate=_safe_div(Σcutoff_gl_visit_count, Σoem_delivery_count)`、`vehicle_extended_warranty_penetration_rate=_safe_div(Σoem_extended_warranty_deal_count, Σoem_delivery_count)`、`oem_rights_penetration_rate=_safe_div(Σoem_worry_free_deal_count, Σoem_delivery_count)`;环比四项 = 本月−上月,从 DB 查 `stat_month=上月` 的 `AvitaSpecialMonthSummaryMetrics`(prev 行)取同口径分子/分母重算上月比率后 `_safe_sub`(无 prev 行则四项留空)。所有比率/环比统一 `round(x,6)` 经 `_to_dec` 写入 DECIMAL(10,6)。
- 验证(重跑 task 37):汇总表 7 字段全部落值——`pre_sales_visit_rate=0.568807`、`vehicle_extended_warranty_penetration_rate=0.444954`、`oem_rights_penetration_rate=0.215596`(与结果表行20一致);四项环比=`0.000000`(非空)。
- 数据隐患:DB 存在 2026-06 测试残留行 `id=18 / task_id=1 / stat_month=2026-06`(交付=218、售后开通率=0.38,与 7月完全相同、比率列空——旧代码未保存)。它使 task 37 四项环比被算成 0。用户确认**保留不动**,故 7月环比维持 0.000000(被视为"环比持平");后续若有真实 6月数据应软删该残留行(置 is_deleted=1)使环比正确留空。
- 后端重启(backend_avita12.log)加载新代码;`avita_special_scan` 调度正常。临时重跑脚本已清理。
# 2026-09-28 工作日志
## 营销人员成本计算逻辑调整(店中店/园区店轻改报表)
- 文件:`light_reform_inshop_processor.py:404`(`light_reform_park_processor.py` 若同口径需同步,待确认)。
- 原:`营销人员成本 = 直营人数 * 3500 + 门店总产值 * 4%`(底薪 3500 固定不折算)。
- 改:底薪 3500 元/人/月 **按统计周期天数折算** = `prorate_by_period(3500, period_start, period_end)`,即 `3500 * 周期天数 / 月份总天数`(周期天数=period_end-period_start+1 含首尾;月份总天数=period_start 所在月 `calendar.monthrange`)。
- 验证:2号~6号、30天月 → 3500*5/30=583.33;全月1~30号 → 3500.00;跨月9/28~10/5(按9月30天)→ 933.33,均符合预期。
- 4% 提成(门店总产值*4%)**不折算**,保持原样。非直营门店仍=0。
- `prorate_by_period` 在处理器 line27 已 import,复用即可;period_start/period_end 来自 task。
- ⚠ 仅改了 inshop(店中店)一处;用户问的「店中店汇总 sheet 营销人员成本」即此字段。park(园区店)同公式是否同步未确认,待用户指认。
## 园区店人员成本同步改为按天折算(已确认)
- 用户确认后,将 `light_reform_park_processor.py:393`(人员成本 `personnel_cost`)同步改为按天折算:`base_salary_prorated = prorate_by_period(Decimal('3500'), period_start, period_end)`。
- 字段名差异:店中店=`marketing_personnel_cost`(提成基数 `store_output_value`)、园区店=`personnel_cost`(提成基数 `store_sales_output`),比例均为 4%。
- park 处理器 line33 已 import `prorate_by_period`,且装修/房租/耗材(329/332/335)已用它折算,仅人员成本漏改 → 现已补。
- 验证:py_compile 通过;grep 命中行 395 确认落盘(沙箱丢写已复核)。
- 现状:**店中店 + 园区店**两处人员/营销人员成本口径已统一(均按天折算底薪)。两处均为处理器代码,需**重启后端**页面「重新生成」才生效;msoffcrypto 已装,解密无需重启。
## 后端缺 msoffcrypto 导致人力成本表解密失败(headcount 全 0)
- 现象:页面点「重新生成」后日志 `[人力成本表] msoffcrypto 未安装` + `Can't find workbook in OLE2 compound document`,headcount 退化为 0 → 营销人员成本只算 4% 提成,底薪整段缺失。
- 根因:后端 Flask 跑在 `C:/Users/66/AppData/Roaming/Python/Python314/site-packages`,该环境未装 msoffcrypto;managed venv 有但后端不用。
- 修复:`C:/Python314/python.exe -m pip install --target "C:/Users/66/AppData/Roaming/Python/Python314/site-packages" msoffcrypto-tool`(顺带 cryptography/cffi/olefile/pycparser)。已验证该解释器 `import msoffcrypto` 成功、解密 task 32 人力成本表得 `遵义广新智腾汽车销售有限公司=3`。
- 关键点:`parse_labor_cost` 在**函数内** `import msoffcrypto`(report_utils.py:1240),属运行时懒加载 → 装好包后**下次重新生成即用,无需重启后端**。
- 建议:重跑 task 32 整体重算,让新公式+正确 headcount 同时生效(此前所有直营店营销成本/毛利均被少算底薪段)。
# 2026-09-29 工作日志
## 总看板「2.3交车数」口径核查(14487 vs 17513)
- 字段:`build_store_effect_board.py:810` `m['2.3交车数'] = fetch_extended_warranty_23_sum('delivery_cnt', period_start, period_end)` → `_lr_sum_one('warranty','delivery_cnt',...)`(line557)。
- 真实口径:`report_extended_warranty` 表 `task_id==max(周期匹配或最新task), is_deleted=0` 的 `delivery_cnt` 之和。**只汇总单个 task_id,非跨所有 task 全量**。
- 用户报:结果表显示 14487、DB 查汇总 17513。实测当前代码算当前 DB(仅 task_id=32 一个任务)=17513;三种 period 取值(None / 整月 / 子集)均 17513;task32 无 NULL 行、75 行 0 值。
- 结论:14487 是**旧结果表快照**,DB 已更新 → 重跑生成结果表即对齐 17513。差异=数据时效,非逻辑 bug。
- ⚠ 设计提醒:看板只取**单个** task_id(周期匹配优先,否则 max(task_id))。当前仅 task32 故与全量等价;若未来并存多月/多 task 延保数据,看板只取最新一个 task,与"不限 task_id 全量"查询将不一致。
## 总看板执行顺序闸门(必须等前4个sheet完成)
- 用户要求:总看板(第5 sheet)必须在前 4 张 sheet(warranty/equity/inshop/park)执行完才执行。
- 根因:5 个调度器(warranty/equity/inshop/park/store_effect_summary)各自独立扫描同一 PROCESSING 主任务并发执行;原 `scan_store_effect_summary` 在跑 `_process_summary`(读前 4 张表的 ORM 数据)**前无闸门** → 竞态,总看板读到未落库/旧前置数据。
- 修复:`store_effect_summary_processor.py`
- `process()` 顶部加两道闸:① 自身已 COMPLETED → 幂等跳过;② `_preceding_sheets_all_completed(task_id)` 检查 `PRECEDING_CATEGORIES=['warranty','equity','inshop','park']` 是否**全部 == SUBTASK_COMPLETED**,否则 `return`(自身子任务保持 PENDING,等下轮调度重试;不置 FAILED)。
- 新增模块常量 `PRECEDING_CATEGORIES` + 方法 `_preceding_sheets_all_completed`(返回 (all_done, pending_list),未就绪态 PENDING/PROCESSING/None/FAILED 均视为等待)。
- 闸门放在 `process()` 内部(而非仅 scan),同时覆盖**两条入口**:调度器 `StoreEffectSummaryScheduler.scan_store_effect_summary` 与手动"处理"按钮 `processor.py:1437` 路由,均调用 `StoreEffectSummaryProcessor.process(task)`。
- 注:某前置 FAILED 时,主任务会被 `promote_subtask_failure_to_main_task` 置 FAILED,调度器不再扫到;手动按钮也因闸门(FAILED≠COMPLETED)而等待,不 deadlock。
- 验证:`py_compile` 通过;monkeypatch 5 用例全过(全完成→True;inshop PENDING/park PROCESSING/equity FAILED/inshop None→均 False+对应 pending 列表)。
...@@ -8,39 +8,6 @@ ...@@ -8,39 +8,6 @@
- `output_value`:`OutputValueScheduler`(扫描 output_value 的 PROCESSING 任务)→ `OutputValueProcessor.scan_output_value()` → 写 `saas_business_achievement` 表(按 task_id 先删后插,幂等)。 - `output_value`:`OutputValueScheduler`(扫描 output_value 的 PROCESSING 任务)→ `OutputValueProcessor.scan_output_value()` → 写 `saas_business_achievement` 表(按 task_id 先删后插,幂等)。
- `DataProcessor.process_task` 按 `data_table_type` 在白名单**前**显式路由:`output_value`→`OutputValueProcessor`、`store_effect_earnings`→`StoreEffectSummaryProcessor`、`avita_special`→`AvitaSpecialProcessor`(三者均在处理后置 COMPLETED 并 return);其余非 `SUPPORTED_PROCESS_TYPES` 类型(`future_expansion`)白名单拦截抛"引擎尚未接入",不再误跑预算流水线。`process_all` 仍只处理 `budget_achievement`。 - `DataProcessor.process_task` 按 `data_table_type` 在白名单**前**显式路由:`output_value`→`OutputValueProcessor`、`store_effect_earnings`→`StoreEffectSummaryProcessor`、`avita_special`→`AvitaSpecialProcessor`(三者均在处理后置 COMPLETED 并 return);其余非 `SUPPORTED_PROCESS_TYPES` 类型(`future_expansion`)白名单拦截抛"引擎尚未接入",不再误跑预算流水线。`process_all` 仍只处理 `budget_achievement`。
## 数据表类型与调度分工
- `config.DATA_TABLE_TYPES` 共 4 类:`budget_achievement`(7表单) / `store_effect_earnings`(11表单, need_period) / `output_value`(2表单: SAAS门店预算分解表+关系表, need_period) / `future_expansion`(占位)。
- 流水线分工:
- `budget_achievement`:`processor.process_all` 编排(先 clean 后 processor)。
- `store_effect_earnings`:4 个 `NewReportScheduler` 子类(warranty/equity/inshop/park)各写 `report_*` 表 + `data_process_subtask` 幂等状态机。
- `output_value`:`OutputValueScheduler`(扫描 output_value 的 PROCESSING 任务)→ `OutputValueProcessor.scan_output_value()` → 写 `saas_business_achievement` 表(按 task_id 先删后插,幂等)。
- `DataProcessor.process_task` 已按 `data_table_type` 路由(2026-09-04 补):`output_value` → `OutputValueProcessor`(手动单任务触发亦可处理);其余非 `SUPPORTED_PROCESS_TYPES` 类型(`store_effect_earnings`/`future_expansion`)白名单拦截抛"引擎尚未接入",不再误跑预算流水线。`process_all` 仍只处理 `budget_achievement`。
## 配置表初始化(2026-09-03)
- `config_brand_category` 表:品牌/品牌区分配置(18 行全"豪华")。新建脚本 `_init_brand_config.py` 幂等。列:brand(UNIQUE 191 前缀) / category / create_time / update_time。来源 `配置表/豪华品牌配置表.xlsx`。
- `merchant_4s`(标准名/别名,流量方,22 行)、`merchant_yq`(标准名/别名,园区店,12 行)已 2026-08-10 录入。
- ⚠️ `配置表/运营报表映射对应一览表.xlsx` 的"流量方映射"sheet **仅有表头+说明、无实际数据行**,初始化时跳过;如用户补好映射数据需重发再灌(刷新逻辑应走 merchant_4s)。
## 任务单据重复校验口径(2026-09-02 修订)
- `data_process_task` 表当前**无 UNIQUE 索引**(仅主键)。原 `uq_task_type_month` 已删除,原因:MariaDB 10.0.19 不支持 STORED 列上的函数索引,无法做"仅约束活跃行"的部分唯一索引。
- 去重完全靠 `app.py task_create` 应用层校验,按 `data_table_type` 维度区分:
- `need_period` 类型(店效人效 / 产值达成表):`(data_table_type, month, period_start, period_end, is_deleted=0)` 4 维唯一;
- 非 need_period(预算达成数据):`(data_table_type, month, is_deleted=0)` 2 维唯一。
- 错误消息带周期提示:`"该数据表类型与月份、周期 2026-08-01~2026-08-20的单据已存在..."`。
- 风险:极端并发理论可穿透(应用层 SELECT 与 INSERT 之间),手点场景可忽略;如要强化,可在 task_create 内 SELECT FOR UPDATE。
- `migrate_comments.py` 已带索引治理段,幂等删除任何遗留 uq_* 唯一索引。
## 导出 Excel 列格式约定(2026-08-20 新增)
- 占比/毛利率列(本月占比/上月占比/技师工资占比/营销团队工资占比/本月毛利率/上月毛利率 = processor.py `RATIO_COLS`)在导出 Excel 中一律用 `number_format='0.00"%"'`。
- **原因**:`biz_budget_achieve` 表中这些占比列存的是**已×100 的百分数值**(46.71 表示 46.71%,max 可达 999.99、min 可到 -999.99),若用标准 `0.00%` 格式会被 Excel 再放大 100 倍(显示 4671%)。`0.00"%"` 仅显示追加 % 号、值不变,符合「导出全部读表不重算」约定。
- 导出文件 40 列(无"字段名称"首列):L/M/O/P/R/S/X/Y=成本/流量费/服务费/市场费占比,AC=技师工资占比,AE=营销团队工资占比,AF/AG=人员工资占比,AM/AN=毛利率(用户消息中的「AB列(技师工资占比)」系笔误,实际技师工资占比在 AC;按表头名匹配不受列号影响)。
- **遗留已知问题(未修)**:表头含 `\n` 的金额列(K 成本GMV口径/N 流量费GMV口径/T 成本收入口径/U 流量费收入口径/AI 房租及水电费)因换行与 AMOUNT_COLS 键不匹配,导出为**文本字符串**(非数字),需在匹配时 strip('\n') 修复。
## 广联报表接口(dj.glsx.com.cn/reportExport,**无需鉴权**)
三步链路:
1. `GET /queryAllExcel?pageSize=10&currentPage=1&filename={YYYY-MM}&business_type=yanbao&report_type=yanbaoMerAndPerRanking&key=` → 取 `data.list` 中 `filename` 含**「通用品牌」**那条的 `key`。
2. `GET /download?key={key}` → `data.list[0].url`。
3. `GET 该 url` 下载 xlsx。
解析要点:表头行 = col0=='业务类型'(表头含换行,须归一 `_norm_header`);门店名在 col2,**小计行 col2 为空 → 从上一业务行向前携带**。行标签 `延保小计` 带:整车延保成交数 / 原厂权益成交数 / **实际完成产值(万元)** / 累计交付数 / 实际售前触客数;行标签 `权益小计` 带:广联权益成交数。⚠ 门店小计行的「目标产值」列**为空**(真实值是「实际完成产值」)。
三处同源实现:`baic_special_processor.fetch_glsx_report` / `avita_special_processor.fetch_glsx_deal_counts` / `glsx_daily_processor._download_glsx_rows`。
## 阿维塔专项(2026-09-16 实现) ## 阿维塔专项(2026-09-16 实现)
- 类型 `avita_special`:config 表单名 `主机厂数据表`(暂定,改名只改 config 的 `forms`);`need_period=False`(不要所属周期项)。 - 类型 `avita_special`:config 表单名 `主机厂数据表`(暂定,改名只改 config 的 `forms`);`need_period=False`(不要所属周期项)。
- 处理器 `avita_special_processor.py`:`AvitaSpecialProcessor.process(task)` 下载附件→解析→按 task_id 先删后插落库(`db.session.add_all` 显式存 NULL,保证未提供列落空而非 0)→置 `status=COMPLETED`、`result_file_url=''`(最终 Excel 待用户提交模板后生成)。 - 处理器 `avita_special_processor.py`:`AvitaSpecialProcessor.process(task)` 下载附件→解析→按 task_id 先删后插落库(`db.session.add_all` 显式存 NULL,保证未提供列落空而非 0)→置 `status=COMPLETED`、`result_file_url=''`(最终 Excel 待用户提交模板后生成)。
...@@ -51,82 +18,37 @@ ...@@ -51,82 +18,37 @@
- **已知缺口(7月样本)**:明细表 `store_mode/entry_time/resident_name` 由源文件解析填充、`regional_operation` 由 dj_smartcarlife 两跳查询填充、`cutoff_gl_extended_warranty_deal_count`/`cutoff_gl_worry_free_deal_count` 由广联报表导出接口填充(见下);汇总表 store_count/output_value/delivery_count/pre_sales_visit_count 及各渗透率/环比列 源文件汇总段未提供→留空,待最终 Excel 生成或后续填充。 - **已知缺口(7月样本)**:明细表 `store_mode/entry_time/resident_name` 由源文件解析填充、`regional_operation` 由 dj_smartcarlife 两跳查询填充、`cutoff_gl_extended_warranty_deal_count`/`cutoff_gl_worry_free_deal_count` 由广联报表导出接口填充(见下);汇总表 store_count/output_value/delivery_count/pre_sales_visit_count 及各渗透率/环比列 源文件汇总段未提供→留空,待最终 Excel 生成或后续填充。
- **广联延保/无忧成交数查询(2026-09-17 加)**:源文件无此两列,改由 `dj.glsx.com.cn` 报表导出接口(`avita_special_processor.fetch_glsx_deal_counts(stat_month)`):①`/queryAllExcel?filename={stat_month}&business_type=yanbao&report_type=yanbaoMerAndPerRanking&key=` 取 `data.list` 中 `filename` 含 **通用品牌** 的 `key`;②`/download?key={key}` 取 `data.list[0].url`;③下载 xlsx 解析 Sheet1,表头行(col0=='业务类型',单元格含换行需归一 `_norm_header`)定位列;行 col0=='延保小计' 取「整车延保成交数」列值作 `cutoff_gl_extended_warranty_deal_count`,行 col0=='权益小计' 取「原厂权益成交数」列值作 `cutoff_gl_worry_free_deal_count`;按 `门店`(col2) 名称与 `avita_special_month_data.store_name` **精确匹配**聚合(同店多行求和)。该接口**无需鉴权**即可访问;查不到/异常不致命,仅告警并留空。注意:仅「通用品牌」报表里的门店能匹配(2026-07 实测 8 家阿维塔门店中仅 4 家在通用品牌报表内,其余 4 家如成都万友翔宇/重庆万友诚行/广州市美昌/江苏万友 不在该报表→留空)。 - **广联延保/无忧成交数查询(2026-09-17 加)**:源文件无此两列,改由 `dj.glsx.com.cn` 报表导出接口(`avita_special_processor.fetch_glsx_deal_counts(stat_month)`):①`/queryAllExcel?filename={stat_month}&business_type=yanbao&report_type=yanbaoMerAndPerRanking&key=` 取 `data.list` 中 `filename` 含 **通用品牌** 的 `key`;②`/download?key={key}` 取 `data.list[0].url`;③下载 xlsx 解析 Sheet1,表头行(col0=='业务类型',单元格含换行需归一 `_norm_header`)定位列;行 col0=='延保小计' 取「整车延保成交数」列值作 `cutoff_gl_extended_warranty_deal_count`,行 col0=='权益小计' 取「原厂权益成交数」列值作 `cutoff_gl_worry_free_deal_count`;按 `门店`(col2) 名称与 `avita_special_month_data.store_name` **精确匹配**聚合(同店多行求和)。该接口**无需鉴权**即可访问;查不到/异常不致命,仅告警并留空。注意:仅「通用品牌」报表里的门店能匹配(2026-07 实测 8 家阿维塔门店中仅 4 家在通用品牌报表内,其余 4 家如成都万友翔宇/重庆万友诚行/广州市美昌/江苏万友 不在该报表→留空)。
- **区域运营(regional_operation)查询(2026-09-16 加)**:源文件无此列,改由 `dj_smartcarlife` 两跳查询(`avita_special_processor.fetch_regional_operation`):①`dj_car_life_service_merchant` 按 `merchant_name=门店名称 AND deleted_flag='N'` 取 `merchant_id`;②`dj_car_life_shop_merchant_director_config` 按 `merchant_id AND director_type=9 AND deleted_flag='N'` 取 `director_name`,多条去重以 `/` 分隔。引擎用 `create_engine(Config.BIZ_SQL_DATABASE_URL)`(注意:该库连接串挂在 `Config` **类**上,不是 `config` 模块属性,需 `from config import Config`)。查不到/异常不致命,仅告警并留空。 - **区域运营(regional_operation)查询(2026-09-16 加)**:源文件无此列,改由 `dj_smartcarlife` 两跳查询(`avita_special_processor.fetch_regional_operation`):①`dj_car_life_service_merchant` 按 `merchant_name=门店名称 AND deleted_flag='N'` 取 `merchant_id`;②`dj_car_life_shop_merchant_director_config` 按 `merchant_id AND director_type=9 AND deleted_flag='N'` 取 `director_name`,多条去重以 `/` 分隔。引擎用 `create_engine(Config.BIZ_SQL_DATABASE_URL)`(注意:该库连接串挂在 `Config` **类**上,不是 `config` 模块属性,需 `from config import Config`)。查不到/异常不致命,仅告警并留空。
## 导出 Excel 列格式约定(2026-08-20 新增)
- 占比/毛利率列(本月占比/上月占比/技师工资占比/营销团队工资占比/本月毛利率/上月毛利率 = processor.py `RATIO_COLS`)在导出 Excel 中一律用 `number_format='0.00"%"'`。
- **原因**:`biz_budget_achieve` 表中这些占比列存的是**已×100 的百分数值**(46.71 表示 46.71%,max 可达 999.99、min 可到 -999.99),若用标准 `0.00%` 格式会被 Excel 再放大 100 倍(显示 4671%)。`0.00"%"` 仅显示追加 % 号、值不变,符合「导出全部读表不重算」约定。
- 导出文件 40 列(无"字段名称"首列):L/M/O/P/R/S/X/Y=成本/流量费/服务费/市场费占比,AC=技师工资占比,AE=营销团队工资占比,AF/AG=人员工资占比,AM/AN=毛利率(用户消息中的「AB列(技师工资占比)」系笔误,实际技师工资占比在 AC;按表头名匹配不受列号影响)。
- **遗留已知问题(未修)**:表头含 `\n` 的金额列(K 成本GMV口径/N 流量费GMV口径/T 成本收入口径/U 流量费收入口径/AI 房租及水电费)因换行与 AMOUNT_COLS 键不匹配,导出为**文本字符串**(非数字),需在匹配时 strip('\n') 修复。
## 标准名 / 别名映射(merchant_4s 流量方 / merchant_yq 园区店,2026-08-11 新增) ## output_value 产值达成表(2026-09-04 实现)
- 结果表列 A~O:A业务类型(2.1+2.3 / 1.1) / B大区经理 / C区域运营 / D线上运营(空) / E运营门店数 / F直营门店数 / G当日新增GMV(接口) / H存量预算 / I存量实际(接口) / J存量达成率 / K新店预算 / L新店实际(接口) / M新店达成率 / N实际GMV合计 / O总达成率。
- 映射规则(用户拍板):A列定 sheet(2.1+2.3→权益延保sheet1 / 1.1→轻改sheet2)→ C列=SAAS表「区域运营」;B列=关系表「E区域经理→D大区经理」;E/F按门店去重;H/K=预估产值(纠偏)按存量/新增汇总。G/I/L来自接口,暂落 NULL(连带 J/M/N/O 留空)。
- 关系表哨兵 `/`、`nan`、`None`、`无` 归一为空。
- 解析复用 `report_utils.parse_saas_achieve_details` / `parse_operator_relation`;config 表单名须精确为 `SAAS门店预算分解表` 与 `关系表`。
- **结果表生成**:`OutputValueProcessor.generate_result_excel(task)` 读 `saas_business_achievement` → 生成「业务达成总览」sheet(A~O 列,行1标题/行2表头/行3口径说明/行4+数据,按业务类型 2.1+2.3 在前、1.1 在后)→ `upload_file` 上传 OSS(object_key `data-process/YYYYMMDD/output_value_{month}_{task}.xlsx`)→ 回写 `task.result_file_url`。`process()` 末尾自动调用。模板其余 sheet(精品业务达成/省份透视)依赖接口数据,暂未生成。
- **接口列必须存 NULL(关键坑)**:`saas_business_achievement` 的 DECIMAL 列带 DB 端默认 `0.00`;`bulk_save_objects` 会省略 None 列导致落 `0`,使"未接入"被误读为"已接入且为 0"。**写入须用 `db.session.add_all(rows)`(而非 bulk_save_objects)** 以显式存 NULL。生成 Excel 时对 None 也写空,保证 G/I/L/J/M/N/O 留空。
- 字典表:`merchant_4s`(standard_name 流量方标准全称 / alias_name 别名)、`merchant_yq`(standard_name 园区店标准全称 / alias_name 别名)。一个标准名可多行别名;别名不重复冲突;部分别名==标准名(幂等)。**园区店标准名均带 `D+` 前缀**,别名覆盖带/不带 D+ 两种。
- 新增 `load_alias_maps(conn)`(模块级缓存 `_ALIAS_MAPS`,整个进程只加载一次)+ `to_standard(raw, kind)`:raw 命中别名→返回 standard(含 D+);否则去 D+ 再查;都查不到→返回 raw 原值(即保留结算汇总表原始名,符合用户要求)。
- **入库(save_budget_rows)**:写 `biz_budget_achieve` 前对每行 `traffic_name=to_standard(.,'4s')`、`park_store=to_standard(.,'yq')`——预算表统一存标准名;gmv_ratio/gmv_ratio_park 随之按标准名归并分组。若不存在映射则原样入库。
- **最终合并键(关键,2026-08-11 修正)**:`biz_budget_achieve` 按「业务类型+主体+流量方(标准名)+品牌+园区店(标准名)+服务商」6 维合并。合并**必须在 `SettlementSummaryParser.generate_budget_metrics/generate_budget_first7` 的分组阶段**就用标准名作为分组合键(通过注入 `traffic_std`/`park_std` 函数),而非仅靠 save_budget_rows 事后归一——事后归一不重新分组,会导致同标准名的多个别名被拆成多行重复入库(实测:内蒙古 4 个别名被拆成 4 行,标准名合并后归并为 1 行)。解析器不依赖 DB,由 `process_task` 注入 `lambda x: to_standard(x,'4s')` / `lambda x: to_standard(x,'yq')`。
- **匹配(装修摊销 / 门店耗材)**:预算行与明细名均先 `to_standard` 再比较——别名数据归属到标准名下。**装修摊销**两侧再 `strip_if_dplus`(与 D+ 口径一致);**门店耗材**保留 D+(候选匹配 F 用 4s、G 用 yq 各自归一,维持"不去 D+"语义)。
- 效果(task #16 / 2026-06):流量方 15 行归并(内蒙古迪达/迪道/迪洋/迪致→内蒙古博饰);园区店入库 0 行变化(DB 原已带 D+ 即标准名,幂等)。东莞寮步门店耗材恢复:9364=7437.59、9366=2592.03(合计 10029.62,此前因源表缺 D+ 落空,现经 `东莞寮步国际汽车城园区店`→`D+东莞寮步国际汽车城园区店` 别名映射命中)。门店耗材 20→28 行 / 12607.95→28016.40;装修摊销不变 67092.74。两口径「池合计==匹配明细总额」差均为 0.0000。
## 共享解析库 report_utils 关键函数
`parse_saas_base`(sheet1) / `_sheet2`(店中店) / `_sheet2_exclude`(园区店) / `parse_region_map` / `parse_delivery_table`(主机厂) / `parse_{inshop,park}_delivery_touch` / `parse_commerce_policy_{inshop,park}` / `parse_labor_cost` / `parse_budget_achieve_excel` / `fetch_indicator_data`(A075成交/A036产值/A084触客) / `is_luxury_brand`。新增报表优先复用。
## 阿维塔专项 avita_special
- `avita_special_processor.py`:process 下载附件→解析→按 task_id **软删**旧行(is_deleted=1) + 插新行 → COMPLETED、`result_file_url=''`。
- ORM:`AvitaSpecialMonthData`(明细,**真实表无 created_at/updated_at**) / `AvitaSpecialMonthSummaryMetrics`(**只有 created_at**)。读表须 `filter_by(is_deleted=0)`。写 ORM 必须逐列对齐真实表,多声明列 INSERT 报 `Unknown column`。
- 源文件:跳过前 2 行表头;0-based 列 = store_name=0 / short=1 / store_mode=2(文本) / entry_time=3(→YYYY-MM-DD) / resident_name=4(文本) / 主机厂交付=5 / 延保=6 / 无忧=7 / 单车收入=8 / 总产值=9 / 广联交付=10 / 广联触客=11;末尾汇总段按标签映射 `after_sales_*`。
- 补齐来源:regional_operation ← dj_smartcarlife 两跳(`dj_car_life_service_merchant` → `dj_car_life_shop_merchant_director_config` director_type=9);广联成交数 ← 上节接口(**仅「通用品牌」报表内门店可匹配**,2026-07 实测 8 家中仅 4 家命中)。
## 共享解析库 report_utils 关键函数 ## 共享解析库 report_utils 关键函数
`parse_saas_base`(sheet1) / `_sheet2`(店中店) / `_sheet2_exclude`(园区店) / `parse_region_map` / `parse_delivery_table`(主机厂) / `parse_{inshop,park}_delivery_touch` / `parse_commerce_policy_{inshop,park}` / `parse_labor_cost` / `parse_budget_achieve_excel` / `fetch_indicator_data`(A075成交/A036产值/A084触客) / `is_luxury_brand`。新增报表优先复用。 `parse_saas_base`(sheet1) / `_sheet2`(店中店) / `_sheet2_exclude`(园区店) / `parse_region_map` / `parse_delivery_table`(主机厂) / `parse_{inshop,park}_delivery_touch` / `parse_commerce_policy_{inshop,park}` / `parse_labor_cost` / `parse_budget_achieve_excel` / `fetch_indicator_data`(A075成交/A036产值/A084触客) / `is_luxury_brand`。新增报表优先复用。
## 标准名 / 别名映射(merchant_4s 流量方 / merchant_yq 园区店,2026-08-11 新增)
- 字典表:`merchant_4s`(standard_name 流量方标准全称 / alias_name 别名)、`merchant_yq`(standard_name 园区店标准全称 / alias_name 别名)。一个标准名可多行别名;别名不重复冲突;部分别名==标准名(幂等)。**园区店标准名均带 `D+` 前缀**,别名覆盖带/不带 D+ 两种。
- 新增 `load_alias_maps(conn)`(模块级缓存 `_ALIAS_MAPS`,整个进程只加载一次)+ `to_standard(raw, kind)`:raw 命中别名→返回 standard(含 D+);否则去 D+ 再查;都查不到→返回 raw 原值(即保留结算汇总表原始名,符合用户要求)。
- **入库(save_budget_rows)**:写 `biz_budget_achieve` 前对每行 `traffic_name=to_standard(.,'4s')`、`park_store=to_standard(.,'yq')`——预算表统一存标准名;gmv_ratio/gmv_ratio_park 随之按标准名归并分组。若不存在映射则原样入库。
- **最终合并键(关键,2026-08-11 修正)**:`biz_budget_achieve` 按「业务类型+主体+流量方(标准名)+品牌+园区店(标准名)+服务商」6 维合并。合并**必须在 `SettlementSummaryParser.generate_budget_metrics/generate_budget_first7` 的分组阶段**就用标准名作为分组合键(通过注入 `traffic_std`/`park_std` 函数),而非仅靠 save_budget_rows 事后归一——事后归一不重新分组,会导致同标准名的多个别名被拆成多行重复入库(实测:内蒙古 4 个别名被拆成 4 行,标准名合并后归并为 1 行)。解析器不依赖 DB,由 `process_task` 注入 `lambda x: to_standard(x,'4s')` / `lambda x: to_standard(x,'yq')`。
- **匹配(装修摊销 / 门店耗材)**:预算行与明细名均先 `to_standard` 再比较——别名数据归属到标准名下。**装修摊销**两侧再 `strip_if_dplus`(与 D+ 口径一致);**门店耗材**保留 D+(候选匹配 F 用 4s、G 用 yq 各自归一,维持"不去 D+"语义)。
- 效果(task #16 / 2026-06):流量方 15 行归并(内蒙古迪达/迪道/迪洋/迪致→内蒙古博饰);园区店入库 0 行变化(DB 原已带 D+ 即标准名,幂等)。东莞寮步门店耗材恢复:9364=7437.59、9366=2592.03(合计 10029.62,此前因源表缺 D+ 落空,现经 `东莞寮步国际汽车城园区店`→`D+东莞寮步国际汽车城园区店` 别名映射命中)。门店耗材 20→28 行 / 12607.95→28016.40;装修摊销不变 67092.74。两口径「池合计==匹配明细总额」差均为 0.0000。
## 装修摊销匹配规则(clean_budget_achievement.py) ## 导出 Excel 列格式约定
- 数据源:装修费用明细汇总(form_type='装修费用表'),仅 business_type='1.1' 参与。 - 占比/毛利率列(`processor.py RATIO_COLS`)用 `number_format='0.00"%"'`(表内已×100,禁用以 `0.00%` 会再放大100倍)。
- 基数 = 合同金额(L) / 36,仅取有实际验收日期(T) 且 stat_month 落在 [验收次月, 验收+36月] 的记录。 - 遗留问题:表头含 `\n` 的金额列(K成本GMV/N流量费GMV/T成本收入/U流量费收入/AI房租水电)因换行与 AMOUNT_COLS 不匹配,导出为文本串,需 strip('\n') 修复。
- 每条明细独立判定、只计一次(F/G 二选一):
- 先用明细「门店名称」(F) 匹配结果表 `traffic_name` → F 池(按命中行 GMV 占比分摊);
- 若 F 未命中**且明细「门店名称」列为空**,再用明细「系统园区店名称」(G) 匹配结果表 `park_store` → G 池(按 `gmv_ratio_park` 分摊)。**门店名称非空但未命中 F 的明细,不允许落到 G 池(2026-08-11 新增限制)。**
- **硬约束(用户拍板 2026-08-11):不允许同一条明细双重命中。F 命中后即占用该明细,不得再落到 G 池与同园区店其它流量方共享。**
- **金额分摊余额补差(2026-08-11):** 装修摊销与门店耗材的分摊都需保证「各方金额合计 == 匹配到的明细金额总和」。做法:新增 `distribute_by_weight(total, items)` 辅助——池总额先对齐到分,逐行 round(total*weight/wsum,2),**最后一个 weight>0 的行用 total-前面已算金额 回填**吸收四舍五入残差(每个池内部精确);再经 `reconcile_total` 做**全局对账**:把所有池的分摊合计对齐到「匹配明细总额(分取整)」,残差(最多几分)加到金额最大的一行,保证跨池也精确相等。renovation 与 consumables 的 F/G 分摊均复用这两个辅助。
- 匹配归一化:装修摊销(compute_renovation_amounts)预算行与明细名均先 `to_standard`(标准名/别名映射)再 `strip_if_dplus` 比较;**门店资产耗材候选匹配**同样先 `to_standard`(F 用 4s、G 用 yq 各自归一)后保留 D+,维持"不去 D+"语义(见上「标准名/别名映射」节)。
## 门店资产耗材 store_consumables(mirror 装修摊销,2026-08-11 新增) ## 标准名/别名映射
- 数据源:门店资产耗材明细表(form_type='门店资产耗材明细表',OSS 附件;task #16 附件 id=123)。 - `merchant_4s`/`merchant_yq` 字典表 + `to_standard(raw, kind)`:别名→标准名(园区店带 D+ 前缀)。
- 解析器 `parsers/consumables_parser.py`,按文件魔数自动选 xlrd(.xls)/openpyxl(.xlsx);业务类型去 精品/权益/延保/尊享/智行 后缀对齐预算表。 - 合并键6维(业务类型+主体+流量方标准名+品牌+园区店标准名+服务商),**必须在解析器分组阶段用标准名**而非事后归一(否则同标准名多别名拆多行)。
- 金额不除摊销月数、不限制业务类型;**按明细自身业务类型分别匹配**预算行;只取与 stat_month 同月的明细(月份标签如 '6月')。 - 装修摊销两侧 `to_standard`+`strip_if_dplus`;门店耗材保留 D+。
- **候选名匹配(关键差异,2026-08-11 再次修正)**:耗材明细「门店名称」+「系统园区店名称」都作候选(去重),**保留原值不去 'D+' 前缀**(用户明确:候选名侧不能 strip_if_dplus)。先试 F(`traffic_name`) 再试 G(`park_store`),每条明细只计一次、不双重命中;F 池按 GMV 占比、G 池按 `gmv_ratio_park` 分摊。预算行 map 侧同样不去 D+,使带 D+ 的园区店名精确命中 `park_store`、不带 D+ 的公司名命中 `traffic_name`。
- 历史:早期"不去 D+"曾使「东莞寮步国际汽车城园区店」(缺 D+ 前缀)2 个预算行落空;后引入别名映射(`东莞寮步国际汽车城园区店`→`D+东莞寮步国际汽车城园区店`)已恢复命中到 1.1 行 **id 9364(7437.59)/ 9366(2592.03)**(注:非此前误记的 8056/8058,查库 8056/8058 为其它行)。
- 不要用严格的「门店名称→traffic_name / 系统园区店名称→park_store」列映射(会漏掉佛山金辉、保定定州等把园区店名填在门店名称列的行)。
## gmv 占比字段 ## 装修摊销 / 门店耗材匹配
- `gmv_ratio` = 本行GMV / 同业务类型+同流量方名称 GMV 合计; - 装修摊销:装修费用明细(business_type='1.1'),基数=合同金额/36,仅验收次月起36月内;先 F(门店名称)→traffic_name 池,F空未命中才 G(系统园区店)→park_store 池;单条不双重命中;`distribute_by_weight`+`reconcile_total` 保证池合计==明细总额。
- `gmv_ratio_park` = 本行GMV / 同业务类型+同园区店 GMV 合计(供 G 池摊分用)。 - 门店耗材:耗材明细表,按明细自身业务类型匹配,F/G候选去重、保留D+,只取同月。
- 保存 gmv 数据时计算;每组末行用 `1 - 其余占比之和` 回填,保证组内合计精确=1.000000;GMV=0 的整组为零 → 该组全部 NULL(正常)。 - `gmv_ratio`=本行GMV/同业务类型+同流量方合计;`gmv_ratio_park`=/同园区店合计;末行 `1-其余` 回填,组合计精确=1。
## 运行约定 ## 两条流水线架构(clean vs processor)
- 任务 #16 对应 2026-06,当前 status=FAILED;手动回填一律加 `--force`(正常流水线应由编排器置 PROCESSING 再跑)。 - `clean_budget_achievement`:DELETE+INSERT 全量重写,8维唯一键,写26列+装修摊销/门店耗材,独立 pymysql 自提交。
- 命令:`python clean_budget_achievement.py -t budget_achievement -m 2026-06 [--force] [--dry-run]` - `processor.py`:仅 UPDATE 成本列(5维键,只读不插),强依赖 clean 先跑(读其 GMV 做市场费分摊分母)。
- 上月占比字段(cost_gmv_ratio_previous 等)在跑过 2026-05 后重跑 2026-06 会自动回填。 - 风险:①顺序 clean→processor;②唯一键粒度不一致(8 vs 5)会让多行同成本值;③processor 只UPDATE不INSERT。
## 两条流水线架构(clean_budget_achievement.py vs processor.py,2026-08-11 厘清)
- 历史:2026-08-11 前两者**互不调用**——`processor.py` 无 import/ subprocess 调用 `clean_budget_achievement`,`clean` 是独立手动 CLI(`python ... -t budget_achievement -m ... --force`)。**现已在 `processor.py` 的 `process_all` 中编排调用 `clean`**(见「调用接入」)。
- 唯一耦合点 = 共用表 `biz_budget_achieve`,是**上下游**而非互相编排:
- **调用接入(2026-08-11 新增,process_all 编排)**:`processor.process_all` 对 `data_table_type == CLEAN_DATA_TABLE_TYPE('budget_achievement')` 的任务,循环内先调新增方法 `_run_clean_pipeline(task)`,成功后才 `self.process_task(task.id)`;**clean 抛异常则该任务直接标记 FAILED、中止成本计算**(用户拍板,对应 AskUserQuestion 选择「直接 import 模块调用 + 中止本任务 cost 计算」)。
- `_run_clean_pipeline` 实现:懒加载 `from clean_budget_achievement import get_conn, process_task as clean_process_task`;用独立 pymysql 连接 `get_conn()` 调 `clean_process_task(conn, {'id':task.id,'month':task.month,'data_table_type':task.data_table_type}, dry_run=False)`,`finally: conn.close()`;结束 `db.session.expire_all()` 刷新 ORM 会话以读到 clean 已提交的新行。
- 注意:clean 使用独立 pymysql 连接并自提交,与本脚本 SQLAlchemy 会话互不干扰;clean 为 DELETE+INSERT 幂等,重复跑安全。仅 `budget_achievement` 任务触发(process_all 扫描所有 PROCESSING 任务,需按 data_table_type 过滤)。**单任务触发路径(app/scheduler 直接调 `process_task`)目前仍未内置 clean 前置**——若需覆盖,应把同一段 `_run_clean_pipeline` 调用提到 `process_task` 开头(否则单次触发仍依赖先手动跑 clean)。
- 数据流细节:
- **clean_budget_achievement.py**:DELETE+INSERT 全量重写整行,**8 维唯一键**(task_id, stat_month, traffic_name, business_type, entity, brand, park_store, service_provider),写 26 列(维度+GMV/营收/成本/流量费/服务费/装修摊销/门店耗材/占比)。另写入装修摊销(`renovation_amortization`)、门店耗材(`store_consumables`)。
- **processor.py**:只 **UPDATE** 成本列(market_fee / personnel_salary / external_construction / technician_salary / marketing_team_salary / rent_utilities 及其占比/毛利),**5 维匹配键**(task_id, stat_month, traffic_name, business_type, brand),且**只更新已存在行、不插入**。`_write_budget_achieve` 的 params 虽带 `renovation_amortization=0/store_consumables=0`,但 SQL 的 set_clause 仅含成本 update_columns,**不会覆盖** clean 算的装修摊销/门店耗材。
- processor 通过 `_fetch_gmv_from_db`(processor.py:349)**读取 clean 写入的 gmv/revenue** 作为市场费按 GMV 分摊的分母 → **强依赖 clean 先跑**;若 clean 未先跑,processor 告警"数据库无 GMV 数据,市场费分摊降级为直接汇总"。
- **集成风险(必须牢记)**:
1. **执行顺序**:必须先 clean(建基础行+GMV)再 processor(读 GMV 算成本并 UPDATE)。若 clean 重跑:DELETE+INSERT 会清空 processor 写入的成本列(clean 的 INSERT 不含这些列,新行取 DB 默认 0/NULL),需再跑 processor 恢复。
2. **唯一键粒度不一致**:clean 8 维、processor 5 维。若同一 (traffic_name,business_type,brand) 被 clean 拆成多行(不同 entity/park_store/service_provider),processor 的 UPDATE 会把这多行**都更新成同一份成本值**(成本按 5 维归因)。
3. **processor 只 UPDATE 不 INSERT**:若 clean 尚未写入对应行,processor 跑了也写不进任何数据。
- 标准名/别名映射只在 clean 侧生效;processor 直接复用 clean 已归一化的 traffic_name/brand 作为归因键,自身不做别名归并。
## 本地服务启动/停止方式(2026-09-03 新增 · 重要) ## 运行约定
- ⚠️ **坑**:用 PowerShell `Start-Process -WindowStyle Hidden app.py` 启动的服务进程会脱离对话工具的**沙箱进程命名空间**,落在宿主会话。后果:工具的 `taskkill`/`Stop-Process`/`Get-CimInstance` 全部报"找不到进程",但 netstat/curl 因共享网络栈仍能看到端口在监听——**无法从对话内停止该服务**。 - 手动回填:`python clean_budget_achievement.py -t budget_achievement -m YYYY-MM [--force] [--dry-run]`。
- ✅ **正确做法**:启动服务用 Bash 工具的 `run_in_background` 或 `nohup python app.py &`,使进程留在沙箱内,后续可随时用 `taskkill` 终止。 - 店效 4 处理器「业务系统 SQL」仍 `biz_sql_data={}` 占位(BIZ_SQL_ENABLED 默认 false),产值/成本类字段恒为 0;需接指标 API 或业务 SQL 才有真实值。
- 历史:PID 11168 为 `Start-Process -WindowStyle Hidden` 误启(宿主会话,对话内不可停),现已被停。服务应一律用 Bash `run_in_background` 或 `nohup python app.py &` 拉起(沙箱可见可管理,如当前 PID 44772),以后停止用 `taskkill /F /PID <当前PID>` 即可。
...@@ -5,10 +5,10 @@ ...@@ -5,10 +5,10 @@
# ============================================ # ============================================
# ---------- 数据库(MySQL) ---------- # ---------- 数据库(MySQL) ----------
MYSQL_HOST=192.168.3.227 MYSQL_HOST=192.168.1.228
MYSQL_PORT=3306 MYSQL_PORT=3307
MYSQL_USER=os_user MYSQL_USER=wechat_user
MYSQL_PASSWORD=os#123 MYSQL_PASSWORD=b4WRTkl
MYSQL_DB=data_report MYSQL_DB=data_report
# ---------- 阿里云 OSS ---------- # ---------- 阿里云 OSS ----------
......
...@@ -6,3 +6,5 @@ uploads/ ...@@ -6,3 +6,5 @@ uploads/
data/ data/
.idea .idea
.idea/* .idea/*
.venv/
\ No newline at end of file \ No newline at end of file
# Default ignored files
/shelf/
/workspace.xml
<?xml version="1.0" encoding="UTF-8"?>
<module type="JAVA_MODULE" version="4">
<component name="NewModuleRootManager" inherit-compiler-output="true">
<exclude-output />
<content url="file://$MODULE_DIR$" />
<orderEntry type="inheritedJdk" />
<orderEntry type="sourceFolder" forTests="false" />
</component>
</module>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="com.github.wanniwa.editorjumper.settings.EditorJumperProjectSettings">
<option name="projectEditorType" value="Trae" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectRootManager" version="2" languageLevel="JDK_17" default="true" project-jdk-name="temurin-17" project-jdk-type="JavaSDK">
<output url="file://$PROJECT_DIR$/out" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="ProjectModuleManager">
<modules>
<module fileurl="file://$PROJECT_DIR$/.idea/data-process.iml" filepath="$PROJECT_DIR$/.idea/data-process.iml" />
</modules>
</component>
</project>
\ No newline at end of file \ No newline at end of file
<?xml version="1.0" encoding="UTF-8"?>
<project version="4">
<component name="VcsDirectoryMappings">
<mapping directory="$PROJECT_DIR$/.." vcs="Git" />
</component>
</project>
\ No newline at end of file \ No newline at end of file
...@@ -8,7 +8,12 @@ ENV PYTHONDONTWRITEBYTECODE=1 \ ...@@ -8,7 +8,12 @@ ENV PYTHONDONTWRITEBYTECODE=1 \
WORKDIR /app WORKDIR /app
RUN apt-get update && apt-get install -y --no-install-recommends \ RUN sed -i \
-e 's@deb.debian.org@mirrors.aliyun.com@g' \
-e 's@security.debian.org@mirrors.aliyun.com@g' \
/etc/apt/sources.list.d/debian.sources \
&& apt-get update \
&& apt-get install -y --no-install-recommends \
gcc \ gcc \
g++ \ g++ \
libffi-dev \ libffi-dev \
...@@ -19,8 +24,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \ ...@@ -19,8 +24,8 @@ RUN apt-get update && apt-get install -y --no-install-recommends \
&& rm -rf /var/lib/apt/lists/* && rm -rf /var/lib/apt/lists/*
COPY requirements.txt . COPY requirements.txt .
RUN pip install --no-cache-dir --upgrade pip setuptools wheel \ RUN pip install -i https://mirrors.aliyun.com/pypi/simple/ --no-cache-dir --upgrade pip setuptools wheel \
&& pip install --no-cache-dir -r requirements.txt && pip install -i https://mirrors.aliyun.com/pypi/simple/ --no-cache-dir -r requirements.txt
COPY . . COPY . .
...@@ -30,4 +35,3 @@ ENV FLASK_HOST=0.0.0.0 \ ...@@ -30,4 +35,3 @@ ENV FLASK_HOST=0.0.0.0 \
EXPOSE 5000 EXPOSE 5000
CMD ["python", "app.py"] CMD ["python", "app.py"]
\ No newline at end of file \ No newline at end of file
"""扫店中店模板 row1+row2 窗膜/车衣/精品/踏板 相关表头"""
from openpyxl import load_workbook
wb = load_workbook(r'f:\360MoveData\Users\11\Desktop\企微SAAS\2026\09\0921\data-report\data-process\exporttemplete\红黄门店盈利测算 轻改 .xlsx')
ws = wb['店中店汇总']
print("=== 店中店 col18~32 (品类成交数区域) row1+row2+row4 ===")
for col in range(18, 33):
h1 = ws.cell(1, col).value or ''
h2 = ws.cell(2, col).value or ''
h4 = ws.cell(4, col).value or ''
print(f" col{col:2d}: row1={h1.strip()!r:25s} row2={h2.strip()!r:30s} fmt_row4={str(h4)[:60]}")
wb.close()
# -*- coding: utf-8 -*-
"""初始化"豪华品牌配置表"到数据库。
新建 config_brand_category 表(brand / category),从 xlsx 灌入,幂等。
"""
import sys
sys.stdout.reconfigure(encoding='utf-8')
import pymysql
import openpyxl
XLSX = 'D:/workspace_daily/日常数据处理需求/运营数据处理/配置表/豪华品牌配置表.xlsx'
DB = {
'host': '192.168.3.227', 'port': 3306,
'user': 'os_user', 'password': 'os#123',
'database': 'data_report', 'charset': 'utf8mb4',
}
def read_rows():
wb = openpyxl.load_workbook(XLSX, data_only=True, read_only=True)
ws = wb['Sheet1']
rows = []
header_skipped = False
for r in ws.iter_rows(values_only=True):
if not header_skipped:
header_skipped = True
continue # 跳过表头「品牌/品牌区分」
brand = (r[0] or '').strip() if r and len(r) > 0 else ''
cat = (r[1] or '').strip() if r and len(r) > 1 else ''
if not brand:
continue
rows.append((brand, cat or '豪华'))
return rows
def main():
rows = read_rows()
print(f'从 xlsx 读取到 {len(rows)} 行品牌配置')
conn = pymysql.connect(**DB)
try:
with conn.cursor() as cur:
# 1) 建表(幂等)
cur.execute('''
CREATE TABLE IF NOT EXISTS config_brand_category (
id BIGINT NOT NULL AUTO_INCREMENT,
brand VARCHAR(200) NOT NULL COMMENT '品牌',
category VARCHAR(50) NOT NULL DEFAULT '' COMMENT '品牌区分(如 豪华/非豪华)',
create_time DATETIME DEFAULT CURRENT_TIMESTAMP,
update_time DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (id),
UNIQUE KEY uq_brand (brand(191))
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='豪华品牌配置表'
''')
print('[OK] 表 config_brand_category 就绪')
# 2) 灌入(幂等:品牌重复则更新 category)
inserted = 0
updated = 0
for brand, cat in rows:
cur.execute(
'SELECT id FROM config_brand_category WHERE brand=%s', (brand,))
if cur.fetchone():
cur.execute(
'UPDATE config_brand_category SET category=%s, update_time=NOW() WHERE brand=%s',
(cat, brand))
updated += 1
else:
cur.execute(
'INSERT INTO config_brand_category (brand, category) VALUES (%s, %s)',
(brand, cat))
inserted += 1
conn.commit()
print(f'[OK] 插入 {inserted} 行,更新 {updated} 行')
# 3) 校验
cur.execute('SELECT COUNT(*) FROM config_brand_category')
print('库内总行数:', cur.fetchone()[0])
cur.execute('SELECT brand, category FROM config_brand_category ORDER BY id')
for r in cur.fetchall():
print(' ', r)
finally:
conn.close()
if __name__ == '__main__':
main()
# -*- coding: utf-8 -*-
"""验证新增两个报表类型:meta 接口、新增(含周期校验)、调度跳过保护"""
import sys
sys.stdout.reconfigure(encoding='utf-8')
import requests, pymysql
BASE = 'http://localhost:5000'
s = requests.Session()
r = s.post(BASE + '/api/login', json={'username': 'admin', 'password': 'admin123'})
print('[1] 登录:', r.json()['msg'])
# 1. meta 返回类型与 need_period
r = s.get(BASE + '/api/meta/task-types').json()['data']
print('[2] 数据表类型:')
for t in r:
print(f" {t['code']} | {t['name']} | need_period={t['need_period']} | forms={len(t['forms'])}")
se = [t for t in r if t['code'] == 'store_effect_earnings'][0]
ov = [t for t in r if t['code'] == 'output_value'][0]
# 2. 店效人效新增(带周期)成功
files_se = [{'form_type': f, 'file_name': f + '.xlsx',
'file_url': f'https://jinrong-huidan-test.oss-cn-shenzhen.aliyuncs.com/data-process/test/{f}.xlsx',
'file_size': 17} for f in se['forms']]
payload = {'data_table_type': 'store_effect_earnings', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-31', 'files': files_se}
r = s.post(BASE + '/api/tasks', json=payload)
d = r.json()
print('[3] 店效人效新增:', d['msg'])
if d['code'] == 0:
print(' 周期:', d['data']['period_start'], '~', d['data']['period_end'], '| 表单数:', len(d['data']['files']))
se_task = d['data']
else:
se_task = None
# 3. 产值达成新增
files_ov = [{'form_type': f, 'file_name': f + '.xlsx',
'file_url': f'https://jinrong-huidan-test.oss-cn-shenzhen.aliyuncs.com/data-process/test/{f}.xlsx',
'file_size': 17} for f in ov['forms']]
payload = {'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-05', 'period_end': '2026-08-20', 'files': files_ov}
r = s.post(BASE + '/api/tasks', json=payload)
d = r.json()
print('[4] 产值达成新增:', d['msg'])
if d['code'] == 0:
print(' 周期:', d['data']['period_start'], '~', d['data']['period_end'], '| 表单数:', len(d['data']['files']))
# 4. 周期校验:缺失周期应拒绝
payload_no_period = {'data_table_type': 'output_value', 'month': '2026-09', 'files': files_ov}
r = s.post(BASE + '/api/tasks', json=payload_no_period)
print('[5] 缺周期提交:', r.json()['msg'])
# 5. 结束早于开始应拒绝
payload_bad = {'data_table_type': 'output_value', 'month': '2026-09',
'period_start': '2026-09-20', 'period_end': '2026-09-01', 'files': files_ov}
r = s.post(BASE + '/api/tasks', json=payload_bad)
print('[6] 结束<开始:', r.json()['msg'])
# 6. 预算达成新增不应要求周期(不带周期应成功)
r = s.get(BASE + '/api/meta/task-types').json()['data']
ba = [t for t in r if t['code'] == 'budget_achievement'][0]
files_ba = [{'form_type': f, 'file_name': f + '.xlsx',
'file_url': f'https://jinrong-huidan-test.oss-cn-shenzhen.aliyuncs.com/data-process/test/{f}.xlsx',
'file_size': 17} for f in ba['forms']]
payload = {'data_table_type': 'budget_achievement', 'month': '2026-10', 'files': files_ba}
r = s.post(BASE + '/api/tasks', json=payload)
print('[7] 预算达成(无周期):', r.json()['msg'], '| 周期字段:', r.json()['data'].get('period_start', '') if r.json()['code']==0 else '-')
# 7. 列表返回周期
r = s.get(BASE + '/api/tasks').json()['data']['list']
print('[8] 列表首条周期列:', [(x['data_table_type_name'], x['period_start'] + '~' + x['period_end'] if x['period_start'] else '-') for x in r[:3]])
# 8. 调度跳过:等 2 轮调度或直接调用 process_all 检查新类型不被误处理
r = s.post(BASE + '/api/tasks/process-all')
print('[9] 批量处理结果:', r.json()['msg'])
conn = pymysql.connect(host='192.168.3.227', port=3306, user='os_user', password='os#123',
database='data_report', charset='utf8mb4')
with conn.cursor() as cur:
cur.execute("SELECT data_table_type, month, status, period_start, period_end FROM data_process_task WHERE is_deleted=0 ORDER BY id DESC LIMIT 5")
print('[10] 数据库最新任务:')
for row in cur.fetchall():
print(' ', row)
conn.close()
import sys, types, datetime
from decimal import Decimal
def stub(name):
m = types.ModuleType(name); sys.modules[name] = m; return m
# requests 桩(indicator_client 仅用 requests.post,验证时由 fake_post 接管)
req = stub('requests'); req.post = lambda *a, **k: None; req.Timeout = Exception; req.ConnectionError = Exception
sys.modules['requests'] = req
# config
cfg = stub('config')
cfg.Config = type('C', (), {'INDICATOR_API_URL':'http://dc.glsx.com.cn/data',
'INDICATOR_API_TIMEOUT':10, 'INDICATOR_API_RETRY':1})()
# ================= Test A: indicator_client bizs 序列化 =================
import importlib.util
spec = importlib.util.spec_from_file_location('indicator_client', r'F:/data-report/data-process/indicator_client.py')
ic = importlib.util.module_from_spec(spec); spec.loader.exec_module(ic)
captured = {}
class FakeResp:
status_code = 200
def json(self): return {'code':200, 'content':[]}
def fake_post(url, json=None, timeout=None):
captured['url'] = url; captured['json'] = json; return FakeResp()
ic.requests.post = fake_post
client = ic.IndicatorClient()
client.fetch('2026-08-01', '2026-08-31', [1, 3], ['A036'])
print("A1 payload(bizs多值):", captured['json'])
assert captured['json'].get('bizs') == '1,3'; assert 'biz' not in captured['json']
client.fetch('2026-08-01', '2026-08-31', 2, ['A036'])
print("A2 payload(biz单值):", captured['json'])
assert captured['json'].get('biz') == 2; assert 'bizs' not in captured['json']
print(">>> Test A 通过:bizs 多值='1,3',单值 biz=2")
# ================= Test B: output_value_processor G/I/L 计算 =================
models = stub('models')
class FakeQuery:
def filter_by(self, **k): return self
def delete(self): return 0
def order_by(self, *a): return self
def all(self): return []
class SaasBusinessAchievement:
query = FakeQuery()
def __init__(self, **kw): self.__dict__.update(kw)
models.SaasBusinessAchievement = SaasBusinessAchievement
models.DataProcessTask = object
class FakeSession:
def __init__(self): self.added=[]
def add_all(self, rows): self.added.extend(rows)
def flush(self): pass
def commit(self): pass
def rollback(self): pass
class FakeDB: session = FakeSession()
models.db = FakeDB()
oss = stub('oss_utils'); oss.upload_file = lambda p,k: 'http://fake/'+k
ru = stub('report_utils')
ru.mark_task_failed = lambda *a,**k: None
ru.cleanup_tmp_dir = lambda *a,**k: None
ru.download_all_files = lambda *a,**k: {'SAAS门店预算分解表':'x', '关系表':'y'}
ru.parse_operator_relation = lambda *a,**k: {}
ru.safe_div_pct_decimal = lambda n,d: (round(n/d*100,2) if (n is not None and d) else None)
MOCK_213 = [
{'region_operator':'华东','store_name':'郑州鸿启汽车贸易有限公司','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('100000'),'biz_type':'2.1'},
{'region_operator':'华东','store_name':'新乡市天驰汽车销售有限公司','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('80000'),'biz_type':'2.1'},
{'region_operator':'华东','store_name':'上海XX店','resident_type':'服务商','store_kind':'新增','budget_corrected':Decimal('20000'),'biz_type':'2.3'},
{'region_operator':'华北','store_name':'北京YY店','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('60000'),'biz_type':'2.1'},
]
MOCK_11 = [
{'region_operator':'华南','store_name':'广州ZZ店','resident_type':'直营','store_kind':'存量','budget_corrected':Decimal('50000'),'biz_type':'1.1'},
{'region_operator':'华南','store_name':'深圳WW店','resident_type':'服务商','store_kind':'新增','budget_corrected':Decimal('10000'),'biz_type':'1.1'},
]
ru.parse_saas_achieve_details = lambda p,k,i: (MOCK_11 if '轻改' in k else MOCK_213)
API_DATA = {
'郑州鸿启汽车贸易有限公司': {'A036': Decimal('12225')},
'新乡市天驰汽车销售有限公司': {'A036': Decimal('3945')},
'上海XX店': {'A036': Decimal('555')},
# '北京YY店' 故意不返回 → 华北组应落 NULL
'广州ZZ店': {'A036': Decimal('888')},
'深圳WW店': {'A036': Decimal('999')},
}
def fake_fetch(start_str, end_str, biz_code, item_codes):
assert biz_code in ([1,3], [2]), f"biz_code 错误: {biz_code}"
return API_DATA
ru.fetch_indicator_data = fake_fetch
spec2 = importlib.util.spec_from_file_location('ovp', r'F:/data-report/data-process/output_value_processor.py')
ovp = importlib.util.module_from_spec(spec2); spec.loader.exec_module(ovp)
class FakeTask:
id=777; month='2026-08'
period_start=datetime.date(2026,8,1); period_end=datetime.date(2026,8,31)
proc = ovp.OutputValueProcessor()
proc._process_output_value(FakeTask())
rows = models.db.session.added
print(f"\n>>> 入库 {len(rows)} 行")
ok = True
for r in rows:
g=r.daily_new_gmv; i=r.existing_actual; l=r.new_actual
print(f" {r.business_type}/{r.region_operator:6s} G={g} I={i} L={l}")
if r.region_operator=='华东':
ok = ok and (i==Decimal('16170') and l==Decimal('555') and g==Decimal('16725'))
elif r.region_operator=='华北':
ok = ok and (i is None and l is None and g is None)
elif r.region_operator=='华南':
ok = ok and (i==Decimal('888') and l==Decimal('999') and g==Decimal('1887'))
assert ok, "G/I/L 数值不符预期"
print(">>> Test B 通过:store_name 匹配、G=I+L、未匹配门店(华北)落 NULL")
# -*- coding: utf-8 -*-
"""验证重复校验已改成 (类型+月份+周期) 4 维唯一"""
import sys
sys.stdout.reconfigure(encoding='utf-8')
import requests
BASE = 'http://localhost:5000'
s = requests.Session()
r = s.post(BASE + '/api/login', json={'username': 'admin', 'password': 'admin123'})
assert r.json()['code'] == 0, r.text
# 1. 拿表单清单
meta = s.get(BASE + '/api/meta/task-types').json()['data']
ov = [t for t in meta if t['code'] == 'output_value'][0]
se = [t for t in meta if t['code'] == 'store_effect_earnings'][0]
ba = [t for t in meta if t['code'] == 'budget_achievement'][0]
def files_for(forms):
return [{'form_type': f, 'file_name': f + '.xlsx',
'file_url': f'https://jinrong-huidan-test.oss-cn-shenzhen.aliyuncs.com/data-process/test/{f}.xlsx',
'file_size': 17} for f in forms]
# 2. 产值达成 2026-08 / 8/1~8/20 — 应成功
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-20',
'files': files_for(ov['forms']),
})
print('[1] 产值 2026-08 / 8/1~8/20:', r.json()['msg'])
assert r.json()['code'] == 0, r.text
task1 = r.json()['data']
# 3. 同月份+同周期 重提 — 应被拦
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-20',
'files': files_for(ov['forms']),
})
print('[2] 产值 2026-08 / 8/1~8/20 重提:', r.json()['msg'])
assert r.json()['code'] != 0, '应当被拦'
# 4. 同月份+不同周期 — 应允许(业务上分段上报)
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-21', 'period_end': '2026-08-31',
'files': files_for(ov['forms']),
})
print('[3] 产值 2026-08 / 8/21~8/31:', r.json()['msg'])
assert r.json()['code'] == 0, r.text
# 5. 店效人效 2026-08 / 8/1~8/31 — 应成功
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'store_effect_earnings', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-31',
'files': files_for(se['forms']),
})
print('[4] 店效 2026-08 / 8/1~8/31:', r.json()['msg'])
assert r.json()['code'] == 0, r.text
# 6. 预算达成 2026-08 / 不带周期 — 库内已有 17 号 (is_deleted=0), 应被 2 维拦
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'budget_achievement', 'month': '2026-08',
'files': files_for(ba['forms']),
})
print('[5] 预算达成 2026-08 (无周期):', r.json()['msg'])
assert r.json()['code'] != 0, '应当被 2 维拦'
# 7. 预算达成 2026-09 — 应成功
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'budget_achievement', 'month': '2026-09',
'files': files_for(ba['forms']),
})
print('[6] 预算达成 2026-09:', r.json()['msg'])
assert r.json()['code'] == 0, r.text
# 8. 错误消息是否含周期提示
r = s.post(BASE + '/api/tasks', json={
'data_table_type': 'output_value', 'month': '2026-08',
'period_start': '2026-08-01', 'period_end': '2026-08-20',
'files': files_for(ov['forms']),
})
msg = r.json()['msg']
print('[7] 错误消息:', msg)
assert '8/1' in msg or '2026-08-01' in msg, '周期应进入错误消息'
print('\n[全部通过] 4 维校验已生效;同月份不同周期可共存;周期进入提示。')
\ No newline at end of file \ No newline at end of file
...@@ -24,7 +24,19 @@ from config import Config ...@@ -24,7 +24,19 @@ from config import Config
from models import DataProcessFile, DataProcessTask, DataProcessUser, db from models import DataProcessFile, DataProcessTask, DataProcessUser, db
from oss_utils import generate_upload_token, save_file from oss_utils import generate_upload_token, save_file
from processor import DataProcessor from processor import DataProcessor
from scheduler import TaskScheduler from scheduler import (
TaskScheduler,
WarrantyReportScheduler,
EquityReportScheduler,
LightReformInshopScheduler,
LightReformParkScheduler,
OutputValueScheduler,
StoreEffectSummaryScheduler,
AvitaSpecialScheduler,
VoyahScheduler,
LeapmotorScheduler,
CommonEquityScheduler,
)
app = Flask(__name__, static_folder='static', static_url_path='') app = Flask(__name__, static_folder='static', static_url_path='')
app.config.from_object(Config) app.config.from_object(Config)
...@@ -69,6 +81,101 @@ def get_type_config(type_code): ...@@ -69,6 +81,101 @@ def get_type_config(type_code):
return Config.DATA_TABLE_TYPES.get(type_code) return Config.DATA_TABLE_TYPES.get(type_code)
def compute_week_period(month, week_num):
"""根据月份 + 周序号计算日期区间(周一至周日)。
- 规则:该月第一个周一作为 W1 起始日,每周周一至周日。
- 示例:2026-08, W3 -> (2026-08-17, 2026-08-23)
- 前置零头(如 8/1-8/2 周六周日)不计入任何周编号。
:param month: 'YYYY-MM'
:param week_num: int 1~5
:return: (start_date, end_date)(datetime.date)
:raises ValueError: month 格式错或 week_num 超出范围
"""
from datetime import date, timedelta
try:
y, m = [int(x) for x in month.split('-')]
first_day = date(y, m, 1)
except (ValueError, AttributeError):
raise ValueError(f'月份格式错误,应为 YYYY-MM:{month}')
if not (1 <= week_num <= 5):
raise ValueError(f'周序号必须在 1~5 之间:{week_num}')
# weekday(): 周一=0, 周日=6
# 该月第一个周一 = 若月初是周一则当天,否则往后推到下一个周一
# 例:2026-08-01 周六 weekday=5 → first_monday = 8/1 + (7-5)天 = 8/3(正确)
offset = (7 - first_day.weekday()) % 7
first_monday = first_day + timedelta(days=offset)
# WN 起始 = first_monday + (N-1) * 7 天
start = first_monday + timedelta(days=(week_num - 1) * 7)
end = start + timedelta(days=6)
# 保护:如果 WN 的起始日已经不在目标月份内,说明该月没有这么多完整周
# 例:2026-02(28天)W5 start = 3/2 → 应拒绝
if start.month != m:
raise ValueError(f'{month} 只有 {week_num - 1} 个完整周,请选择 1~{week_num - 1}')
return start, end
def parse_period(data, tcfg):
"""解析「所属周期」日期区间(period_start / period_end)。
- period_type='week':根据 month + week_num 反推日期(双重保险,忽略前端传入的 period_start/end);
- need_period=True 且 period_type='month'(或未传):必须提供两个 YYYY-MM-DD 日期,且结束 >= 开始;
- need_period=False(如预算达成数据):返回 (None, None)。
返回 (period_type, week_num, start_date, end_date);异常时抛 ValueError。
"""
from datetime import date
period_type = (data.get('period_type') or 'month').strip()
if period_type not in ('month', 'week'):
raise ValueError(f'period_type 仅支持 month / week,当前值:{period_type}')
# 校验:need_period=False 或 support_week=False 的类型不允许按周粒度
if period_type == 'week':
if not tcfg.get('need_period') or not tcfg.get('support_week'):
raise ValueError('该类型仅支持按月粒度,不可选择按周')
if period_type == 'week':
# 按周:强校验 week_num,后端计算权威日期区间
try:
week_num = int(data.get('week_num'))
except (TypeError, ValueError):
raise ValueError('按周时必须提供合法的 week_num(1-5)')
month = (data.get('month') or '').strip()
start, end = compute_week_period(month, week_num)
return period_type, week_num, start, end
# period_type == 'month'
month_str = (data.get('month') or '').strip()
if not tcfg.get('need_period'):
# 不需要周期的类型(如预算达成数据):后端自动填整月日期,参与唯一约束
if month_str:
from calendar import monthrange
y, m = [int(x) for x in month_str.split('-')]
first_day = date(y, m, 1)
last_day = date(y, m, monthrange(y, m)[1])
return period_type, None, first_day, last_day
return period_type, None, None, None
raw_start = (data.get('period_start') or '').strip()
raw_end = (data.get('period_end') or '').strip()
if not raw_start or not raw_end:
return period_type, None, None, None
try:
start = date.fromisoformat(raw_start)
end = date.fromisoformat(raw_end)
except ValueError:
raise ValueError('所属周期格式错误,应为 YYYY-MM-DD')
if end < start:
raise ValueError('所属周期结束日期不能早于开始日期')
# 额外校验:结束日期不能跨月(必须在所选月份内)
month_str = (data.get('month') or '').strip()
if month_str:
if start.strftime('%Y-%m') != month_str or end.strftime('%Y-%m') != month_str:
raise ValueError(f'所属周期必须在 {month_str} 之内')
return period_type, None, start, end
def check_file(file_storage): def check_file(file_storage):
"""校验文件:格式 + 大小""" """校验文件:格式 + 大小"""
filename = file_storage.filename or '' filename = file_storage.filename or ''
...@@ -150,9 +257,11 @@ def oss_upload_token(): ...@@ -150,9 +257,11 @@ def oss_upload_token():
@app.get('/api/meta/task-types') @app.get('/api/meta/task-types')
@login_required @login_required
def meta_task_types(): def meta_task_types():
"""数据表类型配置(含各类型所需表单类型清单)""" """数据表类型配置(含各类型所需表单类型清单、是否需要所属周期)"""
data = [ data = [
{'code': k, 'name': v['name'], 'forms': v['forms']} {'code': k, 'name': v['name'], 'forms': v['forms'],
'need_period': v.get('need_period', False),
'support_week': v.get('support_week', False)}
for k, v in Config.DATA_TABLE_TYPES.items() for k, v in Config.DATA_TABLE_TYPES.items()
] ]
return ok(data) return ok(data)
...@@ -168,6 +277,7 @@ def task_list(): ...@@ -168,6 +277,7 @@ def task_list():
month = request.args.get('month', '').strip() month = request.args.get('month', '').strip()
creator = request.args.get('creator', '').strip() creator = request.args.get('creator', '').strip()
status = request.args.get('status', '').strip() status = request.args.get('status', '').strip()
period_type = request.args.get('periodType', '').strip()
q = DataProcessTask.query.filter(DataProcessTask.is_deleted == 0) q = DataProcessTask.query.filter(DataProcessTask.is_deleted == 0)
if data_table_type: if data_table_type:
...@@ -178,6 +288,8 @@ def task_list(): ...@@ -178,6 +288,8 @@ def task_list():
q = q.filter(DataProcessTask.creator.like(f'%{creator}%')) q = q.filter(DataProcessTask.creator.like(f'%{creator}%'))
if status: if status:
q = q.filter(DataProcessTask.status == status) q = q.filter(DataProcessTask.status == status)
if period_type in ('month', 'week'):
q = q.filter(DataProcessTask.period_type == period_type)
total = q.count() total = q.count()
items = q.order_by(DataProcessTask.created_at.desc()) \ items = q.order_by(DataProcessTask.created_at.desc()) \
...@@ -205,9 +317,10 @@ def task_detail(task_id): ...@@ -205,9 +317,10 @@ def task_detail(task_id):
@app.post('/api/tasks') @app.post('/api/tasks')
@login_required @login_required
def task_create(): def task_create():
"""新增单据:类型 + 月份 + 附件元信息(JSON)。 """新增单据:类型 + 月份 + (周期)+ 附件元信息(JSON)。
附件已由前端直传 OSS,后端仅接收 file_url 等元信息,数据库只保存 OSS 链接。 附件已由前端直传 OSS,后端仅接收 file_url 等元信息,数据库只保存 OSS 链接。
创建人/更新人按真实登录人员(session)填充。 创建人/更新人按真实登录人员(session)填充。
所属周期(period_start/period_end):need_period 类型必填;否则忽略取整月。
""" """
data = request.get_json(silent=True) or {} data = request.get_json(silent=True) or {}
data_table_type = (data.get('data_table_type') or '').strip() data_table_type = (data.get('data_table_type') or '').strip()
...@@ -222,8 +335,35 @@ def task_create(): ...@@ -222,8 +335,35 @@ def task_create():
tcfg = get_type_config(data_table_type) tcfg = get_type_config(data_table_type)
if not tcfg: if not tcfg:
return fail(f'不支持的数据表类型:{data_table_type}') return fail(f'不支持的数据表类型:{data_table_type}')
if DataProcessTask.query.filter_by(data_table_type=data_table_type, month=month, is_deleted=0).first():
return fail('该数据表类型与月份的单据已存在,请勿重复新增') # 所属周期 / 粒度:
# period_type='week' → 后端根据 month+week_num 双重保险反推日期区间
# period_type='month' → need_period=True 的类型必填手动选,False 类型(预算达成)不传
try:
period_type, week_num, period_start, period_end = parse_period(data, tcfg)
except ValueError as e:
return fail(str(e))
needs_period = tcfg.get('need_period') or period_type == 'week'
if needs_period and (not period_start or not period_end):
if period_type == 'week':
return fail('按周时必须提供 week_num(1-5)')
return fail('请选择所属周期(开始日期~结束日期)')
# 去重校验:新唯一约束 (data_table_type, month, period_start, period_end)
# - 按周:同月份不同周 period_start/end 不同,不冲突
# - need_period=False(如预算达成):period_start/end 为 None,按 (type, month) 唯一
dup_filters = {'data_table_type': data_table_type, 'month': month, 'is_deleted': 0}
if needs_period and period_start and period_end:
dup_filters['period_start'] = period_start
dup_filters['period_end'] = period_end
if DataProcessTask.query.filter_by(**dup_filters).first():
if period_type == 'week':
period_hint = f'、W{week_num}'
elif period_start:
period_hint = f'、周期 {period_start}~{period_end}'
else:
period_hint = ''
return fail(f'该数据表类型与月份{period_hint}的单据已存在,请勿重复新增')
# 附件元信息:前端直传 OSS 后回传 {form_type, file_name, file_url, file_size} # 附件元信息:前端直传 OSS 后回传 {form_type, file_name, file_url, file_size}
uploaded = [] uploaded = []
...@@ -249,12 +389,21 @@ def task_create(): ...@@ -249,12 +389,21 @@ def task_create():
task = DataProcessTask(data_table_type=data_table_type, task = DataProcessTask(data_table_type=data_table_type,
data_table_type_name=tcfg['name'], data_table_type_name=tcfg['name'],
month=month, month=month,
period_type=period_type,
week_num=week_num,
period_start=period_start, period_end=period_end,
status='PROCESSING', creator=creator, updater=creator) status='PROCESSING', creator=creator, updater=creator)
db.session.add(task) db.session.add(task)
db.session.flush() db.session.flush()
for u in uploaded: for u in uploaded:
db.session.add(DataProcessFile(task_id=task.id, **u)) db.session.add(DataProcessFile(task_id=task.id, **u))
db.session.commit() db.session.commit()
# store_effect_earnings 类型:自动创建 4 条子任务
if data_table_type == 'store_effect_earnings':
from report_utils import create_subtasks_for_task
create_subtasks_for_task(task.id)
return ok(task.to_dict(), '单据创建成功,进入数据处理') return ok(task.to_dict(), '单据创建成功,进入数据处理')
...@@ -276,6 +425,31 @@ def task_regenerate(task_id): ...@@ -276,6 +425,31 @@ def task_regenerate(task_id):
files = data.get('files') or [] files = data.get('files') or []
tcfg = get_type_config(t.data_table_type) tcfg = get_type_config(t.data_table_type)
# regenerate 时 type / month 在前端 disabled 不传,后端从 task 对象补齐
if not data.get('month'):
data['month'] = t.month
# 所属周期 / 粒度:重新生成时可调整(包括 period_type 切换),类型与月份锁定
try:
period_type, week_num, period_start, period_end = parse_period(data, tcfg)
except ValueError as e:
return fail(str(e))
needs_period = tcfg.get('need_period') or period_type == 'week'
if needs_period and (not period_start or not period_end):
if period_type == 'week':
return fail('按周时必须提供 week_num(1-5)')
return fail('请选择所属周期(开始日期~结束日期)')
# 去重校验(排除自己):避免 regenerate 到已有其他单据的周期上
dup_filters = {'data_table_type': t.data_table_type, 'month': t.month, 'is_deleted': 0}
if needs_period and period_start and period_end:
dup_filters['period_start'] = period_start
dup_filters['period_end'] = period_end
dup = DataProcessTask.query.filter_by(**dup_filters).first()
if dup and dup.id != task_id:
period_hint = f'(W{week_num}' if period_type == 'week' else f'({period_start}~{period_end}'
return fail(f'该数据表类型与月份{period_hint})的单据已存在,请勿重复新增')
# 附件:按表单类型覆盖——只替换本次重新上传的表单类型,未重传的保留原文件 # 附件:按表单类型覆盖——只替换本次重新上传的表单类型,未重传的保留原文件
new_files = [] new_files = []
for item in files: for item in files:
...@@ -307,12 +481,23 @@ def task_regenerate(task_id): ...@@ -307,12 +481,23 @@ def task_regenerate(task_id):
of.is_deleted = 1 of.is_deleted = 1
of.deleted_at = _dt.now() of.deleted_at = _dt.now()
db.session.add(DataProcessFile(task_id=t.id, **u)) db.session.add(DataProcessFile(task_id=t.id, **u))
t.status = 'PROCESSING' t.status = 'PROCESSING' # ← 调度器只扫 PROCESSING 主任务
t.updater = updater t.updater = updater
t.result_file_url = '' t.result_file_url = ''
t.error_msg = '' t.error_msg = ''
# 更新周期粒度字段(可在重新生成时切换按月/按周)
t.period_type = period_type
t.week_num = week_num
t.period_start = period_start
t.period_end = period_end
db.session.commit() db.session.commit()
return ok(t.to_dict(), '已重新生成数据流程')
# 重新生成 → 重置所有子任务状态为 PENDING(否则已 COMPLETED 的子任务会被 is_subtask_completed 跳过)
if t.data_table_type == 'store_effect_earnings':
from report_utils import create_subtasks_for_task
create_subtasks_for_task(t.id, reset=True)
return ok(t.to_dict(), '已重新生成数据流程,等待调度器处理')
@app.get('/api/tasks/<int:task_id>/download') @app.get('/api/tasks/<int:task_id>/download')
...@@ -329,6 +514,40 @@ def task_download(task_id): ...@@ -329,6 +514,40 @@ def task_download(task_id):
return ok({'url': t.result_file_url}, '下载地址') return ok({'url': t.result_file_url}, '下载地址')
@app.post('/api/export/red-yellow-report')
@login_required
def export_red_yellow_report_api():
"""
导出红黄门店盈利测算 - 6 sheet 合并 Excel。
sheet1-4: 延保/权益/店中店汇总/园区店汇总(来自 ORM)
sheet5: 总看板(来自 build_store_effect_board)
sheet6: 字段说明
body: { period_start, period_end, task_id?, src_dir? }
"""
data = request.get_json(silent=True) or {}
period_start = data.get('period_start')
period_end = data.get('period_end')
task_id = data.get('task_id')
src_dir = data.get('src_dir')
if not period_start or not period_end:
return fail('period_start / period_end 必填', 400)
try:
from export_red_yellow_report import export_red_yellow_report
path = export_red_yellow_report(period_start, period_end, task_id=task_id, src_dir=src_dir)
# 上传 OSS 并回填(复用现有 upload 工具)
try:
from report_utils import upload_to_oss
url = upload_to_oss(path, f"red_yellow_report_{period_start}_{period_end}.xlsx")
return ok({'local_path': path, 'oss_url': url}, '导出成功(已上传 OSS)')
except Exception:
return ok({'local_path': path}, '导出成功(本地生成,OSS 上传跳过)')
except Exception as e:
import traceback
traceback.print_exc()
return fail(f'导出失败:{e}', 500)
@app.post('/api/tasks/<int:task_id>/complete') @app.post('/api/tasks/<int:task_id>/complete')
@login_required @login_required
def task_complete(task_id): def task_complete(task_id):
...@@ -436,6 +655,30 @@ def unhandled(e): ...@@ -436,6 +655,30 @@ def unhandled(e):
# ---------------- 定时调度器 ---------------- # ---------------- 定时调度器 ----------------
scheduler = TaskScheduler(app=app) scheduler = TaskScheduler(app=app)
# 红黄门店盈利测算 - 4 张输出表独立调度器
warranty_scheduler = WarrantyReportScheduler(app=app)
equity_scheduler = EquityReportScheduler(app=app)
light_reform_inshop_scheduler = LightReformInshopScheduler(app=app)
light_reform_park_scheduler = LightReformParkScheduler(app=app)
output_value_scheduler = OutputValueScheduler(app=app)
store_effect_summary_scheduler = StoreEffectSummaryScheduler(app=app)
voyah_scheduler = VoyahScheduler(app=app)
leapmotor_scheduler = LeapmotorScheduler(app=app)
common_equity_scheduler = CommonEquityScheduler(app=app)
ALL_SCHEDULERS = [
('budget_achievement', scheduler),
('warranty_report', warranty_scheduler),
('equity_report', equity_scheduler),
('light_reform_inshop', light_reform_inshop_scheduler),
('light_reform_park', light_reform_park_scheduler),
('output_value', output_value_scheduler),
('store_effect_summary', store_effect_summary_scheduler),
('voyah_special', voyah_scheduler),
('leapmotor_special', leapmotor_scheduler),
('common_equity', common_equity_scheduler),
]
@app.get('/api/scheduler/status') @app.get('/api/scheduler/status')
@login_required @login_required
...@@ -516,13 +759,15 @@ if __name__ == '__main__': ...@@ -516,13 +759,15 @@ if __name__ == '__main__':
print('OSS 模式:', '阿里云 OSS' if Config.OSS_ENABLED else '本地回退(未配置 OSS)') print('OSS 模式:', '阿里云 OSS' if Config.OSS_ENABLED else '本地回退(未配置 OSS)')
# 启动定时调度器 # 启动定时调度器
scheduler.start() for name, sch in ALL_SCHEDULERS:
print(f'[调度器] 定时任务已启动(间隔 {Config.SCHEDULER_INTERVAL_SECONDS} 秒)') sch.start()
print(f'[调度器] {name} 定时任务已启动(间隔 {Config.SCHEDULER_INTERVAL_SECONDS} 秒)')
try: try:
app.run(host=os.getenv('FLASK_HOST', '0.0.0.0'), app.run(host=os.getenv('FLASK_HOST', '0.0.0.0'),
port=int(os.getenv('FLASK_PORT', '5000')), port=int(os.getenv('FLASK_PORT', '5000')),
debug=os.getenv('FLASK_DEBUG', 'true').lower() == 'true') debug=os.getenv('FLASK_DEBUG', 'true').lower() == 'true')
finally: finally:
scheduler.stop() for name, sch in ALL_SCHEDULERS:
print('[调度器] 定时任务已停止') sch.stop()
print(f'[调度器] {name} 定时任务已停止')
# -*- coding: utf-8 -*-
"""
阿维塔专项 独立处理器
====================
对应 ORM 表:avita_special_month_data(明细,逐门店一行)
avita_special_month_summary_metrics(汇总指标,单任务一行)
数据来源:主机厂数据表(Excel)。
源文件结构(经 7月样本核对,以实际附件为准):
- 行1(大类合并表头):门店名称 | 门店简称 | 门店模式 | 入驻时间 | 驻店姓名 | 2026-07月主机厂数据(5列) | 2026-07月广联数据(2列)
- 行2(子字段表头) : | | | | | 交付数 延保成交数 无忧成交数 门店单车收入(延保+无忧) 门店总产值 | 交付数 触客数
- 行3 起 :逐门店明细
- 末尾汇总段 :'阿维塔品牌汇总'(品牌标签,空值) + 售后门店数/售后场景开通率/售后订单数 等
本处理器:跳过前 2 行表头 → 解析明细行 → 捕获末尾汇总段 → 按 task_id 先逻辑删除(旧行置 is_deleted=1)后插入新行(is_deleted=0)落库,不再物理删除。
明细表中 store_mode(门店模式,文本)、entry_time(入驻时间,格式化为 YYYY-MM-DD)、resident_name(驻店姓名,文本)现已由源文件解析填充;
regional_operation(区域运营)由 dj_smartcarlife 两跳查询填充(门店名→merchant_id→director_name,director_type=9,多条去重以'/'分隔)。
cutoff_gl_extended_warranty_deal_count(广联延保成交数)/ cutoff_gl_worry_free_deal_count(广联无忧成交数)由 dj.glsx.com.cn 报表导出接口填充:
取「通用品牌」报表 → 按门店名称精确匹配 → 延保小计行取「整车延保成交数」作广联延保成交数、
取「延保小计」行「原厂权益成交数」(Z列) 作广联无忧成交数;
报表中不存在的门店(如未纳入通用品牌)该两列留空(NULL)。
汇总表中 store_count/output_value/delivery_count/pre_sales_visit_count 及各渗透率/环比列,样本汇总段未提供 → 留空,待最终 Excel 生成或后续填充。
结果表生成(generate_result_excel):复制用户模板(exporttemplete/avita_special_report_template.xlsx),标题/表头/段标题的月份与截止日期占位替换:
截止日期规则=用报表所属月(task.month);若当前时间已在报表所属月之后→取所属月最后一天(封账),否则取真实生成日期(进行中);
明细行从 avita_special_month_data 读真实值并计算衍生指标(渗透率/触客率/引荐转化率),6月(上月)主机厂块无源 → '-';
品牌汇总 项目/品牌 固定 = 阿维塔,门店数 = 明细数,售后三项取汇总表;售前触客率=售前触客数/交付数、整车延保渗透率=整车延保成交数/交付数、原厂权益渗透率=原厂权益成交数/交付数;环比(本月-上月)优先从 DB 取上月汇总、无则留空;生成后上传 OSS 并回填 result_file_url。
"""
import io
import logging
import os
import tempfile
from calendar import monthrange
from datetime import datetime, date
from decimal import Decimal, InvalidOperation
import openpyxl
import requests
from sqlalchemy import create_engine, text
from config import Config
from report_utils import (
mark_task_failed, cleanup_tmp_dir, download_all_files,
)
from oss_utils import upload_file
from models import (
DataProcessTask, db,
AvitaSpecialMonthData, AvitaSpecialMonthSummaryMetrics,
)
# 结果表生成模板(由用户提供的「字段取值说明(模板版)」复制而来,作为布局基线)
AVITA_TEMPLATE_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'exporttemplete', 'avita_special_report_template.xlsx')
logger = logging.getLogger('AvitaSpecialProcessor')
AVITA_TYPE = 'avita_special'
# 明细行列索引(0-based),依据最新源文件「行2 子字段」结构
# (门店模式/入驻时间/驻店姓名已插入到 col2/col3/col4,其余指标列整体右移 +3)
# col0=门店名称 col1=门店简称 col2=门店模式 col3=入驻时间 col4=驻店姓名
# col5=主机厂交付数 col6=主机厂延保成交数 col7=主机厂无忧成交数
# col8=门店单车收入(延保+无忧) col9=门店总产值 col10=广联交付数 col11=广联触客数
DETAIL_COL = {
'store_name': 0,
'store_short_name': 1,
'store_mode': 2,
'entry_time': 3,
'resident_name': 4,
'oem_delivery_count': 5,
'oem_extended_warranty_deal_count': 6,
'oem_worry_free_deal_count': 7,
'oem_revenue_per_vehicle': 8,
'oem_total_output': 9,
'cutoff_gl_delivery_count': 10,
'cutoff_gl_visit_count': 11,
}
_INT_COLS = {
'oem_delivery_count', 'oem_extended_warranty_deal_count', 'oem_worry_free_deal_count',
'cutoff_gl_delivery_count', 'cutoff_gl_visit_count',
# 注:cutoff_gl_extended_warranty_deal_count / cutoff_gl_worry_free_deal_count
# 来源于广联报表导出接口(非源文件),在 _save 中由 fetch_glsx_deal_counts 填充。
}
_STR_COLS = {'store_name', 'store_short_name', 'store_mode', 'entry_time', 'resident_name'}
# 末尾汇总段:源文件标签 → ORM 属性
SUMMARY_LABELS = {
'售后门店数': 'after_sales_store_count',
'售后场景开通率': 'after_sales_scene_open_rate',
'售后订单数': 'after_sales_order_count',
}
BRAND_SUMMARY_LABEL = '阿维塔品牌汇总'
def _to_int(v):
if v is None:
return None
s = str(v).strip().replace(',', '')
if s == '':
return None
try:
return int(Decimal(s))
except (InvalidOperation, ValueError):
logger.warning(f"[阿维塔] 非整数值被置空: {v!r}")
return None
def _to_dec(v):
if v is None:
return None
s = str(v).strip().replace(',', '')
if s == '':
return None
try:
return Decimal(s)
except (InvalidOperation, ValueError):
logger.warning(f"[阿维塔] 非小数值被置空: {v!r}")
return None
def _to_date_str(v):
"""入驻时间:datetime/date → 'YYYY-MM-DD';字符串截断到 10 位;空 → None"""
if v is None:
return None
if isinstance(v, (datetime, date)):
return v.strftime('%Y-%m-%d')
s = str(v).strip()
if s == '':
return None
return s[:10]
# ===================================================================
# 区域运营(regional_operation)查询:数据源 dj_smartcarlife
# 第1跳:门店名称 → merchant_id(dj_car_life_service_merchant.deleted_flag='N')
# 第2跳:merchant_id + director_type=9 → director_name
# (dj_car_life_shop_merchant_director_config.deleted_flag='N')
# 多条记录去重后用 '/' 分隔;查不到返回 None(不致命,仅告警留空)
# ===================================================================
_BIZ_ENGINE = None
def _get_biz_engine():
global _BIZ_ENGINE
if _BIZ_ENGINE is None:
_BIZ_ENGINE = create_engine(Config.BIZ_SQL_DATABASE_URL, echo=False, pool_pre_ping=True)
return _BIZ_ENGINE
def fetch_regional_operation(store_name):
"""根据门店名称查询区域运营(dj_smartcarlife 两跳查询)。失败返回 None。"""
if not store_name:
return None
engine = _get_biz_engine()
try:
with engine.connect() as conn:
mids = conn.execute(
text("SELECT merchant_id FROM dj_car_life_service_merchant "
"WHERE merchant_name=:name AND deleted_flag='N'"),
{"name": store_name},
).fetchall()
if not mids:
logger.warning(f"[阿维塔] 区域运营:门店名未匹配商户号 store_name={store_name!r}")
return None
names = set()
for (mid,) in mids:
if mid is None:
continue
rows = conn.execute(
text("SELECT director_name FROM dj_car_life_shop_merchant_director_config "
"WHERE deleted_flag='N' AND merchant_id=:mid AND director_type=9"),
{"mid": mid},
).fetchall()
for (dn,) in rows:
if dn is not None and str(dn).strip() != '':
names.add(str(dn).strip())
if not names:
return None
return '/'.join(sorted(names))
except Exception as e:
logger.warning(f"[阿维塔] 区域运营查询失败 store_name={store_name!r}: {e}")
return None
# ===================================================================
# 广联延保/权益成交数(cutoff_gl_*_deal_count)查询:数据源 dj.glsx.com.cn 报表导出
# 第1步:queryAllExcel?filename={stat_month}&... 取 list 中 filename 含 '通用品牌' 的 key
# 第2步:download?key={key} 取 data.list[0].url
# 第3步:GET 该 url 下载 xlsx,解析 Sheet1
# - 表头行(col0=='业务类型',表头单元格可能含换行需归一)定位列
# - 门店(col2) / 整车延保成交数 / 原厂权益成交数
# - 行 col0=='延保小计' → 取 整车延保成交数 作为 广联延保成交数;
# 取 原厂权益成交数(Z列) 作为 广联权益(无忧)成交数
# (worry_free 由「延保小计」行取「原厂权益成交数」,不再取「权益小计」行)
# 按门店名称(与 avita_special_month_data.store_name 精确匹配)聚合,
# 返回 {store_name: (ext_count, worry_count)};失败返回 {}(不致命,仅告警留空)
# ===================================================================
_GLSX_BASE = 'https://dj.glsx.com.cn/reportExport'
_GLSX_TIMEOUT = (30, 120)
def _norm_header(s):
"""表头单元格归一:去空格/换行,便于按列名定位(如 '整车延保\n成交数'→'整车延保成交数')"""
return ''.join(str(s).split()) if s is not None else ''
def _cell_to_int(v):
"""单元格转 int:空/非数字 → 0(用于求和聚合)"""
if v is None:
return 0
s = str(v).strip().replace(',', '')
if s == '' or s == '-':
return 0
try:
return int(Decimal(s))
except (InvalidOperation, ValueError):
return 0
def fetch_glsx_deal_counts(stat_month):
"""从广联报表导出接口获取各门店的 广联延保成交数 / 广联权益(无忧)成交数。
返回 {门店名称: (ext_count, worry_count)}。任何失败返回空 dict(不致命)。"""
if not stat_month:
logger.warning('[阿维塔] 广联报表:stat_month 为空,跳过获取')
return {}
try:
# 第1步:列出报表,定位 通用品牌
resp = requests.get(_GLSX_BASE + '/queryAllExcel', params={
'pageSize': 10, 'currentPage': 1, 'filename': stat_month,
'business_type': 'yanbao', 'report_type': 'yanbaoMerAndPerRanking', 'key': '',
}, timeout=_GLSX_TIMEOUT)
resp.raise_for_status()
items = (resp.json().get('data') or {}).get('list') or []
target = next((x for x in items if '通用品牌' in (x.get('filename') or '')), None)
if not target:
logger.warning(f'[阿维塔] 广联报表:未找到 通用品牌 报表(filename={stat_month})')
return {}
key = target['key']
# 第2步:获取下载 url
dl = requests.get(_GLSX_BASE + '/download', params={'key': key}, timeout=_GLSX_TIMEOUT)
dl.raise_for_status()
dlist = (dl.json().get('data') or {}).get('list') or []
if not dlist or not dlist[0].get('url'):
logger.warning('[阿维塔] 广联报表:download 未返回有效文件 url')
return {}
file_url = dlist[0]['url']
# 第3步:下载并解析 xlsx
x = requests.get(file_url, timeout=_GLSX_TIMEOUT)
x.raise_for_status()
wb = openpyxl.load_workbook(io.BytesIO(x.content), data_only=True)
ws = wb[wb.sheetnames[0]]
rows = list(ws.iter_rows(values_only=True))
hidx = next((i for i, row in enumerate(rows)
if row and _norm_header(row[0]) == '业务类型'), None)
if hidx is None:
logger.warning('[阿维塔] 广联报表:未找到表头行(业务类型)')
return {}
col = {_norm_header(n): j for j, n in enumerate(rows[hidx]) if n is not None}
ext_c = col.get('整车延保成交数')
worry_c = col.get('原厂权益成交数')
store_c = col.get('门店')
if ext_c is None or worry_c is None or store_c is None:
logger.warning('[阿维塔] 广联报表:缺少必要列(整车延保成交数/原厂权益成交数/门店)')
return {}
result = {}
for row in rows[hidx + 1:]:
if not row:
continue
a = _norm_header(row[0]) if row[0] is not None else ''
if a == '延保小计':
s = str(row[store_c]).strip() if row[store_c] else ''
if not s:
continue
# 广联延保成交数:整车延保成交数(ext_c)
result.setdefault(s, [0, 0])[0] += _cell_to_int(row[ext_c])
# 广联无忧成交数:原厂权益成交数(worry_c,Z列)—— 取自「延保小计」行
result.setdefault(s, [0, 0])[1] += _cell_to_int(row[worry_c])
logger.info(f'[阿维塔] 广联报表:解析到 {len(result)} 个门店的延保/权益成交数')
return result
except Exception as e:
logger.warning(f'[阿维塔] 广联报表获取失败(stat_month={stat_month}): {e}')
return {}
# ===================================================================
# 结果表生成:基于用户提供的模板(exporttemplete/avita_special_report_template.xlsx)
# 按 task 的 month 派生「报表月标签 / 上月标签」,截止日期取真实生成时间;
# 明细行从 avita_special_month_data 读真实值并计算衍生指标;
# 6月(上月)主机厂块与品牌汇总聚合字段无数据源 → 置 '-';
# 品牌汇总 项目/品牌 固定 = 阿维塔。生成后上传 OSS 并回填 result_file_url。
# ===================================================================
def _safe_div(a, b):
"""安全除法:None/0 作 0;b 为 0 时返回 0"""
a = a if a is not None else 0
b = b if b is not None else 0
try:
return (a / b) if b != 0 else 0
except (InvalidOperation, ZeroDivisionError, TypeError):
return 0
def _safe_sub(a, b):
"""安全减法:任一为 None → None;否则 a - b(转 float)"""
if a is None or b is None:
return None
try:
return float(a) - float(b)
except (InvalidOperation, TypeError, ValueError):
return None
def _prev_month_str(ym):
"""'2026-07' -> '2026-06'(跨年 2026-01 -> 2025-12);非法输入 -> None"""
if not isinstance(ym, str) or '-' not in ym:
return None
try:
y, m = ym.split('-')[:2]
y, m = int(y), int(m)
except (ValueError, TypeError):
return None
if m == 1:
return f"{y - 1}-12"
return f"{y}-{m - 1:02d}"
def _dec_to_float(v):
"""DECIMAL/None → float/None(openpyxl 写 DECIMAL 不稳,转 float)"""
if v is None:
return None
try:
return float(v)
except (InvalidOperation, TypeError, ValueError):
return None
def _to_date(v):
"""entry_time:DATE/字符串(YYYY-MM-DD) → date;空 → None"""
if v is None:
return None
if isinstance(v, (datetime, date)):
return v
s = str(v).strip()
if s == '':
return None
try:
return datetime.strptime(s[:10], '%Y-%m-%d').date()
except ValueError:
return s
def _set_cell(ws, r, c, v):
"""写入单元格;v 为 None 时显式清空。
注意:openpyxl 的 ws.cell(r, c, value=None) 不会清除已存在的旧值,
必须用 ws.cell(r, c).value = None 才能真正清空。"""
ws.cell(r, c).value = v
class AvitaSpecialProcessor:
"""阿维塔专项独立处理器"""
def __init__(self, app=None):
self.app = app
def process(self, task):
"""处理单个阿维塔专项任务:解析源文件 → 落明细/汇总表 → 置 COMPLETED"""
task_id = task.id
try:
detail_rows, summary = self._parse(task)
self._save(task, detail_rows, summary)
task = DataProcessTask.query.filter_by(id=task_id).first()
# 生成结果 Excel(基于用户模板:日期占位替换 + 品牌固定 + 明细从 DB 读真实值)
try:
url = self.generate_result_excel(task)
except Exception as ge:
logger.warning(f"[阿维塔] 结果表生成失败(task {task_id}): {ge}")
url = ''
task.status = 'COMPLETED'
task.result_file_url = url or '' # 最终 Excel:基于用户模板生成
task.error_msg = ''
db.session.commit()
logger.info(f"[阿维塔] 任务 {task_id} 处理完成:明细 {len(detail_rows)} 行,汇总 1 行")
except Exception as e:
db.session.rollback()
mark_task_failed(task_id, str(e))
raise
# ============================================================
# 调度器入口
# ============================================================
def scan_avita_special(self):
"""扫描 avita_special 类型的 PROCESSING 任务并逐个处理(供 AvitaSpecialScheduler 调用)。
与 OutputValueProcessor.scan_output_value 对等:扫描 → 逐任务 process → 统计成功/失败。"""
logger.info("[阿维塔] 开始扫描 avita_special 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type='avita_special',
status='PROCESSING',
is_deleted=0,
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[阿维塔] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[阿维塔] 任务 {task.id} 处理成功")
except Exception as e:
import traceback as _tb
fail_count += 1
logger.error(f"[阿维塔] 任务 {task.id} 处理失败: {str(e)}")
logger.error(_tb.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[阿维塔] 标记任务失败时出错: {mark_err}")
logger.info(f"[阿维塔] 扫描完成,成功 {success_count},失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
# ============================================================
# 解析
# ============================================================
def _parse(self, task):
task_id = task.id
tmp_dir = tempfile.mkdtemp(prefix=f'avita_{task_id}_')
try:
file_map = download_all_files(task_id, tmp_dir)
path = None
for _form, p in file_map.items():
if p:
path = p
break
if not path:
raise Exception('未找到可下载的阿维塔专项附件(主机厂数据表)')
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
ws = wb[wb.sheetnames[0]]
rows = list(ws.iter_rows(values_only=True))
finally:
cleanup_tmp_dir(tmp_dir)
detail_rows = []
summary_vals = {attr: None for attr in SUMMARY_LABELS.values()}
brand = None
# 跳过前 2 行表头(大类 + 子字段),从第 3 行起解析
for row in rows[2:]:
a = row[0] if len(row) > 0 else None
if a is None or str(a).strip() == '':
continue
label = str(a).strip()
if label == BRAND_SUMMARY_LABEL:
brand = '阿维塔'
continue
if label in SUMMARY_LABELS:
val = row[1] if len(row) > 1 else None
summary_vals[SUMMARY_LABELS[label]] = val
continue
# 否则视为明细门店行
rec = {}
for attr, idx in DETAIL_COL.items():
v = row[idx] if idx < len(row) else None
if attr in _INT_COLS:
rec[attr] = _to_int(v)
elif attr in _STR_COLS:
if attr == 'entry_time':
rec[attr] = _to_date_str(v)
else:
rec[attr] = str(v).strip() if v is not None and str(v).strip() != '' else None
else:
rec[attr] = _to_dec(v)
detail_rows.append(rec)
if not detail_rows:
logger.warning(f"[阿维塔] 任务 {task_id} 未解析到任何明细门店行")
return detail_rows, (brand, summary_vals)
# ============================================================
# 落库(按 task_id 先删后插,幂等)
# ============================================================
def _save(self, task, detail_rows, summary_tuple):
task_id = task.id
period_start = getattr(task, 'period_start', None)
stat_month = (getattr(task, 'month', None) or ''
or (period_start.strftime('%Y-%m') if period_start else ''))
brand, summary_vals = summary_tuple
# 广联报表:按门店名称匹配 延保小计/权益小计 行,获取 广联延保成交数 / 广联无忧成交数
glsx_map = fetch_glsx_deal_counts(stat_month)
if glsx_map:
logger.info(f"[阿维塔] 广联报表匹配:task {task_id} 命中 {len(glsx_map)} 个门店")
# ---------- 明细 ----------
# 逻辑删除(软删除):将本任务旧行置 is_deleted=1,再插入新行(is_deleted=0),不再物理删除
AvitaSpecialMonthData.query.filter_by(task_id=task_id, is_deleted=0).update(
{AvitaSpecialMonthData.is_deleted: 1}, synchronize_session=False)
db.session.flush()
detail_objs = []
for rec in detail_rows:
sn = rec.get('store_name') or ''
gl = glsx_map.get(sn)
if gl is None and sn:
logger.warning(f"[阿维塔] 门店 {sn!r} 未在广联报表匹配到(延保/无忧成交数留空)")
detail_objs.append(AvitaSpecialMonthData(
task_id=task_id,
is_deleted=0,
stat_month=stat_month,
store_name=sn,
store_short_name=rec.get('store_short_name'),
store_mode=rec.get('store_mode'),
entry_time=rec.get('entry_time'),
regional_operation=fetch_regional_operation(rec.get('store_name')),
resident_name=rec.get('resident_name'),
oem_delivery_count=rec.get('oem_delivery_count'),
oem_extended_warranty_deal_count=rec.get('oem_extended_warranty_deal_count'),
oem_worry_free_deal_count=rec.get('oem_worry_free_deal_count'),
oem_revenue_per_vehicle=rec.get('oem_revenue_per_vehicle'),
oem_total_output=rec.get('oem_total_output'),
cutoff_gl_delivery_count=rec.get('cutoff_gl_delivery_count'),
cutoff_gl_visit_count=rec.get('cutoff_gl_visit_count'),
cutoff_gl_extended_warranty_deal_count=gl[0] if gl else None,
cutoff_gl_worry_free_deal_count=gl[1] if gl else None,
))
db.session.add_all(detail_objs)
# ---------- 汇总(与结果表品牌汇总同源同步)----------
# 逻辑删除(软删除):将本任务旧行置 is_deleted=1,再插入新行(is_deleted=0),不再物理删除
AvitaSpecialMonthSummaryMetrics.query.filter_by(task_id=task_id, is_deleted=0).update(
{AvitaSpecialMonthSummaryMetrics.is_deleted: 1}, synchronize_session=False)
db.session.flush()
# 当前明细月份聚合:门店总产值 / 主机厂交付数 / 广联触客数 /
# 主机厂整车延保成交数 / 主机厂原厂权益(无忧)成交数 对明细行求和
_tot_output = sum(float(d.oem_total_output or 0) for d in detail_objs)
_tot_delivery = int(sum(d.oem_delivery_count or 0 for d in detail_objs))
_tot_visit = int(sum(d.cutoff_gl_visit_count or 0 for d in detail_objs))
_tot_ext = int(sum(d.oem_extended_warranty_deal_count or 0 for d in detail_objs))
_tot_rights = int(sum(d.oem_worry_free_deal_count or 0 for d in detail_objs))
# 售后场景开通率取自源文件汇总段(品牌汇总口径),其余三项渗透率与结果表同源:分子/交付数(E)
_after_rate = _to_dec(summary_vals.get('after_sales_scene_open_rate'))
_pre_rate = _safe_div(_tot_visit, _tot_delivery) # 售前触客率 = 售前触客数/交付数 (F/E)
_veh_rate = _safe_div(_tot_ext, _tot_delivery) # 整车延保渗透率 = 整车延保成交数/交付数 (K/E)
_rights_rate = _safe_div(_tot_rights, _tot_delivery) # 原厂权益渗透率 = 原厂权益成交数/交付数 (M/E)
# 环比(本月 - 上月):优先从 DB 取上一统计月 avita_special_month_summary_metrics;无则留空
_mom_after = _mom_pre = _mom_veh = _mom_rights = None
if stat_month:
_prev_ym = _prev_month_str(stat_month)
if _prev_ym:
_prev = AvitaSpecialMonthSummaryMetrics.query.filter_by(
stat_month=_prev_ym, is_deleted=0).order_by(
AvitaSpecialMonthSummaryMetrics.id.desc()).first()
if _prev is not None:
_p_pre = _safe_div(_prev.pre_sales_visit_count, _prev.delivery_count)
_p_veh = _safe_div(_prev.vehicle_extended_warranty_deal_count, _prev.delivery_count)
_p_rights = _safe_div(_prev.oem_rights_deal_count, _prev.delivery_count)
_p_after = _dec_to_float(_prev.after_sales_scene_open_rate)
_mom_after = _safe_sub(_dec_to_float(_after_rate), _p_after)
_mom_pre = _safe_sub(_pre_rate, _p_pre)
_mom_veh = _safe_sub(_veh_rate, _p_veh)
_mom_rights = _safe_sub(_rights_rate, _p_rights)
sum_obj = AvitaSpecialMonthSummaryMetrics(
task_id=task_id,
is_deleted=0,
stat_month=stat_month,
project_name='阿维塔',
brand=brand or '阿维塔',
store_count=len(detail_objs),
output_value=round(_tot_output, 2),
delivery_count=_tot_delivery,
pre_sales_visit_count=_tot_visit,
pre_sales_visit_rate=_to_dec(round(_pre_rate, 6)),
after_sales_store_count=_to_int(summary_vals.get('after_sales_store_count')),
after_sales_scene_open_rate=_after_rate,
after_sales_order_count=_to_int(summary_vals.get('after_sales_order_count')),
vehicle_extended_warranty_deal_count=_tot_ext,
vehicle_extended_warranty_penetration_rate=_to_dec(round(_veh_rate, 6)),
oem_rights_deal_count=_tot_rights,
oem_rights_penetration_rate=_to_dec(round(_rights_rate, 6)),
after_sales_scene_open_rate_mom=_to_dec(round(_mom_after, 6)) if _mom_after is not None else None,
pre_sales_visit_rate_mom=_to_dec(round(_mom_pre, 6)) if _mom_pre is not None else None,
vehicle_extended_warranty_penetration_rate_mom=_to_dec(round(_mom_veh, 6)) if _mom_veh is not None else None,
oem_rights_penetration_rate_mom=_to_dec(round(_mom_rights, 6)) if _mom_rights is not None else None,
)
db.session.add(sum_obj)
db.session.commit()
logger.info(f"[阿维塔] 落库完成:明细 {len(detail_objs)} 行 + 汇总 1 行(task_id={task_id})")
# ============================================================
# 结果表生成(基于模板 exporttemplete/avita_special_report_template.xlsx)
# ============================================================
def generate_result_excel(self, task):
"""根据 task 生成「阿维塔专项报表」结果 Excel:
- 复制模板布局;标题/表头/段标题中的月份与截止日期占位替换:
截止日期=用报表所属月(task.month),若当前时间已在所属月之后→取所属月最后一天(封账),否则取真实生成日期(进行中);
- 明细行从 avita_special_month_data 读真实值并计算衍生指标(渗透率/触客率/引荐转化率);
- 6月(上月)主机厂块(明细行 G..M)无数据源 → 置 '-';
- 品牌汇总:售前触客率(G)=售前触客数(F)/交付数(E)、整车延保渗透率(L)=整车延保成交数(K)/交付数(E)、
原厂权益渗透率(N)=原厂权益成交数(M)/交付数(E);环比(O/P/Q/R)=本月-上月,上月优先从 DB 取上一统计月
avita_special_month_summary_metrics,无则整行(行16)与环比列留空;
- 品牌汇总 项目/品牌 固定 = 阿维塔。
返回 OSS 可访问 URL(失败抛异常)。"""
task_id = task.id
month = getattr(task, 'month', None) or ''
# 报表月标签 / 上月标签(由 task.month 派生,保证生成器可复用)
if len(month) >= 7 and month[4] == '-':
try:
y, m = int(month[:4]), int(month[5:7])
month_label = f"{m}月"
pm = m - 1 if m > 1 else 12
prev_month_label = f"{pm}月"
except (ValueError, IndexError):
month_label, prev_month_label = '', ''
else:
month_label, prev_month_label = '', ''
# 截止日期规则:用报表所属月(task.month)。
# 若当前时间已在报表所属月之后 → 截止日期取报表所属月最后一天(月份已封账);
# 否则(当前仍在报表所属月内)→ 取真实生成日期(月份进行中,数据为部分)。
today = date.today()
cutoff_date = datetime.now().strftime('%Y-%m-%d') # 兜底
if len(month) >= 7 and month[4] == '-':
try:
y, m = int(month[:4]), int(month[5:7])
last_day = monthrange(y, m)[1]
report_month_last = date(y, m, last_day)
cutoff_date = (report_month_last if today > report_month_last
else today).strftime('%Y-%m-%d')
except (ValueError, IndexError):
cutoff_date = datetime.now().strftime('%Y-%m-%d')
details = AvitaSpecialMonthData.query.filter_by(
task_id=task_id, is_deleted=0).order_by(AvitaSpecialMonthData.id).all()
summary = AvitaSpecialMonthSummaryMetrics.query.filter_by(
task_id=task_id, is_deleted=0).order_by(
AvitaSpecialMonthSummaryMetrics.id.desc()).first()
if not os.path.exists(AVITA_TEMPLATE_PATH):
raise Exception(f'阿维塔结果表模板不存在:{AVITA_TEMPLATE_PATH}')
wb = openpyxl.load_workbook(AVITA_TEMPLATE_PATH)
ws = wb[wb.sheetnames[0]]
# ---- 标题 / 表头 / 段标题 占位替换 ----
ws['A1'] = f"阿维塔专项报表 ·「{month_label}」页签 · 数据截止 {cutoff_date}"
ws['G2'] = f"{prev_month_label}主机厂数据"
ws['N2'] = f"截止{cutoff_date}主机厂数据"
ws['S2'] = f"截止{cutoff_date}广联数据"
ws['W2'] = f"数据截止{cutoff_date}"
ws['A14'] = f"【品牌汇总 · {prev_month_label}段】(原第 24–25 行)"
ws['A18'] = f"【品牌汇总 · {month_label}段】"
# ---- 明细行(自第 4 行起)----
start = 4
for i, d in enumerate(details):
r = start + i
_set_cell(ws, r, 1, d.store_name)
_set_cell(ws, r, 2, d.store_short_name)
_set_cell(ws, r, 3, d.store_mode)
_set_cell(ws, r, 4, _to_date(d.entry_time))
_set_cell(ws, r, 5, d.regional_operation)
_set_cell(ws, r, 6, d.resident_name)
# 6月(上月)主机厂块 G..M:无数据源
for c in range(7, 14):
_set_cell(ws, r, c, '-')
# 当前主机厂块 N..R
_set_cell(ws, r, 14, d.oem_delivery_count)
_set_cell(ws, r, 15, d.oem_extended_warranty_deal_count)
_set_cell(ws, r, 16, d.oem_worry_free_deal_count)
_set_cell(ws, r, 17, _dec_to_float(d.oem_revenue_per_vehicle))
_set_cell(ws, r, 18, _dec_to_float(d.oem_total_output))
# 广联块 S..V
_set_cell(ws, r, 19, d.cutoff_gl_delivery_count)
_set_cell(ws, r, 20, d.cutoff_gl_visit_count)
_set_cell(ws, r, 21, d.cutoff_gl_extended_warranty_deal_count)
_set_cell(ws, r, 22, d.cutoff_gl_worry_free_deal_count)
# 衍生指标
n = d.oem_delivery_count or 0
o = d.oem_extended_warranty_deal_count or 0
p = d.oem_worry_free_deal_count or 0
s = d.cutoff_gl_delivery_count or 0
t = d.cutoff_gl_visit_count or 0
u = d.cutoff_gl_extended_warranty_deal_count or 0
v = d.cutoff_gl_worry_free_deal_count or 0
_set_cell(ws, r, 23, _safe_div(n, t)) # W 触客率 = 主机厂交付数 / 广联触客数 (N/T)
_set_cell(ws, r, 24, _safe_div(o, n)) # X 延保渗透率 = 延保 / 交付
_set_cell(ws, r, 25, _safe_div(p, n)) # Y 无忧渗透率 = 无忧 / 交付
_set_cell(ws, r, 26, _safe_div(u, t)) # Z 延保引荐转化率 = 广联延保 / 触客
_set_cell(ws, r, 27, _safe_div(v, t)) # AA 无忧引荐转化率 = 广联无忧 / 触客
# 清除模板中多余的明细行(若门店数 < 8)
for r in range(start + len(details), 12):
for c in range(1, 28):
_set_cell(ws, r, c, None)
# ---- 品牌汇总 ----
n_stores = len(details)
# 当前月(明细月份)聚合:门店总产值 / 交付数(主机厂) / 触客数(广联) /
# 延保成交数(主机厂) / 无忧成交数(主机厂) 对明细行求和
total_output = sum(float(_dec_to_float(d.oem_total_output) or 0) for d in details)
total_delivery = sum(int(d.oem_delivery_count or 0) for d in details)
total_visit = sum(int(d.cutoff_gl_visit_count or 0) for d in details)
total_ext = sum(int(d.oem_extended_warranty_deal_count or 0) for d in details)
total_rights = sum(int(d.oem_worry_free_deal_count or 0) for d in details)
# 7月段(行20)与 avita_special_month_summary_metrics 同源(优先读汇总表,缺则回退明细实时算)
_sum_out = _dec_to_float(summary.output_value) if summary else None
_sum_del = summary.delivery_count if summary else None
_sum_vis = summary.pre_sales_visit_count if summary else None
_sum_ext = summary.vehicle_extended_warranty_deal_count if summary else None
_sum_rgt = summary.oem_rights_deal_count if summary else None
_sum_stores = summary.store_count if summary else None
E = _sum_del if _sum_del is not None else total_delivery # 交付数
F = _sum_vis if _sum_vis is not None else total_visit # 售前触客数
K = _sum_ext if _sum_ext is not None else total_ext # 整车延保成交数
M = _sum_rgt if _sum_rgt is not None else total_rights # 原厂权益成交数
g_rate = _safe_div(F, E) # 售前触客率 = 售前触客数 / 交付数
l_rate = _safe_div(K, E) # 整车延保渗透率 = 整车延保成交数 / 交付数
n_rate = _safe_div(M, E) # 原厂权益渗透率 = 原厂权益成交数 / 交付数
cur_after = _dec_to_float(summary.after_sales_scene_open_rate) if summary else None # 本月售后场景开通率
# 上月(6月段):优先从 DB 取上一统计月的汇总指标;无则整行留空(用户确认口径)
prev_summary = None
if month:
prev_ym = _prev_month_str(month)
prev_summary = AvitaSpecialMonthSummaryMetrics.query.filter_by(
stat_month=prev_ym, is_deleted=0).order_by(
AvitaSpecialMonthSummaryMetrics.id.desc()).first()
if prev_summary:
p_E = prev_summary.delivery_count
p_F = prev_summary.pre_sales_visit_count
p_K = prev_summary.vehicle_extended_warranty_deal_count
p_M = prev_summary.oem_rights_deal_count
p_g = _safe_div(p_F, p_E)
p_l = _safe_div(p_K, p_E)
p_n = _safe_div(p_M, p_E)
p_after = _dec_to_float(prev_summary.after_sales_scene_open_rate)
# 行16 填充上月真实值
_set_cell(ws, 16, 3, prev_summary.store_count)
_set_cell(ws, 16, 4, _dec_to_float(prev_summary.output_value))
_set_cell(ws, 16, 5, p_E)
_set_cell(ws, 16, 6, p_F)
_set_cell(ws, 16, 7, p_g)
_set_cell(ws, 16, 8, prev_summary.after_sales_store_count)
_set_cell(ws, 16, 9, p_after)
_set_cell(ws, 16, 10, prev_summary.after_sales_order_count)
_set_cell(ws, 16, 11, p_K)
_set_cell(ws, 16, 12, p_l)
_set_cell(ws, 16, 13, p_M)
_set_cell(ws, 16, 14, p_n)
else:
for c in range(3, 15):
_set_cell(ws, 16, c, None)
ws['A16'] = '阿维塔'
ws['B16'] = '阿维塔'
# 7月段(行20):项目/品牌固定;门店数=明细数;聚合五项=明细月份求和;
# 售前触客率/各渗透率按公式算;环比=本月-上月(无上月则留空)
ws['A20'] = '阿维塔'
ws['B20'] = '阿维塔'
_set_cell(ws, 20, 3, _sum_stores if _sum_stores is not None else n_stores) # C 门店数
_set_cell(ws, 20, 4, _sum_out if _sum_out is not None else round(total_output, 2)) # D 产值 = Σ门店总产值
_set_cell(ws, 20, 5, E) # E 交付数 = Σ交付数(主机厂)
_set_cell(ws, 20, 6, F) # F 售前触客数 = Σ触客数(广联)
_set_cell(ws, 20, 7, g_rate) # G 售前触客率 = 售前触客数/交付数 (F/E)
_set_cell(ws, 20, 8, summary.after_sales_store_count if summary else None) # H 售后门店数
_set_cell(ws, 20, 9, cur_after) # I 售后场景开通率
_set_cell(ws, 20, 10, summary.after_sales_order_count if summary else None) # J 售后订单数
_set_cell(ws, 20, 11, K) # K 整车延保成交数 = Σ延保成交数(主机厂)
_set_cell(ws, 20, 12, l_rate) # L 整车延保渗透率 = 整车延保成交数/交付数 (K/E)
_set_cell(ws, 20, 13, M) # M 原厂权益成交数 = Σ无忧成交数(主机厂)
_set_cell(ws, 20, 14, n_rate) # N 原厂权益渗透率 = 原厂权益成交数/交付数 (M/E)
# 环比(本月 - 上月)
_set_cell(ws, 20, 15, _safe_sub(cur_after, p_after) if prev_summary else None) # O 售后场景开通率环比
_set_cell(ws, 20, 16, _safe_sub(g_rate, p_g) if prev_summary else None) # P 售前触客率环比
_set_cell(ws, 20, 17, _safe_sub(l_rate, p_l) if prev_summary else None) # Q 整车延保渗透率环比
_set_cell(ws, 20, 18, _safe_sub(n_rate, p_n) if prev_summary else None) # R 原厂权益渗透率环比
# ---- sheet 重命名(月份占位替换)----
try:
ws.title = f"{month_label}页签-字段取值说明"
except Exception:
pass
# ---- 保存 + 上传 OSS ----
tmp = tempfile.mktemp(suffix='.xlsx')
wb.save(tmp)
object_key = f"data-process/{datetime.now().strftime('%Y%m%d')}/avita_special_{month}_{task_id}.xlsx"
url = upload_file(tmp, object_key)
try:
os.remove(tmp)
except Exception:
pass
logger.info(f"[阿维塔] 结果表已生成并上传:task {task_id} -> {url}")
return url
# -*- coding: utf-8 -*-
"""
门店店效人效汇总表(总看板)构建器
==================================
按桌面模板「门店店效人效汇总表.xlsx」的 总看板 + 字段说明 两个 sheet 输出。
取数口径详见模板 sheet2「字段说明」。本脚本从"源数据"重算(用户确认:从源重算,
不依赖同事的 report_* 结果表):
- SAAS门店预算分解表 sheet1(biz 2.1/2.3) + sheet2(biz 1.1)
→ 门店数/豪华/非豪华/直营/存量新增/预算目标/纠偏预算
- 主机厂数据表(鸿蒙/广联) → 交车数
- 二手车收购与销售台账-汇总销售台账 → 6.1 系列
- config_brand_category(豪华品牌配置表) → 豪华/非豪华判定(模糊匹配)
暂未接入(置 0 并在说明里标注):
- 人力成本表("人力成本表-密码2026.xlsx" 加密/BadZipFile,无法读取)
→ 全国直营总人数/营销人数/店均人数/人均产值/豪华·非豪华员工数 等
- 指标系统 API 产值(A036)/成交(A075)/触客(A084)
→ 全国经营总产值/店均产值/1.1·2.1·2.3 产值 等
- 系统数据(闭店日期/商户创建日期/品牌归属)
→ 本月流失门店/新增门店 及其豪华·非豪华拆分
用法:
python build_store_effect_board.py --src "C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源"
--month 2026-08 [--period-start 2026-08-01 --period-end 2026-08-31]
"""
import os
import sys
import argparse
import logging
from datetime import datetime, date, timedelta
from decimal import Decimal, InvalidOperation
import pandas as pd
import openpyxl
from openpyxl.styles import Font, PatternFill, Alignment, Border, Side
from openpyxl.utils import get_column_letter
logging.basicConfig(level=logging.INFO, format='%(asctime)s [%(levelname)s] %(message)s')
logger = logging.getLogger('board')
# ============================================================
# 通用工具
# ============================================================
def to_decimal(v):
"""金额解析:空/NaN/异常 → 0"""
if v is None or v == '':
return Decimal('0')
# NaN / NaT 必须先拦掉,否则 Decimal(str(nan)) 会得到 Decimal('NaN') 污染求和
try:
if pd.isna(v):
return Decimal('0')
except (TypeError, ValueError):
pass
if isinstance(v, (int, float, Decimal)):
try:
return Decimal(str(v))
except InvalidOperation:
return Decimal('0')
s = str(v).strip().replace(',', '').replace('¥', '').replace('%', '')
if s in ('', '-', 'nan', 'None'):
return Decimal('0')
try:
return Decimal(s)
except InvalidOperation:
return Decimal('0')
def excel_serial_to_date(v):
"""Excel 序列号日期 → date;已是 datetime/date 直接返回;无法解析返回 None"""
if v is None or v == '':
return None
if isinstance(v, datetime):
return v.date()
if isinstance(v, date):
return v
if isinstance(v, (int, float)):
# Excel 1900 日期系统
try:
return (datetime(1899, 12, 30) + pd.Timedelta(days=float(v))).date()
except Exception:
return None
s = str(v).strip()
if not s:
return None
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y-%m-%d %H:%M:%S', '%Y/%m/%d %H:%M:%S'):
try:
return datetime.strptime(s, fmt).date()
except ValueError:
continue
try:
return pd.to_datetime(s).date()
except Exception:
return None
def norm_col(c):
"""列名归一化:去换行/空格/全角括号"""
return str(c).replace('\n', '').replace('\r', '').replace(' ', '').replace('(', '(').replace(')', ')')
def find_col(columns, keywords):
"""按关键字找列名:先精确相等,再包含匹配"""
normed = [(c, norm_col(c)) for c in columns]
for kw in keywords:
for c, nc in normed:
if nc == kw:
return c
for kw in keywords:
for c, nc in normed:
if kw in nc:
return c
return None
def safe_div(a, b, digits=2):
"""安全除法,分母 0 → 0"""
try:
a = Decimal(str(a))
b = Decimal(str(b))
if b == 0:
return Decimal('0')
return (a / b).quantize(Decimal('1.' + '0' * digits))
except Exception:
return Decimal('0')
def pct(a, b, digits=2):
"""百分比:a/b*100,保留 digits 位(表内已 ×100,配 '0.00"%"' 格式)"""
try:
a = Decimal(str(a))
b = Decimal(str(b))
if b == 0:
return Decimal('0')
return (a / b * 100).quantize(Decimal('1.' + '0' * digits))
except Exception:
return Decimal('0')
def div2(a, b):
"""普通比值(如客单价):a/b,保留 2 位小数,不做 ×100"""
try:
a = Decimal(str(a))
b = Decimal(str(b))
if b == 0:
return Decimal('0')
return (a / b).quantize(Decimal('0.01'))
except Exception:
return Decimal('0')
# ============================================================
# 品牌 → 豪华/非豪华(config_brand_category,模糊匹配)
# ============================================================
def load_brand_category():
"""
读取 config_brand_category(brand → category)。
返回 (exact_map, fuzzy_list);无 DB 时返回空。
"""
try:
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from app import app, db
from sqlalchemy import text
with app.app_context():
rows = db.session.execute(text('SELECT brand, category FROM config_brand_category')).fetchall()
exact = {str(b).strip(): str(c).strip() for b, c in rows}
logger.info(f"[品牌配置] 载入 {len(exact)} 条")
return exact, list(exact.keys())
except Exception as e:
logger.warning(f"[品牌配置] 读取失败,全部按非豪华: {e}")
return {}, []
def brand_category(brand, exact_map, keys):
"""
判定豪华/非豪华:先精确匹配,再双向包含匹配(取最长匹配避免误判)。
配置表里目前 18 条全是"豪华",未命中即非豪华。
"""
if not brand:
return '非豪华'
b = str(brand).strip()
if not b or b == 'nan':
return '非豪华'
if b in exact_map:
return exact_map[b]
nb = norm_col(b)
best_cat, best_len = None, 0
for k in keys:
nk = norm_col(k)
if not nk:
continue
if nk == nb or nk in nb or nb in nk:
if len(nk) > best_len:
best_len, best_cat = len(nk), exact_map[k]
return best_cat or '非豪华'
# ============================================================
# SAAS 门店预算分解表
# ============================================================
def parse_saas(src):
"""
解析 SAAS门店预算分解表。
返回 (sheet1_rows, sheet2_rows)
sheet1 (biz 2.1/2.3): store/brand/biz_type/resident_type/budget_target/budget_corrected
sheet2 (biz 1.1) : store/brand/nature(存量|新增)/resident_type/budget_target/budget_corrected
说明:文件里 sheet1 真实表头在第 2 行(第 1 行是标题),sheet2 表头在第 1 行。
"""
path = None
for fn in os.listdir(src):
if 'SAAS' in fn and fn.endswith(('.xlsx', '.xls')):
path = os.path.join(src, fn)
break
if not path:
logger.warning("[SAAS] 未找到文件")
return [], []
def _read(sheet_idx, header_row):
raw = pd.read_excel(path, sheet_name=sheet_idx, header=None)
# 用"表头特征关键字打分"定位真实表头行,避免标题行误判
hints = ['门店', '品牌', '业务类型', '预估产值', '驻店类型', '性质', '序号']
best_i, best_score = header_row, 0
for i in range(min(6, len(raw))):
vals = [str(v) for v in raw.iloc[i].tolist() if v is not None]
score = sum(1 for v in vals if any(h in v for h in hints))
if score > best_score:
best_score, best_i = score, i
df = pd.read_excel(path, sheet_name=sheet_idx, header=best_i)
logger.info(f"[SAAS] sheet{sheet_idx} 表头行={best_i}")
return df
def _pick(df, kws):
return find_col(df.columns, kws)
out1, out2 = [], []
# ---- sheet1: 延保权益 (2.1 / 2.3) ----
try:
df1 = _read(0, 1)
c_store = _pick(df1, ['门店', '门店名称', '门店名'])
c_brand = _pick(df1, ['品牌'])
c_biz = _pick(df1, ['业务类型'])
c_nat = _pick(df1, ['存量/新店', '存量新店'])
c_res = _pick(df1, ['驻店类型', '驻店'])
c_tgt = _pick(df1, ['预估产值(预算目标)', '预估产值(预算)', '预算目标'])
c_cor = _pick(df1, ['预估产值(纠偏)', '预估产值(纠偏', '预估总产值', '纠偏'])
logger.info(f"[SAAS sheet1] 列: store={c_store} brand={c_brand} biz={c_biz} "
f"存量/新店={c_nat} resident={c_res} 预算目标={c_tgt} 纠偏={c_cor}")
if c_store:
for _, r in df1.iterrows():
sn = str(r.get(c_store, '')).strip()
if not sn or sn in ('nan', 'None'):
continue
bt = str(r.get(c_biz, '')).strip() if c_biz else ''
if bt not in ('2.1', '2.3'):
continue
out1.append({
'store': sn,
'brand': str(r.get(c_brand, '')).strip() if c_brand else '',
'biz_type': bt,
'resident_type': str(r.get(c_res, '')).strip() if c_res else '',
'budget_target': to_decimal(r.get(c_tgt)) if c_tgt else Decimal('0'),
'budget_corrected': to_decimal(r.get(c_cor)) if c_cor else Decimal('0'),
'nature': str(r.get(c_nat, '')).strip() if c_nat else '', # 存量/新店
})
except Exception as e:
logger.error(f"[SAAS sheet1] 解析失败: {e}")
# ---- sheet2: 轻改 (1.1) ----
try:
df2 = _read(1, 0)
c_store = _pick(df2, ['门店', '门店名称', '门店名'])
c_brand = _pick(df2, ['品牌'])
c_nat = _pick(df2, ['性质'])
c_res = _pick(df2, ['驻店类型', '驻店', '经营属性'])
c_tgt = _pick(df2, ['预估产值(预算目标)', '预算目标'])
c_cor = _pick(df2, ['预估产值(纠偏)', '预估总产值', '纠偏'])
logger.info(f"[SAAS sheet2] 列: store={c_store} brand={c_brand} 性质={c_nat} "
f"resident={c_res} 预算目标={c_tgt} 纠偏={c_cor}")
if c_store:
for _, r in df2.iterrows():
sn = str(r.get(c_store, '')).strip()
if not sn or sn in ('nan', 'None'):
continue
nat = str(r.get(c_nat, '')).strip() if c_nat else ''
out2.append({
'store': sn,
'brand': str(r.get(c_brand, '')).strip() if c_brand else '',
'biz_type': '1.1',
'resident_type': str(r.get(c_res, '')).strip() if c_res else '',
'budget_target': to_decimal(r.get(c_tgt)) if c_tgt else Decimal('0'),
'budget_corrected': to_decimal(r.get(c_cor)) if c_cor else Decimal('0'),
'nature': nat,
})
except Exception as e:
logger.error(f"[SAAS sheet2] 解析失败: {e}")
logger.info(f"[SAAS] sheet1={len(out1)} 条, sheet2={len(out2)} 条")
return out1, out2
# ============================================================
# 主机厂交车数
# ============================================================
def parse_delivery(src):
"""解析鸿蒙/广联主机厂数据表 → {门店: 交车数}"""
delivery = {}
for fn in os.listdir(src):
if ('主机厂' in fn or '广联' in fn) and fn.endswith(('.xlsx', '.xls')):
path = os.path.join(src, fn)
try:
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from report_utils import parse_delivery_table
part = parse_delivery_table(path)
for k, v in (part or {}).items():
delivery[k] = delivery.get(k, 0) + int(v or 0)
logger.info(f"[主机厂] {fn} → {len(part or {})} 条")
except Exception as e:
logger.warning(f"[主机厂] {fn} 解析失败: {e}")
return delivery
# ============================================================
# 二手车(6.1)
# ============================================================
def parse_used_car(src, period_start, period_end):
"""
解析二手车收购与销售台账 - 汇总销售台账。
口径(字段说明):
6.1产值 = 拍卖日期在周期内 的 拍卖价格 之和
6.1毛利率 = (拍卖价格-收购价格)之和 / 6.1产值
6.1单车均毛利= (拍卖价格-收购价格)之和 / 处置台次
6.1交付平均车价 = 收购日期在周期内 的 收购价格之和 / 收购台次
6.1处置车量 = 拍卖日期在周期内 的明细数量
6.1收车台次 = 收购日期在周期内 的明细数量
6.1处置周期(批售) = 拍卖平台≠个人:(拍卖日期-收车日期)天数之和/明细数
6.1处置周期(零售) = 拍卖平台=个人:同上
6.1库存数量 = 拍卖日期为空 且 处置类型≠寄售 的明细数量
"""
res = {'output': Decimal('0'), 'profit': Decimal('0'), 'dispose_cnt': 0,
'buy_amount': Decimal('0'), 'buy_cnt': 0, 'wholesale_days': 0,
'retail_days': 0, 'stock_cnt': 0, 'avg_price': Decimal('0'),
'gross_rate': Decimal('0'), 'unit_profit': Decimal('0'),
'wholesale_cycle': Decimal('0'), 'retail_cycle': Decimal('0')}
path = None
for fn in os.listdir(src):
if '二手车' in fn and fn.endswith(('.xlsx', '.xls')):
path = os.path.join(src, fn)
break
if not path:
logger.warning("[二手车] 未找到文件")
return res
try:
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
if '汇总销售台账' not in wb.sheetnames:
logger.warning("[二手车] 无「汇总销售台账」sheet")
wb.close()
return res
ws = wb['汇总销售台账']
rows = list(ws.iter_rows(values_only=True))
wb.close()
if len(rows) < 2:
return res
header = [norm_col(c) if c is not None else '' for c in rows[0]]
idx = {name: i for i, name in enumerate(header)}
def col(*names):
for n in names:
for k, i in idx.items():
if n in k:
return i
return None
i_store = col('门店')
i_type = col('处置类型')
i_buy_d = col('收购日期')
i_buy_p = col('收购价格')
i_auc_d = col('拍卖日期')
i_auc_p = col('拍卖价格')
i_plat = col('拍卖平台')
i_profit = col('收拍利润')
def in_period(d):
if d is None:
return False
if period_start and d < period_start:
return False
if period_end and d > period_end:
return False
return True
for r in rows[1:]:
if not r:
continue
first = str(r[i_store]).strip() if (i_store is not None and i_store < len(r) and r[i_store]) else ''
if not first or first == '合计': # 跳过合计行
continue
def gv(i):
if i is None or i >= len(r):
return None
return r[i]
auc_d = excel_serial_to_date(gv(i_auc_d))
buy_d = excel_serial_to_date(gv(i_buy_d))
auc_p = to_decimal(gv(i_auc_p))
buy_p = to_decimal(gv(i_buy_p))
plat = str(gv(i_plat) or '').strip() if i_plat is not None else ''
dtype = str(gv(i_type) or '').strip() if i_type is not None else ''
if in_period(auc_d):
res['output'] += auc_p
pf = to_decimal(gv(i_profit)) if i_profit is not None else (auc_p - buy_p)
res['profit'] += pf
res['dispose_cnt'] += 1
if auc_d and buy_d:
days = (auc_d - buy_d).days
if plat and plat != '个人':
res['wholesale_days'] += days
else:
res['retail_days'] += days
if in_period(buy_d):
res['buy_amount'] += buy_p
res['buy_cnt'] += 1
# 库存:拍卖日期为空 且 处置类型≠寄售(处置类型为空也视为非寄售)
if auc_d is None and dtype != '寄售':
res['stock_cnt'] += 1
res['avg_price'] = safe_div(res['buy_amount'], res['buy_cnt'])
res['gross_rate'] = pct(res['profit'], res['output'])
res['unit_profit'] = safe_div(res['profit'], res['dispose_cnt'])
res['wholesale_cycle'] = safe_div(res['wholesale_days'], res['dispose_cnt'])
res['retail_cycle'] = safe_div(res['retail_days'], res['dispose_cnt'])
logger.info(f"[二手车] 6.1产值={res['output']} 处置={res['dispose_cnt']} 收车={res['buy_cnt']} 库存={res['stock_cnt']}")
except Exception as e:
logger.error(f"[二手车] 解析失败: {e}")
return res
# ============================================================
# 人力成本表(加密需先解密)
# ============================================================
def _resolve_hr_path(src, password='2026'):
"""
定位人力成本表。若为加密的 OLE2 容器(非 zip)则解密:
1) 优先复用 outputs/tmp/hr_decrypted.xlsx 缓存
2) 否则用 msoffcrypto 解密(需安装 msoffcrypto-tool)
"""
import zipfile
hr_file = None
for fn in os.listdir(src):
if '人力成本' in fn and fn.endswith(('.xlsx', '.xls')):
hr_file = os.path.join(src, fn)
break
if not hr_file:
return None
if zipfile.is_zipfile(hr_file):
return hr_file
cache_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs', 'tmp')
os.makedirs(cache_dir, exist_ok=True)
cache = os.path.join(cache_dir, 'hr_decrypted.xlsx')
if os.path.exists(cache):
logger.info("[人力表] 复用已解密缓存")
return cache
try:
import msoffcrypto
with open(hr_file, 'rb') as f:
of = msoffcrypto.OfficeFile(f)
of.load_key(password=password)
with open(cache, 'wb') as g:
of.decrypt(g)
logger.info(f"[人力表] 已解密 → {cache}")
return cache
except Exception as e:
logger.warning(f"[人力表] 解密失败(需 msoffcrypto-tool): {e}")
return None
def parse_hr(src, password='2026'):
"""
解析人力成本表 sheet「人力成本」。
关键列:B=工号 / D=入驻门店 / F=岗位 / AF=检核(注意 AG 也叫"检核",取首次出现的 AF)
返回 list[dict]: emp_no / store / position / checked
"""
path = _resolve_hr_path(src, password)
if not path:
logger.warning("[人力表] 未找到文件")
return []
try:
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
ws = wb['人力成本'] if '人力成本' in wb.sheetnames else wb[wb.sheetnames[0]]
rows = list(ws.iter_rows(values_only=True))
wb.close()
except Exception as e:
logger.error(f"[人力表] 读取失败: {e}")
return []
if len(rows) < 2:
return []
header = [norm_col(c) if c is not None else '' for c in rows[0]]
idx = {}
for i, n in enumerate(header): # 首次出现优先 → '检核' 命中 AF 而非 AG
if n and n not in idx:
idx[n] = i
def col(*names):
for n in names:
if n in idx:
return idx[n]
for n in names:
for k, i in idx.items():
if n in k:
return i
return None
i_no, i_store = col('工号'), col('入驻门店')
i_pos, i_chk = col('岗位'), col('检核')
logger.info(f"[人力表] 列: 工号={i_no} 入驻门店={i_store} 岗位={i_pos} 检核={i_chk}")
out = []
for r in rows[1:]:
if not r:
continue
def gv(i):
return r[i] if (i is not None and i < len(r)) else None
no = str(gv(i_no) or '').strip()
if not no or no in ('nan', 'None'):
continue
out.append({
'emp_no': no,
'store': str(gv(i_store) or '').strip(),
'position': str(gv(i_pos) or '').strip(),
'checked': gv(i_chk),
})
logger.info(f"[人力表] 解析 {len(out)} 条")
return out
# ============================================================
# 指标计算
# ============================================================
def _lr_sum_one(which, col_attr, period_start, period_end):
"""单表某数值列之和;which='inshop'|'park'|'equity';条件:同 task_id, is_deleted=0。返回 Decimal。
task_id 解析:优先与汇总同周期(period_start>=/period_end<=),否则取最新(最大) task_id。
"""
from app import app, db
from models import (ReportLightReformInshop, ReportLightReformPark,
ReportEquityService, ReportExtendedWarranty)
from sqlalchemy import func
model_cls = (ReportLightReformInshop if which == 'inshop'
else ReportLightReformPark if which == 'park'
else ReportEquityService if which == 'equity'
else ReportExtendedWarranty)
tag = ('轻改' if which in ('inshop', 'park')
else '权益' if which == 'equity' else '延保')
with app.app_context():
q = db.session.query(model_cls.task_id).filter(model_cls.is_deleted == 0)
if period_start and period_end:
q = q.filter(model_cls.period_start >= period_start,
model_cls.period_end <= period_end)
tids = [t for (t,) in q.distinct().all()]
if not tids:
t = db.session.query(func.max(model_cls.task_id)).filter(
model_cls.is_deleted == 0).scalar()
tids = [t] if t else []
if not tids:
logger.info(f"[{tag}] 未找到结果 task_id,{which}.{col_attr}=0")
return Decimal('0')
task_id = max(tids)
col = getattr(model_cls, col_attr)
logger.info(f"[{tag}] 取 task_id={task_id}({which}){col_attr} 之和")
s = db.session.query(func.coalesce(func.sum(col), 0)).filter(
model_cls.task_id == task_id, model_cls.is_deleted == 0).scalar() or 0
return Decimal(str(float(s)))
def fetch_light_reform_11_sum(col_attr, period_start, period_end):
"""轻改结果表(inshop + park)某数值列之和;条件:同 task_id, is_deleted=0。返回 Decimal。"""
try:
return _lr_sum_one('inshop', col_attr, period_start, period_end) \
+ _lr_sum_one('park', col_attr, period_start, period_end)
except Exception as e:
logger.warning(f"[轻改] 读取失败,{col_attr} 置0: {e}")
return Decimal('0')
def fetch_light_reform_11_sum_one(which, col_attr, period_start, period_end):
"""轻改单表某数值列之和(安全包装,失败置0);which='inshop'|'park'。"""
try:
return _lr_sum_one(which, col_attr, period_start, period_end)
except Exception as e:
logger.warning(f"[轻改] 读取失败,{which}.{col_attr} 置0: {e}")
return Decimal('0')
def fetch_equity_21_sum(col_attr, period_start, period_end):
"""权益服务结果表(report_equity_service)某数值列之和;同 task_id, is_deleted=0。返回 Decimal。"""
try:
return _lr_sum_one('equity', col_attr, period_start, period_end)
except Exception as e:
logger.warning(f"[权益] 读取失败,{col_attr} 置0: {e}")
return Decimal('0')
def fetch_extended_warranty_23_sum(col_attr, period_start, period_end):
"""延保盈利测算结果表(report_extended_warranty)某数值列之和;同 task_id, is_deleted=0。返回 Decimal。"""
try:
return _lr_sum_one('warranty', col_attr, period_start, period_end)
except Exception as e:
logger.warning(f"[延保] 读取失败,{col_attr} 置0: {e}")
return Decimal('0')
def fetch_closed_stores(month_start, month_end_excl):
"""
读取 dj_smartcarlife.sale_close_store_record 中闭店时间落在
[month_start, month_end_excl) 的门店闭店记录。
返回 [(close_time, main_brands), ...],每行一条闭店记录(一条记录=一个闭店门店)。
数据库不可达时返回空列表(指标置 0)。
"""
try:
from config import Config
from sqlalchemy import create_engine, text
engine = create_engine(Config.BIZ_SQL_DATABASE_URL, echo=False, pool_pre_ping=True)
with engine.connect() as conn:
sql = text(
"SELECT close_time, main_brands "
"FROM sale_close_store_record "
"WHERE close_time >= :s AND close_time < :e"
)
rows = conn.execute(sql, {'s': month_start, 'e': month_end_excl}).fetchall()
logger.info(f"[流失门店] sale_close_store_record 命中 {len(rows)} 条 "
f"({month_start}~{month_end_excl})")
return rows
except Exception as e:
logger.warning(f"[流失门店] 读取 sale_close_store_record 失败,置0: {e}")
return []
def _in_params(ids, prefix):
"""把列表转成 SQLAlchemy text 的具名 IN 参数。空列表返回 (None, None)。"""
if not ids:
return None, None
params = {f'{prefix}{i}': v for i, v in enumerate(ids)}
placeholders = ', '.join(f':{prefix}{i}' for i in range(len(ids)))
return params, placeholders
def _engine(url_key):
from config import Config
from sqlalchemy import create_engine
return create_engine(getattr(Config, url_key), echo=False, pool_pre_ping=True)
def fetch_new_stores(month_start, month_end_excl, exact_map, keys):
"""
本月新增门店(dj_smartcarlife.dj_car_life_scene_merchant_ref_new)。
口径(已与用户确认):
- 按 main_merchant_id(门店商户号)去重;该门店所有 sub_merchant_id 行中
MIN(created_date) 作为「首建日期」。
- 首建日期落在 [month_start, month_end_excl) → 本月新增门店。
- 品牌判定:用 main_merchant_id 查 scrm_account.platform_merchant_brand
取 first_brand_id / sec_brand_id → 查 cyb_os.platform_carbrand 得品牌名
→ brand_category() 定豪华;first 或 sec 任一为豪华即「新增豪华门店」。
返回 (total, lux, nonlux)。容错:首建日期(dj_smartcarlife) 取总数;
若商户品牌关联(scrm_account)/品牌字典(cyb_os) 不可达,则豪华拆分降级为 0/总数
(总量仍保留)。
"""
from sqlalchemy import text
# ---- 1) 各门店首建日期(dj_smartcarlife)----
try:
eng_ref = _engine('BIZ_SQL_DATABASE_URL')
with eng_ref.connect() as conn:
sql = text(
"SELECT main_merchant_id, MIN(created_date) AS first_created "
"FROM dj_car_life_scene_merchant_ref_new "
"GROUP BY main_merchant_id "
"HAVING MIN(created_date) >= :s AND MIN(created_date) < :e"
)
rows = conn.execute(sql, {'s': month_start, 'e': month_end_excl}).fetchall()
new_ids = [r[0] for r in rows if r[0] is not None]
logger.info(f"[新增门店] 首建日期命中 {len(new_ids)} 个门店 ({month_start}~{month_end_excl})")
except Exception as e:
logger.warning(f"[新增门店] 读取首建日期失败,置0: {e}")
return 0, 0, 0
if not new_ids:
return 0, 0, 0
total = len(new_ids)
# ---- 2)+3)+4) 豪华归类(scrm_account + cyb_os,单独立容错)----
lux = 0
try:
# 商户→品牌ID(一个 merchant_id 可能多行,按商户 union 所有 first/sec 品牌 id)
brand_set_map = {} # main_merchant_id -> set([first_brand_id, sec_brand_id, ...])
eng_scrm = _engine('SCRM_DATABASE_URL')
with eng_scrm.connect() as conn:
p, ph = _in_params(new_ids, 'm')
if p is not None:
sql = text(
"SELECT merchant_id, first_brand_id, sec_brand_id "
"FROM platform_merchant_brand "
"WHERE del_flag = 0 AND merchant_id IN ({ph})".format(ph=ph)
)
for r in conn.execute(sql, p).fetchall():
mid = r[0]
bids = brand_set_map.setdefault(mid, set())
for b in (r[1], r[2]):
if b not in (None, '', 0):
bids.add(b)
logger.info(f"[新增门店] platform_merchant_brand 命中 {len(brand_set_map)} 个商户")
# 品牌ID→品牌名(cyb_os.platform_carbrand,bid=first/sec_brand_id,品牌名字段为 brand)
all_bids = set()
for bids in brand_set_map.values():
all_bids |= bids
bid_name = {} # bid -> 品牌名
if all_bids:
eng_cyb = _engine('CYB_OS_DATABASE_URL')
with eng_cyb.connect() as conn:
p, ph = _in_params(list(all_bids), 'b')
if p is not None:
sql = text(f"SELECT bid, brand FROM platform_carbrand WHERE bid IN ({ph})")
for r in conn.execute(sql, p).fetchall():
bid, nm = r[0], r[1]
if bid is not None and nm:
bid_name[bid] = str(nm).strip()
logger.info(f"[新增门店] platform_carbrand 命中 {len(bid_name)} 个品牌")
for mid in new_ids:
brand_names = [bid_name[b] for b in brand_set_map.get(mid, set()) if b in bid_name]
if any(brand_category(nm, exact_map, keys) == '豪华' for nm in brand_names):
lux += 1
except Exception as e:
logger.warning(f"[新增门店] 品牌归类失败,豪华拆分降级为 0/总数: {e}")
nonlux = total - lux
logger.info(f"[新增门店] 合计={total} 豪华={lux} 非豪华={nonlux}")
return total, lux, nonlux
def compute_metrics(src, period_start, period_end, month_start=None, month_end_excl=None):
exact_map, keys = load_brand_category()
s1, s2 = parse_saas(src)
allrows = s1 + s2
# 品牌归类
for r in allrows:
r['category'] = brand_category(r['brand'], exact_map, keys)
def uniq(rows, pred=None):
return {r['store'] for r in rows if r['store'] and (pred is None or pred(r))}
m = {}
# ---- 门店数 ----
m['全国经营门店总数'] = len(uniq(allrows))
m['豪华车门店数量'] = len(uniq(allrows, lambda r: r['category'] == '豪华'))
m['非豪华门店数量'] = len(uniq(allrows, lambda r: r['category'] != '豪华'))
# 存量/新增:sheet1 读"A列 存量/新店",sheet2 读"J列 性质"
# 用户口径:存量 = (sheet1 存量/新店=存量) ∪ (sheet2 性质=存量),门店名去重
# 新增 = (sheet1 存量/新店=新增) ∪ (sheet2 性质=新增),门店名去重
# 注:个别门店可能同时出现在"存量"和"新增"两处,union 后会同时计入两边(与源数据一致),
# 故不再强求 存量+新增=总数。
m['存量门店数量'] = len(uniq(allrows, lambda r: r['nature'] == '存量'))
m['新店数量'] = len(uniq(allrows, lambda r: r['nature'] == '新增'))
m['全国直营门店总数'] = len(uniq(allrows, lambda r: r['resident_type'] == '直营'))
m['豪华直营门店数'] = len(uniq(allrows, lambda r: r['resident_type'] == '直营' and r['category'] == '豪华'))
m['非豪华直营门店数'] = len(uniq(allrows, lambda r: r['resident_type'] == '直营' and r['category'] != '豪华'))
# ---- 预算 ----
def ssum(rows, key, pred=None):
t = Decimal('0')
for r in rows:
if pred is None or pred(r):
t += r.get(key, Decimal('0'))
return t
m['经管预算目标'] = ssum(allrows, 'budget_target')
m['全国经营总预算'] = ssum(allrows, 'budget_corrected')
m['存量门店总预算'] = ssum(allrows, 'budget_corrected', lambda r: r['nature'] == '存量')
m['新增门店总预算'] = ssum(allrows, 'budget_corrected', lambda r: r['nature'] == '新增')
m['1.1预算'] = ssum(s2, 'budget_corrected')
m['2.1预算'] = ssum(s1, 'budget_corrected', lambda r: r['biz_type'] == '2.1')
m['2.3预算'] = ssum(s1, 'budget_corrected', lambda r: r['biz_type'] == '2.3')
m['6.1预算'] = Decimal('0') # 字段说明:默认为空
# ---- 交车数(主机厂) ----
delivery = parse_delivery(src)
def dsum(stores):
return sum(int(delivery.get(s, 0)) for s in stores)
stores_11 = uniq(s2)
stores_21 = uniq(s1, lambda r: r['biz_type'] == '2.1')
stores_23 = uniq(s1, lambda r: r['biz_type'] == '2.3')
m['1.1交车数'] = fetch_light_reform_11_sum('delivery_cnt', period_start, period_end)
m['2.1交车数'] = fetch_equity_21_sum('delivery_cnt', period_start, period_end)
m['2.3交车数'] = fetch_extended_warranty_23_sum('delivery_cnt', period_start, period_end)
# ---- 6.1 二手车 ----
uc = parse_used_car(src, period_start, period_end)
m['6.1产值'] = uc['output']
m['6.1毛利率'] = uc['gross_rate']
m['6.1单车均毛利'] = uc['unit_profit']
m['6.1交付平均车价'] = uc['avg_price']
m['6.1处置车量'] = uc['dispose_cnt']
m['6.1收车台次'] = uc['buy_cnt']
m['6.1处置周期(批售)'] = uc['wholesale_cycle']
m['6.1处置周期(零售)'] = uc['retail_cycle']
m['6.1库存数量'] = uc['stock_cnt']
m['6.1达成率'] = pct(m['6.1产值'], m['6.1预算'])
# ---- 以下依赖 指标系统API / 人力表 / 系统数据,暂置 0(骨架待校准)----
for k in ['全国经营总产值', '豪华车店均产值(w)', '非豪华店均产值(w)',
'1.1产值', '2.1产值', '2.3产值',
'1.1毛利率', '2.1毛利率', '2.3毛利率',
'1.1毛利率(含人力)', '2.1毛利率(含人力)', '2.3毛利率(含人力)',
'1.1接待数', '2.1接待数', '2.3接待数',
'1.1成交单数', '2.1成交单数', '2.3成交单数',
'本月流失门店', '流失豪华门店', '流失非豪华门店',
'本月新增门店', '新增豪华门店', '新增非豪华门店']:
m[k] = Decimal('0')
# ---- 本月流失门店(dj_smartcarlife.sale_close_store_record,闭店时间在统计月份)----
# 一条闭店记录=一个门店;main_brands 多个逗号分隔,按各品牌归类(任一为豪华→豪华门店)
if month_start and month_end_excl:
try:
closed_rows = fetch_closed_stores(month_start, month_end_excl)
closed_total = closed_lux = closed_nonlux = 0
for _ct, mb in closed_rows:
closed_total += 1
brands = [b.strip() for b in (mb or '').split(',') if b and b.strip()]
if any(brand_category(b, exact_map, keys) == '豪华' for b in brands):
closed_lux += 1
else:
closed_nonlux += 1
m['本月流失门店'] = Decimal(str(closed_total))
m['流失豪华门店'] = Decimal(str(closed_lux))
m['流失非豪华门店'] = Decimal(str(closed_nonlux))
logger.info(f"[流失门店] 合计={closed_total} 豪华={closed_lux} 非豪华={closed_nonlux}")
except Exception as e:
logger.warning(f"[流失门店] 统计失败,置0: {e}")
# ---- 本月新增门店(dj_smartcarlife.dj_car_life_scene_merchant_ref_new 首建日期在统计月份)----
# 3 库关联:dj_smartcarlife(首建日期) → scrm_account(商户品牌ID) → cyb_os(品牌名) → config_brand_category(豪华)
if month_start and month_end_excl:
try:
nt, nlux, nnon = fetch_new_stores(month_start, month_end_excl, exact_map, keys)
m['本月新增门店'] = Decimal(str(nt))
m['新增豪华门店'] = Decimal(str(nlux))
m['新增非豪华门店'] = Decimal(str(nnon))
except Exception as e:
logger.warning(f"[新增门店] 统计失败,置0: {e}")
# ---- 指标系统:产值A036 / 成交A075 / 触客A084 ----
# biz: 1=延保(2.3) 2=轻改(1.1) 3=权益(2.1);多业务用 list → bizs="1,2,3"
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
ind_all = ind_23 = ind_21 = ind_11 = ind_total = {}
if start_str and end_str:
try:
from report_utils import fetch_indicator_data, INDICATOR_BIZ_MAP
bz_w = INDICATOR_BIZ_MAP.get('warranty') # 1
bz_e = INDICATOR_BIZ_MAP.get('equity') # 3
bz_l = INDICATOR_BIZ_MAP.get('light_reform') # 2
ind_all = fetch_indicator_data(start_str, end_str, [bz_w, bz_e, bz_l], ['A036']) or {}
# 注意:单值 biz 会被 API 忽略(返回全业务),必须传列表走 bizs="N" 才生效
# 全国经营总产值用 A0018(含二手车业务):不传 bizs 直接查全量总数,不做门店匹配
ind_total = fetch_indicator_data(start_str, end_str, None, ['A0018']) or {}
ind_23 = fetch_indicator_data(start_str, end_str, [bz_w], ['A036', 'A075', 'A084']) or {}
ind_21 = fetch_indicator_data(start_str, end_str, [bz_e], ['A036', 'A075', 'A084']) or {}
ind_11 = fetch_indicator_data(start_str, end_str, [bz_l], ['A036', 'A075', 'A084']) or {}
logger.info(f"[指标] 全业务={len(ind_all)} 延保={len(ind_23)} 权益={len(ind_21)} 轻改={len(ind_11)}")
except Exception as e:
logger.warning(f"[指标] 拉取失败,产值/成交/触客置 0: {e}")
def match_any(name, stores):
"""指标系统商户名 ↔ SAAS 门店名 匹配(精确匹配,不使用包含)"""
if not name:
return False
return name in stores
def ind_sum(ind_map, stores, code):
t = Decimal('0')
for nm, vals in (ind_map or {}).items():
if match_any(nm, stores):
t += to_decimal((vals or {}).get(code))
return t
all_stores = uniq(allrows)
# 全国经营总产值 = A0018 全量(含二手车业务),不传 bizs、不做门店匹配,直接求和
m['全国经营总产值'] = sum((to_decimal((vals or {}).get('A0018'))
for vals in (ind_total or {}).values()), Decimal('0'))
# 1.1产值:来自轻改结果表(report_light_reform_inshop + report_light_reform_park 的
# total_output_value 合计总产值 之和,条件:同 task_id, is_deleted=0)
m['1.1产值'] = fetch_light_reform_11_sum('total_output_value', period_start, period_end)
# 1.1毛利率 =(所有"毛利测算"之和 / 1.1产值)*100%,四舍五入保留百分比后2位
# "毛利测算"之和 = 轻改结果表 gross_profit 之和(同 task_id, is_deleted=0)
m['1.1毛利率'] = pct(
fetch_light_reform_11_sum('gross_profit', period_start, period_end),
m['1.1产值'])
# 1.1毛利率(含人力)=(毛利测算之和 + 营销成本(inshop.marketing_personnel_cost)
# + 人力成本(park.personnel_cost))/ 1.1产值 * 100%,四舍五入保留百分比后2位
# 条件:同 task_id, is_deleted=0
gp_11 = fetch_light_reform_11_sum('gross_profit', period_start, period_end)
mkt_11 = fetch_light_reform_11_sum_one('inshop', 'marketing_personnel_cost', period_start, period_end)
hr_11 = fetch_light_reform_11_sum_one('park', 'personnel_cost', period_start, period_end)
m['1.1毛利率(含人力)'] = pct(gp_11 + mkt_11 + hr_11, m['1.1产值'])
# 2.1产值:report_equity_service.store_output_value(门店产值) 之和,同 task_id, is_deleted=0
m['2.1产值'] = fetch_equity_21_sum('store_output_value', period_start, period_end)
# 2.1毛利率 =(gross_profit 之和 / 2.1产值)*100%,四舍五入保留百分比后2位
gp_21 = fetch_equity_21_sum('gross_profit', period_start, period_end)
m['2.1毛利率'] = pct(gp_21, m['2.1产值'])
# 2.1毛利率(含人力)=(gross_profit 之和 + marketing_fee 之和)/ 2.1产值 *100%,四舍五入保留百分比后2位
mkt_21 = fetch_equity_21_sum('marketing_fee', period_start, period_end)
m['2.1毛利率(含人力)'] = pct(gp_21 + mkt_21, m['2.1产值'])
# 2.3产值:report_extended_warranty.store_output_value(门店产值) 之和,同 task_id, is_deleted=0
m['2.3产值'] = fetch_extended_warranty_23_sum('store_output_value', period_start, period_end)
# 1.1成交单数 = park.deal_cnt(成交数) 之和 + inshop.total_deal_cnt(总成交数) 之和
# 条件:同 task_id, is_deleted=0
m['1.1成交单数'] = (fetch_light_reform_11_sum_one('park', 'deal_cnt', period_start, period_end)
+ fetch_light_reform_11_sum_one('inshop', 'total_deal_cnt', period_start, period_end))
m['2.1成交单数'] = fetch_equity_21_sum('deal_cnt', period_start, period_end)
# 2.3毛利率 =(gross_profit 之和 / 2.3产值)*100%,四舍五入保留百分比后2位
gp_23 = fetch_extended_warranty_23_sum('gross_profit', period_start, period_end)
m['2.3毛利率'] = pct(gp_23, m['2.3产值'])
# 2.3毛利率(含人力)=(gross_profit 之和 + marketing_fee 之和)/ 2.3产值 *100%,四舍五入保留百分比后2位
mkt_23 = fetch_extended_warranty_23_sum('marketing_fee', period_start, period_end)
m['2.3毛利率(含人力)'] = pct(gp_23 + mkt_23, m['2.3产值'])
m['2.3成交单数'] = fetch_extended_warranty_23_sum('deal_cnt', period_start, period_end)
# 1.1接待数 = park.arrival_cnt(到店数) 之和 + inshop.delivery_touch_cnt(交付触客数) 之和
# 条件:同 task_id, is_deleted=0
m['1.1接待数'] = (fetch_light_reform_11_sum_one('park', 'arrival_cnt', period_start, period_end)
+ fetch_light_reform_11_sum_one('inshop', 'delivery_touch_cnt', period_start, period_end))
m['2.1接待数'] = fetch_equity_21_sum('touch_cnt', period_start, period_end)
m['2.3接待数'] = fetch_extended_warranty_23_sum('touch_cnt', period_start, period_end)
lux_stores = {r['store'] for r in allrows if r['category'] == '豪华'}
nonlux_stores = {r['store'] for r in allrows if r['category'] != '豪华'}
lux_output = ind_sum(ind_total, lux_stores, 'A0018')
nonlux_output = ind_sum(ind_total, nonlux_stores, 'A0018')
m['豪华车店均产值(w)'] = safe_div(lux_output, m['豪华车门店数量'])
m['非豪华店均产值(w)'] = safe_div(nonlux_output, m['非豪华门店数量'])
# ---- 人力(人力成本表,AF列检核=TRUE)----
hr = parse_hr(src)
checked = [r for r in hr
if r['checked'] is True or str(r['checked']).strip().lower() == 'true']
not_left = [r for r in checked if '离职' not in r['position']]
sales = [r for r in checked if r['position'] == '门店销售']
logger.info(f"[人力] 检核通过={len(checked)} 非离职={len(not_left)} 门店销售={len(sales)}")
m['全国直营总人数'] = len({r['emp_no'] for r in not_left})
m['全国直营营销人数'] = len({r['emp_no'] for r in sales})
m['全国直营店均人数'] = safe_div(m['全国直营营销人数'], m['全国直营门店总数'])
m['全国人均产值(w)'] = safe_div(m['全国经营总产值'], m['全国直营营销人数'])
# 豪华/非豪华:按「入驻门店」映射门店集合(精确匹配,不使用包含)
lux_stores = {r['store'] for r in allrows if r['category'] == '豪华'}
nonlux_stores = {r['store'] for r in allrows if r['category'] != '豪华'}
def in_stores(hs, stores):
if not hs:
return False
return hs in stores
lux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], lux_stores)}
nonlux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], nonlux_stores)}
lux_sales = {r['emp_no'] for r in sales if in_stores(r['store'], lux_stores)}
nonlux_sales = {r['emp_no'] for r in sales if in_stores(r['store'], nonlux_stores)}
m['豪华车员工数量'] = len(lux_emp)
m['非豪华员工数量'] = len(nonlux_emp)
m['豪华车营销人数'] = len(lux_sales)
m['非豪华车营销人数'] = len(nonlux_sales)
m['豪华车店均人数'] = safe_div(len(lux_sales), m['豪华车门店数量'])
m['非豪华车店均人数'] = safe_div(len(nonlux_sales), m['非豪华门店数量'])
m['豪华车人均产值'] = safe_div(lux_output, len(lux_sales))
m['非豪华车人均产值(w)'] = safe_div(nonlux_output, len(nonlux_sales))
# ---- 派生指标 ----
m['1.1达成率'] = pct(m['1.1产值'], m['1.1预算'])
m['2.1达成率'] = pct(m['2.1产值'], m['2.1预算'])
m['2.3达成率'] = pct(m['2.3产值'], m['2.3预算'])
m['1.1触客率'] = pct(m['1.1接待数'], m['1.1交车数'])
m['2.1触客率'] = pct(m['2.1接待数'], m['2.1交车数'])
m['2.3触客率'] = pct(m['2.3接待数'], m['2.3交车数'])
m['1.1转化率'] = pct(m['1.1成交单数'], m['1.1接待数'])
m['2.1转化率'] = pct(m['2.1成交单数'], m['2.1接待数'])
m['2.3转化率'] = pct(m['2.3成交单数'], m['2.3接待数'])
m['1.1成交客单价'] = div2(m['1.1产值'], m['1.1交车数'])
m['2.1成交客单价'] = div2(m['2.1产值'], m['2.1成交单数'])
m['2.3成交客单价'] = div2(m['2.3产值'], m['2.3成交单数'])
# 人力/招聘类:默认为空
for k in ['原本月招聘需求', '新店拓展需求', '总计', '已入职', '待招聘',
'本月离职人员', '本月净增长人员']:
m[k] = ''
# ---- (w) 列统一换算成万元(用户确认:列名含 (w) 的需 ÷10000)----
for _k in list(m.keys()):
if '(w)' in _k or '(w)' in _k:
_v = m[_k]
try:
if _v not in ('', None) and isinstance(_v, (int, float, Decimal)):
m[_k] = (Decimal(str(_v)) / Decimal('10000')).quantize(Decimal('1.0000'))
except Exception:
pass
return m
# ============================================================
# 渲染「总看板」
# ============================================================
# (行号, [(标签列, 字段名, 值列), ...]) —— 与模板逐格对齐
BOARD = [
(3, [('A', '全国经营门店总数', 'B'), ('C', '豪华车门店数量', 'D'), ('E', '非豪华门店数量', 'F'),
('G', '原本月招聘需求', 'H'), ('I', '新店拓展需求', 'J'), ('K', '总计', 'L')]),
(4, [('A', '经管预算目标', 'B'), ('C', '存量门店数量', 'D'), ('E', '新店数量', 'F'), ('G', '已入职', 'H')]),
(5, [('A', '全国经营总预算', 'B'), ('C', '存量门店总预算', 'D'), ('E', '新增门店总预算', 'F'), ('G', '待招聘', 'H')]),
(6, [('A', '全国经营总产值', 'B'), ('C', '豪华车店均产值(w)', 'D'), ('E', '非豪华店均产值(w)', 'F'), ('G', '本月离职人员', 'H')]),
(7, [('A', '全国直营门店总数', 'B'), ('C', '豪华直营门店数', 'D'), ('E', '非豪华直营门店数', 'F'), ('G', '本月净增长人员', 'H')]),
(8, [('A', '全国直营总人数', 'B'), ('C', '豪华车员工数量', 'D'), ('E', '非豪华员工数量', 'F')]),
(9, [('A', '全国直营营销人数', 'B'), ('C', '豪华车营销人数', 'D'), ('E', '非豪华车营销人数', 'F')]),
(10, [('A', '全国直营店均人数', 'B'), ('C', '豪华车店均人数', 'D'), ('E', '非豪华车店均人数', 'F')]),
(11, [('A', '全国人均产值(w)', 'B'), ('C', '豪华车人均产值', 'D'), ('E', '非豪华车人均产值(w)', 'F')]),
(13, [('A', '1.1预算', 'B'), ('C', '2.1预算', 'D'), ('E', '2.3预算', 'F'), ('G', '6.1预算', 'H'), ('I', '本月流失门店', 'J')]),
(14, [('A', '1.1产值', 'B'), ('C', '2.1产值', 'D'), ('E', '2.3产值', 'F'), ('G', '6.1产值', 'H'), ('I', '流失豪华门店', 'J')]),
(15, [('A', '1.1达成率', 'B'), ('C', '2.1达成率', 'D'), ('E', '2.3达成率', 'F'), ('G', '6.1达成率', 'H'), ('I', '流失非豪华门店', 'J')]),
(16, [('A', '1.1毛利率', 'B'), ('C', '2.1毛利率', 'D'), ('E', '2.3毛利率', 'F'), ('G', '6.1毛利率', 'H'), ('I', '本月新增门店', 'J')]),
(17, [('A', '1.1毛利率(含人力)', 'B'), ('C', '2.1毛利率(含人力)', 'D'), ('E', '2.3毛利率(含人力)', 'F'),
('G', '6.1单车均毛利', 'H'), ('I', '新增豪华门店', 'J')]),
(18, [('A', '1.1交车数', 'B'), ('C', '2.1交车数', 'D'), ('E', '2.3交车数', 'F'), ('G', '6.1交付平均车价', 'H'), ('I', '新增非豪华门店', 'J')]),
(19, [('A', '1.1接待数', 'B'), ('C', '2.1接待数', 'D'), ('E', '2.3接待数', 'F'), ('G', '6.1处置车量', 'H')]),
(20, [('A', '1.1触客率', 'B'), ('C', '2.1触客率', 'D'), ('E', '2.3触客率', 'F'), ('G', '6.1收车台次', 'H')]),
(21, [('A', '1.1转化率', 'B'), ('C', '2.1转化率', 'D'), ('E', '2.3转化率', 'F'), ('G', '6.1处置周期(批售)', 'H')]),
(22, [('A', '1.1成交单数', 'B'), ('C', '2.1成交单数', 'D'), ('E', '2.3成交单数', 'F'), ('G', '6.1处置周期(零售)', 'H')]),
(23, [('A', '1.1成交客单价', 'B'), ('C', '2.1成交客单价', 'D'), ('E', '2.3成交客单价', 'F'), ('G', '6.1库存数量', 'H')]),
]
RATE_FIELDS = {'1.1达成率', '2.1达成率', '2.3达成率', '6.1达成率',
'1.1毛利率', '2.1毛利率', '2.3毛利率', '6.1毛利率',
'1.1毛利率(含人力)', '2.1毛利率(含人力)', '2.3毛利率(含人力)',
'1.1触客率', '2.1触客率', '2.3触客率',
'1.1转化率', '2.1转化率', '2.3转化率'}
# 目标表(存量/新增/总计目标,单位:万)——字段说明未定义取数,留空待填
TARGET_TABLE = [('2.1', 2), ('2.3', 4), ('1.1', 5), ('6.1', 6), ('合计', 7)]
def append_board_to_wb(wb, m, month_label, targets=None, rate_fields=None,
board=None, target_table=None, field_notes=None):
"""
把「总看板」和「字段说明」追加到已有 wb(作为最后两个 sheet)。
复用 render_board 的样式/字段,不另起 wb。
:param wb: openpyxl.Workbook 实例
:param m: compute_metrics 返回的指标 dict
:param month_label: 周期标签(如 '2026-08')
:param targets: 目标表 dict
:return: (ws_board, ws_notes) 两个 sheet 对象
"""
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
title_font = Font(name='微软雅黑', size=14, bold=True)
label_font = Font(name='微软雅黑', size=10)
value_font = Font(name='微软雅黑', size=10, bold=True)
head_font = Font(name='微软雅黑', size=10, bold=True, color='FFFFFF')
head_fill = PatternFill('solid', start_color='4472C4', end_color='4472C4')
center = Alignment(horizontal='center', vertical='center', wrap_text=True)
thin = Border(*[Side(style='thin')] * 4)
_BOARD = board if board is not None else BOARD
_RATE = rate_fields if rate_fields is not None else RATE_FIELDS
_TARGET = target_table if target_table is not None else TARGET_TABLE
_NOTES = field_notes if field_notes is not None else FIELD_NOTES
# ---- 总看板 sheet ----
ws = wb.create_sheet('总看板')
ws['A1'] = '业务运营数据看板'
ws['A1'].font = title_font
ws['A1'].alignment = center
# 标题跨前 16 列合并居中(Q1 期间、R~U1 目标表头独立保留)
ws.merge_cells('A1:P1')
ws['Q1'] = month_label
# 目标表
for c, h in zip(range(18, 22), ['业务类型', '存量目标\n(万)', '新增目标\n(万)', '总计目标\n(万)']):
cell = ws.cell(row=1, column=c, value=h)
cell.font = head_font
cell.fill = head_fill
cell.alignment = center
cell.border = thin
for biz, row in _TARGET:
ws.cell(row=row, column=18, value=biz).border = thin
vals = (targets or {}).get(biz, ('', '', ''))
for i, v in enumerate(vals):
c = ws.cell(row=row, column=19 + i, value=v)
c.border = thin
c.alignment = center
# 看板主体
for row, items in _BOARD:
for label_col, field, val_col in items:
lc = ws[f'{label_col}{row}']
lc.value = field
lc.font = label_font
lc.alignment = center
lc.border = thin
v = m.get(field, 0)
vc = ws[f'{val_col}{row}']
if isinstance(v, Decimal):
vc.value = float(v)
vc.number_format = '0.00"%"' if field in _RATE else '#,##0.00'
elif isinstance(v, int):
vc.value = v
vc.number_format = '#,##0'
else:
vc.value = v
vc.font = value_font
vc.alignment = center
vc.border = thin
ws.column_dimensions[label_col].width = 18
ws.column_dimensions[val_col].width = 14
# ---- 字段说明 sheet ----
ws2 = wb.create_sheet('字段说明')
ws2['A1'], ws2['B1'] = '字段名', '取数说明'
for c in ('A1', 'B1'):
ws2[c].font = head_font
ws2[c].fill = head_fill
ws2[c].alignment = center
ws2[c].border = thin
ws2.column_dimensions['A'].width = 24
ws2.column_dimensions['B'].width = 90
for i, (name, desc) in enumerate(_NOTES, start=2):
ws2.cell(row=i, column=1, value=name).border = thin
c = ws2.cell(row=i, column=2, value=desc)
c.border = thin
c.alignment = Alignment(wrap_text=True, vertical='center')
logger.info(f"[总看板] 已追加到 wb,共 {len(_BOARD)} 行指标 / {len(_NOTES)} 条说明")
return ws, ws2
def render_board(m, out_path, month_label, targets=None):
wb = openpyxl.Workbook()
append_board_to_wb(wb, m, month_label, targets=targets)
# 移除默认空 Sheet
if 'Sheet' in wb.sheetnames:
del wb['Sheet']
wb.save(out_path)
logger.info(f"[输出] 已生成: {out_path}")
return out_path
# 字段说明(源自模板 sheet2,标注当前取数状态)
FIELD_NOTES = [
('全国经营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有门店明细按门店名称去重计算总数'),
('经管预算目标', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(预算目标)"之和'),
('全国经营总预算', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(纠偏)"之和'),
('全国经营总产值', '指标系统 A0018(含二手车业务),biz=None 不传bizs查全量、不做门店匹配;2026-08 全量(不传bizs)实测=98,255,112.51(注:97,681,597.64 为历史快照,数据随业务回写变动)'),
('全国直营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有驻店类型=直营 的门店明细去重计算总数'),
('全国直营总人数', '人力成本表:AF列检核=TRUE、过滤岗位=离职,按工号去重【人力表加密无法读取,当前0】'),
('全国直营营销人数', '人力成本表:检核=TRUE、岗位=门店销售,按工号去重【人力表加密无法读取,当前0】'),
('全国直营店均人数', '全国直营营销人数/全国直营门店总数【依赖人力表,当前0】'),
('全国人均产值(w)', '全国经营总产值/全国直营营销人数【依赖产值+人力表,当前0】'),
('豪华车门店数量', 'saa表sheet1+sheet2,"品牌"信息=豪华 的门店按门店名称去重;判定用 config_brand_category 模糊匹配'),
('存量门店数量', '门店预算分解表 sheet1 以"存量/新店"(A列)=存量、sheet2 以"性质"(J列)=存量,两表满足存量的门店按门店名称去重合计'),
('存量门店总预算', '存量明细的"预估产值(纠偏)"之和'),
('豪华车店均产值(w)', '豪华车门店对应系统产值/豪华车门店数量【待接入A036,当前0】'),
('豪华直营门店数', '品牌=豪华且驻店类型=直营的去重门店数'),
('豪华车员工数量', '豪华车门店映射人力成本表"入驻门店",检核=TRUE、过滤离职,按工号去重【人力表加密,当前0】'),
('豪华车营销人数', '同上条件,岗位=门店销售【人力表加密,当前0】'),
('豪华车店均人数', '豪华车营销人数/豪华门店数量【依赖人力表,当前0】'),
('豪华车人均产值', '豪华车门店产值/豪华车营销人数【待接入,当前0】'),
('非豪华门店数量', '品牌≠豪华的去重门店数'),
('新店数量', '门店预算分解表 sheet1 以"存量/新店"(A列)=新增、sheet2 以"性质"(J列)=新增,两表满足新增的门店按门店名称去重合计'),
('新增门店总预算', '新增明细的"预估产值(纠偏)"之和'),
('非豪华店均产值(w)', '非豪华门店对应产值/非豪华门店数量【待接入A036,当前0】'),
('非豪华直营门店数', '品牌≠豪华且驻店类型=直营的去重门店数'),
('非豪华员工数量', '非豪华门店映射人力表【人力表加密,当前0】'),
('非豪华车营销人数', '非豪华门店映射人力表,岗位=门店销售【人力表加密,当前0】'),
('非豪华车店均人数', '非豪华车营销人数/非豪华门店数量【依赖人力表,当前0】'),
('非豪华车人均产值(w)', '非豪华门店产值/非豪华车营销人数【待接入,当前0】'),
('1.1预算', 'sheet2所有明细的"预估产值(纠偏)"之和'),
('1.1产值', '轻改结果表:report_light_reform_inshop + report_light_reform_park 的 total_output_value(合计总产值) 之和,条件:同 task_id, is_deleted=0'),
('1.1达成率', '(1.1产值/1.1预算)*100%'),
('1.1毛利率', '(report_light_reform_inshop + report_light_reform_park 的 gross_profit(毛利测算) 之和 / 1.1产值)*100%,四舍五入保留百分比后2位;条件:同 task_id, is_deleted=0'),
('1.1毛利率(含人力)', '(report_light_reform_inshop + report_light_reform_park 的 gross_profit(毛利测算) 之和 + inshop.marketing_personnel_cost(营销成本) + park.personnel_cost(人力成本))/ 1.1产值 *100%,四舍五入保留百分比后2位;条件:同 task_id, is_deleted=0'),
('1.1交车数', 'report_light_reform_inshop + report_light_reform_park 的 delivery_cnt(交车数) 之和,条件:同 task_id, is_deleted=0'),
('1.1接待数', 'report_light_reform_park.arrival_cnt(到店数) 之和 + report_light_reform_inshop.delivery_touch_cnt(交付触客数) 之和,条件:同 task_id, is_deleted=0'),
('1.1触客率', '(1.1接待数/1.1交车数)*100%'),
('1.1转化率', '(1.1成交单数/1.1接待数)*100%'),
('1.1成交单数', 'report_light_reform_park.deal_cnt(成交数) 之和 + report_light_reform_inshop.total_deal_cnt(总成交数) 之和,条件:同 task_id, is_deleted=0'),
('1.1成交客单价', '1.1产值/1.1交车数,四舍五入保留2位小数'),
('2.1预算', 'sheet1业务类型=2.1明细的"预估产值(纠偏)"之和'),
('2.1产值', 'report_equity_service.store_output_value(门店产值) 之和,条件:同 task_id, is_deleted=0'),
('2.1达成率', '(2.1产值/2.1预算)*100%'),
('2.1毛利率', 'report_equity_service.gross_profit(毛利测算) 之和 / 2.1产值 *100%,四舍五入保留百分比后2位;同 task_id, is_deleted=0'),
('2.1毛利率(含人力)', '(report_equity_service.gross_profit(毛利测算) 之和 + marketing_fee(营销费用) 之和)/ 2.1产值 *100%,四舍五入保留百分比后2位;同 task_id, is_deleted=0'),
('2.1交车数', 'report_equity_service.delivery_cnt(交车) 之和,条件:同 task_id, is_deleted=0'),
('2.1接待数', 'report_equity_service.touch_cnt(触客) 之和,条件:同 task_id, is_deleted=0'),
('2.1触客率', '(2.1接待数/2.1交车数)*100%'),
('2.1转化率', '(2.1成交单数/2.1接待数)*100%'),
('2.1成交单数', 'report_equity_service.deal_cnt(成交数) 之和,条件:同 task_id, is_deleted=0'),
('2.1成交客单价', '2.1产值/2.1成交单数,四舍五入保留2位小数'),
('2.3预算', 'sheet1业务类型=2.3明细的"预估产值(纠偏)"之和'),
('2.3产值', 'report_extended_warranty.store_output_value(门店产值) 之和,条件:同 task_id, is_deleted=0'),
('2.3达成率', '(2.3产值/2.3预算)*100%'),
('2.3毛利率', 'report_extended_warranty.gross_profit(毛利测算) 之和 / 2.3产值 *100%,四舍五入保留百分比后2位;同 task_id, is_deleted=0'),
('2.3毛利率(含人力)', '(report_extended_warranty.gross_profit(毛利测算) 之和 + marketing_fee(营销费用) 之和)/ 2.3产值 *100%,四舍五入保留百分比后2位;同 task_id, is_deleted=0'),
('2.3交车数', 'report_extended_warranty.delivery_cnt(交车) 之和,条件:同 task_id, is_deleted=0'),
('2.3接待数', 'report_extended_warranty.touch_cnt(触客) 之和,条件:同 task_id, is_deleted=0'),
('2.3触客率', '(2.3接待数/2.3交车数)*100%'),
('2.3转化率', '(2.3成交单数/2.3接待数)*100%'),
('2.3成交单数', 'report_extended_warranty.deal_cnt(成交数) 之和,条件:同 task_id, is_deleted=0'),
('2.3成交客单价', '2.3产值/2.3成交单数,四舍五入保留2位小数'),
('6.1预算', '默认为空'),
('6.1产值', '二手车台账-汇总销售台账:拍卖日期在周期内 的拍卖价格之和'),
('6.1达成率', '(6.1产值/6.1预算)*100%'),
('6.1毛利率', '(拍卖价格-收购价格)之和/6.1产值'),
('6.1单车均毛利', '(拍卖价格-收购价格)之和/处置台次'),
('6.1交付平均车价', '收购日期在周期内 的收购价格之和/收购台次'),
('6.1处置车量', '拍卖日期在周期内 的明细数量'),
('6.1收车台次', '收购日期在周期内 的明细数量'),
('6.1处置周期(批售)', '拍卖平台≠个人:(拍卖日期-收车日期)天数之和/明细数'),
('6.1处置周期(零售)', '拍卖平台=个人:(拍卖日期-收车日期)天数之和/明细数'),
('6.1库存数量', '拍卖日期为空且处置类型≠寄售 的明细数量'),
('本月流失门店', 'dj_smartcarlife.sale_close_store_record:close_time 在统计月份内的闭店门店数(一条记录=一个门店)'),
('流失豪华门店', '本月流失门店中 main_brands 任一品牌归类=豪华 的门店数'),
('流失非豪华门店', '本月流失门店中 main_brands 无豪华品牌 的门店数'),
('本月新增门店', 'dj_smartcarlife.dj_car_life_scene_merchant_ref_new:按 main_merchant_id 去重取 MIN(created_date) 为首建日期,落在统计月份的门店数'),
('新增豪华门店', '本月新增门店中,main_merchant_id→scrm_account.platform_merchant_brand(first/sec_brand_id)→cyb_os.platform_carbrand(品牌名)→config_brand_category 任一品牌=豪华'),
('新增非豪华门店', '本月新增门店中,品牌未归类豪华(含无品牌记录)的门店数'),
]
def main():
ap = argparse.ArgumentParser()
ap.add_argument('--src', default=r'C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源')
ap.add_argument('--month', default='')
ap.add_argument('--period-start', default='')
ap.add_argument('--period-end', default='')
ap.add_argument('--out', default='')
args = ap.parse_args()
ps = excel_serial_to_date(args.period_start) if args.period_start else None
pe = excel_serial_to_date(args.period_end) if args.period_end else None
month_label = args.month or (ps.strftime('%Y%m') if ps else '')
logger.info(f"[构建] 数据源={args.src} 期间={ps}~{pe}")
# 统计月份区间(用于闭店记录查询):优先 --month,其次回退到 --period-start/end
month_start = month_end_excl = None
if args.month:
try:
y, mo = map(int, args.month.split('-'))
month_start = date(y, mo, 1)
if mo == 12:
month_end_excl = date(y + 1, 1, 1)
else:
month_end_excl = date(y, mo + 1, 1)
except Exception:
month_start = month_end_excl = None
elif ps:
month_start = ps
month_end_excl = (pe + timedelta(days=1)) if pe else None
m = compute_metrics(args.src, ps, pe, month_start, month_end_excl)
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True)
out = args.out or os.path.join(out_dir, f'门店店效人效汇总表_{month_label or "总看板"}.xlsx')
render_board(m, out, month_label)
# 控制台回显关键值,便于核对
print('=' * 60)
for k in ['全国经营门店总数', '豪华车门店数量', '非豪华门店数量', '存量门店数量', '新店数量',
'全国直营门店总数', '豪华直营门店数', '非豪华直营门店数',
'经管预算目标', '全国经营总预算', '存量门店总预算', '新增门店总预算',
'1.1预算', '2.1预算', '2.3预算',
'全国经营总产值', '豪华车店均产值(w)', '非豪华店均产值(w)',
'1.1产值', '2.1产值', '2.3产值',
'1.1成交单数', '2.1成交单数', '2.3成交单数',
'1.1接待数', '2.1接待数', '2.3接待数',
'1.1达成率', '2.1达成率', '2.3达成率',
'1.1触客率', '2.1触客率', '2.3触客率',
'1.1交车数', '2.1交车数', '2.3交车数',
'6.1产值', '6.1处置车量', '6.1收车台次', '6.1库存数量',
'全国直营总人数', '全国直营营销人数', '全国直营店均人数', '全国人均产值(w)',
'豪华车员工数量', '豪华车营销人数', '豪华车店均人数', '豪华车人均产值',
'非豪华员工数量', '非豪华车营销人数', '非豪华车店均人数', '非豪华车人均产值(w)',
'本月流失门店', '流失豪华门店', '流失非豪华门店',
'本月新增门店', '新增豪华门店', '新增非豪华门店']:
print(f'{k:16s} = {m.get(k)}')
print('=' * 60)
print('OUT:', out)
if __name__ == '__main__':
main()
# -*- coding: utf-8 -*-
"""
通用+权益 独立处理器
====================
对应 ORM 表:data_process_task (data_table_type='common_equity')
数据来源:dj_smartcarlife / scrm_account / cyb_os / region_province_mapping
输出:门店维度的延保 + 广联权益 Excel 报表
处理流程:
Step1 从任务获取基础信息(data_table_type_name, period_start, period_end)
Step2 批量查询门店基础信息(4s店/省份/运营模式/大区/区域运营/品牌/交付台数)
Step3 批量查询延保指标(触客/订单/收入/整车订单/原厂权益订单)
Step4 批量查询广联权益指标(触客/订单/收入)
Step5 计算派生字段(触客率/客单价/渗透率等)
Step6 生成结果 Excel(两级合并表头)并上传 OSS
"""
import logging
import os
import tempfile
from collections import defaultdict
from datetime import datetime, timedelta
from decimal import Decimal, ROUND_HALF_UP
import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from sqlalchemy import create_engine, text as sa_text
from config import Config
from models import DataProcessTask, db
from oss_utils import upload_file
from report_utils import mark_task_failed, cleanup_tmp_dir
logger = logging.getLogger('CommonEquityProcessor')
COMMON_EQUITY_TYPE = 'common_equity'
# ============================================================
# 数据库连接工具
# ============================================================
def _engine(url_key):
"""创建外部数据库 SQLAlchemy engine(参考 build_store_effect_board._engine)"""
url = getattr(Config, url_key, None)
if not url:
raise ValueError(f"配置项 {url_key} 未设置")
return create_engine(url, echo=False, pool_pre_ping=True)
def _in_params(ids, prefix):
"""把列表转成 SQLAlchemy text 的具名 IN 参数。空列表返回 (None, None)。"""
if not ids:
return None, None
params = {f'{prefix}{i}': v for i, v in enumerate(ids)}
placeholders = ', '.join(f':{prefix}{i}' for i in range(len(ids)))
return params, placeholders
def _safe_decimal(val, scale=2):
"""安全转 Decimal,None/NaN 返回 Decimal('0'),保留指定精度。"""
if val is None:
return Decimal('0')
try:
d = Decimal(str(val))
return d.quantize(Decimal('0.' + '0' * scale), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
def _safe_pct(numerator, denominator, scale=2):
"""百分比计算:(numerator / denominator) * 100,分母为0返回0。"""
if not denominator or denominator == 0:
return Decimal('0')
try:
return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))
).quantize(Decimal('0.' + '0' * scale), rounding=ROUND_HALF_UP)
except Exception:
return Decimal('0')
class CommonEquityProcessor:
"""通用+权益独立处理器"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_common_equity(self):
"""扫描 common_equity 类型的 PROCESSING 任务"""
logger.info("[通用+权益] 开始扫描 common_equity 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=COMMON_EQUITY_TYPE,
status='PROCESSING',
is_deleted=0,
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[通用+权益] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[通用+权益] 任务 {task.id} 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[通用+权益] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[通用+权益] 标记任务失败时出错: {mark_err}")
logger.info(f"[通用+权益] 扫描完成,成功 {success_count},失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
# ============================================================
# 单任务处理
# ============================================================
def process(self, task):
"""处理单个通用+权益任务"""
task_id = task.id
try:
data = self._fetch_all_data(task)
result_file_url = self.generate_result_excel(task, data)
task = DataProcessTask.query.filter_by(id=task_id).first()
task.status = 'COMPLETED'
task.result_file_url = result_file_url
task.error_msg = ''
db.session.commit()
logger.info(f"[通用+权益] 任务 {task_id} 处理完成,结果文件: {result_file_url}")
except Exception as e:
db.session.rollback()
mark_task_failed(task_id, str(e))
raise
# ============================================================
# 数据聚合
# ============================================================
def _fetch_all_data(self, task):
"""批量获取所有门店数据,返回 list[dict],每个 dict 为一行输出数据。"""
task_id = task.id
period_start = task.period_start
period_end = task.period_end
if not period_start or not period_end:
raise Exception("任务缺少所属周期(period_start / period_end)")
start_str = period_start.strftime('%Y-%m-%d')
end_str = period_end.strftime('%Y-%m-%d')
start_dt = f"{start_str} 00:00:00"
end_dt = f"{end_str} 23:59:59"
logger.info(f"[通用+权益] task_id={task_id}, 周期={start_str}~{end_str}")
# ---- Step1: 基础门店列表 (dj_smartcarlife) ----
store_map = self._fetch_stores()
if not store_map:
raise Exception("未查询到任何门店数据(pg_group_store_rel)")
merchant_ids = list(store_map.keys())
logger.info(f"[通用+权益] 基础门店 {len(merchant_ids)} 个")
# ---- Step2: 运营模式 ----
operate_mode_map = self._fetch_operate_mode(merchant_ids)
# ---- Step3: 大区 ----
provinces = list({s['province_name'] for s in store_map.values() if s['province_name']})
region_map = self._fetch_region(provinces)
# ---- Step4: 区域运营 ----
director_map = self._fetch_directors(merchant_ids)
# ---- Step5: 品牌 ----
brand_map = self._fetch_brands(merchant_ids)
# ---- Step6: 门店交付台数 ----
delivery_map = self._fetch_delivery_count(merchant_ids, start_str, end_str)
# ---- Step7: 延保触客 ----
extend_touch_map = self._fetch_extend_touch(merchant_ids, start_str, end_str)
# ---- Step8: 延保售前/售后订单 ----
extend_pre_order_map = self._fetch_extend_orders(merchant_ids, start_dt, end_dt, sales_type=0)
extend_post_order_map = self._fetch_extend_orders(merchant_ids, start_dt, end_dt, sales_type=1)
# ---- Step9: 延保累计收入 ----
extend_income_map = self._fetch_extend_income(merchant_ids, start_dt, end_dt)
# ---- Step10: 延保整车订单数 ----
extend_car_order_map = self._fetch_extend_special_orders(merchant_ids, start_dt, end_dt, upgrade_goods_type=155)
# ---- Step11: 延保原厂权益订单数 ----
extend_equity_order_map = self._fetch_extend_special_orders(merchant_ids, start_dt, end_dt, upgrade_goods_type=126)
# ---- Step12: 广联权益触客 ----
equity_touch_map = self._fetch_equity_touch(merchant_ids, start_str, end_str)
# ---- Step13: 广联权益售前/售后订单 ----
equity_pre_order_map = self._fetch_equity_orders(merchant_ids, start_dt, end_dt, sales_type=0)
equity_post_order_map = self._fetch_equity_orders(merchant_ids, start_dt, end_dt, sales_type=1)
# ---- Step14: 广联权益累计收入 ----
equity_income_map = self._fetch_equity_income(merchant_ids, start_dt, end_dt)
# ---- 组装结果 ----
rows = []
for mid, store in store_map.items():
mname = store['merchant_name']
province = store['province_name']
# 基础字段
operate_mode = operate_mode_map.get(mid, '非直营')
region = region_map.get(province, '')
director = director_map.get(mid, '')
brand = brand_map.get(mid, '')
delivery_cnt = delivery_map.get(mid, 0)
# 延保字段
ext_pre_touch = extend_touch_map.get(mid, {}).get('pre', 0)
ext_post_touch = extend_touch_map.get(mid, {}).get('post', 0)
ext_pre_touch_rate = _safe_pct(ext_pre_touch, delivery_cnt)
ext_pre_order = extend_pre_order_map.get(mid, 0)
ext_post_order = extend_post_order_map.get(mid, 0)
ext_order_total = ext_pre_order + ext_post_order
ext_income = extend_income_map.get(mid, Decimal('0'))
ext_unit_price = (ext_income / Decimal(str(ext_order_total))).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP) if ext_order_total > 0 else Decimal('0')
ext_car_order = extend_car_order_map.get(mid, 0)
ext_car_penetration = _safe_pct(ext_car_order, delivery_cnt)
ext_equity_order = extend_equity_order_map.get(mid, 0)
ext_equity_penetration = _safe_pct(ext_equity_order, delivery_cnt)
# 广联权益字段
eq_pre_touch = equity_touch_map.get(mid, {}).get('pre', 0)
eq_post_touch = equity_touch_map.get(mid, {}).get('post', 0)
eq_pre_touch_rate = _safe_pct(eq_pre_touch, delivery_cnt)
eq_pre_order = equity_pre_order_map.get(mid, 0)
eq_post_order = equity_post_order_map.get(mid, 0)
eq_order_total = eq_pre_order + eq_post_order
eq_income = equity_income_map.get(mid, Decimal('0'))
eq_delivery_penetration = _safe_pct(ext_order_total, delivery_cnt)
eq_unit_price = (eq_income / Decimal(str(eq_order_total))).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP) if eq_order_total > 0 else Decimal('0')
rows.append({
'merchant_name': mname,
'operate_mode': operate_mode,
'brand': brand,
'region': region,
'province': province,
'director': director,
'delivery_cnt': delivery_cnt,
# 延保
'ext_pre_touch': ext_pre_touch,
'ext_pre_touch_rate': ext_pre_touch_rate,
'ext_post_touch': ext_post_touch,
'ext_pre_order': ext_pre_order,
'ext_post_order': ext_post_order,
'ext_order_total': ext_order_total,
'ext_income': ext_income,
'ext_unit_price': ext_unit_price,
'ext_car_order': ext_car_order,
'ext_car_penetration': ext_car_penetration,
'ext_equity_order': ext_equity_order,
'ext_equity_penetration': ext_equity_penetration,
# 广联权益
'eq_pre_touch': eq_pre_touch,
'eq_pre_touch_rate': eq_pre_touch_rate,
'eq_post_touch': eq_post_touch,
'eq_pre_order': eq_pre_order,
'eq_post_order': eq_post_order,
'eq_order_total': eq_order_total,
'eq_income': eq_income,
'eq_pre_touch_convert_rate': eq_pre_touch_rate,
'eq_delivery_penetration': eq_delivery_penetration,
'eq_unit_price': eq_unit_price,
})
logger.info(f"[通用+权益] 数据组装完成,共 {len(rows)} 行")
return rows
# ============================================================
# 各数据源查询方法
# ============================================================
def _fetch_stores(self):
"""Step1: 基础门店列表 (dj_smartcarlife)"""
group_id = Config.COMMON_EQUITY_GROUP_ID
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT sr.merchant_id, sr.merchant_name, sm.province_name "
"FROM pg_group_store_rel sr "
"LEFT JOIN dj_car_life_service_merchant sm "
" ON sm.merchant_id = sr.merchant_id AND sm.deleted_flag = 'N' "
"WHERE sr.deleted_flag = 'N' "
" AND sr.group_id = :group_id"
)
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, {'group_id': group_id}).fetchall():
mid = r[0]
if mid:
result[mid] = {
'merchant_name': str(r[1] or '').strip(),
'province_name': str(r[2] or '').strip(),
}
eng.dispose()
logger.info(f"[通用+权益] 门店列表: {len(result)} 个")
return result
def _fetch_operate_mode(self, merchant_ids):
"""Step2: 运营模式 (dj_smartcarlife) — 有 partner_merchant_id=基准值 则直营"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
partner_id = Config.COMMON_EQUITY_PARTNER_MERCHANT_ID
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT smr.main_merchant_id, yc.partner_merchant_id "
"FROM dj_car_life_scene_merchant_ref smr "
"LEFT JOIN dj_car_life_yqmerchant_config yc "
" ON smr.sub_merchant_id = yc.merchant_id AND yc.deleted_flag = 'N' "
"WHERE smr.deleted_flag = 'N' "
" AND smr.main_merchant_type = 2 "
" AND smr.scene = 0 "
" AND smr.sub_merchant_type IN (6, 8) "
f" AND smr.main_merchant_id IN ({ph})"
)
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid = r[0]
pid = r[1]
if mid not in result:
result[mid] = '非直营'
if pid == partner_id:
result[mid] = '直营'
eng.dispose()
logger.info(f"[通用+权益] 运营模式: {len(result)} 个匹配")
return result
def _fetch_region(self, provinces):
"""Step3: 大区 (data_report 主库 region_province_mapping)"""
if not provinces:
return {}
p, ph = _in_params(provinces, 'p')
if p is None:
return {}
eng = create_engine(Config.SQLALCHEMY_DATABASE_URI, echo=False, pool_pre_ping=True)
sql = sa_text(
f"SELECT province_name, region_name FROM region_province_mapping "
f"WHERE province_name IN ({ph}) "
f"GROUP BY province_name, region_name"
)
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
prov = str(r[0] or '').strip()
region = str(r[1] or '').strip()
if prov and region and prov not in result:
result[prov] = region
eng.dispose()
logger.info(f"[通用+权益] 大区映射: {len(result)} 个省份")
return result
def _fetch_directors(self, merchant_ids):
"""Step4: 区域运营 (dj_smartcarlife)"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT merchant_id, GROUP_CONCAT(director_name SEPARATOR '/') AS director_names "
"FROM dj_car_life_shop_merchant_director_config "
"WHERE deleted_flag = 'N' AND director_type = 9 "
f"AND merchant_id IN ({ph}) "
"GROUP BY merchant_id"
)
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid = r[0]
names = str(r[1] or '').strip()
if mid and names:
result[mid] = names
eng.dispose()
logger.info(f"[通用+权益] 区域运营: {len(result)} 个匹配")
return result
def _fetch_brands(self, merchant_ids):
"""Step5: 品牌 (scrm_account → cyb_os)"""
# 5a: merchant_id → brand_ids
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng_scrm = _engine('SCRM_DATABASE_URL')
merchant_brands = defaultdict(set) # merchant_id → set(brand_id)
with eng_scrm.connect() as conn:
sql = sa_text(
"SELECT merchant_id, first_brand_id FROM platform_merchant_brand "
f"WHERE del_flag = 0 AND merchant_id IN ({ph})"
)
for r in conn.execute(sql, p).fetchall():
mid, bid = r[0], r[1]
if mid and bid:
merchant_brands[mid].add(bid)
eng_scrm.dispose()
# 5b: brand_id → brand_name
all_bids = set()
for bids in merchant_brands.values():
all_bids |= bids
bid_name = {}
if all_bids:
bp, bph = _in_params(list(all_bids), 'b')
eng_cyb = _engine('CYB_OS_DATABASE_URL')
with eng_cyb.connect() as conn:
sql = sa_text(f"SELECT bid, brand FROM platform_carbrand WHERE bid IN ({bph})")
for r in conn.execute(sql, bp).fetchall():
bid, nm = r[0], r[1]
if bid and nm:
bid_name[bid] = str(nm).strip()
eng_cyb.dispose()
# 组装: merchant_id → "品牌A/品牌B"
result = {}
for mid, bids in merchant_brands.items():
names = sorted({bid_name[b] for b in bids if b in bid_name})
if names:
result[mid] = '/'.join(names)
logger.info(f"[通用+权益] 品牌映射: {len(result)} 个商户")
return result
def _fetch_delivery_count(self, merchant_ids, start_str, end_str):
"""Step6: 门店交付台数 (dj_smartcarlife)"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT merchant_id, SUM(delivery_count) AS total "
"FROM dj_car_life_merchant_daily_report_huawei "
"WHERE deleted_flag = 'N' "
" AND brand_id = -1 AND first_brand_id = -1 and scene_type = 0"
f" AND merchant_id IN ({ph}) "
" AND report_date >= :start_date AND report_date <= :end_date "
"GROUP BY merchant_id"
)
p['start_date'] = start_str
p['end_date'] = end_str
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid, total = r[0], r[1]
if mid:
result[mid] = int(total or 0)
eng.dispose()
logger.info(f"[通用+权益] 交付台数: {len(result)} 个门店")
return result
def _fetch_extend_touch(self, merchant_ids, start_str, end_str):
"""Step7: 延保触客 (dj_smartcarlife staff_daily_report)"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT merchant_id, "
" SUM(extended_warranty_to_shop_count) AS pre_touch, "
" IFNULL(SUM(after_sale_extended_warranty_to_shop_count), 0) AS post_touch "
"FROM dj_car_life_staff_daily_report_huawei "
"WHERE deleted_flag = 'N' "
" AND brand_id = -1 AND first_brand_id = -1 "
" AND scene_type = 0 "
f" AND merchant_id IN ({ph}) "
" AND report_date >= :start_date AND report_date <= :end_date "
"GROUP BY merchant_id"
)
p['start_date'] = start_str
p['end_date'] = end_str
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid = r[0]
if mid:
result[mid] = {'pre': int(r[1] or 0), 'post': int(r[2] or 0)}
eng.dispose()
logger.info(f"[通用+权益] 延保触客: {len(result)} 个门店")
return result
def _fetch_extend_orders(self, merchant_ids, start_dt, end_dt, sales_type=0):
"""Step8: 延保订单 (售前 sales_type=0 / 售后 sales_type=1)"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT lgo.merchant_id, COUNT(DISTINCT gso.sub_order_code) AS subTotal "
"FROM dj_car_life_goods_sub_order gso "
"INNER JOIN dj_car_life_goods_order lgo ON gso.order_code = lgo.order_code "
"LEFT JOIN dj_car_life_goods_order_customer goc ON lgo.order_code = goc.order_code "
"LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
"WHERE gso.deleted_flag = 'N' AND lgo.deleted_flag = 'N' AND goc.deleted_flag = 'N' "
" AND lgo.base_scene_code IN (110201, 110202) "
f" AND goc.sales_type = {sales_type} "
" AND lgo.status = 4 "
" AND gso.supplier_code = 22 "
f" AND lgo.merchant_id IN ({ph}) "
" AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
"GROUP BY lgo.merchant_id"
)
p['start_dt'] = start_dt
p['end_dt'] = end_dt
result = {}
label = '售前' if sales_type == 0 else '售后'
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid, total = r[0], r[1]
if mid:
result[mid] = int(total or 0)
eng.dispose()
logger.info(f"[通用+权益] 延保{label}订单: {len(result)} 个门店")
return result
def _fetch_extend_income(self, merchant_ids, start_dt, end_dt):
"""Step9: 延保累计收入"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT lgo.merchant_id, IFNULL(SUM(lgo.total_price), 0) AS extendTotalPrice "
"FROM dj_car_life_goods_order lgo "
"LEFT JOIN dj_car_life_goods_sub_order gso ON gso.order_code = lgo.order_code "
"LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
"WHERE lgo.deleted_flag = 'N' AND gso.deleted_flag = 'N' "
" AND lgo.base_scene_code IN (110201, 110202) "
" AND lgo.status = 4 "
" AND gso.supplier_code = 22 "
f" AND lgo.merchant_id IN ({ph}) "
" AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
"GROUP BY lgo.merchant_id"
)
p['start_dt'] = start_dt
p['end_dt'] = end_dt
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid, total = r[0], r[1]
if mid:
result[mid] = _safe_decimal(total)
eng.dispose()
logger.info(f"[通用+权益] 延保累计收入: {len(result)} 个门店")
return result
def _fetch_extend_special_orders(self, merchant_ids, start_dt, end_dt, upgrade_goods_type):
"""Step10/11: 延保整车订单(155) / 原厂权益订单(126)"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT lgo.merchant_id, COUNT(DISTINCT gso.sub_order_code) AS subTotal "
"FROM dj_car_life_goods_sub_order gso "
"INNER JOIN dj_car_life_goods_order lgo ON gso.order_code = lgo.order_code "
"LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
"WHERE gso.deleted_flag = 'N' AND lgo.deleted_flag = 'N' "
" AND lgo.base_scene_code IN (110201, 110202) "
" AND lgo.status = 4 "
" AND gso.supplier_code = 22 "
f" AND gso.upgrade_goods_type = {upgrade_goods_type} "
f" AND lgo.merchant_id IN ({ph}) "
" AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
"GROUP BY lgo.merchant_id"
)
p['start_dt'] = start_dt
p['end_dt'] = end_dt
type_label = '整车' if upgrade_goods_type == 155 else '原厂权益'
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid, total = r[0], r[1]
if mid:
result[mid] = int(total or 0)
eng.dispose()
logger.info(f"[通用+权益] 延保{type_label}订单: {len(result)} 个门店")
return result
def _fetch_equity_touch(self, merchant_ids, start_str, end_str):
"""Step12: 广联权益触客 (dj_smartcarlife staff_daily_report)"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT merchant_id, "
" IFNULL(SUM(real_equity_to_shop_count), 0) AS pre_touch, "
" IFNULL(SUM(after_sale_real_equity_to_shop_count), 0) AS post_touch "
"FROM dj_car_life_staff_daily_report_huawei "
"WHERE deleted_flag = 'N' "
" AND brand_id = -1 AND first_brand_id = -1 "
" AND scene_type = 0 "
f" AND merchant_id IN ({ph}) "
" AND report_date >= :start_date AND report_date <= :end_date "
"GROUP BY merchant_id"
)
p['start_date'] = start_str
p['end_date'] = end_str
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid = r[0]
if mid:
result[mid] = {'pre': int(r[1] or 0), 'post': int(r[2] or 0)}
eng.dispose()
logger.info(f"[通用+权益] 广联权益触客: {len(result)} 个门店")
return result
def _fetch_equity_orders(self, merchant_ids, start_dt, end_dt, sales_type=0):
"""Step13: 广联权益订单 (售前 sales_type=0 / 售后 sales_type=1)"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT lgo.merchant_id, COUNT(DISTINCT gso.sub_order_code) AS subTotal "
"FROM dj_car_life_goods_sub_order gso "
"INNER JOIN dj_car_life_goods_order lgo ON gso.order_code = lgo.order_code "
"LEFT JOIN dj_car_life_goods_order_customer goc ON lgo.order_code = goc.order_code "
"LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
"WHERE gso.deleted_flag = 'N' AND lgo.deleted_flag = 'N' AND goc.deleted_flag = 'N' "
" AND lgo.scene_type = 0 "
f" AND goc.sales_type = {sales_type} "
" AND lgo.status = 4 "
" AND gso.supplier_code = 12 "
f" AND lgo.merchant_id IN ({ph}) "
" AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
"GROUP BY lgo.merchant_id"
)
p['start_dt'] = start_dt
p['end_dt'] = end_dt
label = '售前' if sales_type == 0 else '售后'
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid, total = r[0], r[1]
if mid:
result[mid] = int(total or 0)
eng.dispose()
logger.info(f"[通用+权益] 广联权益{label}订单: {len(result)} 个门店")
return result
def _fetch_equity_income(self, merchant_ids, start_dt, end_dt):
"""Step14: 广联权益累计收入"""
p, ph = _in_params(merchant_ids, 'm')
if p is None:
return {}
eng = _engine('BIZ_SQL_DATABASE_URL')
sql = sa_text(
"SELECT lgo.merchant_id, IFNULL(SUM(lgo.total_price), 0) AS equityTotalPrice "
"FROM dj_car_life_goods_order lgo "
"LEFT JOIN dj_car_life_goods_sub_order gso ON gso.order_code = lgo.order_code "
"LEFT JOIN dj_car_life_pay_order dclpo ON lgo.order_code = dclpo.order_code AND dclpo.deleted_flag = 'N' "
"WHERE lgo.deleted_flag = 'N' AND gso.deleted_flag = 'N' "
" AND lgo.scene_type = 0 "
" AND lgo.status = 4 "
" AND gso.supplier_code = 12 "
f" AND lgo.merchant_id IN ({ph}) "
" AND dclpo.success_date >= :start_dt AND dclpo.success_date <= :end_dt "
"GROUP BY lgo.merchant_id"
)
p['start_dt'] = start_dt
p['end_dt'] = end_dt
result = {}
with eng.connect() as conn:
for r in conn.execute(sql, p).fetchall():
mid, total = r[0], r[1]
if mid:
result[mid] = _safe_decimal(total)
eng.dispose()
logger.info(f"[通用+权益] 广联权益累计收入: {len(result)} 个门店")
return result
# ============================================================
# 结果 Excel 生成
# ============================================================
# 输出列定义:(表头名, 数据 key, 类型)
# 类型:'text' / 'int' / 'decimal' / 'pct'
RESULT_COLUMNS = [
# 基础字段 A~G
('4s店', 'merchant_name', 'text'),
('运营模式', 'operate_mode', 'text'),
('品牌', 'brand', 'text'),
('大区', 'region', 'text'),
('省份', 'province', 'text'),
('区域运营', 'director', 'text'),
('门店交付台数', 'delivery_cnt', 'int'),
# 延保 H~R
('售前触客', 'ext_pre_touch', 'int'),
('售前触客率', 'ext_pre_touch_rate', 'pct'),
('售后触客', 'ext_post_touch', 'int'),
('售前订单', 'ext_pre_order', 'int'),
('售后订单', 'ext_post_order', 'int'),
('订单数合计', 'ext_order_total', 'int'),
('累计收入', 'ext_income', 'decimal'),
('客单价', 'ext_unit_price', 'decimal'),
('整车订单数', 'ext_car_order', 'int'),
('整车渗透率', 'ext_car_penetration', 'pct'),
('原厂权益订单数', 'ext_equity_order', 'int'),
('权益渗透率', 'ext_equity_penetration', 'pct'),
# 广联权益 S~AB
('售前触客', 'eq_pre_touch', 'int'),
('售前触客率', 'eq_pre_touch_rate', 'pct'),
('售后触客', 'eq_post_touch', 'int'),
('售前订单', 'eq_pre_order', 'int'),
('售后订单', 'eq_post_order', 'int'),
('订单数合计', 'eq_order_total', 'int'),
('累计收入', 'eq_income', 'decimal'),
('售前触客转化率', 'eq_pre_touch_convert_rate', 'pct'),
('交付渗透率', 'eq_delivery_penetration', 'pct'),
('客单价', 'eq_unit_price', 'decimal'),
]
def generate_result_excel(self, task, data):
"""根据聚合数据生成《通用+权益》结果 Excel 并上传,返回 URL。
行结构:
行1: 两级表头(基础字段合并行1-2,延保/广联权益各有上级表头)
行2: 子表头
行3+: 数据行
"""
task_id = task.id
period_start = task.period_start
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
# ---------- 构建工作簿 ----------
wb = openpyxl.Workbook()
ws = wb.active
ws.title = '门店展示表'
# 样式定义
header_font = Font(name='微软雅黑', size=11, bold=True, color='FFFFFF')
header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
cell_font = Font(name='微软雅黑', size=10)
center = Alignment(horizontal='center', vertical='center', wrap_text=True)
right_align = Alignment(horizontal='right', vertical='center')
thin = Border(
left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin'),
)
total_cols = len(self.RESULT_COLUMNS) # 29列
# ---------- 行1-2: 两级表头 ----------
# 基础字段(A~G, 列1-7):行1-2 合并
basic_cols = 7
for i in range(basic_cols):
col = i + 1
header, _, _ = self.RESULT_COLUMNS[i]
cell = ws.cell(row=1, column=col, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center
cell.border = thin
ws.merge_cells(start_row=1, start_column=col, end_row=2, end_column=col)
# 延保上级表头(H~R, 列8-19):行1 合并
extend_start = 8
extend_end = 19
cell = ws.cell(row=1, column=extend_start, value='延保')
cell.font = header_font
cell.fill = header_fill
cell.alignment = center
cell.border = thin
ws.merge_cells(start_row=1, start_column=extend_start, end_row=1, end_column=extend_end)
# 补边框(合并区域中间列)
for c in range(extend_start + 1, extend_end + 1):
ws.cell(row=1, column=c).border = thin
# 延保子表头(行2)
for i in range(extend_start - 1, extend_end):
col = i + 1
header, _, _ = self.RESULT_COLUMNS[i]
cell = ws.cell(row=2, column=col, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center
cell.border = thin
# 广联权益上级表头(S~AB, 列20-29):行1 合并
equity_start = 20
equity_end = total_cols
cell = ws.cell(row=1, column=equity_start, value='广联权益')
cell.font = header_font
cell.fill = header_fill
cell.alignment = center
cell.border = thin
ws.merge_cells(start_row=1, start_column=equity_start, end_row=1, end_column=equity_end)
# 补边框
for c in range(equity_start + 1, equity_end + 1):
ws.cell(row=1, column=c).border = thin
# 广联权益子表头(行2)
for i in range(equity_start - 1, equity_end):
col = i + 1
header, _, _ = self.RESULT_COLUMNS[i]
cell = ws.cell(row=2, column=col, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center
cell.border = thin
# ---------- 行3+: 数据行 ----------
for row_idx, row_data in enumerate(data, start=3):
for col_idx, (_header, key, kind) in enumerate(self.RESULT_COLUMNS, start=1):
val = row_data.get(key)
cell = ws.cell(row=row_idx, column=col_idx)
cell.border = thin
if kind == 'text':
cell.value = str(val) if val else ''
cell.font = cell_font
cell.alignment = center
elif kind == 'int':
try:
cell.value = int(val) if val else 0
cell.number_format = '#,##0'
except (ValueError, TypeError):
cell.value = 0
cell.font = cell_font
cell.alignment = right_align
elif kind == 'decimal':
try:
cell.value = float(val) if val else 0.0
cell.number_format = '#,##0.00'
except (ValueError, TypeError):
cell.value = 0.0
cell.font = cell_font
cell.alignment = right_align
elif kind == 'pct':
try:
cell.value = float(val) if val else 0.0
cell.number_format = '0.00"%"'
except (ValueError, TypeError):
cell.value = 0.0
cell.font = cell_font
cell.alignment = right_align
# ---------- 列宽 ----------
col_widths = {
'4s店': 20, '运营模式': 10, '品牌': 15, '大区': 10, '省份': 16,
'区域运营': 14, '门店交付台数': 12,
'售前触客': 10, '售前触客率': 12, '售后触客': 10,
'售前订单': 10, '售后订单': 10, '订单数合计': 12,
'累计收入': 14, '客单价': 10, '整车订单数': 12,
'整车渗透率': 12, '原厂权益订单数': 14, '权益渗透率': 12,
'售前触客转化率': 14, '交付渗透率': 12,
}
for i, (header, _key, _kind) in enumerate(self.RESULT_COLUMNS, start=1):
col_letter = openpyxl.utils.get_column_letter(i)
ws.column_dimensions[col_letter].width = col_widths.get(header, 12)
# 冻结窗格(冻结表头行)
ws.freeze_panes = 'A3'
ws.row_dimensions[1].height = 24
ws.row_dimensions[2].height = 30
# ---------- 保存 + 上传 ----------
tmp_dir = tempfile.mkdtemp(prefix=f'common_equity_{task_id}_')
try:
period_label = start_str.replace('-', '') if start_str else 'unknown'
excel_path = os.path.join(tmp_dir, f'通用+权益_{period_label}.xlsx')
wb.save(excel_path)
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
f"/common_equity_{period_label}_{task_id}.xlsx")
file_url = upload_file(excel_path, object_key)
logger.info(f"[通用+权益] 结果表已生成并上传: {file_url}({len(data)} 行数据)")
return file_url
finally:
cleanup_tmp_dir(tmp_dir)
python : C:\Users\11\AppData\Local\Programs\Python\Python312\Lib\site-packages\openpyxl\worksheet\_reader.py:329: UserW
arning: Unknown extension is not supported and will be removed
At line:15 char:3205
+ ... data-process"; python _compare_cols.py > compare_out.txt 2>&1; Get-Co ...
+ ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
+ CategoryInfo : NotSpecified: (C:\Users\11\App...will be removed:String) [], RemoteException
+ FullyQualifiedErrorId : NativeCommandError
warn(msg)
C:\Users\11\AppData\Local\Programs\Python\Python312\Lib\site-packages\openpyxl\worksheet\_reader.py:329: UserWarning: C
onditional Formatting extension is not supported and will be removed
warn(msg)
======================================================================
【延保】模板 sheet: 延保 表头行: row1
模板表头列数: 39
ORM 模型字段数: 46
col_map 条目数: 39
✅ col1: "序号" -> None(序号列)
✅ col2: "片区" -> region_area
✅ col3: "省份" -> province
✅ col4: "城市" -> city
✅ col5: "区域运营" -> region_manager
✅ col6: "培训督导" -> training_supervisor
✅ col7: "业务经理" -> biz_manager
✅ col8: "驻店类型" -> resident_type
✅ col9: "门店名" -> store_name
✅ col10: "品牌" -> brand
✅ col11: "交车" -> delivery_cnt
✅ col12: "触客" -> touch_cnt
✅ col13: "成交数" -> deal_cnt
✅ col14: "渗透率" -> penetration_rate
✅ col15: "整车延保成交数" -> vehicle_warranty_cnt
✅ col16: "整车延保渗透率" -> vehicle_warranty_penetration
✅ col17: "整车延保触客成交率" -> vehicle_warranty_touch_convert
✅ col18: "电池成交数" -> battery_warranty_cnt
✅ col19: "电池渗透率" -> battery_warranty_penetration
✅ col20: "安心包成交数" -> easy_bag_cnt
✅ col21: "安心包渗透率" -> easy_bag_penetration
✅ col22: "门店产值" -> store_output_value
✅ col23: "升级客单价" -> upgrade_unit_price
✅ col24: "商品成本" -> product_cost
✅ col25: "门店分成" -> store_share
✅ col26: "兜底金额" -> guarantee_amount
✅ col27: "广联分成" -> gl_share
✅ col28: "市场费" -> market_fee
✅ col29: "市场费占比" -> market_fee_ratio
✅ col30: "营销费用" -> marketing_fee
✅ col31: "营销费用占比" -> marketing_fee_ratio
✅ col32: "服务费用" -> service_fee
✅ col33: "服务费用占比" -> service_fee_ratio
✅ col34: "成本总计" -> total_cost
✅ col35: "成本占比" -> cost_ratio
✅ col36: "毛利测算" -> gross_profit
✅ col37: "预估毛利率" -> gross_profit_rate
✅ col38: "预估毛利情况" -> gross_profit_status
✅ col39: "门店毛利排名" -> gross_profit_rank
ORM 字段未在 col_map 中覆盖 (8 个):
- created_at
- deleted_at
- id
- is_deleted
- period_end
- period_start
- task_id
- updated_at
======================================================================
【权益】模板 sheet: 权益 表头行: row1
模板表头列数: 32
ORM 模型字段数: 39
col_map 条目数: 32
✅ col1: "序号" -> None(序号列)
✅ col2: "片区" -> region_area
✅ col3: "省份" -> province
✅ col4: "城市" -> city
✅ col5: "区域运营" -> region_manager
✅ col6: "培训督导" -> training_supervisor
✅ col7: "业务经理" -> biz_manager
✅ col8: "驻店类型" -> resident_type
✅ col9: "门店名" -> store_name
✅ col10: "品牌" -> brand
✅ col11: "交车" -> delivery_cnt
✅ col12: "触客" -> touch_cnt
✅ col13: "成交数" -> deal_cnt
✅ col14: "渗透率" -> penetration_rate
✅ col15: "门店产值" -> store_output_value
✅ col16: "升级客单价" -> upgrade_unit_price
✅ col17: "商品成本" -> product_cost
✅ col18: "门店分成" -> store_share
✅ col19: "兜底金额" -> guarantee_amount
✅ col20: "广联分成" -> gl_share
✅ col21: "市场费" -> market_fee
✅ col22: "市场费占比" -> market_fee_ratio
✅ col23: "营销费用" -> marketing_fee
✅ col24: "营销费用占比" -> marketing_fee_ratio
✅ col25: "服务费用" -> service_fee
✅ col26: "服务费用占比" -> service_fee_ratio
✅ col27: "成本总计" -> total_cost
✅ col28: "成本占比" -> cost_ratio
✅ col29: "毛利测算" -> gross_profit
✅ col30: "预估毛利率" -> gross_profit_rate
✅ col31: "预估毛利情况" -> gross_profit_status
✅ col32: "门店毛利排名" -> gross_profit_rank
ORM 字段未在 col_map 中覆盖 (8 个):
- created_at
- deleted_at
- id
- is_deleted
- period_end
- period_start
- task_id
- updated_at
======================================================================
【店中店】模板 sheet: 店中店汇总 表头行: row2
模板表头列数: 78
ORM 模型字段数: 90
col_map 条目数: 78
✅ col1: "序号" -> None(序号列)
✅ col2: "大区名称" -> region_area
✅ col3: "区域(省)" -> province
✅ col4: "区域 (市)" -> city
✅ col5: "园区类型" -> park_type
✅ col6: "业务线" -> biz_line
✅ col7: "经营属性" -> operate_type
✅ col8: "区域经理" -> region_manager
✅ col9: "园区名称" -> park_name
✅ col10: "门店名称" -> store_name
✅ col11: "品牌(问界/鸿蒙)" -> brand
✅ col12: "品牌分类" -> brand_category
✅ col13: "采买/兜底指标" -> purchase_indicator
✅ col14: "销售大定数" -> sales_order_cnt
✅ col15: "销售触客数" -> sales_touch_cnt
✅ col16: "销售触客率" -> sales_touch_rate
✅ col17: "交车数" -> delivery_cnt
✅ col18: "交付触客数" -> delivery_touch_cnt
✅ col19: "交付触客率" -> delivery_touch_rate
✅ col20: "售后首保回厂数" -> aftersales_baohui_cnt
✅ col21: "售后事故回厂数" -> aftersales_shigu_cnt
✅ col22: "售后触客数" -> aftersales_touch_cnt
✅ col23: "售后触客率" -> aftersales_touch_rate
✅ col24: "总触客数" -> total_touch_cnt
✅ col25: "总成交数" -> total_deal_cnt
✅ col26: "窗膜/成交数" -> window_film_oe_cnt
✅ col28: "车衣/成交数" -> car_wrap_oe_cnt
✅ col30: "精品/成交数" -> premium_oe_cnt
✅ col32: "踏板" -> pedal_cnt
✅ col33: "门店总产值" -> store_output_value
✅ col34: "内部结算产值" -> internal_settle_value
✅ col35: "合计总产值" -> total_output_value
✅ col36: "原厂总产值" -> oe_output_value
✅ col37: "副厂总产值" -> nonoe_output_value
✅ col38: "平均客单价(交车)" -> avg_unit_price_delivery
✅ col39: "平客目标值" -> avg_price_target
✅ col40: "平客差值" -> avg_price_diff
✅ col41: "交付触客客单价" -> delivery_touch_unit_price
✅ col42: "升级客单价" -> upgrade_unit_price
✅ col43: "总订单渗率" -> total_penetration_rate
✅ col44: "窗膜渗透率" -> window_film_penetration
✅ col45: "车衣渗透率" -> car_wrap_penetration
✅ col46: "精品渗透率" -> premium_penetration
✅ col47: "产品成本/(财务列表)" -> product_cost_finance
✅ col48: "内部结算成本/(财务列表)" -> internal_settle_cost
✅ col49: "原厂产品成本/(财务列表)" -> oe_product_cost
✅ col50: "副厂产品成本/(财务列表)" -> nonoe_product_cost
✅ col51: "窗膜成本" -> window_film_cost
✅ col52: "车衣成本" -> car_wrap_cost
✅ col53: "精品成本" -> premium_cost
✅ col54: "产品总成本/(占比)" -> product_cost_ratio
✅ col55: "施工成本" -> construction_cost
✅ col57: "施工成本占比" -> construction_cost_ratio
✅ col58: "一线激励" -> frontline_incentive
✅ col59: "一线激励(占比)" -> frontline_incentive_ratio
✅ col60: "进销差/(未分成)" -> gross_profit_pre_share
✅ col61: "进销差/占比" -> gross_profit_pre_share_ratio
✅ col62: "门店分成/流量费/(财务列表)" -> store_share
✅ col63: "门店分成" -> store_share_per_car
✅ col64: "门店单车利润" -> guarantee_amount
✅ col65: "兜底金额情况" -> gl_share
✅ col66: "兜底金额" -> gl_share_ratio
✅ col67: "广联分成" -> construction_income
✅ col68: "广联分成/(占比)" -> internal_settle_profit
✅ col69: "施工收入" -> gl_total_share
✅ col70: "内部结算" -> marketing_personnel_cost
✅ col71: "广联总分成" -> marketing_personnel_ratio
✅ col72: "营销人员成本" -> market_fee
✅ col73: "营销人员成本占比" -> market_fee_ratio
✅ col74: "施工成本" -> renovation_amortization
✅ col75: "施工成本占比" -> rent_utilities
✅ col76: "市场费" -> store_consumables
✅ col77: "市场费成本(占比)" -> service_provider_share
✅ col78: "装修分摊" -> service_provider_share_ratio
✅ col79: "房租、水电费用" -> total_cost
✅ col80: "门店耗材" -> cost_ratio
✅ col81: "服务商分成/(商务报表)" -> gross_profit
✅ col82: "服务商分成/占比" -> gross_profit_rate
ORM 字段未在 col_map 中覆盖 (13 个):
- car_wrap_nonoe_cnt
- created_at
- deleted_at
- gross_profit_rank
- gross_profit_status
- id
- is_deleted
- period_end
- period_start
- premium_nonoe_cnt
- task_id
- updated_at
- window_film_nonoe_cnt
======================================================================
【园区店】模板 sheet: 园区店汇总 表头行: row2
模板表头列数: 69
ORM 模型字段数: 76
col_map 条目数: 69
✅ col1: "序号" -> None(序号列)
✅ col2: "大区名称" -> region_area
✅ col3: "区域(省)" -> province
✅ col4: "区域 (市)" -> city
✅ col5: "园区类型" -> park_type
✅ col6: "经营属性" -> operate_type
✅ col7: "合作门店数量" -> partner_store_cnt
✅ col8: "区域经理" -> region_manager
✅ col9: "园区名称" -> park_name
✅ col10: "门店名称" -> store_name
✅ col11: "品牌" -> brand
✅ col12: "类型" -> biz_type
✅ col13: "采买/兜底指标/(流量费)" -> purchase_indicator
✅ col14: "交车数" -> delivery_cnt
✅ col15: "到店数" -> arrival_cnt
✅ col16: "到店无效客户数" -> arrival_invalid_cnt
✅ col17: "无效/到店率" -> invalid_arrival_rate
✅ col18: "到店率" -> arrival_rate
✅ col19: "成交数" -> deal_cnt
✅ col20: "转化率" -> conversion_rate
✅ col21: "门店销售产值" -> store_sales_output
✅ col22: "内部结算产值" -> internal_settle_value
✅ col23: "合计总产值" -> total_output_value
✅ col24: "产值达成进度" -> output_progress
✅ col25: "平均客单价(到店)" -> avg_unit_price_arrival
✅ col26: "平客目标值" -> avg_price_target
✅ col27: "平客差值" -> avg_price_diff
✅ col28: "升级客单价" -> upgrade_unit_price
✅ col29: "窗膜成交数" -> window_film_cnt
✅ col30: "车衣成交数" -> car_wrap_cnt
✅ col31: "精品成交数" -> premium_cnt
✅ col32: "窗膜转化率" -> window_film_convert
✅ col33: "车衣转化率" -> car_wrap_convert
✅ col34: "精品转化率" -> premium_convert
✅ col35: "商务上架预估流量" -> est_traffic
✅ col36: "预估/交车数" -> est_delivery_cnt
✅ col37: "预估总产值/(预算目标)" -> est_output_value
✅ col38: "产品成本/(财务列表)" -> product_cost_finance
✅ col39: "产品成本占比" -> product_cost_ratio
✅ col40: "内部结算成本/(财务列表)" -> internal_settle_cost
✅ col41: "流量费/(财务列表)" -> traffic_fee_finance
✅ col42: "按单台计算流量/台" -> traffic_fee_per_car
✅ col43: "按台次计算流量费" -> traffic_fee_order
✅ col44: "门店流量费" -> store_traffic_fee
✅ col45: "流量费率/(列表测算)" -> traffic_fee_ratio
✅ col46: "广联分成" -> gl_share
✅ col47: "广联分成/(占比)" -> gl_share_ratio
✅ col48: "内部结算" -> internal_settle_profit
✅ col49: "广联总分成" -> gl_total_share
✅ col50: "人员成本" -> personnel_cost
✅ col51: "常规人员费率/(加权参考)" -> personnel_cost_ratio
✅ col52: "施工成本" -> construction_cost
✅ col53: "施工成本占比" -> construction_cost_ratio
✅ col54: "市场费/(加权测算)" -> market_fee_weighted
✅ col55: "市场费费率/(加权参考)" -> market_fee_weighted_ratio
✅ col56: "服务费/(商务报表)" -> service_fee
✅ col57: "服务费费率/(加权参考)" -> service_fee_ratio
✅ col58: "装修分摊/(商务报表)" -> renovation_amortization
✅ col59: "装修占比" -> renovation_ratio
✅ col60: "房租、水电费用" -> rent_utilities
✅ col61: "房租、水电占比" -> rent_utilities_ratio
✅ col62: "门店耗材" -> store_consumables
✅ col63: "门店耗材占比" -> store_consumables_ratio
✅ col64: "成本总计" -> total_cost
✅ col65: "总计占比" -> cost_ratio
✅ col66: "毛利测算" -> gross_profit
✅ col67: "毛利率" -> gross_profit_rate
✅ col68: "毛利情况" -> gross_profit_status
✅ col69: "门店毛利排名" -> gross_profit_rank
ORM 字段未在 col_map 中覆盖 (8 个):
- created_at
- deleted_at
- id
- is_deleted
- period_end
- period_start
- task_id
- updated_at
...@@ -85,16 +85,55 @@ class Config: ...@@ -85,16 +85,55 @@ class Config:
SCHEDULER_ENABLED = os.getenv('SCHEDULER_ENABLED', 'true').lower() == 'true' SCHEDULER_ENABLED = os.getenv('SCHEDULER_ENABLED', 'true').lower() == 'true'
SCHEDULER_INTERVAL_SECONDS = int(os.getenv('SCHEDULER_INTERVAL_SECONDS', '60')) SCHEDULER_INTERVAL_SECONDS = int(os.getenv('SCHEDULER_INTERVAL_SECONDS', '60'))
# ---------- 指标系统 API ----------
INDICATOR_API_URL = os.getenv('INDICATOR_API_URL', 'http://dc.glsx.com.cn/data')
INDICATOR_API_TIMEOUT = int(os.getenv('INDICATOR_API_TIMEOUT', '10')) # 秒
INDICATOR_API_RETRY = int(os.getenv('INDICATOR_API_RETRY', '2')) # 失败重试次数
# biz 编码:1=延保 2=轻改 3=权益
INDICATOR_BIZ_WARRANTY = 1
INDICATOR_BIZ_LIGHT_REFORM = 2
INDICATOR_BIZ_EQUITY = 3
# ---------- 通用+权益:直营判定基准商户号 ----------
COMMON_EQUITY_PARTNER_MERCHANT_ID = int(os.getenv('COMMON_EQUITY_PARTNER_MERCHANT_ID', '44206988'))
COMMON_EQUITY_GROUP_ID = int(os.getenv('COMMON_EQUITY_GROUP_ID', '12'))
# ---------- 业务系统 SQL 数据源(嘀加 dj_smartcarlife 库)----------
BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'true').lower() == 'true'
BIZ_SQL_DATABASE_URL = os.getenv(
'BIZ_SQL_DATABASE_URL',
'mysql+pymysql://read_dj_smartcarlife:X9RNTOLr@192.168.5.23:3306/dj_smartcarlife?charset=utf8mb4'
)
# ---------- 商户关系 / 品牌数据源(新增门店判定,3 库关联)----------
# scrm_account:platform_merchant_brand(商户↔品牌,merchant_id=main_merchant_id)
# 用户提供的只读账号:read_scrm_account @ 192.168.5.1:3310
SCRM_DATABASE_URL = os.getenv(
'SCRM_DATABASE_URL',
'mysql+pymysql://read_scrm_account:TnZobW2b@192.168.5.1:3310/scrm_account?charset=utf8mb4'
)
# cyb_os:platform_carbrand(bid↔品牌名 字典表,bid 对应 first_brand_id / sec_brand_id)
# 用户提供的只读账号
CYB_OS_DATABASE_URL = os.getenv(
'CYB_OS_DATABASE_URL',
'mysql+pymysql://read_cyb_os:ebf6C0D6@192.168.5.5:3311/cyb_os?charset=utf8mb4'
)
# ---------- 文件上传 ---------- # ---------- 文件上传 ----------
MAX_CONTENT_LENGTH = 100 * 1024 * 1024 # 单文件最大 100M MAX_CONTENT_LENGTH = 100 * 1024 * 1024 # 单文件最大 100M
ALLOWED_EXTS = {'.xlsx', '.xls'} # 仅支持 Excel ALLOWED_EXTS = {'.xlsx', '.xls'} # 仅支持 Excel
UPLOAD_FOLDER = BASE_DIR / 'uploads' UPLOAD_FOLDER = BASE_DIR / 'uploads'
# ---------- 数据表类型配置(第一期仅预算达成数据)---------- # ---------- 数据表类型配置 ----------
# forms: 该类型所需的表单类型清单,前端附件上传区据此动态渲染 # forms: 该类型所需的表单类型清单,前端附件上传区据此动态渲染
# need_period: 是否需要「所属周期」(日期区间)字段;
# True => 新增/重新生成时展示并必填,默认当月1号~最后一天;
# False => 不展示该字段,默认取整月(如:预算达成数据)。
DATA_TABLE_TYPES = { DATA_TABLE_TYPES = {
'budget_achievement': { 'budget_achievement': {
'name': '预算达成数据', 'name': '预算达成数据',
'need_period': False,
'support_week': False,
'forms': [ 'forms': [
'结算数据汇总表', '结算数据汇总表',
'市场费总表', '市场费总表',
...@@ -105,8 +144,68 @@ class Config: ...@@ -105,8 +144,68 @@ class Config:
'门店资产耗材明细表', '门店资产耗材明细表',
], ],
}, },
'future_expansion': { 'store_effect_earnings': {
'name': '未来拓展', 'name': '店效人效及盈利测算',
'need_period': True,
'support_week': False,
'forms': [
'SAAS门店预算分解表',
'关系表',
'店中店交车触客表',
'园区店交车触客表',
'广联主机厂数据表',
'鸿蒙主机厂数据表',
'商务政策表(园区店)',
'商务政策表(店中店)',
'人力成本表',
'二手车收购与销售台账',
'预算达成数据(商务)',
],
},
'output_value': {
'name': '产值达成表',
'need_period': True,
'support_week': False,
'forms': [
'SAAS门店预算分解表',
'关系表',
],
},
# 阿维塔专项:当前仅需上传主机厂数据表(表名暂定,后续若改名只改下方 forms)。
# 注意:此「主机厂数据表」为阿维塔专项独立数据表,格式不保证与现有
# 「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,切勿复用
# report_utils.parse_delivery_table(鸿蒙/广联共用结构);
# 后续接入引擎时须按用户实际提供的附件字段解析并写入阿维塔专属结果表。
# 'avita_special': {
# 'name': '阿维塔专项',
# 'need_period': False,
# 'support_week': False,
# 'forms': [
# '主机厂数据表',
# ],
# },
# 零跑专项 / 岚图专项:无需上传 Excel,need_period=True 需要所属周期
'leapmotor_special': {
'name': '零跑专项',
'need_period': True,
'support_week': False,
'forms': [],
},
'voyah_special': {
'name': '岚图专项',
'need_period': True,
'support_week': False,
'forms': [], 'forms': [],
}, },
# 通用+权益:支持按月/按周粒度,含 3 个附件
# 'common_equity': {
# 'name': '通用+权益',
# 'need_period': True,
# 'support_week': True,
# 'forms': [
# '区域维度数据',
# '汇总区数据',
# '红黄门店数据',
# ],
# },
} }
import sys
sys.path.insert(0, "F:/data-report/data-process")
from app import app, db
from models import ReportLightReformInshop, ReportLightReformPark
from sqlalchemy import func, text
with app.app_context():
# how many rows / task linkage
print("== inshop rows ==")
inshop_all = db.session.query(ReportLightReformInshop).all()
print("inshop total rows:", len(inshop_all))
# distinct task_id / period
q = db.session.query(ReportLightReformInshop.task_id,
func.min(ReportLightReformInshop.period_start),
func.max(ReportLightReformInshop.period_end),
func.count(),
func.sum(ReportLightReformInshop.total_output_value))\
.group_by(ReportLightReformInshop.task_id).all()
for tid, ps, pe, cnt, s in q:
print(f" task_id={tid} period={ps}~{pe} rows={cnt} SUM(合计总产值)={float(s) if s is not None else None}")
print("== park rows ==")
park_all = db.session.query(ReportLightReformPark).all()
print("park total rows:", len(park_all))
q2 = db.session.query(ReportLightReformPark.task_id,
func.min(ReportLightReformPark.period_start),
func.max(ReportLightReformPark.period_end),
func.count(),
func.sum(ReportLightReformPark.total_output_value))\
.group_by(ReportLightReformPark.task_id).all()
for tid, ps, pe, cnt, s in q2:
print(f" task_id={tid} period={ps}~{pe} rows={cnt} SUM(合计总产值)={float(s) if s is not None else None}")
# Also check a few sample rows' total_output_value to see if non-zero
print("== sample inshop total_output_value (first 5) ==")
for r in inshop_all[:5]:
print(f" store={r.store_name!r} 合计总产值={float(r.total_output_value) if r.total_output_value is not None else None} 门店总产值={float(r.store_output_value) if r.store_output_value is not None else None}")
print("== sample park total_output_value (first 5) ==")
for r in park_all[:5]:
print(f" store={r.store_name!r} 合计总产值={float(r.total_output_value) if r.total_output_value is not None else None} 门店总产值={float(r.store_output_value) if r.store_output_value is not None else None}")
import openpyxl
path = r"F:/data-report/data-process/outputs/store_effect_summary/门店店效人效汇总表_2026-08.xlsx"
wb = openpyxl.load_workbook(path, data_only=True)
ws = wb['总看板']
# find 1.1产值 / 1.1预算 labels
targets = ['1.1产值','1.1预算','2.1产值','2.3产值','全国经营总产值']
for row in ws.iter_rows():
for c in row:
if c.value in targets:
# value is 2 cells to the right (label, value) per layout A=label B=value
col = c.column
valcell = ws.cell(row=c.row, column=col+1)
print(f"row{c.row} col{col} {c.value!r} -> {valcell.value!r}")
import sys
sys.path.insert(0, "F:/data-report/data-process")
from report_utils import fetch_indicator_data, INDICATOR_BIZ_MAP
bz_l = INDICATOR_BIZ_MAP.get('light_reform')
print("light_reform biz =", bz_l)
ind_11 = fetch_indicator_data('2026-08-01', '2026-08-31', [bz_l], ['A036', 'A075', 'A084']) or {}
print("ind_11 entries:", len(ind_11))
tot_A036 = sum(float((v or {}).get('A036') or 0) for v in ind_11.values())
print("SUM A036 over matched merchants:", tot_A036)
# also test A0018 full
ind_total = fetch_indicator_data('2026-08-01', '2026-08-31', None, ['A0018']) or {}
print("A0018 entries:", len(ind_total), "SUM:", sum(float((v or {}).get('A0018') or 0) for v in ind_total.values()))
import sys
sys.path.insert(0, "F:/data-report/data-process")
import build_store_effect_board as B
from report_utils import fetch_indicator_data, INDICATOR_BIZ_MAP
from decimal import Decimal
src = r"C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源"
s1, s2 = B.parse_saas(src)
stores_11 = B.uniq(s2)
print("1.1 stores (sheet2 unique):", len(stores_11))
bz_l = INDICATOR_BIZ_MAP.get('light_reform')
ind_11 = fetch_indicator_data('2026-08-01', '2026-08-31', [bz_l], ['A036', 'A075', 'A084']) or {}
def ind_sum(ind_map, stores, code):
t = Decimal('0')
matched = []
for nm, vals in (ind_map or {}).items():
if B.match_any(nm, stores):
v = B.to_decimal((vals or {}).get(code))
t += v
matched.append((nm, float(v)))
return t, matched
t11, matched11 = ind_sum(ind_11, stores_11, 'A036')
print("BOARD 1.1产值 (indicator A036 matched to 1.1 stores) =", float(t11))
print(" matched merchants:", len(matched11))
for nm, v in matched11[:10]:
print(f" {nm!r}: {v}")
import sys
sys.path.insert(0, "F:/data-report/data-process")
import build_store_effect_board as B
from report_utils import fetch_indicator_data, INDICATOR_BIZ_MAP
from decimal import Decimal
src = r"C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源"
s1, s2 = B.parse_saas(src)
stores_11 = {r['store'] for r in s2 if r['store']}
print("1.1 stores (sheet2 unique):", len(stores_11))
bz_l = INDICATOR_BIZ_MAP.get('light_reform')
ind_11 = fetch_indicator_data('2026-08-01', '2026-08-31', [bz_l], ['A036', 'A075', 'A084']) or {}
def ind_sum(ind_map, stores, code):
t = Decimal('0'); matched = []
for nm, vals in (ind_map or {}).items():
if B.match_any(nm, stores):
v = B.to_decimal((vals or {}).get(code)); t += v; matched.append((nm, float(v)))
return t, matched
t11, matched11 = ind_sum(ind_11, stores_11, 'A036')
print("BOARD 1.1产值 (indicator A036 matched to 1.1 stores) =", float(t11))
print(" matched merchants:", len(matched11))
for nm, v in matched11[:12]:
print(f" {nm!r}: {v}")
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 延保表独立处理器
====================================
对应 ORM 表:report_extended_warranty
业务类型过滤:biz_type=2.3 (对比权益表的 2.1)
指标系统 biz 编码:1 (延保)
流程:
Step1 Excel(SAAS预算分解表 biz_type=2.3 + 关系表 + 主机厂交车)
Step2 指标系统 API(biz=1 延保)
Step3 业务系统 SQL(TODO 占位)
Step4 系统公式计算 + 上月预算达成占比
Step5 排名 + 批量入库
"""
import logging
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_WARRANTY, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps,
parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, exact_match_store,
fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
)
from models import ReportExtendedWarranty, db
logger = logging.getLogger('WarrantyProcessor')
class WarrantyProcessor:
"""延保盈利测算独立处理器"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_store_effect_earnings(self, output_category='warranty'):
"""扫描 store_effect_earnings 任务并处理延保表"""
from models import DataProcessTask
logger.info(f"[warranty] 开始扫描 store_effect_earnings 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=STORE_EFFECT_EARNINGS_TYPE,
status='PROCESSING',
is_deleted=0
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[warranty] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[warranty] 任务 {task.id} 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[warranty] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[warranty] 标记任务失败时出错: {str(mark_err)}")
logger.info(f"[warranty] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
"""处理单个 task 的延保表输出"""
task_id = task.id
category = 'warranty'
# 子任务已完成 → 跳过(幂等)
if is_subtask_completed(task_id, category):
logger.info(f"[warranty] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
# 子任务状态 → PROCESSING
update_subtask(task_id, category, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
try:
row_count = self._process_extended_warranty(task)
update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
logger.info(f"[warranty] 任务 {task_id} 处理完成,{row_count} 行")
except Exception as e:
db.session.rollback()
update_subtask(task_id, category, SUBTASK_FAILED, error_msg=str(e))
db.session.commit()
promote_subtask_failure_to_main_task(task_id)
raise
def _process_extended_warranty(self, task):
"""
延保盈利测算完整处理流程。
与权益表的差异:
- biz_type 过滤值 2.3(权益是 2.1)
- 指标系统 biz=1(权益是 3)
- 指标编码多 A066/A070/A086(整车延保/电池/安心包)
- 输出表多延保专属字段(vehicle_warranty_cnt / battery_warranty_cnt / easy_bag_cnt 及各自渗透率)
"""
task_id = task.id
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
logger.info(f"[延保] 开始处理, task_id={task_id}, period={start_str}~{end_str}")
# ========== Step1: Excel ==========
tmp_dir = tempfile.mkdtemp(prefix=f"warranty_{task_id}_")
try:
file_map = download_all_files(task.id, tmp_dir)
saas_path = file_map.get('SAAS门店预算分解表')
if not saas_path:
raise Exception("缺少必需文件: SAAS门店预算分解表")
base_records = parse_saas_base(saas_path, BIZ_TYPE_WARRANTY)
rel_path = file_map.get('关系表')
region_map = parse_region_map(rel_path) if rel_path else {}
# 鸿蒙 + 广联主机厂交车 → 跨表模糊匹配合并
hm_part = parse_delivery_table(file_map.get('鸿蒙主机厂数据表')) if file_map.get('鸿蒙主机厂数据表') else {}
gl_part = parse_delivery_table(file_map.get('广联主机厂数据表')) if file_map.get('广联主机厂数据表') else {}
delivery_map = merge_delivery_maps(hm_part, gl_part)
# 预算达成数据(商务)→ 人员工资占比 = 营销费用占比
# form_type 兼容中英文括号
budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
prev_labor_ratio_map = {}
if budget_path:
prev_labor_ratio_map = parse_budget_achieve_excel(budget_path, biz_type='2.3')
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step1.5: 主机厂交车数未匹配门店 → 系统日报 scene_type=0 兜底 ==========
all_store_names = [r.get('store_name', '') for r in base_records if r.get('store_name')]
unfitted_names = [sn for sn in all_store_names if not fuzzy_match_store(sn, delivery_map)]
system_delivery_map = {}
if unfitted_names:
logger.info(f"[延保] Excel交车未匹配 {len(unfitted_names)} 家门店,查系统日报 scene_type=0 兜底")
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
try:
system_delivery_map = fetch_park_daily_report(start_str, end_str, scene_type=0)
logger.info(f"[延保] 系统日报 scene_type=0 → {len(system_delivery_map)} 个门店")
except Exception as e:
logger.warning(f"[延保] 系统日报兜底查询失败: {e}")
system_delivery_map = {}
# ========== Step2: 指标系统(延保 2.3)→ 产值/成交/触客/延保各项 ==========
# 注意:单值 biz 会被指标 API 忽略(返回全业务),必须传列表走 bizs="N" 才生效
try:
indicator_data = fetch_indicator_data(
start_str, end_str, [INDICATOR_BIZ_MAP.get('warranty')],
['A036', 'A075', 'A084', 'A066', 'A070', 'A086']) or {}
except Exception as e:
logger.warning(f"[延保] 指标系统拉取失败,指标类字段置 0: {e}")
indicator_data = {}
# ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
# 不传 store_names 过滤(419 个 OR LIKE 会导致 MySQL 优化器异常丢 50% 门店)
# 后续用 fuzzy_match_store 在 Python 层做精确模糊匹配
# BIZ_TYPE_WARRANTY='2.3' → scene_type=0, business_type=2
biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_WARRANTY)
# ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========
# ========== Step5: 逐行公式计算 ==========
rows_to_insert = []
for rec in base_records:
store_name = rec.get('store_name', '')
brand = rec.get('brand', '')
province = rec.get('province', '')
resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {})
# 业务系统 SQL — 精确匹配,避免模糊误匹配(如"广西河池中达"误匹配到其他"中达"门店)
biz_data = exact_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表(两边都是 Excel,命名可能不同 → 模糊保留)
delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0
if delivery_cnt == 0 and system_delivery_map:
_sys_entry = exact_match_store(store_name, system_delivery_map) or {}
delivery_cnt = _sys_entry.get('delivery_cnt', 0) if isinstance(_sys_entry, dict) else 0
# 指标系统取值
touch_cnt = int(Decimal(str(ind.get('A084', 0))))
deal_cnt = int(Decimal(str(ind.get('A075', 0))))
vehicle_warranty_cnt = int(Decimal(str(ind.get('A066', 0))))
battery_warranty_cnt = int(Decimal(str(ind.get('A070', 0))))
easy_bag_cnt = int(Decimal(str(ind.get('A086', 0))))
store_output_value = Decimal(str(ind.get('A036', 0)))
# ======= 公式 =======
penetration_rate = safe_div_pct(deal_cnt, delivery_cnt)
vehicle_warranty_penetration = safe_div_pct(vehicle_warranty_cnt, delivery_cnt)
vehicle_warranty_touch_convert = safe_div_pct(vehicle_warranty_cnt, touch_cnt)
battery_warranty_penetration = safe_div_pct(battery_warranty_cnt, delivery_cnt)
easy_bag_penetration = safe_div_pct(easy_bag_cnt, delivery_cnt)
upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2)
# —— 业务系统 SQL 取值(已在 L172 用 fuzzy_match_store 拿到 biz_data)——
product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', Decimal('0'))
service_fee = Decimal('0') if resident_type != '服务商' else biz_data.get('service_fee', Decimal('0'))
# —— 门店分成:普通品牌取系统流量费 shop_traffic_money;岚图按渗透率区间算比例 * 门店产值 ——
# penetration_rate 范围 0-100(safe_div_pct 已 ×100)
is_lantu = (brand or '') == '岚图'
if is_lantu:
pr = float(penetration_rate)
if pr < 30:
lantu_ratio = Decimal('0.88')
elif pr < 50:
lantu_ratio = Decimal('0.85')
else:
lantu_ratio = Decimal('0.80')
store_share = (store_output_value * lantu_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
else:
store_share = biz_data.get('shop_traffic_money', Decimal('0'))
guarantee_amount = Decimal('0')
gl_share = store_output_value - product_cost - store_share - guarantee_amount
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
marketing_fee_ratio = clamp_ratio(extract_budget_ratio(prev_labor_ratio_map, store_name, 'labor_ratio'))
# Excel 预算表的百分比是"带百分号"的原值(如 5.0 = 5%),算费用时需除以 100
marketing_fee = (store_output_value * marketing_fee_ratio / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_fee_ratio = safe_div_pct_decimal(service_fee, store_output_value)
total_cost = market_fee + marketing_fee + service_fee
cost_ratio = safe_div_pct_decimal(total_cost, store_output_value)
gross_profit = gl_share - total_cost
gross_profit_rate = safe_div_pct_decimal(gross_profit, store_output_value)
if gross_profit_rate > 0:
gross_profit_status = '盈利'
elif gross_profit_rate == 0:
gross_profit_status = '零毛利'
else:
gross_profit_status = '亏损'
region_area = region_map.get((BIZ_TYPE_WARRANTY, province), '') or region_map.get(('', province), '')
row = ReportExtendedWarranty(
task_id=task_id,
period_start=period_start,
period_end=period_end,
# 基础维度
region_area=region_area, province=province, city=rec.get('city', ''),
region_manager=rec.get('region_manager', ''),
training_supervisor=rec.get('training_supervisor', ''),
biz_manager=rec.get('biz_manager', ''),
resident_type=resident_type, store_name=store_name, brand=brand,
# 触客/成交
delivery_cnt=delivery_cnt, touch_cnt=touch_cnt, deal_cnt=deal_cnt,
penetration_rate=penetration_rate,
# 延保特有指标
vehicle_warranty_cnt=vehicle_warranty_cnt,
vehicle_warranty_penetration=vehicle_warranty_penetration,
vehicle_warranty_touch_convert=vehicle_warranty_touch_convert,
battery_warranty_cnt=battery_warranty_cnt,
battery_warranty_penetration=battery_warranty_penetration,
easy_bag_cnt=easy_bag_cnt,
easy_bag_penetration=easy_bag_penetration,
# 产值/成本/费用/毛利
store_output_value=store_output_value,
upgrade_unit_price=upgrade_unit_price,
product_cost=product_cost, store_share=store_share,
guarantee_amount=guarantee_amount, gl_share=gl_share,
market_fee=market_fee, market_fee_ratio=market_fee_ratio,
marketing_fee=marketing_fee, marketing_fee_ratio=marketing_fee_ratio,
service_fee=service_fee, service_fee_ratio=service_fee_ratio,
total_cost=total_cost, cost_ratio=cost_ratio,
gross_profit=gross_profit, gross_profit_rate=gross_profit_rate,
gross_profit_status=gross_profit_status,
)
rows_to_insert.append(row)
# ========== Step6: 排名 ==========
rows_to_insert.sort(key=lambda r: (r.gross_profit_rate or Decimal('0')), reverse=True)
for idx, row in enumerate(rows_to_insert, 1):
row.gross_profit_rank = idx
# ========== Step7: 批量入库 ==========
ReportExtendedWarranty.query.filter_by(task_id=task_id, is_deleted=0).delete()
db.session.flush()
for i in range(0, len(rows_to_insert), 500):
batch = rows_to_insert[i:i + 500]
db.session.add_all(batch)
db.session.flush()
logger.info(f"[延保] 完成入库 {len(rows_to_insert)} 条")
return len(rows_to_insert)
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 权益表独立处理器
====================================
对应 ORM 表:report_equity_service
业务类型过滤:biz_type=2.1 (对比延保表的 2.3)
指标系统 biz 编码:3 (权益)
流程:
Step1 Excel(SAAS预算分解表 biz_type=2.1 + 关系表 + 主机厂交车)
Step2 指标系统 API(biz=3 权益)
Step3 业务系统 SQL(TODO 占位)
Step4 系统公式计算 + 上月预算达成占比
Step5 排名 + 批量入库
"""
import logging
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_EQUITY, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps,
parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, exact_match_store,
fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
)
from models import ReportEquityService, db
logger = logging.getLogger('EquityProcessor')
class EquityProcessor:
"""权益盈利测算独立处理器"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_store_effect_earnings(self, output_category='equity'):
"""扫描 store_effect_earnings 任务并处理权益表"""
from models import DataProcessTask
logger.info(f"[equity] 开始扫描 store_effect_earnings 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=STORE_EFFECT_EARNINGS_TYPE,
status='PROCESSING',
is_deleted=0
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[equity] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[equity] 任务 {task.id} 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[equity] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[equity] 标记任务失败时出错: {str(mark_err)}")
logger.info(f"[equity] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
"""处理单个 task 的权益表输出"""
task_id = task.id
category = 'equity'
if is_subtask_completed(task_id, category):
logger.info(f"[equity] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
update_subtask(task_id, category, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
try:
row_count = self._process_equity_service(task)
update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
logger.info(f"[equity] 任务 {task_id} 处理完成,{row_count} 行")
except Exception as e:
db.session.rollback()
update_subtask(task_id, category, SUBTASK_FAILED, error_msg=str(e))
db.session.commit()
promote_subtask_failure_to_main_task(task_id)
raise
# ============================================================
# 核心处理逻辑
# ============================================================
def _process_equity_service(self, task):
"""
权益盈利测算完整处理流程。
与延保表的差异:
- biz_type 过滤值 2.1(延保是 2.3)
- 指标系统 biz=3(延保是 1)
- 指标编码仅 A084/A075/A036(延保还有 A066/A070/A086 延保专属字段)
- 输出表列更简洁(无延保/电池/安心包特有字段)
"""
task_id = task.id
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
logger.info(f"[权益] 开始处理, task_id={task_id}, period={start_str}~{end_str}")
# ========== Step1: Excel ==========
tmp_dir = tempfile.mkdtemp(prefix=f"equity_{task_id}_")
try:
file_map = download_all_files(task.id, tmp_dir)
saas_path = file_map.get('SAAS门店预算分解表')
if not saas_path:
raise Exception("缺少必需文件: SAAS门店预算分解表")
# 权益表用 biz_type=2.1
base_records = parse_saas_base(saas_path, BIZ_TYPE_EQUITY)
rel_path = file_map.get('关系表')
region_map = parse_region_map(rel_path) if rel_path else {}
# 鸿蒙 + 广联主机厂交车 → 跨表模糊匹配合并
hm_part = parse_delivery_table(file_map.get('鸿蒙主机厂数据表')) if file_map.get('鸿蒙主机厂数据表') else {}
gl_part = parse_delivery_table(file_map.get('广联主机厂数据表')) if file_map.get('广联主机厂数据表') else {}
delivery_map = merge_delivery_maps(hm_part, gl_part)
# 预算达成数据(商务)→ 人员工资占比 = 营销费用占比
budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
prev_labor_ratio_map = {}
if budget_path:
prev_labor_ratio_map = parse_budget_achieve_excel(budget_path, biz_type='2.1')
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step1.5: 主机厂交车数未匹配门店 → 系统日报 scene_type=0 兜底 ==========
all_store_names = [r.get('store_name', '') for r in base_records if r.get('store_name')]
unfitted_names = [sn for sn in all_store_names if not fuzzy_match_store(sn, delivery_map)]
system_delivery_map = {}
if unfitted_names:
logger.info(f"[权益] Excel交车未匹配 {len(unfitted_names)} 家门店,查系统日报 scene_type=0 兜底")
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
try:
system_delivery_map = fetch_park_daily_report(start_str, end_str, scene_type=0)
logger.info(f"[权益] 系统日报 scene_type=0 → {len(system_delivery_map)} 个门店")
except Exception as e:
logger.warning(f"[权益] 系统日报兜底查询失败: {e}")
system_delivery_map = {}
# ========== Step2: 指标系统(权益 2.1)→ 产值/成交/触客 ==========
# 注意:单值 biz 会被指标 API 忽略(返回全业务),必须传列表走 bizs="N" 才生效
try:
indicator_data = fetch_indicator_data(
start_str, end_str, [INDICATOR_BIZ_MAP.get('equity')],
['A036', 'A075', 'A084']) or {}
except Exception as e:
logger.warning(f"[权益] 指标系统拉取失败,指标类字段置 0: {e}")
indicator_data = {}
# ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
# 不传 store_names 过滤(419 个 OR LIKE 会导致 MySQL 优化器异常丢 50% 门店)
# 后续用 fuzzy_match_store 在 Python 层做精确模糊匹配
# BIZ_TYPE_EQUITY='2.1' → scene_type=0, business_type=1
biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_EQUITY)
# ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========
# ========== Step5: 逐行公式计算 ==========
rows_to_insert = []
for rec in base_records:
store_name = rec.get('store_name', '')
brand = rec.get('brand', '')
province = rec.get('province', '')
resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {})
# 业务系统 SQL — 精确匹配
biz_data = exact_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表(Excel → Excel 保留模糊)
delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0
if delivery_cnt == 0 and system_delivery_map:
# system_delivery_map value 是 dict{delivery_cnt, equity_to_shop_count, ...}
_sys_entry = exact_match_store(store_name, system_delivery_map) or {}
delivery_cnt = _sys_entry.get('delivery_cnt', 0) if isinstance(_sys_entry, dict) else 0
# 指标系统取值
touch_cnt = int(Decimal(str(ind.get('A084', 0))))
deal_cnt = int(Decimal(str(ind.get('A075', 0))))
store_output_value = Decimal(str(ind.get('A036', 0)))
# ======= 公式 =======
penetration_rate = safe_div_pct(deal_cnt, delivery_cnt)
upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2)
# —— 业务系统 SQL 取值 ——
product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', Decimal('0'))
service_fee = Decimal('0') if resident_type != '服务商' else biz_data.get('service_fee', Decimal('0'))
# 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录)
store_share = biz_data.get('shop_traffic_money', Decimal('0'))
guarantee_amount = Decimal('0')
gl_share = store_output_value - product_cost - store_share - guarantee_amount
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
marketing_fee_ratio = clamp_ratio(extract_budget_ratio(prev_labor_ratio_map, store_name, 'labor_ratio'))
# Excel 预算表的百分比是"带百分号"的原值(如 5.0 = 5%),算费用时需除以 100
marketing_fee = (store_output_value * marketing_fee_ratio / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_fee_ratio = safe_div_pct_decimal(service_fee, store_output_value)
total_cost = market_fee + marketing_fee + service_fee
cost_ratio = safe_div_pct_decimal(total_cost, store_output_value)
gross_profit = gl_share - total_cost
gross_profit_rate = safe_div_pct_decimal(gross_profit, store_output_value)
if gross_profit_rate > 0:
gross_profit_status = '盈利'
elif gross_profit_rate == 0:
gross_profit_status = '零毛利'
else:
gross_profit_status = '亏损'
region_area = region_map.get((BIZ_TYPE_EQUITY, province), '') or region_map.get(('', province), '')
row = ReportEquityService(
task_id=task_id,
period_start=period_start,
period_end=period_end,
# 基础维度
region_area=region_area, province=province, city=rec.get('city', ''),
region_manager=rec.get('region_manager', ''),
training_supervisor=rec.get('training_supervisor', ''),
biz_manager=rec.get('biz_manager', ''),
resident_type=resident_type, store_name=store_name, brand=brand,
# 触客/成交
delivery_cnt=delivery_cnt, touch_cnt=touch_cnt, deal_cnt=deal_cnt,
penetration_rate=penetration_rate,
# 产值/成本/费用/毛利
store_output_value=store_output_value,
upgrade_unit_price=upgrade_unit_price,
product_cost=product_cost, store_share=store_share,
guarantee_amount=guarantee_amount, gl_share=gl_share,
market_fee=market_fee, market_fee_ratio=market_fee_ratio,
marketing_fee=marketing_fee, marketing_fee_ratio=marketing_fee_ratio,
service_fee=service_fee, service_fee_ratio=service_fee_ratio,
total_cost=total_cost, cost_ratio=cost_ratio,
gross_profit=gross_profit, gross_profit_rate=gross_profit_rate,
gross_profit_status=gross_profit_status,
)
rows_to_insert.append(row)
# ========== Step6: 排名 ==========
rows_to_insert.sort(key=lambda r: (r.gross_profit_rate or Decimal('0')), reverse=True)
for idx, row in enumerate(rows_to_insert, 1):
row.gross_profit_rank = idx
# ========== Step7: 批量入库 ==========
ReportEquityService.query.filter_by(task_id=task_id, is_deleted=0).delete()
db.session.flush()
for i in range(0, len(rows_to_insert), 500):
batch = rows_to_insert[i:i + 500]
db.session.add_all(batch)
db.session.flush()
logger.info(f"[权益] 完成入库 {len(rows_to_insert)} 条")
return len(rows_to_insert)
# -*- coding: utf-8 -*-
"""探查 taskId=37(阿维塔专项):任务信息 + 附件实际字段。"""
import os
import sys
# 用户级 site-packages(C:/Python314 默认未纳入 sys.path)
SP = r"C:\Users\66\AppData\Roaming\Python\Python314\site-packages"
if SP not in sys.path:
sys.path.insert(0, SP)
import pymysql
import openpyxl
import oss2
from oss_utils import download_file
BASE = r"F:\data-report\data-process"
# ---- 解析 .env ----
def load_env(path):
env = {}
if os.path.exists(path):
with open(path, encoding="utf-8") as f:
for line in f:
line = line.strip()
if not line or line.startswith("#") or "=" not in line:
continue
k, v = line.split("=", 1)
env[k.strip()] = v.strip()
return env
env = load_env(os.path.join(BASE, ".env"))
DB = env["data_report"] if False else None
host, port, user, pwd, db = (
env["MYSQL_HOST"], int(env["MYSQL_PORT"]),
env["MYSQL_USER"], env["MYSQL_PASSWORD"], env["MYSQL_DB"],
)
conn = pymysql.connect(host=host, port=port, user=user, password=pwd,
database=db, charset="utf8mb4")
try:
with conn.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute(
"SELECT id,data_table_type,data_table_type_name,month,status,"
"result_file_url,period_start,period_end,creator FROM data_process_task WHERE id=37")
print("=== TASK 37 ===")
for r in cur.fetchall():
print(r)
cur.execute(
"SELECT id,task_id,form_type,file_name,file_url,file_size,clean_status "
"FROM data_process_file WHERE task_id=37 AND is_deleted=0")
print("\n=== FILES ===")
files = cur.fetchall()
for f in files:
print(f)
finally:
conn.close()
# ---- 下载第一个附件并读表头 ----
if files:
f0 = files[0]
local = os.path.join(BASE, "uploads", "explore", "task37.xlsx")
os.makedirs(os.path.dirname(local), exist_ok=True)
download_file(f0["file_url"], local)
print(f"\n=== 下载完成: {local} ===")
wb = openpyxl.load_workbook(local, read_only=True, data_only=True)
print("SHEETS:", wb.sheetnames)
for sn in wb.sheetnames:
ws = wb[sn]
print(f"\n--- SHEET: {sn} (max_row={ws.max_row}, max_col={ws.max_column}) ---")
rows = list(ws.iter_rows(values_only=True))
for i, r in enumerate(rows[:12]):
print(f"r{i}:", r)
print("... total rows:", len(rows))
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 4 表统一导出模块 v2
====================================
从 4 张 ORM 表查询数据,写入 2 个模板 Excel 对应 sheet,
输出 1 个合并 Excel(6 sheet:延保、权益、店中店汇总、园区店汇总、总看板、字段说明)。
模板真实行结构:
延保 sheet(模板 max_row=5)
row1 表头(序号~门店毛利排名,39列)
row2 表头续行(合并单元格)
row3 备注行("按统计数据自动排序"...)
row4 格式行(示例数据 + #REF! 公式)
row5 总计行(=SUM 公式)
数据写入从 row5 开始(覆盖模板总计行),写完后追加新总计行到最后
权益 sheet(模板 max_row=4)
row1 表头(32列)
row2 备注行
row3 格式行
row4 总计行
数据写入从 row4 开始
店中店汇总 sheet(模板 max_row=13)
row1 分类表头(门店基础信息...)
row2 详细表头(82 列有效值 + 空列)
row3 空
row4 备注行
row5 格式行(示例 #1)
row6~11 模板预填的示例数据行(全要清掉!)
数据写入从 row6 开始
园区店汇总 sheet(模板 max_row=18,max_col=10244 是 openpyxl 误报)
row1 分类表头
row2 详细表头(69 列有效值)
row3 备注行
row4 格式行
row5~18 模板预填的示例数据行 + 总计信号
数据写入从 row5 开始
"""
import os
import sys
import tempfile
import logging
from datetime import date, datetime
from copy import copy
from openpyxl import load_workbook, Workbook
from openpyxl.utils import get_column_letter
from openpyxl.styles import Font, Alignment, Border, Side
logger = logging.getLogger(__name__)
# ============ 列映射 ============
# key: Excel 列索引 (1-based),value: ORM attr_name;None=序号列自动填
# 空列(模板里合并单元格产生的无表头列)不配置
# ---- 延保 (report_extended_warranty):模板 39 列 ----
# col1=序号, col2=片区, ..., col39=门店毛利排名
WARRANTY_COL_MAP = {
1: None,
2: 'region_area', # 片区
3: 'province', # 省份
4: 'city', # 城市
5: 'region_manager', # 区域运营
6: 'training_supervisor', # 培训督导
7: 'biz_manager', # 业务经理
8: 'resident_type', # 驻店类型
9: 'store_name', # 门店名
10: 'brand', # 品牌
11: 'delivery_cnt', # 交车
12: 'touch_cnt', # 触客
13: 'deal_cnt', # 成交数
14: 'penetration_rate', # 渗透率
15: 'vehicle_warranty_cnt', # 整车延保成交数
16: 'vehicle_warranty_penetration', # 整车延保渗透率
17: 'vehicle_warranty_touch_convert',# 整车延保触客成交率
18: 'battery_warranty_cnt', # 电池成交数
19: 'battery_warranty_penetration', # 电池渗透率
20: 'easy_bag_cnt', # 安心包成交数
21: 'easy_bag_penetration', # 安心包渗透率
22: 'store_output_value', # 门店产值
23: 'upgrade_unit_price', # 升级客单价
24: 'product_cost', # 商品成本
25: 'store_share', # 门店分成
26: 'guarantee_amount', # 兜底金额
27: 'gl_share', # 广联分成
28: 'market_fee', # 市场费
29: 'market_fee_ratio', # 市场费占比
30: 'marketing_fee', # 营销费用
31: 'marketing_fee_ratio', # 营销费用占比
32: 'service_fee', # 服务费用
33: 'service_fee_ratio', # 服务费用占比
34: 'total_cost', # 成本总计
35: 'cost_ratio', # 成本占比
36: 'gross_profit', # 毛利测算
37: 'gross_profit_rate', # 预估毛利率
38: 'gross_profit_status', # 预估毛利情况
39: 'gross_profit_rank', # 门店毛利排名
}
WARRANTY_HEADER_ROW = 1
WARRANTY_FORMAT_ROW = 4 # 模板 row4=格式行
WARRANTY_DATA_START = 5 # 模板 row5=总计行;从 row5 开始写覆盖总计行
WARRANTY_MAX_COL = 39
# ---- 权益 (report_equity_service):模板 32 列 ----
EQUITY_COL_MAP = {
1: None,
2: 'region_area',
3: 'province',
4: 'city',
5: 'region_manager',
6: 'training_supervisor',
7: 'biz_manager',
8: 'resident_type',
9: 'store_name',
10: 'brand',
11: 'delivery_cnt',
12: 'touch_cnt',
13: 'deal_cnt',
14: 'penetration_rate',
15: 'store_output_value', # 门店产值
16: 'upgrade_unit_price', # 升级客单价
17: 'product_cost', # 商品成本
18: 'store_share', # 门店分成
19: 'guarantee_amount', # 兜底金额
20: 'gl_share', # 广联分成
21: 'market_fee', # 市场费
22: 'market_fee_ratio', # 市场费占比
23: 'marketing_fee', # 营销费用
24: 'marketing_fee_ratio', # 营销费用占比
25: 'service_fee', # 服务费用
26: 'service_fee_ratio', # 服务费用占比
27: 'total_cost', # 成本总计
28: 'cost_ratio', # 成本占比
29: 'gross_profit', # 毛利测算
30: 'gross_profit_rate', # 预估毛利率
31: 'gross_profit_status', # 预估毛利情况
32: 'gross_profit_rank', # 门店毛利排名
}
EQUITY_HEADER_ROW = 1
EQUITY_FORMAT_ROW = 3 # 模板 row3=格式行
EQUITY_DATA_START = 4 # 模板 row4=总计行;从 row4 开始写
EQUITY_MAX_COL = 32
# ---- 店中店汇总 (report_light_reform_inshop):模板 82 列(含空列) ----
# 模板 row2 有效表头:col1~25 顺序,col26/28/30/32,col33~55,col57~65,col67~82
INSHOP_COL_MAP = {
1: None,
2: 'region_area', # 大区名称
3: 'province', # 区域(省)
4: 'city', # 区域(市)
5: 'park_type', # 园区类型
6: 'biz_line', # 业务线
7: 'operate_type', # 经营属性
8: 'region_manager', # 区域经理
9: 'park_name', # 园区名称
10: 'store_name', # 门店名称
11: 'brand', # 品牌(问界/鸿蒙)
12: 'brand_category', # 品牌分类
13: 'purchase_indicator', # 采买/兜底指标
14: 'sales_order_cnt', # 销售大定数
15: 'sales_touch_cnt', # 销售触客数
16: 'sales_touch_rate', # 销售触客率
17: 'delivery_cnt', # 交车数
18: 'delivery_touch_cnt', # 交付触客数
19: 'delivery_touch_rate', # 交付触客率
20: 'aftersales_baohui_cnt',# 售后首保回厂数
21: 'aftersales_shigu_cnt', # 售后事故回厂数
22: 'aftersales_touch_cnt', # 售后触客数
23: 'aftersales_touch_rate',# 售后触客率
24: 'total_touch_cnt', # 总触客数
25: 'total_deal_cnt', # 总成交数
26: 'window_film_oe_cnt', # 窗膜/成交数(原厂)
27: 'window_film_nonoe_cnt',# 窗膜/成交数(副厂) ← col27之前是合并空列
28: 'car_wrap_oe_cnt', # 车衣/成交数(原厂)
29: 'car_wrap_nonoe_cnt', # 车衣/成交数(副厂) ← col29之前是合并空列
30: 'premium_oe_cnt', # 精品/成交数(原厂)
31: 'premium_nonoe_cnt', # 精品/成交数(副厂) ← col31之前是合并空列
32: 'pedal_cnt', # 踏板
33: 'store_output_value', # 门店总产值
34: 'internal_settle_value',# 内部结算产值
35: 'total_output_value', # 合计总产值
36: 'oe_output_value', # 原厂总产值
37: 'nonoe_output_value', # 副厂总产值
38: 'avg_unit_price_delivery',# 平均客单价(交车)
39: 'avg_price_target', # 平客目标值
40: 'avg_price_diff', # 平客差值
41: 'delivery_touch_unit_price',# 交付触客客单价
42: 'upgrade_unit_price', # 升级客单价
43: 'total_penetration_rate',# 总订单渗率
44: 'window_film_penetration',# 窗膜渗透率
45: 'car_wrap_penetration', # 车衣渗透率
46: 'premium_penetration', # 精品渗透率
47: 'product_cost_finance', # 产品成本/财务
48: 'internal_settle_cost', # 内部结算成本/财务
49: 'oe_product_cost', # 原厂产品成本/财务
50: 'nonoe_product_cost', # 副厂产品成本/财务
51: 'window_film_cost', # 窗膜成本
52: 'car_wrap_cost', # 车衣成本
53: 'premium_cost', # 精品成本
54: 'product_cost_ratio', # 产品总成本/占比
55: 'construction_cost_oe', # 施工成本/原厂
56: 'construction_cost_nonoe', # 施工成本/副厂
57: 'construction_cost_ratio',# 施工成本占比(前置合计占比)
58: 'frontline_incentive', # 一线激励
59: 'frontline_incentive_ratio',# 一线激励占比
60: 'gross_profit_pre_share',# 进销差/未分成
61: 'gross_profit_pre_share_ratio',# 进销差/占比
62: 'store_share', # 门店分成/流量费(财务列表) → SQL 直接值
63: 'store_share_ratio', # 门店分成(占比) → store_share/store_output_value*100%
64: 'store_share_per_car', # 门店单车利润 → store_share/delivery_cnt
65: None, # 兜底金额情况 → 默认为空(ORM 无此字段)
66: 'guarantee_amount', # 兜底金额 → 默认=0
67: 'gl_share', # 广联分成 → 进销差-门店分成-兜底金额
68: 'gl_share_ratio', # 广联分成(占比) → gl_share/store_output_value*100%
69: 'construction_income', # 施工收入 → construction_income
70: 'internal_settle_profit', # 内部结算 → internal_settle_profit
71: 'gl_total_share', # 广联总分成 → gl_total_share
72: 'marketing_personnel_cost', # 营销人员成本 → marketing_personnel_cost
73: 'marketing_personnel_ratio', # 营销人员成本占比 → marketing_personnel_ratio
74: 'construction_cost_post', # 施工成本(与 col55 同一 ORM 字段,模板分两处布局)
75: 'construction_cost_post_ratio', # 施工成本占比(与 col57 同一 ORM 字段)
76: 'market_fee', # 市场费 → market_fee
77: 'market_fee_ratio', # 市场费成本(占比) → market_fee_ratio
78: 'renovation_amortization', # 装修分摊 → renovation_amortization
79: 'rent_utilities', # 房租、水电费用 → rent_utilities
80: 'store_consumables', # 门店耗材 → store_consumables
81: 'service_provider_share', # 服务商分成/商务报表 → service_provider_share
82: 'service_provider_share_ratio', # 服务商分成/占比 → service_provider_share_ratio
# col83~88 模板 row1 有分类表头(成本总计/毛利测算区域),之前被遗漏
83: 'total_cost', # 成本总计 → total_cost
84: 'cost_ratio', # 总计占比 → cost_ratio
85: 'gross_profit', # 毛利测算 → gross_profit
86: 'gross_profit_rate', # 毛利率 → gross_profit_rate
87: 'gross_profit_status', # 毛利情况 → gross_profit_status
88: 'gross_profit_rank', # 门店毛利排名 → gross_profit_rank
}
INSHOP_HEADER_ROW = 2
INSHOP_FORMAT_ROW = 5 # 模板 row5=格式行
INSHOP_DATA_START = 6 # 模板 row6~13=示例数据;从 row6 开始
INSHOP_MAX_COL = 88 # 模板有效列 col1~88(col83~88 有 row1 分类表头)
# ---- 园区店汇总 (report_light_reform_park):模板 69 列 ----
PARK_COL_MAP = {
1: None,
2: 'region_area', # 大区名称
3: 'province', # 区域(省)
4: 'city', # 区域(市)
5: 'park_type', # 园区类型
6: 'operate_type', # 经营属性
7: 'partner_store_cnt', # 合作门店数量
8: 'region_manager', # 区域经理
9: 'park_name', # 园区名称
10: 'store_name', # 门店名称
11: 'brand', # 品牌
12: 'biz_type', # 类型
13: 'purchase_indicator', # 采买/兜底指标/流量费
14: 'delivery_cnt', # 交车数
15: 'arrival_cnt', # 到店数
16: 'arrival_invalid_cnt', # 到店无效客户数
17: 'invalid_arrival_rate', # 无效/到店率
18: 'arrival_rate', # 到店率
19: 'deal_cnt', # 成交数
20: 'conversion_rate', # 转化率
21: 'store_sales_output', # 门店销售产值
22: 'internal_settle_value', # 内部结算产值
23: 'total_output_value', # 合计总产值
24: 'output_progress', # 产值达成进度
25: 'avg_unit_price_arrival', # 平均客单价(到店)
26: 'avg_price_target', # 平客目标值
27: 'avg_price_diff', # 平客差值
28: 'upgrade_unit_price', # 升级客单价
29: 'window_film_cnt', # 窗膜成交数
30: 'car_wrap_cnt', # 车衣成交数
31: 'premium_cnt', # 精品成交数
32: 'window_film_convert', # 窗膜转化率
33: 'car_wrap_convert', # 车衣转化率
34: 'premium_convert', # 精品转化率
35: 'est_traffic', # 商务上架预估流量
36: 'est_delivery_cnt', # 预估/交车数
37: 'est_output_value', # 预估总产值/预算目标
38: 'product_cost_finance', # 产品成本/财务
39: 'product_cost_ratio', # 产品成本占比
40: 'internal_settle_cost', # 内部结算成本/财务
41: 'traffic_fee_finance', # 流量费/财务
42: 'traffic_fee_per_car', # 按单台计算流量/台
43: 'traffic_fee_order', # 按台次计算流量费
44: 'store_traffic_fee', # 门店流量费
45: 'traffic_fee_ratio', # 流量费率/列表测算
46: 'gl_share', # 广联分成
47: 'gl_share_ratio', # 广联分成/占比
48: 'internal_settle_profit', # 内部结算
49: 'gl_total_share', # 广联总分成
50: 'personnel_cost', # 人员成本
51: 'personnel_cost_ratio', # 常规人员费率/加权参考
52: 'construction_cost', # 施工成本
53: 'construction_cost_ratio',# 施工成本占比
54: 'market_fee_weighted', # 市场费/加权测算
55: 'market_fee_weighted_ratio',# 市场费费率/加权参考
56: 'service_fee', # 服务费/商务报表
57: 'service_fee_ratio', # 服务费费率/加权参考
58: 'renovation_amortization',# 装修分摊/商务报表
59: 'renovation_ratio', # 装修占比
60: 'rent_utilities', # 房租、水电费用
61: 'rent_utilities_ratio', # 房租、水电占比
62: 'store_consumables', # 门店耗材
63: 'store_consumables_ratio',# 门店耗材占比
64: 'total_cost', # 成本总计
65: 'cost_ratio', # 总计占比
66: 'gross_profit', # 毛利测算
67: 'gross_profit_rate', # 毛利率
68: 'gross_profit_status', # 毛利情况
69: 'gross_profit_rank', # 门店毛利排名
}
PARK_HEADER_ROW = 2
PARK_FORMAT_ROW = 4 # 模板 row4=格式行
PARK_DATA_START = 5 # 模板 row5~18=示例数据;从 row5 开始
PARK_MAX_COL = 69
# ============ 模板路径 ============
_TPL_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'exporttemplete')
_TPL_WARRANTY_EQUITY = os.path.join(_TPL_DIR, '红黄门店盈利测算 延保权益.xlsx')
_TPL_LIGHT_REFORM = os.path.join(_TPL_DIR, '红黄门店盈利测算 轻改 .xlsx')
def _clear_data_region(ws, data_start_row, clear_to_row, max_col):
"""
彻底清除模板中 data_start_row ~ clear_to_row 之间的所有内容:
1. 先解除该区域内所有合并单元格(否则 MergedCell 只读)
2. 逐格清空(值 + #REF! 公式 + 格式行示例数据 + 总计行公式)
:param max_col: 精确有效列数(避免 ws.max_column=10244 的 openpyxl 误报)
"""
# 解除数据区域的合并单元格
for merged in list(ws.merged_cells.ranges):
if merged.min_row >= data_start_row:
try:
ws.unmerge_cells(str(merged))
except Exception:
pass
# 清除数据到 clear_to_row,列数用精确 max_col
for r in range(data_start_row, clear_to_row + 1):
for c in range(1, max_col + 1):
cell = ws.cell(r, c)
cell.value = None
def _write_sheet_rows(ws, col_map, data_start_row, records, format_row=None):
"""把 ORM 记录写入 sheet(自动填序号列 + 继承格式行样式)"""
# 预先缓存格式行的样式(避免每格重复读取)
style_cache = {}
if format_row:
for col_idx in col_map.keys():
src = ws.cell(format_row, col_idx)
attr_name = col_map.get(col_idx)
fmt = _fix_number_format(src.number_format, attr_name)
style_cache[col_idx] = {
'font': copy(src.font),
'border': copy(src.border),
'fill': copy(src.fill),
'number_format': fmt,
'alignment': copy(src.alignment),
}
# 清除格式行的示例值/#REF!公式(只清值,保留样式供数据行继承)
for col_idx in col_map.keys():
ws.cell(format_row, col_idx).value = None
# 写数据 + 应用格式
for idx, rec in enumerate(records):
row = data_start_row + idx
for col_idx, attr_name in col_map.items():
cell = ws.cell(row, col_idx)
if attr_name is None and col_idx == 1:
cell.value = idx + 1 # 仅 col1 序号列自动填序号
elif attr_name is None:
pass # 其他 None 表示无对应 ORM 字段(如店中店 col74/75 模板重复表头),保持空
else:
val = getattr(rec, attr_name, None)
cell.value = None if val is None else val
# 应用格式行样式
if col_idx in style_cache:
s = style_cache[col_idx]
cell.font = s['font']
cell.border = s['border']
cell.fill = s['fill']
cell.number_format = s['number_format']
cell.alignment = s['alignment']
logger.info(f"[导出] 写入 {len(records)} 行, sheet={ws.title}, 起始行={data_start_row}")
# 比例/率类字段关键字(DB 存 1-100 范围,需字面百分号格式,不应做跨门店求和)
_RATIO_KEYWORDS = ('rate', 'ratio', 'penetration', 'progress', 'convert')
def _is_ratio_field(attr_name):
"""判断是否真正的比例/率类字段(模板配 % 格式是正确的,DB 已存 1-100)"""
return attr_name is not None and any(kw in attr_name for kw in _RATIO_KEYWORDS)
def _fix_number_format(fmt, attr_name):
"""根据 ORM 字段语义修正模板 number_format:
- 比例字段(含 ratio/rate...):Excel 自动 *100 的 % → 字面 "%"
- 金额/数值字段被模板误配了 % 格式:强制去掉 %,保留精度
"""
if not fmt or '%' not in fmt:
return fmt
if _is_ratio_field(attr_name):
# 真正的比例字段 → 统一保留 2 位小数 + 字面 "%"
# 防模板整数百分比格式(0%)四舍五入:DB 存 1.5 显示成 2%
return '0.00"%"'
else:
# 金额/数值字段被误配 % → 去掉百分号字符,保留数字精度
cleaned = fmt.replace('%', '').strip()
return cleaned if cleaned else '0.00'
def _no_total_field(attr_name):
"""判断字段在总计行是否应留空(不做跨门店求和)。
覆盖 3 类:
- 比例/率类:含 rate/ratio/penetration/progress/convert
- 排名/状态/业务维度:含 rank/status/type/line(排名求和无意义;字符串维度字段非数值)
- 特定业务线字段:biz_line(店中店业务线是业务分类不是数值指标)
"""
if attr_name is None:
return False
no_total_keywords = ('rate', 'ratio', 'penetration', 'progress', 'convert',
'rank', 'status', 'biz_line', 'operate_type',
'resident_type', 'park_type', 'brand_category')
return any(kw in attr_name for kw in no_total_keywords)
def _append_total_row(ws, col_map, total_row, records, format_row=None):
"""
在 total_row 写"总计"行:
- A 列写"总计"
- 数值列(非比例)写实际合计值
- 比例/率类列留空(跨门店求和无数学意义)
- 应用格式行样式(含字面%格式转换)
"""
# 预先缓存格式行样式(同 _write_sheet_rows 的 _fix_number_format 逻辑)
style_cache = {}
if format_row:
for col_idx in col_map.keys():
src = ws.cell(format_row, col_idx)
attr_name = col_map.get(col_idx)
fmt = _fix_number_format(src.number_format, attr_name)
style_cache[col_idx] = {
'font': copy(src.font),
'border': copy(src.border),
'fill': copy(src.fill),
'number_format': fmt,
'alignment': copy(src.alignment),
}
# A 列写"总计"
a_cell = ws.cell(total_row, 1)
a_cell.value = '总计'
if 1 in style_cache:
s = style_cache[1]
a_cell.font = s['font']
a_cell.border = s['border']
a_cell.alignment = s['alignment']
if not records:
return
from decimal import Decimal
for col_idx, attr_name in col_map.items():
if attr_name is None or attr_name == 'store_name':
continue # 序号列和门店名已处理
cell = ws.cell(total_row, col_idx)
# 应用格式行样式
if col_idx in style_cache:
s = style_cache[col_idx]
cell.font = s['font']
cell.border = s['border']
cell.fill = s['fill']
cell.number_format = s['number_format']
cell.alignment = s['alignment']
# 不应求和的字段留空(比例类、排名、状态字符串、业务维度等)
if _no_total_field(attr_name):
continue
# 数值列求和
vals = []
for rec in records:
v = getattr(rec, attr_name, None)
if v is None:
continue
try:
vals.append(Decimal(str(v)))
except Exception:
break # 非数值字段(如 gross_profit_status 字符串),跳过求和
if vals and all(isinstance(v, Decimal) for v in vals):
total = sum(vals, Decimal('0'))
cell.value = float(total) if isinstance(total, Decimal) else total
logger.info(f"[导出] 已写总计行 row={total_row}, sheet={ws.title}")
def _copy_sheet(src_ws, new_ws):
"""复制 sheet(值+样式+合并+列宽),限制到 src_ws.max_row 防内存"""
for row in src_ws.iter_rows(min_row=1, max_row=src_ws.max_row, max_col=src_ws.max_column):
for cell in row:
new_cell = new_ws.cell(row=cell.row, column=cell.column, value=cell.value)
if cell.has_style:
new_cell.font = copy(cell.font)
new_cell.border = copy(cell.border)
new_cell.fill = copy(cell.fill)
new_cell.number_format = cell.number_format
new_cell.protection = copy(cell.protection)
new_cell.alignment = copy(cell.alignment)
for merged in src_ws.merged_cells.ranges:
try:
new_ws.merge_cells(str(merged))
except Exception:
pass
for col_idx, dim in src_ws.column_dimensions.items():
new_ws.column_dimensions[col_idx].width = dim.width
def export_red_yellow_report(period_start, period_end, task_id=None, output_dir=None,
metrics=None, src_dir=None):
"""
从 4 张 ORM 表读取 period 数据,生成 6 sheet Excel:
[延保, 权益, 店中店汇总, 园区店汇总, 总看板, 字段说明]
:param period_start: date/str 'YYYY-MM-DD'
:param period_end: date/str 'YYYY-MM-DD'
:param task_id: 可选,按 task_id 精确过滤
:param output_dir: 输出目录;不传用 tempfile.mkdtemp()
:param metrics: build_store_effect_board.compute_metrics() 返回值;传了渲染总看板
:param src_dir: 可选,指标计算的数据源目录;传了自动算 metrics
:return: 输出文件绝对路径
"""
# 可选:自动计算 metrics
if metrics is None and src_dir:
try:
from build_store_effect_board import compute_metrics
from datetime import date as _date
ps = period_start if isinstance(period_start, _date) else _date.fromisoformat(str(period_start)[:10])
pe = period_end if isinstance(period_end, _date) else _date.fromisoformat(str(period_end)[:10])
metrics = compute_metrics(src_dir, ps, pe)
logger.info(f"[导出] 自动计算总看板指标,共 {len(metrics or {})} 项")
except Exception as e:
logger.warning(f"[导出] src_dir 存在但 compute_metrics 失败: {e}")
metrics = None
from models import (
ReportExtendedWarranty, ReportEquityService,
ReportLightReformInshop, ReportLightReformPark,
)
logger.info(f"[导出] 开始, period={period_start}~{period_end}, task_id={task_id}")
# 1. ORM 查询
def _q(Model):
q = Model.query.filter(
Model.period_start == period_start,
Model.period_end == period_end,
Model.is_deleted == 0,
)
if task_id is not None:
q = q.filter(Model.task_id == task_id)
return q
warranty_rows = _q(ReportExtendedWarranty).all()
equity_rows = _q(ReportEquityService).all()
inshop_rows = _q(ReportLightReformInshop).all()
park_rows = _q(ReportLightReformPark).all()
logger.info(f"[导出] DB 行数: 延保={len(warranty_rows)}, 权益={len(equity_rows)}, "
f"店中店={len(inshop_rows)}, 园区店={len(park_rows)}")
# 2. 加载模板
assert os.path.exists(_TPL_WARRANTY_EQUITY), f"模板不存在: {_TPL_WARRANTY_EQUITY}"
assert os.path.exists(_TPL_LIGHT_REFORM), f"模板不存在: {_TPL_LIGHT_REFORM}"
wb1 = load_workbook(_TPL_WARRANTY_EQUITY)
wb2 = load_workbook(_TPL_LIGHT_REFORM)
# 3. 清除模板预填数据 + 写入 ORM 数据 + 追加总计行
jobs = [
(wb1['延保'], WARRANTY_COL_MAP, WARRANTY_DATA_START, WARRANTY_FORMAT_ROW, WARRANTY_MAX_COL, warranty_rows),
(wb1['权益'], EQUITY_COL_MAP, EQUITY_DATA_START, EQUITY_FORMAT_ROW, EQUITY_MAX_COL, equity_rows),
(wb2['店中店汇总'], INSHOP_COL_MAP, INSHOP_DATA_START, INSHOP_FORMAT_ROW, INSHOP_MAX_COL, inshop_rows),
(wb2['园区店汇总'], PARK_COL_MAP, PARK_DATA_START, PARK_FORMAT_ROW, PARK_MAX_COL, park_rows),
]
for ws, col_map, data_start, format_row, max_col, rows in jobs:
# 清除:到模板 max_row(彻底清除预填的示例数据行 + 总计公式),列数用精确 max_col
_clear_data_region(ws, data_start, ws.max_row, max_col)
# 写数据 + 继承格式行样式
_write_sheet_rows(ws, col_map, data_start, rows, format_row)
# 追加总计行(在数据行下一行)
total_row = data_start + len(rows)
_append_total_row(ws, col_map, total_row, rows, format_row)
# 4. 合并成一个 wb
final_wb = Workbook()
final_wb.remove(final_wb.active)
for sn in ['延保', '权益']:
_copy_sheet(wb1[sn], final_wb.create_sheet(sn))
for sn in ['店中店汇总', '园区店汇总']:
_copy_sheet(wb2[sn], final_wb.create_sheet(sn))
# 5. 追加总看板 (sheet5) + 字段说明 (sheet6)
if metrics is not None:
try:
from build_store_effect_board import append_board_to_wb
month_label = period_start.strftime('%Y%m') if isinstance(period_start, date) else str(period_start)[:7]
append_board_to_wb(final_wb, metrics, month_label)
except Exception as e:
logger.warning(f"[导出] 总看板追加失败: {e}")
from openpyxl.styles import Font, Alignment
ws = final_wb.create_sheet('总看板')
ws['A1'] = '业务运营数据看板'
ws['A1'].font = Font(name='微软雅黑', size=14, bold=True)
ws['A1'].alignment = Alignment(horizontal='center')
final_wb.create_sheet('字段说明')
else:
from openpyxl.styles import Font, Alignment
ws = final_wb.create_sheet('总看板')
ws['A1'] = '业务运营数据看板'
ws['A1'].font = Font(name='微软雅黑', size=14, bold=True)
ws['A1'].alignment = Alignment(horizontal='center')
final_wb.create_sheet('字段说明')
# 6. 保存
out_dir = output_dir or tempfile.mkdtemp(prefix='red_yellow_report_')
os.makedirs(out_dir, exist_ok=True)
fname = f"红黄门店盈利测算_{period_start}_{period_end}.xlsx"
out_path = os.path.join(out_dir, fname)
final_wb.save(out_path)
logger.info(f"[导出] 完成: {out_path}, sheets={final_wb.sheetnames}")
return out_path
if __name__ == '__main__':
import argparse
parser = argparse.ArgumentParser()
parser.add_argument('--start', required=True, help='period_start YYYY-MM-DD')
parser.add_argument('--end', required=True, help='period_end YYYY-MM-DD')
parser.add_argument('--task-id', type=int, default=None)
args = parser.parse_args()
from app import app
with app.app_context():
path = export_red_yellow_report(args.start, args.end, args.task_id)
print(f"[OK] 生成: {path}")
"""导出 SAAS 门店预算分解表 全量去重门店清单(合并 sheet1+sheet2,按门店名去重,无过滤)。
输出: outputs/store_effect_summary/门店清单_2026-08.xlsx
"""
import os
import sys
import logging
logging.disable(logging.CRITICAL)
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Border, Side
from openpyxl.utils import get_column_letter
from build_store_effect_board import parse_saas, load_brand_category, brand_category
SRC = r'C:/Users/66/Desktop/2026-09报表/店效人效及盈利测算/数据源/'
OUT = r'F:/data-report/data-process/outputs/store_effect_summary/门店清单_2026-08.xlsx'
def main():
s1, s2 = parse_saas(SRC)
exact_map, keys = load_brand_category() # (brand->category, [brand keys])
# 汇总每个门店: 出现sheet、业务类型集合、驻店类型集合、品牌集合
rec = {} # store -> dict
def add(rows, sheet):
for r in rows:
st = r['store']
d = rec.setdefault(st, {'sheets': set(), 'biz': set(), 'res': set(), 'brand': set()})
d['sheets'].add(sheet)
if r['biz_type']:
d['biz'].add(r['biz_type'])
if r['resident_type']:
d['res'].add(r['resident_type'])
if r['brand']:
d['brand'].add(r['brand'])
add(s1, 'sheet1')
add(s2, 'sheet2')
wb = Workbook()
ws = wb.active
ws.title = '门店清单'
head = ['序号', '门店名称', '出现sheet', '业务类型', '驻店类型', '品牌', '豪华/非豪华']
ws.append(head)
head_font = Font(bold=True)
thin = Side(style='thin')
border = Border(left=thin, right=thin, top=thin, bottom=thin)
for c in range(1, len(head) + 1):
ws.cell(row=1, column=c).font = head_font
ws.cell(row=1, column=c).border = border
ws.cell(row=1, column=c).alignment = Alignment(horizontal='center')
for i, store in enumerate(sorted(rec.keys()), 1):
d = rec[store]
biz = '/'.join(sorted(d['biz'])) or '-'
res = '/'.join(sorted(d['res'])) or '-'
brand = '/'.join(sorted(d['brand'])) or '-'
sheets = '+'.join(sorted(d['sheets']))
# 豪华判定: 用与汇总表一致的模糊匹配逻辑
cat = '非豪华'
for b in d['brand']:
if brand_category(b, exact_map, keys) == '豪华':
cat = '豪华'
break
ws.append([i, store, sheets, biz, res, brand, cat])
# 列宽
widths = [6, 46, 12, 12, 14, 22, 12]
for i, w in enumerate(widths, 1):
ws.column_dimensions[get_column_letter(i)].width = w
os.makedirs(os.path.dirname(OUT), exist_ok=True)
wb.save(OUT)
# 统计
both = sum(1 for d in rec.values() if d['sheets'] == {'sheet1', 'sheet2'})
only1 = sum(1 for d in rec.values() if d['sheets'] == {'sheet1'})
only2 = sum(1 for d in rec.values() if d['sheets'] == {'sheet2'})
lux = sum(1 for d in rec.values()
if any(brand_category(b, exact_map, keys) == '豪华' for b in d['brand']))
print(f'去重门店总数: {len(rec)}')
print(f' 仅sheet1: {only1} | 仅sheet2: {only2} | 两表都有: {both}')
print(f' 豪华: {lux} | 非豪华: {len(rec) - lux}')
print(f'已导出 -> {OUT}')
if __name__ == '__main__':
main()
-- ============================================================
-- 红黄门店盈利测算 - 子任务表 DDL
-- 一张主任务对应 4 条子任务,各自追踪 1 张输出表的处理状态
-- ============================================================
DROP TABLE IF EXISTS `data_process_subtask`;
CREATE TABLE `data_process_subtask` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '主任务ID(关联 data_process_task.id)',
`output_category` VARCHAR(30) NOT NULL COMMENT '输出类别:warranty=延保 / equity=权益 / inshop=轻改店中店 / park=轻改园区店',
`status` VARCHAR(20) NOT NULL DEFAULT 'PENDING'
COMMENT '子任务状态:PENDING待处理 / PROCESSING处理中 / COMPLETED已完成 / FAILED失败',
`error_msg` VARCHAR(500) DEFAULT '' COMMENT '失败时的错误信息',
`row_count` INT DEFAULT 0 COMMENT '实际写入行数(处理完成后更新)',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` INT NOT NULL DEFAULT 0 COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_subtask_task_category` (`task_id`, `output_category`),
CONSTRAINT `fk_subtask_task` FOREIGN KEY (`task_id`) REFERENCES `data_process_task` (`id`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-子任务表(追踪 4 张输出表的独立处理状态)';
-- ============================================================
-- 豪华品牌配置表 DDL
-- 轻改店中店/园区店用于判断门店品牌属于豪华 or 非豪华
-- ============================================================
DROP TABLE IF EXISTS `luxury_brand_config`;
CREATE TABLE `luxury_brand_config` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`brand_name` VARCHAR(100) NOT NULL COMMENT '品牌名称(如 问界/鸿蒙/奔驰/宝马 等)',
`is_luxury` INT NOT NULL DEFAULT 1 COMMENT '是否豪华品牌:1豪华 / 0非豪华',
`remark` VARCHAR(200) DEFAULT '' COMMENT '备注',
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` INT NOT NULL DEFAULT 0 COMMENT '是否删除:0正常 / 1已删除',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_luxury_brand_name` (`brand_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='豪华品牌配置表';
-- 初始化数据(可按需调整 is_luxury 值)
INSERT INTO `luxury_brand_config` (`brand_name`, `is_luxury`, `remark`) VALUES
('问界', 1, 'AITO 旗下豪华品牌'),
('鸿蒙', 1, 'AITO 旗下'),
('智界', 1, '奇瑞合作'),
('享界', 1, '北汽合作'),
('尚界', 1, '江淮合作'),
('尊界', 1, '豪华系列'),
('AITO', 1, '华为高端汽车品牌');
-- data_report.luxury_brand_config definition
ALTER TABLE data_report.data_process_task ADD period_start date NULL COMMENT '所属周期-开始日期(need_period 类型使用,如 2026-08-01)';
ALTER TABLE data_report.data_process_task ADD period_end date NULL COMMENT '所属周期-结束日期(need_period 类型使用,如 2026-08-31)';
-- Step 1. 新增字段(period_type/week_num)
ALTER TABLE data_process_task
ADD COLUMN period_type VARCHAR(10) NOT NULL DEFAULT 'month'
COMMENT '周期粒度:month 按月 / week 按周' AFTER month,
ADD COLUMN week_num INT NULL
COMMENT '按周时的周序号 1-5;按月时为 NULL' AFTER period_type;
ALTER TABLE data_process_task DROP INDEX uq_task_type_month;
CREATE TABLE `luxury_brand_config` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`brand_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '品牌名称(如 问界/鸿蒙/奔驰/宝马 等)',
`is_luxury` int(11) NOT NULL COMMENT '是否豪华品牌:1豪华 / 0非豪华',
`remark` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '备注',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`is_deleted` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_luxury_brand_name` (`brand_name`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='豪华品牌配置表';
-- data_report.data_process_subtask definition
CREATE TABLE `data_process_subtask` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '主任务ID(关联 data_process_task.id)',
`output_category` varchar(30) NOT NULL COMMENT '输出类别:warranty=延保 / equity=权益 / inshop=轻改店中店 / park=轻改园区店',
`status` varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '子任务状态:PENDING待处理 / PROCESSING处理中 / COMPLETED已完成 / FAILED失败',
`error_msg` varchar(500) DEFAULT '' COMMENT '失败时的错误信息',
`row_count` int(11) DEFAULT '0' COMMENT '实际写入行数(处理完成后更新)',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_subtask_task_category` (`task_id`,`output_category`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-子任务表(追踪 4 张输出表的独立处理状态)';
-- data_report.report_equity_service definition
CREATE TABLE `report_equity_service` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`period_start` date DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` date DEFAULT NULL COMMENT '统计周期结束日期',
`region_area` varchar(50) DEFAULT '' COMMENT '片区',
`province` varchar(50) DEFAULT '' COMMENT '省份',
`city` varchar(50) DEFAULT '' COMMENT '城市',
`region_manager` varchar(50) DEFAULT '' COMMENT '区域运营',
`training_supervisor` varchar(50) DEFAULT '' COMMENT '培训督导',
`biz_manager` varchar(50) DEFAULT '' COMMENT '业务经理',
`resident_type` varchar(50) DEFAULT '' COMMENT '驻店类型',
`store_name` varchar(200) DEFAULT '' COMMENT '门店名',
`brand` varchar(50) DEFAULT '' COMMENT '品牌',
`delivery_cnt` int(11) DEFAULT '0' COMMENT '交车',
`touch_cnt` int(11) DEFAULT '0' COMMENT '触客',
`deal_cnt` int(11) DEFAULT '0' COMMENT '成交数',
`penetration_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '渗透率',
`store_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '门店产值',
`upgrade_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '升级客单价',
`product_cost` decimal(15,2) DEFAULT '0.00' COMMENT '商品成本',
`store_share` decimal(15,2) DEFAULT '0.00' COMMENT '门店分成',
`guarantee_amount` decimal(15,2) DEFAULT '0.00' COMMENT '兜底金额',
`gl_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联分成',
`market_fee` decimal(15,2) DEFAULT '0.00' COMMENT '市场费',
`market_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '市场费占比',
`marketing_fee` decimal(15,2) DEFAULT '0.00' COMMENT '营销费用',
`marketing_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '营销费用占比',
`service_fee` decimal(15,2) DEFAULT '0.00' COMMENT '服务费用',
`service_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '服务费用占比',
`total_cost` decimal(15,2) DEFAULT '0.00' COMMENT '成本总计',
`cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '成本占比',
`gross_profit` decimal(15,2) DEFAULT '0.00' COMMENT '毛利测算',
`gross_profit_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '预估毛利率',
`gross_profit_status` varchar(20) DEFAULT '' COMMENT '预估毛利情况',
`gross_profit_rank` int(11) DEFAULT '0' COMMENT '门店毛利排名',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15232 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-权益表';
-- data_report.report_extended_warranty definition
CREATE TABLE `report_extended_warranty` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`period_start` date DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` date DEFAULT NULL COMMENT '统计周期结束日期',
`region_area` varchar(50) DEFAULT '' COMMENT '片区',
`province` varchar(50) DEFAULT '' COMMENT '省份',
`city` varchar(50) DEFAULT '' COMMENT '城市',
`region_manager` varchar(50) DEFAULT '' COMMENT '区域运营',
`training_supervisor` varchar(50) DEFAULT '' COMMENT '培训督导',
`biz_manager` varchar(50) DEFAULT '' COMMENT '业务经理',
`resident_type` varchar(50) DEFAULT '' COMMENT '驻店类型',
`store_name` varchar(200) DEFAULT '' COMMENT '门店名',
`brand` varchar(50) DEFAULT '' COMMENT '品牌',
`delivery_cnt` int(11) DEFAULT '0' COMMENT '交车',
`touch_cnt` int(11) DEFAULT '0' COMMENT '触客',
`deal_cnt` int(11) DEFAULT '0' COMMENT '成交数',
`penetration_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '渗透率',
`vehicle_warranty_cnt` int(11) DEFAULT '0' COMMENT '整车延保成交数',
`vehicle_warranty_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '整车延保渗透率',
`vehicle_warranty_touch_convert` decimal(10,6) DEFAULT '0.000000' COMMENT '整车延保触客成交率',
`battery_warranty_cnt` int(11) DEFAULT '0' COMMENT '电池成交数',
`battery_warranty_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '电池渗透率',
`easy_bag_cnt` int(11) DEFAULT '0' COMMENT '安心包成交数',
`easy_bag_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '安心包渗透率',
`store_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '门店产值',
`upgrade_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '升级客单价',
`product_cost` decimal(15,2) DEFAULT '0.00' COMMENT '商品成本',
`store_share` decimal(15,2) DEFAULT '0.00' COMMENT '门店分成',
`guarantee_amount` decimal(15,2) DEFAULT '0.00' COMMENT '兜底金额',
`gl_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联分成',
`market_fee` decimal(15,2) DEFAULT '0.00' COMMENT '市场费',
`market_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '市场费占比',
`marketing_fee` decimal(15,2) DEFAULT '0.00' COMMENT '营销费用',
`marketing_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '营销费用占比',
`service_fee` decimal(15,2) DEFAULT '0.00' COMMENT '服务费用',
`service_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '服务费用占比',
`total_cost` decimal(15,2) DEFAULT '0.00' COMMENT '成本总计',
`cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '成本占比',
`gross_profit` decimal(15,2) DEFAULT '0.00' COMMENT '毛利测算',
`gross_profit_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '预估毛利率',
`gross_profit_status` varchar(20) DEFAULT '' COMMENT '预估毛利情况',
`gross_profit_rank` int(11) DEFAULT '0' COMMENT '门店毛利排名',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=43461 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-延保表';
-- data_report.report_light_reform_inshop definition
CREATE TABLE `report_light_reform_inshop` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`period_start` date DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` date DEFAULT NULL COMMENT '统计周期结束日期',
`region_area` varchar(50) DEFAULT '' COMMENT '大区名称',
`province` varchar(50) DEFAULT '' COMMENT '区域省',
`city` varchar(50) DEFAULT '' COMMENT '区域市',
`park_type` varchar(50) DEFAULT '' COMMENT '园区类型',
`biz_line` varchar(50) DEFAULT '' COMMENT '业务线',
`operate_type` varchar(50) DEFAULT '' COMMENT '经营属性',
`region_manager` varchar(50) DEFAULT '' COMMENT '区域经理',
`park_name` varchar(200) DEFAULT '' COMMENT '园区名称',
`store_name` varchar(200) DEFAULT '' COMMENT '门店名称',
`brand` varchar(50) DEFAULT '' COMMENT '品牌(问界/鸿蒙)',
`brand_category` varchar(50) DEFAULT '' COMMENT '品牌分类(豪华/非豪华)',
`purchase_indicator` varchar(200) DEFAULT '' COMMENT '采买/兜底指标',
`sales_order_cnt` int(11) DEFAULT '0' COMMENT '销售大定数',
`sales_touch_cnt` int(11) DEFAULT '0' COMMENT '销售触客数',
`sales_touch_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '销售触客率',
`delivery_cnt` int(11) DEFAULT '0' COMMENT '交车数',
`delivery_touch_cnt` int(11) DEFAULT '0' COMMENT '交付触客数',
`delivery_touch_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '交付触客率',
`aftersales_baohui_cnt` int(11) DEFAULT '0' COMMENT '售后首保回厂数',
`aftersales_shigu_cnt` int(11) DEFAULT '0' COMMENT '售后事故回厂数',
`aftersales_touch_cnt` int(11) DEFAULT '0' COMMENT '售后触客数',
`aftersales_touch_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '售后触客率',
`total_touch_cnt` int(11) DEFAULT '0' COMMENT '总触客数',
`total_deal_cnt` int(11) DEFAULT '0' COMMENT '总成交数',
`window_film_oe_cnt` int(11) DEFAULT '0' COMMENT '窗膜成交数-原厂',
`window_film_nonoe_cnt` int(11) DEFAULT '0' COMMENT '窗膜成交数-副厂',
`car_wrap_oe_cnt` int(11) DEFAULT '0' COMMENT '车衣成交数-原厂',
`car_wrap_nonoe_cnt` int(11) DEFAULT '0' COMMENT '车衣成交数-副厂',
`premium_oe_cnt` int(11) DEFAULT '0' COMMENT '精品成交数-原厂',
`premium_nonoe_cnt` int(11) DEFAULT '0' COMMENT '精品成交数-副厂',
`pedal_cnt` int(11) DEFAULT '0' COMMENT '踏板',
`store_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '门店总产值',
`internal_settle_value` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算产值',
`total_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '合计总产值',
`oe_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '原厂总产值',
`nonoe_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '副厂总产值',
`avg_unit_price_delivery` decimal(15,2) DEFAULT '0.00' COMMENT '平均客单价(交车)',
`avg_price_target` decimal(15,2) DEFAULT '0.00' COMMENT '平客目标值',
`avg_price_diff` decimal(15,2) DEFAULT '0.00' COMMENT '平客差值',
`delivery_touch_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '交付触客客单价',
`upgrade_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '升级客单价',
`total_penetration_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '总订单渗透率',
`window_film_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '窗膜渗透率',
`car_wrap_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '车衣渗透率',
`premium_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '精品渗透率',
`product_cost_finance` decimal(15,2) DEFAULT '0.00' COMMENT '产品成本(财务列表)',
`internal_settle_cost` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算成本(财务列表)',
`oe_product_cost` decimal(15,2) DEFAULT '0.00' COMMENT '原厂产品成本(财务列表)',
`nonoe_product_cost` decimal(15,2) DEFAULT '0.00' COMMENT '副厂产品成本(财务列表)',
`window_film_cost` decimal(15,2) DEFAULT '0.00' COMMENT '窗膜成本',
`car_wrap_cost` decimal(15,2) DEFAULT '0.00' COMMENT '车衣成本',
`premium_cost` decimal(15,2) DEFAULT '0.00' COMMENT '精品成本',
`product_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '产品总成本占比',
`construction_cost` decimal(15,2) DEFAULT '0.00' COMMENT '施工成本',
`construction_cost_oe` decimal(15,2) DEFAULT '0.00' COMMENT '原厂施工成本',
`construction_cost_nonoe` decimal(15,2) DEFAULT '0.00' COMMENT '副厂施工成本',
`construction_cost_post` decimal(15,2) DEFAULT '0.00' COMMENT '后置施工成本(直营按商务政策, 服务商=0)',
`construction_cost_post_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '后置施工成本占比(post/门店总产值)',
`construction_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '施工成本占比',
`frontline_incentive` decimal(15,2) DEFAULT '0.00' COMMENT '一线激励',
`frontline_incentive_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '一线激励占比',
`gross_profit_pre_share` decimal(15,2) DEFAULT '0.00' COMMENT '进销差(未分成)',
`gross_profit_pre_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '进销差占比',
`store_share` decimal(15,2) DEFAULT '0.00' COMMENT '门店分成',
`store_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '门店分成占比',
`store_share_per_car` decimal(15,2) DEFAULT '0.00' COMMENT '门店单车利润',
`guarantee_amount` decimal(15,2) DEFAULT '0.00' COMMENT '兜底金额',
`gl_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联分成',
`gl_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '广联分成占比',
`construction_income` decimal(15,2) DEFAULT '0.00' COMMENT '施工收入',
`internal_settle_profit` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算',
`gl_total_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联总分成',
`marketing_personnel_cost` decimal(15,2) DEFAULT '0.00' COMMENT '营销人员成本',
`marketing_personnel_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '营销人员成本占比',
`market_fee` decimal(15,2) DEFAULT '0.00' COMMENT '市场费',
`market_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '市场费占比',
`renovation_amortization` decimal(15,2) DEFAULT '0.00' COMMENT '装修分摊',
`rent_utilities` decimal(15,2) DEFAULT '0.00' COMMENT '房租、水电费用',
`store_consumables` decimal(15,2) DEFAULT '0.00' COMMENT '门店耗材',
`service_provider_share` decimal(15,2) DEFAULT '0.00' COMMENT '服务商分成',
`service_provider_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '服务商分成占比',
`total_cost` decimal(15,2) DEFAULT '0.00' COMMENT '成本总计',
`cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '总计占比',
`gross_profit` decimal(15,2) DEFAULT '0.00' COMMENT '毛利测算',
`gross_profit_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '毛利率',
`gross_profit_status` varchar(20) DEFAULT '' COMMENT '毛利情况',
`gross_profit_rank` int(11) DEFAULT '0' COMMENT '门店毛利排名',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4673 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-轻改店中店汇总表';
-- data_report.report_light_reform_park definition
CREATE TABLE `report_light_reform_park` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`period_start` date DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` date DEFAULT NULL COMMENT '统计周期结束日期',
`region_area` varchar(50) DEFAULT '' COMMENT '大区名称',
`province` varchar(50) DEFAULT '' COMMENT '区域省',
`city` varchar(50) DEFAULT '' COMMENT '区域市',
`park_type` varchar(50) DEFAULT '' COMMENT '园区类型',
`operate_type` varchar(50) DEFAULT '' COMMENT '经营属性',
`partner_store_cnt` int(11) DEFAULT '0' COMMENT '合作门店数量',
`region_manager` varchar(50) DEFAULT '' COMMENT '区域经理',
`park_name` varchar(200) DEFAULT '' COMMENT '园区名称',
`store_name` varchar(200) DEFAULT '' COMMENT '门店名称',
`brand` varchar(50) DEFAULT '' COMMENT '品牌',
`biz_type` varchar(50) DEFAULT '' COMMENT '类型',
`purchase_indicator` varchar(200) DEFAULT '' COMMENT '采买/兜底指标(流量费)',
`delivery_cnt` int(11) DEFAULT '0' COMMENT '交车数',
`arrival_cnt` int(11) DEFAULT '0' COMMENT '到店数',
`arrival_invalid_cnt` int(11) DEFAULT '0' COMMENT '到店无效客户数',
`invalid_arrival_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '无效到店率',
`arrival_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '到店率',
`deal_cnt` int(11) DEFAULT '0' COMMENT '成交数',
`conversion_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '转化率',
`store_sales_output` decimal(15,2) DEFAULT '0.00' COMMENT '门店销售产值',
`internal_settle_value` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算产值',
`total_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '合计总产值',
`output_progress` decimal(10,6) DEFAULT '0.000000' COMMENT '产值达成进度',
`avg_unit_price_arrival` decimal(15,2) DEFAULT '0.00' COMMENT '平均客单价(到店)',
`avg_price_target` decimal(15,2) DEFAULT '0.00' COMMENT '平客目标值',
`avg_price_diff` decimal(15,2) DEFAULT '0.00' COMMENT '平客差值',
`upgrade_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '升级客单价',
`window_film_cnt` int(11) DEFAULT '0' COMMENT '窗膜成交数',
`window_film_convert` decimal(10,6) DEFAULT '0.000000' COMMENT '窗膜转化率',
`car_wrap_cnt` int(11) DEFAULT '0' COMMENT '车衣成交数',
`car_wrap_convert` decimal(10,6) DEFAULT '0.000000' COMMENT '车衣转化率',
`premium_cnt` int(11) DEFAULT '0' COMMENT '精品成交数',
`premium_convert` decimal(10,6) DEFAULT '0.000000' COMMENT '精品转化率',
`est_traffic` int(11) DEFAULT '0' COMMENT '商务上架预估流量',
`est_delivery_cnt` int(11) DEFAULT '0' COMMENT '预估交车数',
`est_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '预估总产值(预算目标)',
`product_cost_finance` decimal(15,2) DEFAULT '0.00' COMMENT '产品成本(财务列表)',
`product_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '产品成本占比',
`internal_settle_cost` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算成本(财务列表)',
`traffic_fee_finance` decimal(15,2) DEFAULT '0.00' COMMENT '流量费(财务列表)',
`traffic_fee_per_car` decimal(15,2) DEFAULT '0.00' COMMENT '按单台计算流量/台',
`traffic_fee_order` decimal(15,2) DEFAULT '0.00' COMMENT '按台次计算流量费',
`store_traffic_fee` decimal(15,2) DEFAULT '0.00' COMMENT '门店流量费',
`traffic_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '流量费率(列表测算)',
`gl_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联分成',
`gl_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '广联分成占比',
`internal_settle_profit` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算',
`gl_total_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联总分成',
`personnel_cost` decimal(15,2) DEFAULT '0.00' COMMENT '人员成本',
`personnel_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '常规人员费率(加权参考)',
`construction_cost` decimal(15,2) DEFAULT '0.00' COMMENT '施工成本',
`construction_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '施工成本占比',
`market_fee_weighted` decimal(15,2) DEFAULT '0.00' COMMENT '市场费(加权测算)',
`market_fee_weighted_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '市场费费率(加权参考)',
`service_fee` decimal(15,2) DEFAULT '0.00' COMMENT '服务费(商务报表)',
`service_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '服务费费率(加权参考)',
`renovation_amortization` decimal(15,2) DEFAULT '0.00' COMMENT '装修分摊(商务报表)',
`renovation_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '装修占比',
`rent_utilities` decimal(15,2) DEFAULT '0.00' COMMENT '房租、水电费用',
`rent_utilities_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '房租、水电占比',
`store_consumables` decimal(15,2) DEFAULT '0.00' COMMENT '门店耗材',
`store_consumables_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '门店耗材占比',
`total_cost` decimal(15,2) DEFAULT '0.00' COMMENT '成本总计',
`cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '总计占比',
`gross_profit` decimal(15,2) DEFAULT '0.00' COMMENT '毛利测算',
`gross_profit_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '毛利率',
`gross_profit_status` varchar(20) DEFAULT '' COMMENT '毛利情况',
`gross_profit_rank` int(11) DEFAULT '0' COMMENT '门店毛利排名',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2081 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-轻改园区店汇总表';
-- data_report.report_store_effect_summary definition
CREATE TABLE `report_store_effect_summary` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`stat_month` varchar(7) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '统计月份 YYYY-MM',
`period_start` date DEFAULT NULL COMMENT '统计周期开始',
`period_end` date DEFAULT NULL COMMENT '统计周期结束',
`store_count` int(11) DEFAULT NULL COMMENT '门店数(跨业务类型去重)',
`delivery_total` int(11) DEFAULT NULL COMMENT '交车数合计',
`touch_total` int(11) DEFAULT NULL COMMENT '触客数合计',
`deal_total` int(11) DEFAULT NULL COMMENT '成交数合计',
`output_value_total` decimal(15,2) DEFAULT NULL COMMENT '产值合计',
`cost_total` decimal(15,2) DEFAULT NULL COMMENT '成本合计',
`gross_profit_total` decimal(15,2) DEFAULT NULL COMMENT '毛利合计',
`gross_profit_rate` decimal(10,6) DEFAULT NULL COMMENT '毛利率',
`labor_cost_total` decimal(15,2) DEFAULT NULL COMMENT '人力成本合计',
`headcount_total` int(11) DEFAULT NULL COMMENT '人员数合计',
`per_capita_output` decimal(15,2) DEFAULT NULL COMMENT '人均产值',
`per_capita_profit` decimal(15,2) DEFAULT NULL COMMENT '人均毛利',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`is_deleted` int(11) NOT NULL,
`deleted_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_store_effect_summary_task_period` (`task_id`,`period_start`,`period_end`)
) ENGINE=InnoDB AUTO_INCREMENT=318 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='门店店效人效汇总表(整体合计)';
-- data_report.saas_business_achievement definition
CREATE TABLE `saas_business_achievement` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`stat_month` char(7) NOT NULL COMMENT '统计月份,格式 YYYY-MM,如 2026-09',
`start_date` char(10) NOT NULL COMMENT '统计周期开始时间,如 2026-09-01',
`end_date` char(10) NOT NULL COMMENT '统计周期结束时间,如 2026-09-15',
`business_type` varchar(20) NOT NULL COMMENT '业务类型:2.1+2.3 或 1.1',
`manager` varchar(50) DEFAULT NULL COMMENT '大区经理(B列)',
`region_operator` varchar(50) NOT NULL COMMENT '区域运营负责人(B列)',
`online_operator` varchar(50) DEFAULT NULL COMMENT '线上运营(D列)',
`operated_stores` int(10) unsigned DEFAULT '0' COMMENT '运营门店数(E列)',
`direct_stores` int(10) unsigned DEFAULT '0' COMMENT '直营门店数(F列)',
`daily_new_gmv` decimal(15,2) DEFAULT '0.00' COMMENT '当日新增 GMV(G列)',
`existing_budget` decimal(15,2) DEFAULT '0.00' COMMENT '存量门店预算(H列)',
`existing_actual` decimal(15,2) DEFAULT '0.00' COMMENT '存量门店实际达成(I列)',
`existing_rate` decimal(5,2) DEFAULT '0.00' COMMENT '存量目标达成率(%)(J列)',
`new_budget` decimal(15,2) DEFAULT '0.00' COMMENT '新店预算(K列)',
`new_actual` decimal(15,2) DEFAULT '0.00' COMMENT '新店实际达成(L列)',
`new_rate` decimal(5,2) DEFAULT '0.00' COMMENT '新店目标达成率(%)(M列)',
`total_actual_gmv` decimal(15,2) DEFAULT '0.00' COMMENT '实际达成 GMV 合计(存量+新店)(N列)',
`total_rate` decimal(5,2) DEFAULT '0.00' COMMENT '总预算达成率(%)(O列)',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '记录更新时间',
PRIMARY KEY (`id`),
KEY `idx_stat_month` (`stat_month`),
KEY `idx_business_type` (`business_type`),
KEY `idx_region_operator` (`region_operator`)
) ENGINE=InnoDB AUTO_INCREMENT=913 DEFAULT CHARSET=utf8mb4 COMMENT='产值达成表';
-- data_report.config_brand_category2 definition
CREATE TABLE `config_brand_category2` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`brand` varchar(200) NOT NULL COMMENT '品牌',
`category` varchar(50) NOT NULL DEFAULT '' COMMENT '品牌区分(如 豪华/非豪华)',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_brand` (`brand`(191))
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COMMENT='豪华品牌配置表';
-- data_report.config_brand_category definition
CREATE TABLE `config_brand_category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`brand` varchar(200) NOT NULL COMMENT '品牌',
`category` varchar(50) NOT NULL DEFAULT '' COMMENT '品牌区分(如 豪华/非豪华)',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_brand` (`brand`(191))
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8mb4 COMMENT='豪华品牌配置表';
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(1, 'AITO', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(2, '鸿蒙智行', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(3, '奥迪', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(4, '腾势', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(5, '奔驰', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(6, '领克', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(7, 'AITO&鸿蒙', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(8, '宝马mini', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(9, '鸿蒙', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(10, '问界&鸿蒙', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(11, '问界', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(12, '腾势汽车', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(13, '红旗', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(14, '奔驰smart', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(15, '凯迪拉克', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(16, '尚界&问界', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(17, 'AITO&鸿蒙智行', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(18, 'Smart', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(1, 'AITO', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(2, '鸿蒙智行', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(3, '奥迪', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(4, '腾势', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(5, '奔驰', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(6, '领克', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(7, 'AITO&鸿蒙', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(8, '宝马mini', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(9, '鸿蒙', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(10, '问界&鸿蒙', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(11, '问界', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(12, '腾势汽车', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(13, '红旗', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(14, '奔驰smart', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(15, '凯迪拉克', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(16, '尚界&问界', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(17, 'AITO&鸿蒙智行', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(18, 'Smart', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(33, 'AITO&鸿蒙智行', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(34, '鸿蒙智行', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(35, '北汽极狐', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(36, 'AITO', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(37, '极氪', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(38, '鸿蒙智行(含尚界)', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(39, '岚图', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(40, '奔驰', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(41, '极狐', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(42, '鸿蒙+尚界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(43, '阿维塔', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(44, '尚界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(45, '东风奕派', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(46, '奇瑞icar', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(47, '广汽丰田', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(48, '领克', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(49, '长安', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(50, '东风岚图', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(51, '奇瑞', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(52, '零跑', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(53, '腾势', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(54, '奥迪', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(55, '大众', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(56, '鸿蒙-尚界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(57, '东本', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(58, 'Smart', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(59, '比亚迪', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(60, '坦克', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(62, '吉利', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(63, '广汽传祺', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(64, '北京越野', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(65, '方程豹', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(66, '广汽埃安', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(67, '广汽本田', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(68, '吉利银河', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(69, '阿维塔、长安、长城、哈弗、欧拉、坦克', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(70, '银河', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(71, '上汽大众', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(72, '捷途纵横', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(73, '东风日产', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(74, '埃安', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(75, '星途', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(76, '比亚迪方程豹', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(77, '启源', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(78, '深蓝', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(79, '长安引力', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(80, 'AITO/鸿蒙智行', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(81, '智界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(82, '智已', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(83, '智己', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(84, 'AITO&鸿蒙', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(85, '鸿蒙', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(86, '捷途', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(87, '奔驰smart', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(88, '广爱埃安、广汽传祺', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(89, '鸿蒙智界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(90, '长安汽车', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(91, '启境', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(92, '坦克,奇瑞', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(93, '长城', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(94, '欧拉', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(95, '福特', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(96, '领克、银河', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(97, '路虎', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(98, '广本', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(99, '广丰', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(100, '传祺', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(101, '品牌', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(102, '收尾接待', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
\ No newline at end of file \ No newline at end of file
-- =====================================================
-- 2. 轻改日报:新车交付数
-- Python函数: fetch_park_daily_report() SQL 1
-- 场景: scene_type=1 轻改, scene_type=0 延保/权益
-- =====================================================
SELECT merchant_name, SUM(IFNULL(delivery_count, 0)) AS delivery_cnt
FROM dj_car_life_merchant_daily_report_huawei
WHERE deleted_flag = 'N'
AND report_date >= '{{start_date}}'
AND report_date <= '{{end_date}}'
AND scene_type = {{scene_type}}
GROUP BY merchant_name;
-- =====================================================
-- 3. 轻改日报:权益到店 + 售后权益到店
-- Python函数: fetch_park_daily_report() SQL 2
-- 场景: scene_type=1 轻改, scene_type=0 延保/权益
-- =====================================================
SELECT merchant_name,
SUM(IFNULL(equity_to_shop_count, 0)) AS equity_to_shop_count,
SUM(IFNULL(after_sale_equity_to_shop_count, 0)) AS after_sale_equity_to_shop_count
FROM dj_car_life_staff_daily_report_huawei
WHERE deleted_flag = 'N'
AND report_date >= '{{start_date}}'
AND report_date <= '{{end_date}}'
AND scene_type = {{scene_type}}
GROUP BY merchant_name;
-- =====================================================
-- 6. 预估交车数(静态配置表)
-- Python函数: fetch_est_delivery_count()
-- 场景: base_scene_code='100101' 轻改
-- =====================================================
SELECT traffic_party_name,
IF(estimated_delivery_count_per_month IS NULL,
delivery_count,
estimated_delivery_count_per_month) AS final_delivery_count
FROM dj_car_life_merchant_store_info
WHERE base_scene_code = '100101'
AND deleted_flag = 'N'
ORDER BY created_date DESC;
-- =====================================================
-- 7. 查询园区店
-- 场景: base_scene_code='100101' 轻改
-- =====================================================
select traffic_party_name,parking_store_name from dj_car_life_merchant_store_info where base_scene_code ='100101' and deleted_flag ='N'
\ No newline at end of file \ No newline at end of file
No preview for this file type
# 门店自建商品销售数据
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
/* 窗膜 */
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
-- AND t1.supplier_name = '第三方'
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN t2.order_code END) AS `窗膜(原厂)`,
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
-- AND t1.supplier_name = '广联直营'
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN t2.order_code END) AS `窗膜(副厂)`,
/* 车衣 */
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('车衣','改色膜')
-- AND t1.supplier_name = '第三方'
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN t2.order_code END) AS `车衣(原厂)`,
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name IN ('车衣','改色膜')
-- AND t1.supplier_name = '广联直营'
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN t2.order_code END) AS `车衣(副厂)`,
/* 踏板 */
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name = '踏板'
THEN t2.order_code END) AS `踏板`,
/* 精品 */
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name NOT IN (
'自建商品-太阳膜','天窗冰甲','车衣','改色膜',
'踏板','充电桩','验收一级类目','太阳膜'
)
-- AND t1.supplier_name = '第三方'
AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
THEN t2.order_code END) AS `精品(原厂)`,
COUNT(DISTINCT CASE
WHEN t1.upgrade_goods_type_name NOT IN (
'自建商品-太阳膜','天窗冰甲','车衣','改色膜',
'踏板','充电桩','验收一级类目','太阳膜'
)
-- AND t1.supplier_name = '广联直营'
AND (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
THEN t2.order_code END) AS `精品(副厂)`
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
AND t1.upgrade_goods_name NOT LIKE '%(赠)%'
GROUP BY
t2.merchant_id,
t2.merchant_name
# 总成交数
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
count(distinct t1.order_code)
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1 and t1.del_flag='N'
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6
GROUP BY
t2.merchant_id,
t2.merchant_name
#门店总产值
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
SUM(IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0))
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6
GROUP BY
t2.merchant_id,
t2.merchant_name
# 内部结算产值
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
SUM(IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0))
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type =6
GROUP BY
t2.merchant_id,
t2.merchant_name
# 原厂总产值
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
SUM(IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0))
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6 AND (t1.upgrade_goods_name LIKE '%AITO%' OR t1.upgrade_goods_name LIKE '%HIMA%')
GROUP BY
t2.merchant_id,
t2.merchant_name
# 副厂总产值
SELECT
t2.merchant_id,
t2.merchant_name AS 门店名称,
SUM(IFNULL(t1.total_price, 0) - IFNULL(t1.refund_amount, 0))
FROM dj_smartcarlife.dj_car_life_goods_sub_order t1
LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6 and (t1.upgrade_goods_name NOT LIKE '%AITO%' AND t1.upgrade_goods_name NOT LIKE '%HIMA%')
GROUP BY
t2.merchant_id,
t2.merchant_name
-- ============================================================================
-- 延保 财务成本分项批量查询
-- 业务系统: dj_smartcarlife
-- 场景: scene_type = 0 (延保/权益)
-- 业务: business_type = 2 (延保)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- 关联表:
-- gopa 利润分配主表 (子订单级, order_flag='N' 非汇总)
-- gopa2 利润分配汇总记录 (order_flag='Y', grain_size_type=1, 拿服务费/施工收入/产值)
-- gso 子订单表 (拿嘀加与第三方成本)
-- go 订单表 (scene_type / business_type / merchant_name)
-- po 支付单表 (success_date 周期过滤)
-- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901))
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY, order 级字段用 MAX 取单次值
-- 外层按 merchant_name GROUP BY, 全部 SUM 跨订单聚合
--
-- 字段口径:
-- 商品成本 = upgrade_dj_cost + (shop_traffic_money_calculate_type=1 时才加 upgrade_third_party_cost)
-- 第三方成本仅在 GMV 口径算流量费时才计入
-- 门店分成/流量费 = shop_traffic_money (来自 gopa 主表)
-- 市场费 = 四项费用累计 (fee 子查询, 内层用 MAX 取单次值)
-- 服务费用 = 服务商金额 franchisee_profit_money (来自 gopa2, 内层用 MAX)
-- 门店产值 = total_price (来自 gopa2, 内层用 MAX)
-- 其他费用 = custom_common_cost (来自 gopa2, 内层用 MAX)
-- ============================================================================
-- ========= 查询参数 =========
SET @start_time = '2026-08-01 00:00:00';
SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 2; -- 2=延保 (1=权益, 另见 权益_财务成本分项.sql)
SELECT
t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(t.product_cost) AS `商品成本`,
-- 门店分成/流量费
SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
SUM(t.market_fee) AS `市场费`,
-- 服务费用 = 服务商金额
SUM(t.service_fee) AS `服务费用`,
-- 门店产值
SUM(t.store_output_value) AS `门店产值`,
-- 其他费用
SUM(t.other_cost) AS `其他费用`
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(IFNULL(gso.upgrade_dj_cost, 0)
+ IF(gopa.shop_traffic_money_calculate_type = 1,
IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- 四项费用累计子查询: 日期 + scene_type + business_type 必须与外层同步!
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND go.business_type = @business_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
-- ============================================================================
-- 权益 财务成本分项批量查询
-- 业务系统: dj_smartcarlife
-- 场景: scene_type = 0 (延保/权益)
-- 业务: business_type = 1 (权益)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- 关联表: 同 延保_财务成本分项.sql
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY, order 级字段用 MAX 取单次值
-- 外层按 merchant_name GROUP BY, 全部 SUM 跨订单聚合
--
-- 字段口径: 同延保 (仅 business_type 不同)
-- ============================================================================
-- ========= 查询参数 =========
SET @start_time = '2026-08-01 00:00:00';
SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 1; -- 1=权益 (2=延保, 另见 延保_财务成本分项.sql)
SELECT
t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(t.product_cost) AS `商品成本`,
-- 门店分成/流量费
SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
SUM(t.market_fee) AS `市场费`,
-- 服务费用 = 服务商金额
SUM(t.service_fee) AS `服务费用`,
-- 门店产值
SUM(t.store_output_value) AS `门店产值`,
-- 其他费用
SUM(t.other_cost) AS `其他费用`
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(IFNULL(gso.upgrade_dj_cost, 0)
+ IF(gopa.shop_traffic_money_calculate_type = 1,
IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type + business_type 与外层同步
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND go.business_type = @business_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
-- ============================================================================
-- 轻改(园区店) 财务成本分项批量查询
-- 业务系统: dj_smartcarlife
-- 场景: scene_type = 1 (轻改)
-- 业务: business_type = 1 OR 2 (轻改不区分)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积 (同店中店)
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY
-- - gopa/gso 级字段 → SUM(同订单多 sub_order_code 要累加)
-- - order 级字段(fee.total) → MAX(避免 JOIN 膨胀)
-- 外层按 merchant_name GROUP BY → 全部 SUM 跨订单聚合
--
-- 与"轻改店中店"的区别:
-- 园区店只消费 4 个字段 (不需要窗膜/车衣/精品/原厂/副厂/施工收入等):
-- 产品成本(财务列表) = dj_order_type != 6 → upgrade_shop_price - base_shop_price
-- 内部结算成本(财务列表) = dj_order_type = 6 → upgrade_shop_price - base_shop_price
-- 流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money
-- 市场费(加权测算) = 四项费用累计 (fee 子查询, 内层用 MAX)
-- 字段口径/表关联与店中店完全相同
-- ============================================================================
-- ========= 查询参数 =========
SET @start_time = '2026-08-01 00:00:00';
SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 1; -- 固定: 1=轻改
SELECT
t.merchant_name AS `门店名称`,
-- ===== 产品成本口径: upgrade_shop_price - base_shop_price =====
-- 外层 SUM 跨订单聚合, 内层已按 merchant_name + order_code 聚合好
SUM(t.product_cost_finance) AS `产品成本(财务列表)`,
SUM(t.internal_settle_cost) AS `内部结算成本(财务列表)`,
SUM(t.store_share) AS `流量费(财务列表)`,
-- order 级字段: 内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合
SUM(t.market_fee) AS `市场费`
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- ===== 内层: 按 merchant_name + order_code GROUP BY =====
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS product_cost_finance,
SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS internal_settle_cost,
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS store_share,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
-- ============================================================================
-- 轻改(店中店) 财务成本分项批量查询
-- 业务系统: dj_smartcarlife
-- 场景: scene_type = 1 (轻改)
-- 业务: business_type = 1 OR 2 (轻改不区分权益/延保, 都算)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- 关联表:
-- gopa 利润分配主表 (子订单级, order_flag='N' 非汇总)
-- gopa2 利润分配汇总记录 (order_flag='Y', grain_size_type=1)
-- gso 子订单表 (dj_order_type 区分 内部结算=6 / 非内部结算!=6)
-- go 订单表 (scene_type / merchant_name)
-- po 支付单表 (success_date 周期过滤)
-- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901))
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY
-- - gopa/gso 级字段 → SUM(同订单多 sub_order_code 要累加)
-- - order 级字段(fee.total, gopa2.custom_common_cost) → MAX(避免 JOIN 膨胀)
-- 外层按 merchant_name GROUP BY → 全部 SUM 跨订单聚合
--
-- 字段口径 (店中店消费全部 10 项):
-- 产品成本(财务列表) = dj_order_type != 6 (非内部结算) 的 upgrade_shop_price - base_shop_price
-- 内部结算成本(财务列表) = dj_order_type = 6 (内部结算) 的 upgrade_shop_price - base_shop_price
-- 原厂产品成本(财务列表) = dj_order_type != 6 + goods_name LIKE '%AITO%' OR '%HIMA%'
-- 副厂产品成本(财务列表) = dj_order_type != 6 + goods_name NOT LIKE '%AITO%' AND NOT LIKE '%HIMA%'
-- 窗膜成本 = upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
-- 车衣成本 = upgrade_goods_type_name IN ('车衣','改色膜')
-- 精品成本 = upgrade_goods_type_name NOT IN (窗膜/车衣 所有类型)
-- 门店分成/流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money
-- 施工收入 = custom_common_cost (汇总记录 gopa2, 内层用 MAX)
-- 市场费 = 四项费用累计 (fee 子查询, 内层用 MAX)
-- ============================================================================
-- ========= 查询参数 =========
SET @start_time = '2026-08-01 00:00:00';
SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 1; -- 固定: 1=轻改
SELECT
t.merchant_name AS `门店名称`,
-- ===== 产品成本口径: upgrade_shop_price - base_shop_price =====
-- 外层 SUM 跨订单聚合, 内层已按 merchant_name + order_code 聚合好
SUM(t.product_cost_finance) AS `产品成本(财务列表)`,
SUM(t.internal_settle_cost) AS `内部结算成本(财务列表)`,
SUM(t.oe_product_cost) AS `原厂产品成本(财务列表)`,
SUM(t.nonoe_product_cost) AS `副厂产品成本(财务列表)`,
SUM(t.window_film_cost) AS `窗膜成本`,
SUM(t.car_wrap_cost) AS `车衣成本`,
SUM(t.premium_cost) AS `精品成本`,
SUM(t.store_share) AS `门店分成/流量费(财务列表)`,
-- order 级字段: 内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合
SUM(t.construction_income) AS `施工收入`,
SUM(t.market_fee) AS `市场费`
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- ===== 内层: 按 merchant_name + order_code GROUP BY =====
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS product_cost_finance,
SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS internal_settle_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND (gso.upgrade_goods_name LIKE '%AITO%'
OR gso.upgrade_goods_name LIKE '%HIMA%')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS oe_product_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS nonoe_product_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS window_film_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('车衣','改色膜')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS car_wrap_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN ('自建商品-太阳膜','天窗冰甲','太阳膜','车衣','改色膜','踏板','充电桩','验收一级类目')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS premium_cost,
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS store_share,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS construction_income,
MAX(IFNULL(fee.total, 0)) AS market_fee
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
No preview for this file type
# -*- coding: utf-8 -*-
"""
门店店效人效汇总表 - 结果输出独立脚本(第5个 sheet)
============================================================================
用途:不依赖完整调度链路,直接产出「门店店效人效汇总表」单 sheet Excel。
用法:
1) 本地骨架/样例(不需要数据库、不需要任何凭证):
python generate_store_effect_summary.py --demo
python generate_store_effect_summary.py --demo --month 2026-08
2) 基于已计算的任务结果(需要应用运行环境,读取 report_store_effect_summary):
python generate_store_effect_summary.py --task-id <ID> # 本地落盘
python generate_store_effect_summary.py --task-id <ID> --oss # 上传 OSS 并回填
输出位置:
--demo / --task-id(默认): data-process/outputs/store_effect_summary/门店店效人效汇总表_<月份>.xlsx
--oss:上传 OSS,返回 URL,并回填 task.result_file_url
"""
import argparse
import os
import sys
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
# 与 store_effect_summary_processor.RESULT_COLUMNS 保持一致
RESULT_COLUMNS = [
('门店数', 'store_count', 'int'),
('交车数', 'delivery_total', 'int'),
('触客数', 'touch_total', 'int'),
('成交数', 'deal_total', 'int'),
('产值合计', 'output_value_total', 'amount'),
('成本合计', 'cost_total', 'amount'),
('毛利合计', 'gross_profit_total', 'amount'),
('毛利率', 'gross_profit_rate', 'rate'),
('人力成本', 'labor_cost_total', 'amount'),
('人员数', 'headcount_total', 'int'),
('人均产值', 'per_capita_output', 'amount'),
('人均毛利', 'per_capita_profit', 'amount'),
]
NOTE_TEXT = ('注:整体合计,不分组;业务系统SQL字段在 BIZ_SQL_ENABLED=false 时'
'为0,数字待校准。')
FONT_NAME = '微软雅黑'
def build_workbook(stat_month, end_date_str, values):
"""纯 openpyxl 构建结果表(与处理器 generate_result_excel 同布局)。"""
from openpyxl import Workbook
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
wb = Workbook()
ws = wb.active
ws.title = '门店店效人效汇总表'
header_font = Font(name=FONT_NAME, size=11, bold=True, color='FFFFFF')
header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
title_font = Font(name=FONT_NAME, size=12, bold=True)
cell_font = Font(name=FONT_NAME, size=10)
center = Alignment(horizontal='center', vertical='center', wrap_text=True)
right = Alignment(horizontal='right', vertical='center')
thin = Border(left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin'))
ncol = len(RESULT_COLUMNS)
# 行1 标题
title_cell = ws.cell(
row=1, column=1,
value=f'{stat_month}月门店店效人效汇总表(整体合计,截止"{end_date_str}")')
title_cell.font = title_font
title_cell.alignment = center
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=ncol)
# 行2 表头
for c, (header, _attr, _kind) in enumerate(RESULT_COLUMNS, 1):
cell = ws.cell(row=2, column=c, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center
cell.border = thin
# 行3 数据(整体合计一行)
for c, (_header, attr, kind) in enumerate(RESULT_COLUMNS, 1):
val = values.get(attr)
cell = ws.cell(row=3, column=c)
if kind == 'int':
try:
cell.value = int(val) if val is not None else 0
cell.number_format = '#,##0'
except (ValueError, TypeError):
cell.value = ''
elif kind == 'amount':
try:
cell.value = float(val) if val is not None else 0.0
cell.number_format = '#,##0.00'
except (ValueError, TypeError):
cell.value = ''
elif kind == 'rate':
try:
cell.value = float(val) if val is not None else 0.0
cell.number_format = '0.00"%"'
except (ValueError, TypeError):
cell.value = ''
else:
cell.value = str(val) if val is not None else ''
cell.font = cell_font
cell.border = thin
cell.alignment = right if kind in ('int', 'amount', 'rate') else center
# 行4 说明
note = ws.cell(row=4, column=1, value=NOTE_TEXT)
note.font = Font(name=FONT_NAME, size=9, italic=True, color='999999')
note.alignment = Alignment(horizontal='left', vertical='center')
ws.merge_cells(start_row=4, start_column=1, end_row=4, end_column=ncol)
for c in range(1, ncol + 1):
from openpyxl.utils import get_column_letter
ws.column_dimensions[get_column_letter(c)].width = 13
ws.freeze_panes = 'A3'
return wb
def run_demo(month):
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True)
path = os.path.join(out_dir, f'门店店效人效汇总表_{month}.xlsx')
values = {attr: 0 for _, attr, _ in RESULT_COLUMNS}
wb = build_workbook(month, '', values)
wb.save(path)
print(f'[demo] 已生成骨架结果表: {path}')
return path
def run_task(task_id, use_oss):
from app import app
with app.app_context():
from models import DataProcessTask, ReportStoreEffectSummary
from store_effect_summary_processor import StoreEffectSummaryProcessor
task = DataProcessTask.query.filter_by(id=task_id).first()
if not task:
raise SystemExit(f'任务 {task_id} 不存在')
row = ReportStoreEffectSummary.query.filter_by(task_id=task_id).first()
if not row:
raise SystemExit(f'任务 {task_id} 尚未计算(report_store_effect_summary 无数据),'
f'请先由调度器/手动触发计算')
processor = StoreEffectSummaryProcessor()
if use_oss:
url = processor.generate_result_excel(task, row, local_only=False)
task.result_file_url = url
from models import db
db.session.commit()
print(f'[task] 已上传 OSS 并回填 result_file_url: {url}')
else:
path = processor.generate_result_excel(task, row, local_only=True)
print(f'[task] 已生成本地结果表: {path}')
def main():
parser = argparse.ArgumentParser(description='生成门店店效人效汇总表(第5个sheet)')
parser.add_argument('--task-id', type=int, help='基于已计算任务结果生成')
parser.add_argument('--demo', action='store_true', help='生成骨架样例(无需数据库)')
parser.add_argument('--month', default='2026-08', help='--demo 使用的统计月份')
parser.add_argument('--oss', action='store_true', help='--task-id 模式下上传 OSS 并回填')
args = parser.parse_args()
if args.demo:
run_demo(args.month)
elif args.task_id:
run_task(args.task_id, args.oss)
else:
parser.print_help()
if __name__ == '__main__':
main()
# -*- coding: utf-8 -*-
"""
指标系统 API 客户端
===================
封装 http://dc.glsx.com.cn/data 的 POST 调用。
入参:周期 startDate/endDate、biz(1=延保 2=轻改 3=权益)、itemCodes(指标编码列表)
返回:{merchantName: {itemCode: itemValue, ...}, ...} 双层字典,按商户名聚合
百分比字段处理:API 返回的 itemValue 如果是小数(如 0.25 表示 25%),
需在调用侧或本客户端统一 *100 再存库。提供 rate_codes 参数标记哪些是率指标。
"""
import logging
import time
import requests
from decimal import Decimal
from config import Config
logger = logging.getLogger('IndicatorClient')
class IndicatorClient:
"""指标系统 API 客户端(单例 + 重试)"""
# 率类指标编码(API 返回 0.25 表示 25%,需 *100 存库)
RATE_CODES = {
'A076', # 升级客单价(注:A076 是比值类,具体是否率取决于业务定义)
}
def __init__(self):
self.url = Config.INDICATOR_API_URL
self.timeout = Config.INDICATOR_API_TIMEOUT
self.retry = Config.INDICATOR_API_RETRY
# ---------- 底层 HTTP 调用 ----------
def _post(self, payload):
"""单次 POST 请求,返回 (成功布尔, 响应内容或错误信息)"""
try:
resp = requests.post(self.url, json=payload, timeout=self.timeout)
if resp.status_code != 200:
return False, f"HTTP {resp.status_code}: {resp.text[:200]}"
data = resp.json()
if data.get('code') != 200:
return False, f"业务错误 code={data.get('code')} msg={data.get('msg')}"
return True, data.get('content') or []
except requests.Timeout:
return False, "请求超时"
except requests.ConnectionError as e:
return False, f"连接失败: {e}"
except Exception as e:
return False, f"解析异常: {e}"
# ---------- 对外主入口 ----------
def fetch(self, start_date, end_date, biz, item_codes, rate_codes=None):
"""
查询指标数据并按 merchantName 聚合。
参数:
- start_date: str 'YYYY-MM-DD'
- end_date: str 'YYYY-MM-DD'
- biz: int 单值(1=延保 2=轻改 3=权益) 或 list/tuple(如 [1,3] 多业务线);
多值会序列化为逗号字符串 bizs="1,3"(与 itemCodes 风格一致);
单值序列化为 bizs="N"(API 仅认 bizs 键,不再有 "biz" 单数形式);
None 表示不限定业务线 → 不传 bizs 键、查全量(A0018 全国经营总产值用此)。
- item_codes: list[str] 指标编码列表,如 ['A036', 'A075']
- rate_codes: set[str] 率类指标编码,API 返回小数会 *100;None 则用 RATE_CODES 默认
返回:
dict[merchant_name][item_code] = Decimal|float
空 dict 表示查询失败或无数据
"""
if not item_codes:
return {}
rate_set = set(rate_codes) if rate_codes else self.RATE_CODES
payload = {
"dateType": 4,
"startDate": start_date,
"endDate": end_date,
"exts": "merchantIds",
"itemCodes": ",".join(item_codes),
}
# biz=None 表示查全量:不要传 bizs 键,否则 API 把 "None" 当无效业务线过滤返回空
if biz is None:
pass # 不传 bizs → 返回全业务线全量
elif isinstance(biz, (list, tuple, set)):
payload["bizs"] = ",".join(str(b) for b in biz)
else:
payload["bizs"] = str(biz)
last_err = None
# 请求参数日志
logger.info(f"[IndicatorAPI] POST {self.url} payload={payload}")
for attempt in range(1, self.retry + 2): # 首次 + retry 次
ok, content = self._post(payload)
if ok:
if attempt > 1:
logger.info(f"[IndicatorAPI] 第 {attempt} 次重试成功")
return self._aggregate(content, rate_set)
last_err = content
logger.warning(f"[IndicatorAPI] 第 {attempt} 次失败 err={last_err}")
if attempt <= self.retry:
time.sleep(1 * attempt)
logger.error(f"[指标系统] 最终请求失败: {last_err}")
return {}
# ---------- 结果聚合 ----------
def _aggregate(self, content, rate_set):
"""
将 API 返回的扁平列表按 merchantName 聚合成双层字典。
率类指标 *100(四舍五入 6 位小数)。
输入:
content = [{"itemCode":"A036","merchantName":"郑州鸿启汽车贸易有限公司","itemValue":12225,...}, ...]
输出:
{"郑州鸿启汽车贸易有限公司": {"A036": Decimal("12225"), "A075": Decimal("85.500000")}, ...}
"""
result = {}
for row in content or []:
code = row.get('itemCode')
name = row.get('merchantName')
val = row.get('itemValue')
if not code or not name or val is None:
continue
if code in rate_set:
# 率类:API 返回小数 → *100 保留 6 位
try:
raw = Decimal(str(val))
val_dec = (raw * Decimal('100')).quantize(Decimal('0.000001'))
except Exception:
val_dec = float(val) * 100
else:
try:
val_dec = Decimal(str(val))
except Exception:
val_dec = float(val)
merchant_dict = result.setdefault(name, {})
# 同一 merchant + itemCode 如果出现多条(异常情况),取第一条
merchant_dict.setdefault(code, val_dec)
logger.info(f"[指标系统] 聚合完成:{len(result)} 个商户, {len(content or [])} 条原始数据")
return result
# ---------- 便捷批量查询 ----------
def fetch_bulk(self, start_date, end_date, biz, code_groups):
"""
一次请求多组指标编码(自动去重 + 合并)。
code_groups: dict[label, list[item_code]]
例如 {'warranty_core': ['A036','A075'], 'warranty_extra': ['A066','A070']}
返回:fetch() 的结果,直接用 merchantName 查即可。
"""
all_codes = []
for codes in code_groups.values():
all_codes.extend(codes)
# 去重保持顺序
seen = set()
unique = []
for c in all_codes:
if c not in seen:
seen.add(c)
unique.append(c)
return self.fetch(start_date, end_date, biz, unique)
# ---------- 按商户 ID 列表查询(岚图/零跑专项等按 merchant_id 匹配的场景)----------
def fetch_by_merchant_ids(self, start_date, end_date, item_codes, merchant_ids, biz=1):
"""
查询指定商户列表在指定周期的指标数据。
与 fetch() 的区别:
- payload 显式携带 merchantIds(多个英文逗号分隔)+ exts=merchantIds + bizs;
- 返回按 merchant_id(而非 merchantName)聚合,便于用商户号直接取值,
避免门店名匹配的歧义。
参数:
- start_date / end_date: str 'YYYY-MM-DD'
- item_codes: list[str],如 ['A075', 'A084']
- merchant_ids: list[str|int],商户 ID 列表(会序列化为英文逗号分隔)
- biz: int,业务线(1=延保),payload 键为 bizs
返回:
dict[merchant_id(str)][item_code] = Decimal
注意粒度为「商户 × 指标」:同一请求传多个 itemCodes 时,每个商户
每个指标各一条数据,本方法已按 (merchant_id, item_code) 建好双层索引。
空 dict 表示查询失败或无数据。
"""
if not item_codes or not merchant_ids:
return {}
payload = {
"dateType": 4,
"startDate": start_date,
"endDate": end_date,
"exts": "merchantIds",
"itemCodes": ",".join(item_codes),
"merchantIds": ",".join(str(m) for m in merchant_ids),
"bizs": biz,
}
last_err = None
logger.info(f"[IndicatorAPI] POST {self.url} payload={payload}")
for attempt in range(1, self.retry + 2): # 首次 + retry 次
ok, content = self._post(payload)
if ok:
if attempt > 1:
logger.info(f"[IndicatorAPI] 第 {attempt} 次重试成功")
return self._aggregate_by_merchant_id(content)
last_err = content
logger.warning(f"[IndicatorAPI] 第 {attempt} 次失败 err={last_err}")
if attempt <= self.retry:
time.sleep(1 * attempt)
logger.error(f"[指标系统] 按商户查询最终失败: {last_err}")
return {}
@staticmethod
def _aggregate_by_merchant_id(content):
"""
将 API 返回的扁平列表按 merchant_id + itemCode 聚合成双层字典。
输入(商户 × 指标 粒度,每商户每 itemCode 各一条):
content = [{"itemCode":"A075","merchantId":"1001","itemValue":216,...},
{"itemCode":"A084","merchantId":"1001","itemValue":480,...}, ...]
输出:
{"1001": {"A075": Decimal("216"), "A084": Decimal("480")}, ...}
"""
result = {}
for row in content or []:
code = row.get('itemCode')
mid = row.get('merchantId') or row.get('merchant_id')
val = row.get('itemValue')
if not code or not mid or val is None:
continue
try:
val_dec = Decimal(str(val))
except Exception:
val_dec = float(val)
merchant_dict = result.setdefault(str(mid), {})
# 同一 merchant_id + itemCode 出现多条(异常情况)取第一条
merchant_dict.setdefault(code, val_dec)
logger.info(f"[指标系统] 按商户聚合完成:{len(result)} 个商户, "
f"{len(content or [])} 条原始数据")
return result
# -*- coding: utf-8 -*-
"""
零跑专项报表 独立处理器
=======================
对应数据表类型:leapmotor_special(零跑专项,无需上传附件,need_period=True)
功能:查询"零跑"品牌(pg_group_info.group_name='零跑')旗下门店的延保业务经营数据,
按模板 exporttemplete/零跑专项.xlsx 渲染,生成结果 Excel 上传 OSS 并回填 task.result_file_url。
设计见《零跑专项报表设计文档.md》(项目根目录,2026-09-17 已确认)。
与岚图专项(voyah_processor.py)同套管线,差异点:
- 双层表头(第 1~2 行),A~N/R/S 纵向合并、O1:Q1/T1:X1 及尾部 4 组横向合并;
- 评灯区:截止目前(Y 列,黄底,endDate)在前 + 周一/周四动态日期列
(替换模板固定的 W1/W2/W3 周评灯);
- 评灯阈值:渗透率(A075 成交/A062 交车)<30% 红 / [30%,40%) 黄 / >=40% 绿;
- 尾部 12 列:交车数/触客数/订单数/收入 4 组(一店一群 留空 / 日报或系统=对应指标 / 差异 留空);
- T~X 列(渗透率 主机厂/一店一群/W1主机厂/W1一店一群/W3)保留列位、全部留空;
- 合计行:A3:J3 合并"合计",K3~AN3 清空不计算;
- 文件名:零跑专项_{起YYYYMMDD}-{止YYYYMMDD}_{YYYYMMDDHHMMSS}.xlsx。
关键口径(同岚图,已确认):
- 指标返回粒度:商户 × 指标,按 (merchant_id, item_code) 取值;
- 所有单元格写计算值,不写 Excel 公式;渲染时清空模板条件格式。
"""
import logging
import os
import tempfile
from copy import copy
from datetime import date, datetime, timedelta
from decimal import Decimal
import openpyxl
from openpyxl.styles import PatternFill
from openpyxl.utils import get_column_letter
from sqlalchemy import text, bindparam
from config import Config # noqa: F401 (保持与岚图一致的配置加载副作用)
from indicator_client import IndicatorClient
from oss_utils import upload_file
from report_utils import mark_task_failed, cleanup_tmp_dir, _get_biz_sql_conn
from models import DataProcessTask, db
from voyah_processor import shorten_province
logger = logging.getLogger('LeapmotorProcessor')
LEAPMOTOR_TYPE = 'leapmotor_special'
GROUP_NAME = '零跑'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_PATH = os.path.join(BASE_DIR, 'exporttemplete', '零跑专项.xlsx')
TEMPLATE_SHEET = '展示表'
# 指标编码:A036 产值 / A062 交付(交车)数 / A084 触客(引荐)数 / A075 成交(订单)数
CODE_OUTPUT = 'A036'
CODE_DELIVERY = 'A062'
CODE_REFER = 'A084'
CODE_DEAL = 'A075'
# 评灯底色(浅红 / 浅黄 / 浅绿)——与岚图一致
RATE_FILL = {
'红色': 'FFC7CE',
'黄色': 'FFEB9C',
'绿色': 'C6EFCE',
}
# ---------- 模板布局常量(列号 1 起) ----------
# A~S(1~19) 固定列;T~X(20~24) 渗透率 5 列(保留留空);
# Y(25) 截止目前;Z~AB(26~28) 模板周评灯 3 列 → 动态日期列;AC~AN(29~40) 尾部 12 列。
FIXED_COLS = 19 # A~S
T_START = 20 # T~X 渗透率 5 列(留空)
ZHICI_COL = 25 # 截止目前(评灯区第 1 列,黄底)
DYN_COL_START = 26 # 动态日期列起始(模板 Z)
TEMPLATE_DATE_COLS = 3 # 模板动态位数量(Z/AA/AB)
TAIL_START = 29 # 尾部 12 列起始(模板 AC)
# 末列 = ZHICI_COL + n_dates + 12
# 尾部 4 组:行1组标题 / 行2子表头(一店一群留空、日报或系统=对应指标、差异留空)
TAIL_GROUPS = [
('交车数', '生意助手日报'),
('触客数', '生意助手日报'),
('订单数', '系统'),
('收入', '系统'),
]
# 尾部子列取值:None=留空 / 'L'/'M'/'P'/'Q'=同对应指标列
TAIL_VALUES = ['L', 'M', 'P', 'Q']
# TAIL_VALUES 中的列标识 → 指标编码
CODE_MAP = {
'L': CODE_DELIVERY,
'M': CODE_REFER,
'P': CODE_DEAL,
'Q': CODE_OUTPUT,
}
def generate_stat_nodes(period_start, period_end):
"""评灯日期列节点:统计周期内的每个周一、周四(去重升序)。
endDate 不作为日期列,由固定的"截止目前"列体现(与岚图同口径)。"""
nodes = set()
d = period_start
while d <= period_end:
if d.weekday() in (0, 3): # 0=周一 3=周四
nodes.add(d)
d += timedelta(days=1)
return sorted(nodes)
def rating_text(deal, refer):
"""零跑评灯:渗透率(A075/A062)<30% 红 / [30%,40%) 黄 / >=40% 绿。
无数据(成交/交车为空,或交车=0)返回空字符串。"""
if deal is None or refer is None:
return ''
try:
deal_d = Decimal(str(deal))
refer_d = Decimal(str(refer))
except Exception:
return ''
if refer_d == 0:
return ''
pct = deal_d / refer_d * 100
if pct < 30:
return '红色'
if pct < 40:
return '黄色'
return '绿色'
def _pct(num, den):
"""比率(小数),供 '0%' 格式单元格展示;分母空/0 → None(留空)。"""
if num is None or den is None:
return None
try:
num_d, den_d = Decimal(str(num)), Decimal(str(den))
except Exception:
return None
if den_d == 0:
return None
return float(num_d / den_d)
def _int_div(num, den):
"""客单价:Q/P 四舍五入取整;分母空/0 → None。"""
if num is None or den is None:
return None
try:
num_d, den_d = Decimal(str(num)), Decimal(str(den))
except Exception:
return None
if den_d == 0:
return None
return int(num_d / den_d + Decimal('0.5'))
class LeapmotorProcessor:
"""零跑专项报表处理器(调度扫描 + 单任务处理 + Excel 渲染)"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_leapmotor(self):
"""扫描 leapmotor_special 类型的 PROCESSING 任务并逐个处理"""
logger.info("[零跑专项] 开始扫描 leapmotor_special 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=LEAPMOTOR_TYPE,
status='PROCESSING',
is_deleted=0,
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[零跑专项] 扫描到 {len(tasks)} 个待处理任务")
success_count, fail_count = 0, 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[零跑专项] 任务 {task.id} 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[零跑专项] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[零跑专项] 标记任务失败时出错: {mark_err}")
logger.info(f"[零跑专项] 扫描完成,成功 {success_count},失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
# ============================================================
# 单任务处理
# ============================================================
def process(self, task):
"""处理单个零跑专项任务:取数 → 渲染 Excel → 上传 OSS → 回填任务状态"""
task_id = task.id
try:
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
if not period_start or not period_end:
raise Exception("缺少所属周期(period_start/period_end),无法处理")
period_start = self._as_date(period_start)
period_end = self._as_date(period_end)
# 周期校验:开始/结束必须同月(不能跨月)
if (period_start.year, period_start.month) != (period_end.year, period_end.month):
raise Exception(
f"所属周期不能跨月: {period_start} ~ {period_end}")
logger.info(f"[零跑专项] 开始处理 task_id={task_id}, "
f"周期={period_start}~{period_end}")
# Step1+2: 取数
data = self.collect_data(period_start, period_end)
logger.info(f"[零跑专项] 取数完成: {len(data['stores'])} 个门店, "
f"{len(data['nodes'])} 个评灯节点")
# Step3: 渲染 Excel(零跑专项_{起}-{止}_{时间戳}.xlsx)
ts = datetime.now().strftime('%Y%m%d%H%M%S')
file_name = (f"零跑专项_{period_start.strftime('%Y%m%d')}"
f"-{period_end.strftime('%Y%m%d')}_{ts}.xlsx")
tmp_dir = tempfile.mkdtemp(prefix=f'leapmotor_{task_id}_')
try:
excel_path = os.path.join(tmp_dir, file_name)
self.build_workbook(data, period_start, period_end, excel_path)
# Step4: 上传 OSS + 回填任务
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
f"/{file_name}")
file_url = upload_file(excel_path, object_key)
finally:
cleanup_tmp_dir(tmp_dir)
task = DataProcessTask.query.filter_by(id=task_id).first()
task.status = 'COMPLETED'
task.result_file_url = file_url
task.error_msg = ''
db.session.commit()
logger.info(f"[零跑专项] 任务 {task_id} 处理完成,结果文件: {file_url}")
except Exception as e:
db.session.rollback()
mark_task_failed(task_id, str(e))
raise
# ============================================================
# 数据采集(业务库 SQL + 指标系统)
# ============================================================
def collect_data(self, period_start, period_end):
"""采集正文全部数据,返回渲染所需字典(结构同岚图,另含 city)。"""
period_start = self._as_date(period_start)
period_end = self._as_date(period_end)
start_str = period_start.strftime('%Y-%m-%d')
end_str = period_end.strftime('%Y-%m-%d')
# ---------- Step1: 业务库 SQL ----------
conn = _get_biz_sql_conn()
if conn is None:
raise Exception("业务库(dj_smartcarlife)连接失败")
try:
# 门店清单(按 pgr.id 倒序)
rows = conn.execute(text(
"select pgr.merchant_id, pgr.merchant_name "
"from pg_group_info pg "
"inner join pg_group_store_rel pgr on pg.id = pgr.group_id "
" and pgr.deleted_flag = 'N' "
"where pg.deleted_flag = 'N' and pg.group_name = :gname "
"order by pgr.id desc"
), {'gname': GROUP_NAME}).fetchall()
stores = [{'merchant_id': str(r[0]), 'merchant_name': r[1]} for r in rows]
mids = [s['merchant_id'] for s in stores]
logger.info(f"[零跑专项] 门店清单: {len(mids)} 家({GROUP_NAME})")
if not mids:
return {'stores': [], 'province': {}, 'city': {}, 'directors': {},
'staff': {}, 'ind_cur': {}, 'ind_prev': {},
'nodes': generate_stat_nodes(period_start, period_end),
'node_ratings': {period_end: {}}}
# 省份 + 城市(批量,同一条 SQL)
province, city = {}, {}
for r in conn.execute(text(
"select merchant_id, province_name, city_name "
"from dj_car_life_service_merchant "
"where deleted_flag = 'N' and merchant_id in :mids"
).bindparams(bindparam('mids', expanding=True)), {'mids': mids}):
province[str(r[0])] = shorten_province(r[1])
city[str(r[0])] = r[2] or None
# 区域运营(批量,多 director_name 用 / 分割,去重保序)
directors = {}
for r in conn.execute(text(
"select merchant_id, director_name "
"from dj_car_life_shop_merchant_director_config "
"where deleted_flag = 'N' and director_type = 9 "
" and merchant_id in :mids"
).bindparams(bindparam('mids', expanding=True)), {'mids': mids}):
mid = str(r[0])
seen = directors.setdefault(mid, [])
if r[1] and r[1] not in seen:
seen.append(r[1])
directors = {k: '/'.join(v) for k, v in directors.items()}
# 驻店人员(日报 ∪ 开单,按商户 GROUP_CONCAT 去重,'/' 分割)
staff = {}
end_dt_str = period_end.strftime('%Y-%m-%d 23:59:59')
staff_rows = conn.execute(text(
"select t.merchant_id, "
" group_concat(distinct si.staff_name order by si.staff_name separator '/') as staff_names "
"from ( "
" select merchant_id, staff_uuid from dj_car_life_staff_daily_report "
" where deleted_flag = 'N' and scene_type = 0 "
" and template_type in (1, 2) "
" and merchant_id in :mids1 "
" and report_date >= :sdate and report_date <= :edate "
" union "
" select merchant_id, seller_user_id as staff_uuid "
" from dj_car_life_goods_order "
" where deleted_flag = 'N' and scene_type = 0 and business_type = 2 "
" and merchant_id in :mids2 "
" and order_time >= :sdt and order_time <= :edt "
") t "
"inner join dj_car_life_staff_info si "
" on si.staff_uuid = t.staff_uuid and si.deleted_flag in ('N', 'I') "
"group by t.merchant_id"
).bindparams(
bindparam('mids1', expanding=True), bindparam('mids2', expanding=True),
), {
'mids1': mids, 'mids2': mids,
'sdate': start_str, 'edate': end_str,
'sdt': f'{start_str} 00:00:00', 'edt': end_dt_str,
}).fetchall()
for r in staff_rows:
staff[str(r[0])] = r[1] or ''
finally:
conn.close()
# ---------- Step2: 指标系统 ----------
client = IndicatorClient()
# 当前周期:A036/A062/A084/A075(L/M/P/Q 一次取齐)
ind_cur = client.fetch_by_merchant_ids(
start_str, end_str,
[CODE_OUTPUT, CODE_DELIVERY, CODE_REFER, CODE_DEAL], mids)
logger.info(f"[零跑专项] 指标拉取完成: 当前周期 {len(ind_cur)} 商户")
# 评灯取数日期集合:周一/周四(日期列)∪ endDate("截止目前"列),
# 各按 1号~该日 累计 A075/A062(渗透率=订单/交车)
nodes = generate_stat_nodes(period_start, period_end)
rating_dates = sorted(set(nodes) | {period_end})
month_first = date(period_start.year, period_start.month, 1)
node_ratings = {}
for d in rating_dates:
ind_node = client.fetch_by_merchant_ids(
month_first.strftime('%Y-%m-%d'), d.strftime('%Y-%m-%d'),
[CODE_DEAL, CODE_DELIVERY], mids)
node_ratings[d] = {
mid: rating_text((ind_node.get(mid) or {}).get(CODE_DEAL),
(ind_node.get(mid) or {}).get(CODE_DELIVERY))
for mid in mids
}
logger.info(f"[零跑专项] 评灯取数 {d} 完成({len(ind_node)} 商户)")
return {
'stores': stores,
'province': province,
'city': city,
'directors': directors,
'staff': staff,
'ind_cur': ind_cur,
'nodes': nodes,
'node_ratings': node_ratings,
}
# ============================================================
# Excel 渲染(加载模板 → 动态列调整 → 清样例 → 写正文)
# ============================================================
def build_workbook(self, data, period_start, period_end, out_path):
"""按模板渲染零跑专项报表并保存到 out_path。"""
period_start = self._as_date(period_start)
period_end = self._as_date(period_end)
stores = data.get('stores') or []
nodes = data.get('nodes') or generate_stat_nodes(period_start, period_end)
node_ratings = data.get('node_ratings') or {}
n_dates = len(nodes)
tail_start = TAIL_START + (n_dates - TEMPLATE_DATE_COLS) # 尾部 12 列起始
last_col = ZHICI_COL + n_dates + 12
wb = openpyxl.load_workbook(TEMPLATE_PATH)
ws = wb[TEMPLATE_SHEET]
# ---------- 0) 清空模板条件格式(colorScale/cellIs 等会残留上色) ----------
from openpyxl.formatting.formatting import ConditionalFormattingList
ws.conditional_formatting = ConditionalFormattingList()
# ---------- 1) 解除模板全部合并(结束后按最终列数重建) ----------
for rng in [str(r) for r in ws.merged_cells.ranges]:
ws.unmerge_cells(rng)
# ---------- 2) 动态列数调整(模板 Z~AB 共 3 个动态位,Y/尾部列样式随平移保留) ----------
delta = n_dates - TEMPLATE_DATE_COLS
if delta > 0:
src_style = {} # 以模板 Z 列(26) 行1~4 样式为蓝本
for r in range(1, 5):
src_style[r] = copy(ws.cell(row=r, column=DYN_COL_START)._style)
src_width = ws.column_dimensions[get_column_letter(DYN_COL_START)].width
for _ in range(delta):
ws.insert_cols(TAIL_START) # 在尾部 12 列(AC)前插入
for r in range(1, 5):
ws.cell(row=r, column=TAIL_START)._style = copy(src_style[r])
ws.column_dimensions[get_column_letter(TAIL_START)].width = src_width
elif delta < 0:
# 从动态位右端(28=AB)起、位置逐次左移删除,只删多余动态位
pos = DYN_COL_START + TEMPLATE_DATE_COLS - 1
for _ in range(-delta):
ws.delete_cols(pos)
pos -= 1
# ---------- 3) 捕获正文行样式(模板第 4 行样例,按列捕获) ----------
row_styles = {}
for col in range(1, last_col + 1):
row_styles[col] = copy(ws.cell(row=4, column=col)._style)
# ---------- 4) 清除模板样例正文(第 4 行起全部删除) ----------
if ws.max_row >= 4:
ws.delete_rows(4, ws.max_row - 3)
# ---------- 5) 重建表头合并(双层表头) ----------
# A~N(1~14)、R(18)、S(19):纵向合并 1~2 行
for col in list(range(1, 15)) + [18, 19]:
ws.merge_cells(start_row=1, start_column=col, end_row=2, end_column=col)
# O1:Q1 合计(主机厂订单数/广联系统订单数/广联系统产值)
ws.merge_cells(start_row=1, start_column=15, end_row=1, end_column=17)
# T1:X1 渗透率(保留 5 列,值留空)
ws.merge_cells(start_row=1, start_column=T_START, end_row=1, end_column=T_START + 4)
# Y1:{末动态列}1 评灯(截止目前 + 动态日期列)
ws.merge_cells(start_row=1, start_column=ZHICI_COL,
end_row=1, end_column=ZHICI_COL + n_dates)
# 尾部 4 组横向合并
for g in range(4):
ws.merge_cells(start_row=1, start_column=tail_start + 3 * g,
end_row=1, end_column=tail_start + 3 * g + 2)
# 第 3 行合计行 A3:J3
ws.merge_cells(start_row=3, start_column=1, end_row=3, end_column=10)
# 行1 组标题(尾部 4 组标题随列平移可能错位,显式重写)
for g, (title, _sub) in enumerate(TAIL_GROUPS):
ws.cell(row=1, column=tail_start + 3 * g, value=title)
# 行2:截止目前 + 动态日期列 + 尾部子表头
ws.cell(row=2, column=ZHICI_COL, value='截止目前')
for i, node in enumerate(nodes):
ws.cell(row=2, column=DYN_COL_START + i,
value=f'{node.month}月{node.day}日')
for g, (_title, sub) in enumerate(TAIL_GROUPS):
ws.cell(row=2, column=tail_start + 3 * g + 1, value=sub)
# 行3:合计行 —— A3:J3 合并"合计",K3 及之后全部留空(不计算)
ws.cell(row=3, column=1, value='合计')
for col in range(11, last_col + 1):
ws.cell(row=3, column=col).value = None
# ---------- 6) 写正文(第 4 行起,每门店一行) ----------
province = data.get('province') or {}
city = data.get('city') or {}
directors = data.get('directors') or {}
staff = data.get('staff') or {}
ind_cur = data.get('ind_cur') or {}
# 尾部 12 列取值映射(相对 tail_start 的偏移 → 来源列)
tail_offsets = {1: 12, 4: 13, 7: 16, 10: 17} # 日报/系统列 = L/M/P/Q
for idx, store in enumerate(stores):
r = 4 + idx
mid = store['merchant_id']
cur = ind_cur.get(mid) or {}
values = {
1: province.get(mid, '') or None, # A 区域(省份简称)
2: city.get(mid) or None, # B 城市
3: None, # C 零跑门店名称
4: store['merchant_name'], # D 广联门店名称
5: None, # E 备注
6: '零跑', # F 业务品牌
7: '2.3', # G 业务类型
8: directors.get(mid, '') or None, # H 区域运营
9: staff.get(mid, '') or None, # I 驻店
10: None, # J 实际到岗日期
11: None, # K 主机厂交车数
12: cur.get(CODE_DELIVERY), # L 交车数
13: cur.get(CODE_REFER), # M 触客数
14: _pct(cur.get(CODE_REFER), cur.get(CODE_DELIVERY)), # N 触客率
15: None, # O 主机厂订单数
16: cur.get(CODE_DEAL), # P 广联系统订单数
17: cur.get(CODE_OUTPUT), # Q 广联系统产值
18: _int_div(cur.get(CODE_OUTPUT), cur.get(CODE_DEAL)), # R 客单价
19: _pct(cur.get(CODE_DEAL), cur.get(CODE_REFER)), # S 当月触客渗透率
20: None, 21: None, 22: None, 23: None, 24: None, # T~X 留空
ZHICI_COL: (node_ratings.get(period_end) or {}).get(mid) or None,
}
for i, node in enumerate(nodes):
values[DYN_COL_START + i] = \
(node_ratings.get(node) or {}).get(mid) or None
# 尾部 12 列
for g in range(4):
values[tail_start + 3 * g] = None # 一店一群
values[tail_start + 3 * g + 1] = cur.get(
CODE_MAP[TAIL_VALUES[g]]) # 日报/系统 = 对应指标
values[tail_start + 3 * g + 2] = None # 差异
ws.row_dimensions[r].height = 20
for col in range(1, last_col + 1):
cell = ws.cell(row=r, column=col)
cell._style = copy(row_styles.get(col))
val = values.get(col)
cell.value = val if val is not None else None
if col in (14, 19): # N 触客率 / S 当月触客渗透率
cell.number_format = '0%'
fill_color = RATE_FILL.get(val) if isinstance(val, str) else None
if fill_color:
cell.fill = PatternFill(start_color=fill_color,
end_color=fill_color, fill_type='solid')
wb.save(out_path)
logger.info(f"[零跑专项] Excel 已生成: {out_path}({len(stores)} 门店, "
f"{n_dates} 评灯节点, 共 {last_col} 列)")
return out_path
# ============================================================
# 工具
# ============================================================
@staticmethod
def _as_date(val):
"""date/datetime/字符串 统一转 date"""
if isinstance(val, datetime):
return val.date()
if isinstance(val, date):
return val
return datetime.strptime(str(val)[:10], '%Y-%m-%d').date()
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 轻改店中店汇总独立处理器
============================================
对应 ORM 表:report_light_reform_inshop
输出类别:inshop
指标系统 biz 编码:2(轻改)
取值优先级:Excel 第一优先,SQL/指标系统第二优先(双优先模式)。
SQL 数据源:dj_smartcarlife 库
- fetch_park_daily_report → 日报数据(交车数/交付触客/售后触客)
- fetch_light_reform_goods_stats → 品类成交数 + 产值(从 goods_sub_order 按 dj_order_type + AITO/HIMA 关键字条件聚合)
"""
import logging
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE,
mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files,
parse_saas_base_sheet2, parse_region_map,
parse_inshop_delivery_touch, parse_commerce_policy_inshop,
parse_labor_cost, is_luxury_brand,
parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats, fetch_park_name_map, fuzzy_match_store, exact_match_store,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
)
from models import ReportLightReformInshop, db
logger = logging.getLogger('LightReformInshopProcessor')
class LightReformInshopProcessor:
"""轻改店中店汇总独立处理器"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_store_effect_earnings(self, output_category='inshop'):
"""扫描 store_effect_earnings 任务并处理轻改店中店汇总"""
from models import DataProcessTask
logger.info(f"[inshop] 开始扫描 store_effect_earnings 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=STORE_EFFECT_EARNINGS_TYPE,
status='PROCESSING',
is_deleted=0
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[inshop] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[inshop] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception:
pass
logger.info(f"[inshop] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
"""处理单个 task 的店中店汇总输出"""
task_id = task.id
category = 'inshop'
if is_subtask_completed(task_id, category):
logger.info(f"[inshop] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
update_subtask(task_id, category, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
try:
row_count = self._process_light_reform_inshop(task)
update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
logger.info(f"[inshop] 任务 {task_id} 处理完成,{row_count} 行")
except Exception as e:
db.session.rollback()
update_subtask(task_id, category, SUBTASK_FAILED, error_msg=str(e))
db.session.commit()
promote_subtask_failure_to_main_task(task_id)
raise
# ============================================================
# 核心处理
# ============================================================
def _process_light_reform_inshop(self, task):
task_id = task.id
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
logger.info(f"[轻改店中店] 开始处理, task_id={task_id}, period={start_str}~{end_str}")
# ========== Step1: Excel ==========
tmp_dir = tempfile.mkdtemp(prefix=f"inshop_{task_id}_")
try:
file_map = download_all_files(task.id, tmp_dir)
saas_path = file_map.get('SAAS门店预算分解表')
if not saas_path:
raise Exception("缺少必需文件: SAAS门店预算分解表")
base_records = parse_saas_base_sheet2(saas_path)
rel_path = file_map.get('关系表')
region_map = parse_region_map(rel_path) if rel_path else {}
# 店中店交车触客表(区域运营填的,Excel 第一优先)
delivery_touch_map = {}
dt_path = file_map.get('店中店交车触客表')
logger.info(f"[店中店] file_map keys={list(file_map.keys())}")
logger.info(f"[店中店交车触客表] dt_path={dt_path}")
if dt_path:
delivery_touch_map = parse_inshop_delivery_touch(dt_path)
logger.info(f"[店中店交车触客表] 解析后 {len(delivery_touch_map)} 个门店, 样本keys={list(delivery_touch_map.keys())[:5]}")
# 商务政策表(店中店处理版)
commerce_map = {}
cp_path = file_map.get('商务政策表(店中店)') or file_map.get('商务政策表(店中店)')
if cp_path:
commerce_map = parse_commerce_policy_inshop(cp_path, biz_type='1.1')
# 人力成本表
labor_map = {}
lc_path = file_map.get('人力成本表')
if lc_path:
labor_map = parse_labor_cost(lc_path, biz_type='1.1')
# 预算达成数据(商务)→ 装修分摊/房租水电/门店耗材/服务费占比
budget_achieve_map = {}
budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
if budget_path:
budget_achieve_map = parse_budget_achieve_excel(budget_path, biz_type='1.1')
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step2: 业务系统 SQL ==========
# 2a. 日报数据(scene_type=1 轻改,复用 park 的函数,3 字段全返回)
daily_report_map = fetch_park_daily_report(period_start, period_end, scene_type=1)
# 2c. 品类成交数 + 产值(店中店+园区店共用 SQL,按 dj_order_type + AITO/HIMA 关键字聚合)
goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end)
# 2d. 财务成本分项(店中店+园区店共用 SQL,按 dj_order_type + 品类 + 原厂/副厂切分)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 2b. 精确匹配系统数据(系统 merchant_name 命名规范,精确避免误匹配)
biz_sql_data = {}
for rec in base_records:
sn = rec.get('store_name', '')
dr = exact_match_store(sn, daily_report_map) or {}
gs = exact_match_store(sn, goods_stats_map) or {}
fs = exact_match_store(sn, finance_map) or {}
biz_sql_data[sn] = {
# —— 日报类(来自 fetch_park_daily_report)——
'delivery_cnt': dr.get('delivery_cnt', 0),
'delivery_touch_cnt': dr.get('equity_to_shop_count', 0),
'aftersales_touch_cnt': dr.get('after_sale_equity_to_shop_count', 0),
'aftersales_baohui_cnt': 0, # 无 SQL
'aftersales_shigu_cnt': 0, # 无 SQL
'sales_order_cnt': 0, # 无 SQL(销售大定数)
'sales_touch_cnt': 0, # 无 SQL(销售触客数)
# —— 品类成交数 + 产值(来自 fetch_light_reform_goods_stats)——
'total_deal_cnt': gs.get('total_deal_cnt', 0),
'window_film_oe_cnt': gs.get('window_film_oe_cnt', 0),
'window_film_nonoe_cnt': gs.get('window_film_nonoe_cnt', 0),
'car_wrap_oe_cnt': gs.get('car_wrap_oe_cnt', 0),
'car_wrap_nonoe_cnt': gs.get('car_wrap_nonoe_cnt', 0),
'premium_oe_cnt': gs.get('premium_oe_cnt', 0),
'premium_nonoe_cnt': gs.get('premium_nonoe_cnt', 0),
'pedal_cnt': gs.get('pedal_cnt', 0),
'store_output_value': gs.get('store_output_value', Decimal('0')),
'internal_settle_value': gs.get('internal_settle_value', Decimal('0')),
'oe_output_value': gs.get('oe_output_value', Decimal('0')),
'nonoe_output_value': gs.get('nonoe_output_value', Decimal('0')),
# —— 财务成本分项(来自 fetch_light_reform_finance_stats)——
'product_cost_finance': fs.get('product_cost_finance', Decimal('0')),
'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')),
'oe_product_cost': fs.get('oe_product_cost', Decimal('0')),
'nonoe_product_cost': fs.get('nonoe_product_cost', Decimal('0')),
'window_film_cost': fs.get('window_film_cost', Decimal('0')),
'car_wrap_cost': fs.get('car_wrap_cost', Decimal('0')),
'premium_cost': fs.get('premium_cost', Decimal('0')),
'store_share': fs.get('store_share', Decimal('0')),
'construction_income': fs.get('construction_income', Decimal('0')),
'market_fee': fs.get('market_fee', Decimal('0')),
'mgmt_market_fee': fs.get('mgmt_market_fee', Decimal('0')),
'sunshine_incentive_fee': fs.get('sunshine_incentive_fee', Decimal('0')),
}
# ========== Step3: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map
# ========== Step4.5: store_name → park_name 映射(系统表优先,与园区店同逻辑) ==========
park_name_sys_map = fetch_park_name_map(base_scene_code='100101')
store_to_park = {}
for rec in base_records:
sn = rec.get('store_name', '')
store_to_park[sn] = (
park_name_sys_map.get(sn) # 精确匹配
or rec.get('park_name', '') # Excel 原值兜底
)
_hit = sum(1 for v in store_to_park.values() if v)
logger.info(f"[park_name-inshop] store_to_park 映射 {_hit}/{len(store_to_park)} 有值, "
f"sample={list(store_to_park.items())[:5]}")
# ========== Step5: 逐行计算 ==========
rows_to_insert = []
for rec in base_records:
sn = rec.get('store_name', '')
province = rec.get('province', '')
operate_type = rec.get('operate_type', '')
brand = rec.get('brand', '')
# —— 基础维度 ——
region_area = region_map.get(('', province), '')
brand_category = is_luxury_brand(brand)
# —— 双优先:Excel 第一,SQL 回退 ——
# 模糊匹配:SAAS 门店名 vs Excel 门店名 / SQL merchant_name
dt_excel = fuzzy_match_store(sn, delivery_touch_map) or {}
sql_data = biz_sql_data.get(sn, {})
sales_order_cnt = get_with_fallback(
dt_excel.get('sales_order_cnt'), sql_data.get('sales_order_cnt', 0))
sales_touch_cnt = get_with_fallback(
dt_excel.get('sales_touch_cnt'), sql_data.get('sales_touch_cnt', 0))
delivery_cnt = get_with_fallback(
dt_excel.get('delivery_cnt'), sql_data.get('delivery_cnt', 0))
delivery_touch_cnt = get_with_fallback(
dt_excel.get('delivery_touch_cnt'), sql_data.get('delivery_touch_cnt', 0))
aftersales_baohui_cnt = get_with_fallback(
dt_excel.get('aftersales_baohui_cnt'), sql_data.get('aftersales_baohui_cnt', 0))
aftersales_shigu_cnt = get_with_fallback(
dt_excel.get('aftersales_shigu_cnt'), sql_data.get('aftersales_shigu_cnt', 0))
aftersales_touch_cnt = get_with_fallback(
dt_excel.get('aftersales_touch_cnt'), sql_data.get('aftersales_touch_cnt', 0))
purchase_indicator = dt_excel.get('purchase_indicator', '')
# —— 业务系统 SQL 取值(fetch_inshop_goods_stats 一次聚合返回)——
total_deal_cnt = int(Decimal(str(sql_data.get('total_deal_cnt', 0))))
store_output_value = Decimal(str(sql_data.get('store_output_value', Decimal('0'))))
# —— 品类成交数 / 产值(来自 fetch_inshop_goods_stats 的条件聚合结果)——
window_film_oe_cnt = sql_data.get('window_film_oe_cnt', 0)
window_film_nonoe_cnt = sql_data.get('window_film_nonoe_cnt', 0)
car_wrap_oe_cnt = sql_data.get('car_wrap_oe_cnt', 0)
car_wrap_nonoe_cnt = sql_data.get('car_wrap_nonoe_cnt', 0)
premium_oe_cnt = sql_data.get('premium_oe_cnt', 0)
premium_nonoe_cnt = sql_data.get('premium_nonoe_cnt', 0)
pedal_cnt = sql_data.get('pedal_cnt', 0)
internal_settle_value = sql_data.get('internal_settle_value', Decimal('0'))
oe_output_value = sql_data.get('oe_output_value', Decimal('0'))
nonoe_output_value = sql_data.get('nonoe_output_value', Decimal('0'))
product_cost_finance = sql_data.get('product_cost_finance', Decimal('0'))
internal_settle_cost = sql_data.get('internal_settle_cost', Decimal('0'))
oe_product_cost = sql_data.get('oe_product_cost', Decimal('0'))
nonoe_product_cost = sql_data.get('nonoe_product_cost', Decimal('0'))
window_film_cost = sql_data.get('window_film_cost', Decimal('0'))
car_wrap_cost = sql_data.get('car_wrap_cost', Decimal('0'))
premium_cost = sql_data.get('premium_cost', Decimal('0'))
store_share = sql_data.get('store_share', Decimal('0'))
construction_income = sql_data.get('construction_income', Decimal('0'))
mgmt_market_fee = sql_data.get('mgmt_market_fee', Decimal('0'))
sunshine_incentive_fee = sql_data.get('sunshine_incentive_fee', Decimal('0'))
# —— 商务政策(店中店)——
# 先精确匹配,失败则 fuzzy 包含匹配
cp = commerce_map.get(sn)
if cp is None:
cp = fuzzy_match_store(sn, commerce_map) or {}
if not cp and commerce_map:
logger.warning(f"[店中店] 商务政策未匹配到门店: {sn} (cp_map_keys 样本={list(commerce_map.keys())[:3]})")
oe_film_unit = Decimal(str(cp.get('oe_window_film_cost', 0)))
oe_wrap_unit = Decimal(str(cp.get('oe_car_wrap_cost', 0)))
oe_premium_unit = Decimal(str(cp.get('oe_premium_cost', 0)))
pedal_unit = Decimal(str(cp.get('pedal_cost', 0)))
nonoe_film_unit = Decimal(str(cp.get('nonoe_window_film_cost', 0)))
nonoe_wrap_unit = Decimal(str(cp.get('nonoe_car_wrap_cost', 0)))
nonoe_premium_unit = Decimal(str(cp.get('nonoe_premium_cost', 0)))
post_film_unit = Decimal(str(cp.get('construction_cost_post_film', 0)))
post_wrap_unit = Decimal(str(cp.get('construction_cost_post_wrap', 0)))
post_premium_unit = Decimal(str(cp.get('construction_cost_post_premium', 0)))
frontline_ratio_cp = Decimal(str(cp.get('frontline_incentive_ratio', 0)))
# —— 预算达成 Excel(按周期天数摊销月度固定费用) ——
# 装修分摊 / 房租水电 / 门店耗材:按"周期天数/月份总天数"摊销
renovation_amortization = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'renovation_amortization'),
period_start, period_end)
rent_utilities = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'rent_utilities'),
period_start, period_end)
store_consumables = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'store_consumables'),
period_start, period_end)
# 服务费占比:直营店强制 0,服务商直接取(与 park_processor 对齐)
sp_ratio = Decimal('0') if operate_type == '直营' else extract_budget_ratio(
prev_budget_map, sn, 'service_provider_share_ratio')
# —— 人力成本 ——
headcount = labor_map.get(sn, 0)
# ======= 公式计算 =======
# 触客率
sales_touch_rate = safe_div_pct(sales_touch_cnt, sales_order_cnt)
delivery_touch_rate = safe_div_pct(delivery_touch_cnt, delivery_cnt)
aftersales_denom = aftersales_baohui_cnt + aftersales_shigu_cnt
aftersales_touch_rate = safe_div_pct(aftersales_touch_cnt, aftersales_denom)
total_touch_cnt = sales_touch_cnt + delivery_touch_cnt + aftersales_touch_cnt
# 产值/合计
total_output_value = store_output_value + internal_settle_value
# 施工成本拆分(进销差只用前置合计,后置单独列展示)
construction_cost_oe = (
window_film_oe_cnt * oe_film_unit +
car_wrap_oe_cnt * oe_wrap_unit +
premium_oe_cnt * oe_premium_unit +
pedal_cnt * pedal_unit
)
construction_cost_nonoe = (
window_film_nonoe_cnt * nonoe_film_unit +
car_wrap_nonoe_cnt * nonoe_wrap_unit +
premium_nonoe_cnt * nonoe_premium_unit
)
construction_cost_post = Decimal('0') if (operate_type == '服务商') else (
(window_film_oe_cnt + window_film_nonoe_cnt) * post_film_unit +
(car_wrap_oe_cnt + car_wrap_nonoe_cnt) * post_wrap_unit +
(premium_oe_cnt + premium_nonoe_cnt) * post_premium_unit
)
construction_cost_post_ratio = safe_div_pct_decimal(construction_cost_post, store_output_value)
construction_cost_pre = construction_cost_oe + construction_cost_nonoe # 前置合计,进销差用
construction_cost_ratio = safe_div_pct_decimal(construction_cost_pre, store_output_value) # 复用 DB 字段存前置合计占比
# construction_cost 总计暂不更新(保持默认 0)
# 一线激励(cp_map 已存 1-100 的百分比值,计算金额需 /100)
frontline_incentive = (store_output_value * frontline_ratio_cp / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
frontline_incentive_ratio = frontline_ratio_cp
# 进销差(未分成):只用前置施工成本合计
gross_profit_pre_share = (
store_output_value - product_cost_finance - construction_cost_pre - frontline_incentive
)
gross_profit_pre_share_ratio = safe_div_pct_decimal(gross_profit_pre_share, store_output_value)
# 门店分成占比/单车利润
store_share_ratio = safe_div_pct_decimal(store_share, store_output_value)
store_share_per_car = safe_div(store_share, delivery_cnt, 2)
guarantee_amount = Decimal('0')
gl_share = gross_profit_pre_share - store_share - guarantee_amount
gl_share_ratio = safe_div_pct_decimal(gl_share, store_output_value)
# 内部结算
internal_settle_profit = internal_settle_value - internal_settle_cost
# 广联总分成
gl_total_share = gl_share + construction_income + internal_settle_profit
# 客单价/渗透
avg_unit_price_delivery = safe_div(store_output_value, delivery_cnt, 2)
avg_price_target = rec.get('avg_price_target', Decimal('0'))
avg_price_diff = avg_unit_price_delivery - avg_price_target
delivery_touch_unit_price = safe_div(store_output_value, delivery_touch_cnt, 2)
upgrade_unit_price = safe_div(store_output_value, total_deal_cnt, 2)
total_penetration_rate = safe_div_pct(total_deal_cnt, delivery_cnt)
window_film_penetration = safe_div_pct(window_film_oe_cnt, delivery_cnt)
car_wrap_penetration = safe_div_pct(car_wrap_oe_cnt, delivery_cnt)
premium_penetration = safe_div_pct(premium_oe_cnt, delivery_cnt)
product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_output_value)
# 市场费:若一线激励存在(> 0),则只算管理层市场费1+2;否则管理层+阳光激励全算
if frontline_incentive and frontline_incentive > 0:
market_fee = mgmt_market_fee
else:
market_fee = mgmt_market_fee + sunshine_incentive_fee
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
# 营销人员成本
marketing_personnel_cost = Decimal('0')
if operate_type == '直营':
# 底薪 3500 元/人/月,按统计周期天数折算:3500 * 周期天数 / 月份总天数
# (周期天数 = period_end - period_start + 1,含首尾;月份总天数 = period_start 所在月天数)
base_salary_prorated = prorate_by_period(Decimal('3500'), period_start, period_end)
marketing_personnel_cost = (
Decimal(str(headcount)) * base_salary_prorated +
store_output_value * Decimal('0.04')
)
marketing_personnel_ratio = safe_div_pct_decimal(marketing_personnel_cost, store_output_value)
# 服务商分成(商务报表)= 服务商分成占比 * 门店总产值 / 100(占比为百分比值)
service_provider_share = (store_output_value * sp_ratio / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_provider_share_ratio = sp_ratio
# 成本总计(前置施工成本 + 人力 + 市场费 + 固定费用 + 服务商分成)
total_cost = (
marketing_personnel_cost + construction_cost_pre + market_fee +
renovation_amortization + rent_utilities + store_consumables +
service_provider_share
)
cost_ratio = safe_div_pct_decimal(total_cost, store_output_value)
# 毛利
gross_profit = gl_total_share - total_cost
gross_profit_rate = safe_div_pct_decimal(gross_profit, store_output_value)
if gross_profit_rate > 0:
gross_profit_status = '盈利'
elif gross_profit_rate == 0:
gross_profit_status = '零毛利'
else:
gross_profit_status = '亏损'
row = ReportLightReformInshop(
task_id=task_id, period_start=period_start, period_end=period_end,
# 基础维度
region_area=region_area, province=province, city=rec.get('city', ''),
park_type=(rec.get('park_type') or '店中店'), biz_line=rec.get('biz_line', '1.12'),
operate_type=operate_type, region_manager=rec.get('region_manager', ''),
park_name=store_to_park.get(sn, ''), store_name=sn, brand=brand,
brand_category=brand_category, purchase_indicator=purchase_indicator,
# 销售
sales_order_cnt=sales_order_cnt, sales_touch_cnt=sales_touch_cnt,
sales_touch_rate=sales_touch_rate,
# 交付
delivery_cnt=delivery_cnt, delivery_touch_cnt=delivery_touch_cnt,
delivery_touch_rate=delivery_touch_rate,
# 售后
aftersales_baohui_cnt=aftersales_baohui_cnt,
aftersales_shigu_cnt=aftersales_shigu_cnt,
aftersales_touch_cnt=aftersales_touch_cnt,
aftersales_touch_rate=aftersales_touch_rate,
total_touch_cnt=total_touch_cnt, total_deal_cnt=total_deal_cnt,
# 品类成交
window_film_oe_cnt=window_film_oe_cnt,
window_film_nonoe_cnt=window_film_nonoe_cnt,
car_wrap_oe_cnt=car_wrap_oe_cnt,
car_wrap_nonoe_cnt=car_wrap_nonoe_cnt,
premium_oe_cnt=premium_oe_cnt,
premium_nonoe_cnt=premium_nonoe_cnt,
pedal_cnt=pedal_cnt,
# 产值
store_output_value=store_output_value,
internal_settle_value=internal_settle_value,
total_output_value=total_output_value,
oe_output_value=oe_output_value,
nonoe_output_value=nonoe_output_value,
# 客单/渗透
avg_unit_price_delivery=avg_unit_price_delivery,
avg_price_target=avg_price_target,
avg_price_diff=avg_price_diff,
delivery_touch_unit_price=delivery_touch_unit_price,
upgrade_unit_price=upgrade_unit_price,
total_penetration_rate=total_penetration_rate,
window_film_penetration=window_film_penetration,
car_wrap_penetration=car_wrap_penetration,
premium_penetration=premium_penetration,
# 产品成本
product_cost_finance=product_cost_finance,
internal_settle_cost=internal_settle_cost,
oe_product_cost=oe_product_cost,
nonoe_product_cost=nonoe_product_cost,
window_film_cost=window_film_cost,
car_wrap_cost=car_wrap_cost,
premium_cost=premium_cost,
product_cost_ratio=product_cost_ratio,
# 施工成本:oe/nonoe 写入拆分值,ratio 复用存前置合计占比,post/post_ratio 新增写入
construction_cost_oe=construction_cost_oe,
construction_cost_nonoe=construction_cost_nonoe,
construction_cost_ratio=construction_cost_ratio,
construction_cost_post=construction_cost_post,
construction_cost_post_ratio=construction_cost_post_ratio,
frontline_incentive=frontline_incentive,
frontline_incentive_ratio=frontline_incentive_ratio,
gross_profit_pre_share=gross_profit_pre_share,
gross_profit_pre_share_ratio=gross_profit_pre_share_ratio,
store_share=store_share,
store_share_ratio=store_share_ratio,
store_share_per_car=store_share_per_car,
guarantee_amount=guarantee_amount,
gl_share=gl_share,
gl_share_ratio=gl_share_ratio,
# 广联总分成
construction_income=construction_income,
internal_settle_profit=internal_settle_profit,
gl_total_share=gl_total_share,
# 营销/市场/装修/服务商
marketing_personnel_cost=marketing_personnel_cost,
marketing_personnel_ratio=marketing_personnel_ratio,
market_fee=market_fee, market_fee_ratio=market_fee_ratio,
renovation_amortization=renovation_amortization,
rent_utilities=rent_utilities,
store_consumables=store_consumables,
service_provider_share=service_provider_share,
service_provider_share_ratio=service_provider_share_ratio,
# 成本/毛利
total_cost=total_cost, cost_ratio=cost_ratio,
gross_profit=gross_profit, gross_profit_rate=gross_profit_rate,
gross_profit_status=gross_profit_status,
)
rows_to_insert.append(row)
# ========== Step6: 排名 ==========
rows_to_insert.sort(key=lambda r: (r.gross_profit_rate or Decimal('0')), reverse=True)
for idx, row in enumerate(rows_to_insert, 1):
row.gross_profit_rank = idx
# ========== Step7: 批量入库 ==========
ReportLightReformInshop.query.filter_by(task_id=task_id, is_deleted=0).delete()
db.session.flush()
for i in range(0, len(rows_to_insert), 500):
batch = rows_to_insert[i:i + 500]
db.session.add_all(batch)
db.session.flush()
logger.info(f"[轻改店中店] 完成入库 {len(rows_to_insert)} 条")
return len(rows_to_insert)
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 轻改园区店汇总独立处理器
============================================
对应 ORM 表:report_light_reform_park
输出类别:park
指标系统:✅ 有(成交数 A075 — 用户明确指定)
关键差异(对比店中店):
- sheet2 反过滤(不包含鸿蒙/AITO/问界/智界/享界/尚界/尊界)
- 用"园区店交车触客表"和"商务政策表(园区店)"
- 施工成本是固定公式(窗膜×95 + 车衣×900 + 精品×60 + 无效×50)
- 园区名称从 Excel park_name 列直接取
SQL 数据源:dj_smartcarlife 库
- fetch_park_daily_report → 日报数据(交车数/到店数)
- fetch_light_reform_goods_stats → 品类成交数(原厂+副厂聚合)+ 产值(与店中店共用 SQL)
- fetch_est_delivery_count → 预估交车数(dj_car_life_merchant_store_info 静态配置表)
"""
import logging
import tempfile
from decimal import Decimal, ROUND_HALF_UP
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files,
parse_saas_base_sheet2_exclude, parse_region_map,
parse_park_delivery_touch, parse_commerce_policy_park,
parse_labor_cost, is_luxury_brand,
parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_indicator_data, fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats,
fetch_est_delivery_count, fetch_park_name_map, fuzzy_match_store, exact_match_store,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
)
from models import ReportLightReformPark, db
logger = logging.getLogger('LightReformParkProcessor')
class LightReformParkProcessor:
"""轻改园区店汇总独立处理器"""
def __init__(self, app=None):
self.app = app
def scan_store_effect_earnings(self, output_category='park'):
from models import DataProcessTask
logger.info(f"[park] 开始扫描 store_effect_earnings 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=STORE_EFFECT_EARNINGS_TYPE,
status='PROCESSING',
is_deleted=0
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[park] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[park] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception:
pass
logger.info(f"[park] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def process(self, task):
task_id = task.id
category = 'park'
if is_subtask_completed(task_id, category):
logger.info(f"[park] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
update_subtask(task_id, category, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
try:
row_count = self._process_light_reform_park(task)
update_subtask(task_id, category, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
except Exception as e:
db.session.rollback()
update_subtask(task_id, category, SUBTASK_FAILED, error_msg=str(e))
db.session.commit()
promote_subtask_failure_to_main_task(task_id)
raise
# ============================================================
# 核心处理
# ============================================================
def _process_light_reform_park(self, task):
task_id = task.id
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
logger.info(f"[轻改园区店] 开始处理, task_id={task_id}, period={start_str}~{end_str}")
# ========== Step1: Excel ==========
tmp_dir = tempfile.mkdtemp(prefix=f"park_{task_id}_")
try:
file_map = download_all_files(task.id, tmp_dir)
saas_path = file_map.get('SAAS门店预算分解表')
if not saas_path:
raise Exception("缺少必需文件: SAAS门店预算分解表")
# 园区店用反过滤(不包含品牌关键字)
base_records = parse_saas_base_sheet2_exclude(saas_path)
rel_path = file_map.get('关系表')
region_map = parse_region_map(rel_path) if rel_path else {}
# 园区店交车触客表
delivery_touch_map = {}
dt_path = file_map.get('园区店交车触客表')
if dt_path:
delivery_touch_map = parse_park_delivery_touch(dt_path, biz_type='1.1')
# 商务政策表(园区店处理版)
commerce_map = {}
cp_path = file_map.get('商务政策表(园区店)') or file_map.get('商务政策表(园区店)')
if cp_path:
commerce_map = parse_commerce_policy_park(cp_path, biz_type='1.1')
# 人力成本表
labor_map = {}
lc_path = file_map.get('人力成本表')
if lc_path:
labor_map = parse_labor_cost(lc_path, biz_type='1.1')
# 预算达成数据(商务)→ 装修分摊/房租水电/门店耗材/服务费占比
budget_achieve_map = {}
budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
if budget_path:
budget_achieve_map = parse_budget_achieve_excel(budget_path, biz_type='1.1')
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统 biz=2 轻改 ==========
park_codes = ['A075'] # A075=成交数
indicator_data = fetch_indicator_data(
start_str, end_str, INDICATOR_BIZ_MAP.get('light_reform', 2), park_codes)
# ========== Step3: 业务系统 SQL ==========
# 3a. 日报数据(scene_type=1 轻改,一次连接两次 GROUP BY,3 字段全返回)
daily_report_map = fetch_park_daily_report(period_start, period_end, scene_type=1)
# 3b. 品类成交数 + 产值(店中店+园区店共用 SQL,park 侧聚合 oe+nonoe)
goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end)
# 3c. 预估交车数(静态配置表,无日期参数,traffic_party_name 即门店名)
est_delivery_map = fetch_est_delivery_count(base_scene_code='100101')
# 3d. 财务成本分项(店中店+园区店共用 SQL,park 侧仅消费 4 项)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 3e. 园区店名称(系统表 dj_car_life_merchant_store_info → parking_store_name)
park_name_sys_map = fetch_park_name_map(base_scene_code='100101')
# 3e. 精确匹配系统数据 → 组装 sql_data dict
biz_sql_data = {}
for rec in base_records:
sn = rec.get('store_name', '')
dr = exact_match_store(sn, daily_report_map) or {}
gs = exact_match_store(sn, goods_stats_map) or {}
fs = exact_match_store(sn, finance_map) or {}
eq = dr.get('equity_to_shop_count', 0)
af = dr.get('after_sale_equity_to_shop_count', 0)
biz_sql_data[sn] = {
# —— 日报类(来自 fetch_park_daily_report)——
'delivery_cnt': dr.get('delivery_cnt', 0),
'arrival_cnt': eq + af,
'arrival_invalid_cnt': 0, # 无 SQL
# —— 品类成交数(原厂+副厂聚合,来自 fetch_light_reform_goods_stats)——
'deal_cnt': gs.get('total_deal_cnt', 0),
'window_film_cnt': gs.get('window_film_oe_cnt', 0) + gs.get('window_film_nonoe_cnt', 0),
'car_wrap_cnt': gs.get('car_wrap_oe_cnt', 0) + gs.get('car_wrap_nonoe_cnt', 0),
'premium_cnt': gs.get('premium_oe_cnt', 0) + gs.get('premium_nonoe_cnt', 0),
# —— 产值(来自 fetch_light_reform_goods_stats)——
'store_sales_output': gs.get('store_output_value', Decimal('0')),
'internal_settle_value': gs.get('internal_settle_value', Decimal('0')),
# —— 预估交车数(来自 fetch_est_delivery_count)——
'est_delivery_cnt': exact_match_store(sn, est_delivery_map) or 0,
# —— 财务分项(park 仅消费产品成本/内部结算成本/流量费/市场费)——
'product_cost_finance': fs.get('product_cost_finance', Decimal('0')),
'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')),
'traffic_fee_finance': fs.get('store_share', Decimal('0')), # 流量费 = gopa.shop_traffic_money (dj_order_type!=6)
'market_fee_weighted': fs.get('market_fee', Decimal('0')), # 市场费加权测算 = fee 四项费用累计
}
# 3f. 其他字段(service_fee / construction_cost 等) park 从 Excel 或公式取,保持 0
# ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map
# ========== Step4.5: store_name → park_name 映射(系统表优先,用于 Step6 输出) ==========
store_to_park = {}
for rec in base_records:
sn = rec.get('store_name', '')
store_to_park[sn] = (
park_name_sys_map.get(sn) # 精确匹配
or rec.get('park_name', '') # Excel 原值兜底
)
_hit = sum(1 for v in store_to_park.values() if v)
logger.info(f"[park_name] store_to_park 映射 {_hit}/{len(store_to_park)} 有值, "
f"sample={list(store_to_park.items())[:5]}")
# ========== Step5: 合作门店数量 + park 预估交车合计(保持原逻辑) ==========
from collections import Counter
park_counter = Counter(p for p in store_to_park.values() if p)
park_est_delivery_total = {}
for rec in base_records:
sn = rec.get('store_name', '')
pn = store_to_park.get(sn, '')
est = int(get_with_fallback(
rec.get('est_delivery_cnt', 0),
get_with_fallback(
exact_match_store(sn, est_delivery_map) or 0,
biz_sql_data.get(sn, {}).get('est_delivery_cnt', 0),
),
) or 0)
park_est_delivery_total[pn] = park_est_delivery_total.get(pn, 0) + est
# ========== Step5.5: 识别合并组(Excel 合并单元格) ==========
# 按物理行顺序:est_output_value > 0 的行是"头行",后面连续 est=0 的行属于同一合并组
from decimal import Decimal as _D
merge_groups = []
cur_group = None
for rec in base_records:
sn = rec.get('store_name', '')
est_val = rec.get('est_output_value', _D('0')) or _D('0')
est_del = int(rec.get('est_delivery_cnt', 0) or 0)
if est_val > 0:
if cur_group is not None:
merge_groups.append(cur_group)
cur_group = {
'head_est': est_val,
'stores': [sn],
'deliveries': {sn: est_del},
}
else:
if cur_group is None:
cur_group = {'head_est': _D('0'), 'stores': [sn], 'deliveries': {sn: est_del}}
else:
cur_group['stores'].append(sn)
cur_group['deliveries'][sn] = est_del
if cur_group is not None:
merge_groups.append(cur_group)
store_to_group = {}
for g in merge_groups:
for sn in g['stores']:
store_to_group[sn] = g
multi_groups = [g for g in merge_groups if len(g['stores']) > 1]
logger.info(f"[合并行] 共 {len(merge_groups)} 个合并组, 其中 {len(multi_groups)} 个是多门店组:")
for g in multi_groups:
logger.info(f" head_est={g['head_est']}, stores={g['stores']}")
# ========== Step6: 逐行计算 ==========
rows_to_insert = []
for rec in base_records:
sn = rec.get('store_name', '')
province = rec.get('province', '')
park_name = store_to_park.get(sn, '')
operate_type = rec.get('operate_type', '')
brand = rec.get('brand', '')
region_area = region_map.get(('', province), '')
biz_type = is_luxury_brand(brand)
partner_store_cnt = park_counter.get(park_name, 1)
# —— Excel 第一优先 / SQL 回退 ——
pt_excel = delivery_touch_map.get(sn, {})
sql_data = biz_sql_data.get(sn, {})
delivery_cnt = get_with_fallback(
pt_excel.get('delivery_cnt'), sql_data.get('delivery_cnt', 0))
arrival_cnt = get_with_fallback(
pt_excel.get('arrival_cnt'), sql_data.get('arrival_cnt', 0))
arrival_invalid_cnt = get_with_fallback(
pt_excel.get('arrival_invalid_cnt'), sql_data.get('arrival_invalid_cnt', 0))
purchase_indicator = pt_excel.get('purchase_indicator', '')
# —— 指标系统 A075 ——
ind = indicator_data.get(sn, {})
deal_cnt = int(Decimal(str(ind.get('A075', sql_data.get('deal_cnt', 0)))))
# —— SQL 取值(来自 fetch_inshop_goods_stats,品类=原厂+副厂聚合)——
store_sales_output = Decimal(str(sql_data.get('store_sales_output', Decimal('0'))))
internal_settle_value = Decimal(str(sql_data.get('internal_settle_value', Decimal('0'))))
window_film_cnt = sql_data.get('window_film_cnt', 0)
car_wrap_cnt = sql_data.get('car_wrap_cnt', 0)
premium_cnt = sql_data.get('premium_cnt', 0)
est_traffic = sql_data.get('est_traffic', 0)
product_cost_finance = Decimal(str(sql_data.get('product_cost_finance', Decimal('0'))))
internal_settle_cost = Decimal(str(sql_data.get('internal_settle_cost', Decimal('0'))))
traffic_fee_finance = Decimal(str(sql_data.get('traffic_fee_finance', Decimal('0'))))
market_fee_weighted = Decimal(str(sql_data.get('market_fee_weighted', Decimal('0'))))
# —— 商务政策(园区店)——
cp = commerce_map.get(sn, {})
traffic_fee_per_car = Decimal(str(cp.get('traffic_fee_per_car', 0)))
# —— 人力成本 ——
headcount = labor_map.get(sn, 0)
# —— 预算目标(预估交车数:Excel 第一优先,SQL 回退)——
avg_price_target = rec.get('avg_price_target', Decimal('0'))
est_delivery_cnt = get_with_fallback(
rec.get('est_delivery_cnt', 0), sql_data.get('est_delivery_cnt', 0))
est_output_value_raw = rec.get('est_output_value', Decimal('0'))
# —— 预算达成 Excel(按周期天数摊销月度固定费用) ——
renovation_amortization = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'renovation_amortization'),
period_start, period_end)
rent_utilities = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'rent_utilities'),
period_start, period_end)
store_consumables = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'store_consumables'),
period_start, period_end)
# 服务费占比:直营店强制 0,服务商直接取
sp_ratio = Decimal('0') if operate_type == '直营' else extract_budget_ratio(
prev_budget_map, sn, 'service_provider_share_ratio')
# ======= 公式 =======
total_output_value = store_sales_output + internal_settle_value
# 产值达成进度:从合并组取头行预估产值,多门店合并组按预估交车数占比分摊
group = store_to_group.get(sn)
group_head_est = group['head_est'] if group else (rec.get('est_output_value', Decimal('0')) or Decimal('0'))
est_output_value = group_head_est
if group and len(group['stores']) > 1 and group_head_est > 0:
# 多门店合并组 → 按预估交车数占比分摊
group_total_del = sum(group['deliveries'].values())
store_del = group['deliveries'].get(sn, 0)
if group_total_del > 0:
est_output_value = (group_head_est
* Decimal(store_del) / Decimal(group_total_del)
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
output_progress = safe_div_pct_decimal(total_output_value, est_output_value)
# 转化率链路
valid_arrival = arrival_cnt - arrival_invalid_cnt # 有效到店
invalid_arrival_rate = safe_div_pct(arrival_invalid_cnt, arrival_cnt)
arrival_rate = safe_div_pct(arrival_cnt, delivery_cnt)
conversion_rate = safe_div_pct(deal_cnt, arrival_cnt)
avg_unit_price_arrival = safe_div(store_sales_output, valid_arrival, 2)
avg_price_diff = avg_unit_price_arrival - avg_price_target
upgrade_unit_price = safe_div(store_sales_output, deal_cnt, 2)
# 品类转化率
window_film_convert = safe_div_pct(window_film_cnt, arrival_cnt)
car_wrap_convert = safe_div_pct(car_wrap_cnt, arrival_cnt)
premium_convert = safe_div_pct(premium_cnt, arrival_cnt)
product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_sales_output)
# 流量费:优先商务政策按台次算,否则用财务列表流量费
traffic_fee_order = (traffic_fee_per_car * Decimal(str(valid_arrival))
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
store_traffic_fee = traffic_fee_order if traffic_fee_order and traffic_fee_order > 0 else traffic_fee_finance
traffic_fee_ratio = safe_div_pct_decimal(store_traffic_fee, store_sales_output)
# 广联分成
gl_share = store_sales_output - product_cost_finance - store_traffic_fee
gl_share_ratio = safe_div_pct_decimal(gl_share, store_sales_output)
internal_settle_profit = internal_settle_value - internal_settle_cost
gl_total_share = gl_share + internal_settle_profit
# 人员成本(直营才算)
personnel_cost = Decimal('0')
if operate_type == '直营':
# 底薪 3500 元/人/月,按统计周期天数折算:3500 * 周期天数 / 月份总天数
# (周期天数 = period_end - period_start + 1,含首尾;月份总天数 = period_start 所在月天数)
base_salary_prorated = prorate_by_period(Decimal('3500'), period_start, period_end)
personnel_cost = (
Decimal(str(headcount)) * base_salary_prorated +
store_sales_output * Decimal('0.04')
)
personnel_cost_ratio = safe_div_pct_decimal(personnel_cost, store_sales_output)
# 施工成本(直营固定公式)
construction_cost = Decimal('0')
if operate_type != '服务商':
construction_cost = (
Decimal(str(window_film_cnt)) * Decimal('95') +
Decimal(str(car_wrap_cnt)) * Decimal('900') +
Decimal(str(premium_cnt)) * Decimal('60') +
Decimal(str(arrival_invalid_cnt)) * Decimal('50')
)
construction_cost_ratio = safe_div_pct_decimal(construction_cost, store_sales_output)
market_fee_weighted_ratio = safe_div_pct_decimal(market_fee_weighted, store_sales_output)
# 服务费(商务报表)= 服务商分成占比 * 门店总产值 / 100(占比为百分比值)
service_fee = (store_sales_output * sp_ratio / Decimal('100')).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
service_fee_ratio = sp_ratio if operate_type != '直营' else Decimal('0')
renovation_ratio = safe_div_pct_decimal(renovation_amortization, store_sales_output)
rent_utilities_ratio = safe_div_pct_decimal(rent_utilities, store_sales_output)
store_consumables_ratio = safe_div_pct_decimal(store_consumables, store_sales_output)
# 成本总计
total_cost = (
personnel_cost + construction_cost + market_fee_weighted +
service_fee + renovation_amortization + rent_utilities + store_consumables
)
cost_ratio = safe_div_pct_decimal(total_cost, store_sales_output)
# 毛利
gross_profit = gl_total_share - total_cost
gross_profit_rate = safe_div_pct_decimal(gross_profit, store_sales_output)
if gross_profit_rate > 0:
gross_profit_status = '盈利'
elif gross_profit_rate == 0:
gross_profit_status = '零毛利'
else:
gross_profit_status = '亏损'
row = ReportLightReformPark(
task_id=task_id, period_start=period_start, period_end=period_end,
region_area=region_area, province=province, city=rec.get('city', ''),
park_type=rec.get('park_type', '园区店'),
operate_type=operate_type, partner_store_cnt=partner_store_cnt,
region_manager=rec.get('region_manager', ''),
park_name=park_name, store_name=sn, brand=brand,
biz_type=biz_type, purchase_indicator=purchase_indicator,
# 触客/交车/转化
delivery_cnt=delivery_cnt, arrival_cnt=arrival_cnt,
arrival_invalid_cnt=arrival_invalid_cnt,
invalid_arrival_rate=invalid_arrival_rate,
arrival_rate=arrival_rate,
deal_cnt=deal_cnt, conversion_rate=conversion_rate,
# 产值/客单
store_sales_output=store_sales_output,
internal_settle_value=internal_settle_value,
total_output_value=total_output_value,
output_progress=output_progress,
avg_unit_price_arrival=avg_unit_price_arrival,
avg_price_target=avg_price_target,
avg_price_diff=avg_price_diff,
upgrade_unit_price=upgrade_unit_price,
# 品类成交+转化
window_film_cnt=window_film_cnt, window_film_convert=window_film_convert,
car_wrap_cnt=car_wrap_cnt, car_wrap_convert=car_wrap_convert,
premium_cnt=premium_cnt, premium_convert=premium_convert,
# 预算
est_traffic=est_traffic,
est_delivery_cnt=est_delivery_cnt,
est_output_value=est_output_value,
# 成本/流量费/广联
product_cost_finance=product_cost_finance,
product_cost_ratio=product_cost_ratio,
internal_settle_cost=internal_settle_cost,
traffic_fee_finance=traffic_fee_finance,
traffic_fee_per_car=traffic_fee_per_car,
traffic_fee_order=traffic_fee_order,
store_traffic_fee=store_traffic_fee,
traffic_fee_ratio=traffic_fee_ratio,
gl_share=gl_share, gl_share_ratio=gl_share_ratio,
internal_settle_profit=internal_settle_profit,
gl_total_share=gl_total_share,
# 人/施/市/服/装/租/耗
personnel_cost=personnel_cost,
personnel_cost_ratio=personnel_cost_ratio,
construction_cost=construction_cost,
construction_cost_ratio=construction_cost_ratio,
market_fee_weighted=market_fee_weighted,
market_fee_weighted_ratio=market_fee_weighted_ratio,
service_fee=service_fee,
service_fee_ratio=service_fee_ratio,
renovation_amortization=renovation_amortization,
renovation_ratio=renovation_ratio,
rent_utilities=rent_utilities,
rent_utilities_ratio=rent_utilities_ratio,
store_consumables=store_consumables,
store_consumables_ratio=store_consumables_ratio,
# 成本/毛利
total_cost=total_cost, cost_ratio=cost_ratio,
gross_profit=gross_profit, gross_profit_rate=gross_profit_rate,
gross_profit_status=gross_profit_status,
)
rows_to_insert.append(row)
# ========== Step7: 排名 ==========
rows_to_insert.sort(key=lambda r: (r.gross_profit_rate or Decimal('0')), reverse=True)
for idx, row in enumerate(rows_to_insert, 1):
row.gross_profit_rank = idx
# ========== Step8: 批量入库 ==========
ReportLightReformPark.query.filter_by(task_id=task_id, is_deleted=0).delete()
db.session.flush()
for i in range(0, len(rows_to_insert), 500):
db.session.add_all(rows_to_insert[i:i + 500])
db.session.flush()
logger.info(f"[轻改园区店] 完成入库 {len(rows_to_insert)} 条")
return len(rows_to_insert)
# -*- coding: utf-8 -*-
"""
订单分润导出分页查询(Python 版)
与 Java 方法 GoodsOrderProfitAllocationService#listForExportByOrderWithPage 功能一致:
1. 执行 rpc-dj-smartcarlife/src/main/resources/META-INF/orm/GoodsOrderProfitAllocationMapper.xml
中 id=listForExportByOrder 的 SQL(同样的 join / 过滤 / 排序 / 分页);
2. 执行 compileData 同等的内存数据组装:
- 费用类目累计(管理层市场费1/2、阳光激励费/2、资源费、人力成本、服务商分润)
- 门店/服务商收益逻辑值 shopProfitMoneyWithLogic、serverProfitMoneyWithLogic
- 线下平台订单(内部结算/自然到店)goodsCost 重算
查询参数仅支持:门店商户号 merchantId、支付开始/结束时间、场景 sceneType、门店名称 merchantName。
依赖: pip install pymysql
"""
import argparse
import json
import os
import sys
from decimal import Decimal, ROUND_HALF_UP
import pymysql
# ==================== 数据库配置(优先读环境变量) ====================
DB_CONFIG = {
"host": os.environ.get("DB_HOST", "192.168.1.228"),
"port": int(os.environ.get("DB_PORT", "3307")),
"user": os.environ.get("DB_USER", "wechat_user"),
"password": os.environ.get("DB_PASSWORD", "b4WRTkl"),
"database": os.environ.get("DB_NAME", "dj_smartcarlife"),
"charset": "utf8mb4",
}
# ==================== 与 Java 枚举保持一致 ====================
# FeeCategoryEnum
FEE_SERVICE_PROVIDER_PROFIT_SHARING = 2 # 服务商分润
FEE_MANAGER_MARKET_FEE1 = 706 # 管理层市场费1
FEE_MANAGER_MARKET_FEE2 = 808 # 管理层市场费2
FEE_SUNSHINE_INCENTIVE_POINT1 = 809 # 阳光激励费
FEE_SUNSHINE_INCENTIVE_POINT2 = 901 # 阳光激励费2
FEE_PLATFORM_RESOURCE_FEE = 900 # 资源费
FEE_LABOR_COST = 807 # 人力成本
EXPENSE_CATEGORY_IDS = [
FEE_SERVICE_PROVIDER_PROFIT_SHARING, FEE_MANAGER_MARKET_FEE1, FEE_MANAGER_MARKET_FEE2,
FEE_SUNSHINE_INCENTIVE_POINT1, FEE_SUNSHINE_INCENTIVE_POINT2,
FEE_PLATFORM_RESOURCE_FEE, FEE_LABOR_COST,
]
# DistributionRuleTypeEnum
RULE_OWNING_DISTRIBUTE = 1 # 费用归属设置
RULE_ACTUAL_DISTRIBUTE = 2 # 实际分账设置
# MerchantDistributionRuleTargetMerchantTypeEnum
TARGET_PLATFORM = 1
TARGET_PARTNER = 2
# DjOrderTypeEnum / SalesTypeEnum
DJ_ORDER_TYPE_INNER_SETTLE = 6 # 内部结算
SALES_TYPE_WALK_IN = 2 # 自然到店
ZERO_2 = Decimal("0.00")
# ==================== SQL(与 Mapper.xml 保持一致) ====================
# 主查询:只保留业务必要列 + compileData 需要的列
BASE_FROM_WHERE = """
from dj_car_life_goods_order_profit_allocation gopa
left join dj_car_life_goods_order_profit_allocation gopa2
on gopa2.order_code = gopa.order_code and gopa2.deleted_flag = 'N'
and gopa2.order_flag = 'Y' and gopa2.grain_size_type = 1
left join dj_car_life_goods_sub_order gso
on gopa.sub_order_code = gso.sub_order_code and gso.deleted_flag = 'N'
left join dj_car_life_goods_order go
on go.order_code = gopa.order_code and go.deleted_flag = 'N'
left join dj_car_life_pay_order po
on go.order_code = po.order_code and po.deleted_flag = 'N'
left join dj_car_life_order_division od
on go.order_code = od.order_code and od.deleted_flag = 'N'
left join dj_car_life_goods_order_customer goc
on go.order_code = goc.order_code and goc.deleted_flag = 'N'
left join dj_car_life_shopmall_sub_order sso
on sso.goods_sub_order_code = gopa.sub_order_code and sso.deleted_flag = 'N' and gopa.scene_type = 3
left join dj_car_life_order_reconciliation_record orr
on orr.order_code = gopa.order_code and orr.deleted_flag = 'N'
where gopa.deleted_flag = 'N' and gopa.order_flag = 'N'
"""
MAIN_SELECT_COLUMNS = """
select
-- ===== 分润明细表 dj_car_life_goods_order_profit_allocation(gopa) =====
gopa.id, -- 主键ID
gopa.order_code, -- 主订单编号
gopa.sub_order_code, -- 子订单编号
gopa.scene_type, -- 场景(0:1.0;1:1.1;2:1.2;3:1.3)
gopa.base_scene_code, -- 场景标识
gopa.total_price, -- 子订单金额
gopa.actual_income_money, -- 子订单实收金额[元](统一0.6%%计算,非真实实收金额,总分账金额)
gopa.gross_profit, -- 毛利
gopa.allocation_money, -- 参与分账金额
gopa.shop_merchant_id, -- 4S店分润商户号
gopa.shop_merchant_name, -- 4S店分润商户名称
gopa.shop_profit_money, -- 4S店分润金额
gopa.yq_merchant_id, -- 园区店分润商户号
gopa.yq_merchant_name, -- 园区店分润商户名称
gopa.yq_profit_money, -- 园区店分润金额
gopa.yq_gross_profit, -- 园区店毛利收益
gopa.gl_profit_money, -- 广联分润金额
gopa.data_date, -- 分润日期(确认升级日期)
gopa.goods_cost, -- 商品成本
gopa.dj_cost, -- 嘀加成本
gopa.third_party_cost, -- 第三方成本
gopa.virtual_account_cost, -- 虚拟对账成本
gopa.recovery_cost, -- 回收成本
gopa.reward_and_penalty_cost, -- 服务商对账奖惩费金额
gopa.purchase_num, -- 购买数量
-- ===== 主汇总分润记录(同表 gopa2: order_flag='Y' 且 grain_size_type=1) =====
gopa2.install_cost as main_install_cost, -- 服务商对账营销费金额(主汇总记录)
gopa2.marketing_cost as main_marketing_cost, -- 服务商对账安装费金额(主汇总记录)
gopa2.reward_and_penalty_cost as main_reward_and_penalty_cost, -- 服务商对账奖惩费金额(主汇总记录)
gopa2.franchisee_profit_money as main_franchisee_profit_money, -- 加盟商分润金额(主汇总记录)
gopa2.gl_profit_money as main_gl_profit_money, -- 广联分润金额(主汇总记录)
gopa2.platform_merchant_name as main_platform_merchant_name, -- 平台方商户名称(主汇总记录)
gopa2.total_price as main_total_price, -- 订单总额(主汇总记录)
gopa2.yq_gross_profit as main_yq_gross_profit, -- 园区店毛利收益(主汇总记录)
gopa2.yq_profit_money as main_yq_profit_money, -- 园区店分润金额(主汇总记录)
gopa2.shop_traffic_money as main_shop_traffic_money, -- 4S店流量费(主汇总记录)
gopa2.custom_common_cost as main_custom_common_cost, -- 自定义公共参数费用(主汇总记录)
gopa2.sunshine_incentive_fee as main_sunshine_incentive_fee, -- 阳光激励费(主汇总记录)
gopa2.other_fee as main_other_fee, -- 其他费用(主汇总记录)
gopa2.purchase_num as main_purchase_num, -- 购买数量(主汇总记录)
-- ===== 商品子订单表 dj_car_life_goods_sub_order(gso) =====
gso.upgrade_goods_code, -- 升级商品编号
gso.upgrade_goods_name, -- 升级商品名称
gso.upgrade_shop_price, -- 升级商品到店价
gso.upgrade_price, -- 升级价
gso.number, -- 商品件数
(gso.upgrade_shop_price - gso.base_shop_price) as goodsCost, -- 商品成本(升级商品到店价-基础商品到店价;内部结算/自然到店按升级到店价×件数重算)
gso.total_price as gso_total_price, -- 订单总额(子订单)
gso.final_price as gso_final_price, -- 优惠后最终金额(子订单)
-- ===== 主订单表 dj_car_life_goods_order(go) =====
go.order_code as go_order_code, -- 主订单编号
go.merchant_id, -- 门店商户号
go.merchant_name, -- 商户名称
go.employee_name, -- 员工姓名
go.seller_merchant_id, -- 销售商户号(园区店)
go.seller_merchant_name, -- 销售(园区店)商户名称
go.seller_name, -- 销售姓名(园区店)
go.total_price as go_total_price, -- 订单总额
go.final_price as go_final_price, -- 优惠后最终金额
go.dj_order_type as go_dj_order_type, -- 嘀加下单订单类型(1:正常,2:打折策略,3:买赠,4:冲量,5:组合付款,6:内部结算)
go.order_time, -- 下单时间
go.order_type, -- 订单类型(1正常,2异常,3正常测试,4异常测试,5未收款)
go.status, -- 订单状态(1待升级;2未升级;3待支付;4已支付;5已退款;6已完成;9已撤销;10已关闭;11已失效;12已退款;13待上传;14审核中)
go.remark, -- 备注
go.business_type, -- 业务类型(1:权益;2:延保)
-- ===== 客户表 dj_car_life_goods_order_customer(goc) =====
goc.customer_name, -- 客户姓名
goc.sales_type, -- 客户类型(0门店引流-售前;1门店引流-售后;2自然到店;3交付端引流-售前)
goc.customer_phone, -- 客户手机号
goc.plate_number, -- 车牌号
-- ===== 支付单表 dj_car_life_pay_order(po) =====
po.pay_type, -- 支付方式(1线上微信,2线下收款,3POS机,4支付宝,5嘀加收款,6对公转账,7其他)
po.order_money, -- 订单金额(元)
po.success_date, -- 支付成功时间
po.out_trade_no, -- 交易单号
po.trade_no, -- 交易凭证号
po.actual_money as po_actual_money, -- 实付金额(元)
-- ===== 分账表 dj_car_life_order_division(od) =====
od.division_status as od_division_status, -- 分账状态(1待分账,2分账中,3分账成功,4分账失败)
od.division_type as od_division_type, -- 分账方式(1线下对账,2线上分账)
od.division_money as od_division_money, -- 分账金额(减0.6%%手续费)
od.gl_division_money as od_gl_division_money, -- 广联分账金额(线上分账时为实际分账金额)
od.gl_owning_division_money as od_gl_owning_division_money, -- 广联应付分账金额
od.shop_owning_division_money, -- 4S店应付分账金额
od.shop_division_money as od_shop_division_money, -- 4S店分账金额(线上分账时为实际分账金额)
od.shop_merchant_name as od_shop_merchant_name, -- 4S店商户名称
od.division_order_code as od_division_order_code, -- 分账单编号
od.division_date as od_division_date, -- 分账时间
-- ===== 商城定金子订单表 dj_car_life_shopmall_sub_order(sso, 仅场景3) =====
sso.order_status as scene3SubOrderStatus, -- 定金订单状态(1待付款,2已支付,3已关闭,4已发货,5已收货,6待发货,7待安装,8已安装,9售后中,10售后完成)
-- ===== 对账记录表 dj_car_life_order_reconciliation_record(orr) =====
if(orr.id is not null, 'Y', 'N') as reconciliationFlag -- 是否已生成对账记录(Y/N)
"""
def build_conditions(args):
"""动态查询条件,与 listForExportByOrderCondition 中对应分支一致"""
cond_sql = []
cond_params = []
if args.scene_type is not None:
cond_sql.append("and go.scene_type = %s")
cond_params.append(args.scene_type)
if args.merchant_id is not None:
cond_sql.append("and go.merchant_id = %s")
cond_params.append(args.merchant_id)
if args.pay_start_date:
cond_sql.append("and po.success_date >= %s")
cond_params.append(args.pay_start_date)
if args.pay_end_date:
cond_sql.append("and po.success_date <= %s")
cond_params.append(args.pay_end_date)
if args.merchant_name:
cond_sql.append("and go.merchant_name like concat('%%', %s, '%%')")
cond_params.append(args.merchant_name)
if args.business_type is not None:
cond_sql.append("and go.business_type = %s")
cond_params.append(args.business_type)
return " ".join(cond_sql), cond_params
def query_page(conn, args):
"""分页查询,等价于 PageHelper.startPage + listForExportByOrder"""
cond_sql, cond_params = build_conditions(args)
where = BASE_FROM_WHERE + ("\n" + cond_sql if cond_sql else "")
order_by = "\norder by po.success_date desc, gopa.id desc"
total = None
if not args.no_count:
with conn.cursor() as cur:
cur.execute("select count(*)" + where, cond_params)
total = cur.fetchone()[0]
sql = (MAIN_SELECT_COLUMNS + where + order_by + "\nlimit %s offset %s")
params = cond_params + [args.page_size, (args.page_num - 1) * args.page_size]
with conn.cursor(pymysql.cursors.DictCursor) as cur:
cur.execute(sql, params)
rows = cur.fetchall()
return rows, total
def get_order_expense_map(conn, order_codes):
"""等价于 getOrderExpenseMap:订单费用类目累计 sum(order_code, expense_category_id)"""
if not order_codes:
return {}
placeholders = ",".join(["%s"] * len(order_codes))
sql = (
"select order_code, expense_category_id, sum(expense_category_result) as expense_category_result "
"from dj_car_life_order_expense_category_calculated "
"where deleted_flag = 'N' "
f"and order_code in ({placeholders}) "
f"and expense_category_id in ({','.join(['%s'] * len(EXPENSE_CATEGORY_IDS))}) "
"group by order_code, expense_category_id"
)
with conn.cursor() as cur:
cur.execute(sql, order_codes + EXPENSE_CATEGORY_IDS)
return {
f"{r[0]}_{r[1]}": r[2]
for r in cur.fetchall()
}
def get_order_partner_distribution_map(conn, order_codes):
"""等价于 getOrderPartnerDistributionMap:服务商分账累计 + 平台方费用归属规则校验"""
if not order_codes:
return {}
placeholders = ",".join(["%s"] * len(order_codes))
def query(target_merchant_type, rule_type=None):
sql = (
"select order_code, rule_type, sum(division_money) "
"from dj_car_life_merchant_distribution "
"where deleted_flag = 'N' and target_merchant_type = %s "
f"and order_code in ({placeholders})"
)
params = [target_merchant_type] + order_codes
if rule_type is not None:
sql += " and rule_type = %s"
params.append(rule_type)
sql += " group by order_code, rule_type"
with conn.cursor() as cur:
cur.execute(sql, params)
return cur.fetchall()
# 服务商分账累计
result = {f"{r[0]}_{r[1]}": r[2] for r in query(TARGET_PARTNER)}
# 平台方记录中配置了费用归属规则(orderCode集合)
has_owning = {r[0] for r in query(TARGET_PLATFORM, RULE_OWNING_DISTRIBUTE)}
# 未分配给服务商的应付记录置空
for key in list(result.keys()):
order_code, rule_type = key.rsplit("_", 1)
if int(rule_type) == RULE_OWNING_DISTRIBUTE and order_code not in has_owning:
result[key] = None
# 配置了归属规则但没有服务商记录的补 0
for order_code in has_owning:
key = f"{order_code}_{RULE_OWNING_DISTRIBUTE}"
if key not in result:
result[key] = Decimal("0")
return result
def compile_data(conn, rows):
"""等价于 compileData 的内存数据组装"""
if not rows:
return
order_codes = list({r["order_code"] for r in rows if r.get("order_code")})
if not order_codes:
return
expense_map = get_order_expense_map(conn, order_codes)
partner_map = get_order_partner_distribution_map(conn, order_codes)
for r in rows:
oc = r.get("order_code")
# 费用类目累计(无记录默认 0.00,与 Java Optional.orElse 一致)
r["managerMarketFee1"] = expense_map.get(f"{oc}_{FEE_MANAGER_MARKET_FEE1}") or ZERO_2
r["managerMarketFee2"] = expense_map.get(f"{oc}_{FEE_MANAGER_MARKET_FEE2}") or ZERO_2
r["sunshineIncentiveFee"] = expense_map.get(f"{oc}_{FEE_SUNSHINE_INCENTIVE_POINT1}") or ZERO_2
r["sunshineIncentiveFee2"] = expense_map.get(f"{oc}_{FEE_SUNSHINE_INCENTIVE_POINT2}") or ZERO_2
r["resourceFee"] = expense_map.get(f"{oc}_{FEE_PLATFORM_RESOURCE_FEE}") or ZERO_2
r["laborCost"] = expense_map.get(f"{oc}_{FEE_LABOR_COST}") or ZERO_2
# 门店(流量方)收益逻辑值
if r.get("od_gl_owning_division_money") is not None:
r["shopProfitMoneyWithLogic"] = (
r.get("shop_owning_division_money") if r.get("shop_owning_division_money") is not None else ZERO_2
)
elif r.get("od_shop_division_money") is not None and r.get("od_shop_division_money") != 0:
r["shopProfitMoneyWithLogic"] = r.get("od_shop_division_money")
elif r.get("main_shop_traffic_money") is not None:
r["shopProfitMoneyWithLogic"] = r.get("main_shop_traffic_money")
# 服务商收益逻辑值
partner_owning = partner_map.get(f"{oc}_{RULE_OWNING_DISTRIBUTE}")
partner_actual = partner_map.get(f"{oc}_{RULE_ACTUAL_DISTRIBUTE}")
if partner_owning is not None:
r["serverProfitMoneyWithLogic"] = partner_owning
elif partner_actual is not None and partner_actual != 0:
r["serverProfitMoneyWithLogic"] = partner_actual
else:
r["serverProfitMoneyWithLogic"] = (
expense_map.get(f"{oc}_{FEE_SERVICE_PROVIDER_PROFIT_SHARING}") or Decimal("0")
)
# 线下平台订单(内部结算/自然到店),goodsCost = upgradeShopPrice × number
is_offline_platform = (
r.get("go_dj_order_type") == DJ_ORDER_TYPE_INNER_SETTLE
or r.get("sales_type") == SALES_TYPE_WALK_IN
)
if is_offline_platform and r.get("upgrade_shop_price") is not None and r.get("number") is not None:
r["goodsCost"] = (r["upgrade_shop_price"] * r["number"]).quantize(ZERO_2, ROUND_HALF_UP)
def list_for_export_by_order_with_page(conn, args):
rows, total = query_page(conn, args)
compile_data(conn, rows)
return {"total": total, "pageNum": args.page_num, "pageSize": args.page_size, "list": rows}
def default_serializer(o):
if isinstance(o, Decimal):
return float(o)
if hasattr(o, "strftime"):
return o.strftime("%Y-%m-%d %H:%M:%S")
return str(o)
def parse_args():
p = argparse.ArgumentParser(description="订单分润导出分页查询(对应 listForExportByOrderWithPage)")
p.add_argument("--scene-type", type=int, help="场景(0:1.0;1:1.1;2:1.2;3:1.3)")
p.add_argument("--merchant-id", type=int, help="门店商户号")
p.add_argument("--merchant-name", help="门店名称(模糊匹配)")
p.add_argument("--business-type", type=int, help="业务类型(1:权益;2:延保)")
p.add_argument("--pay-start-date", help="支付开始时间, 如 2026-01-01 00:00:00")
p.add_argument("--pay-end-date", help="支付结束时间, 如 2026-01-31 23:59:59")
p.add_argument("--page-num", type=int, default=1, help="页码, 默认 1")
p.add_argument("--page-size", type=int, default=10, help="每页条数, 默认 10")
p.add_argument("--no-count", action="store_true", help="不执行 count 查询")
p.add_argument("--out", help="结果输出到文件(JSON), 默认打印到控制台")
return p.parse_args()
def main():
args = parse_args()
conn = pymysql.connect(**DB_CONFIG)
try:
result = list_for_export_by_order_with_page(conn, args)
text = json.dumps(result, ensure_ascii=False, indent=2, default=default_serializer)
if args.out:
with open(args.out, "w", encoding="utf-8") as f:
f.write(text)
print(f"查询完成, 共 {result['total']} 条, 已写入 {args.out}")
else:
print(text)
finally:
conn.close()
if __name__ == "__main__":
sys.exit(main())
...@@ -21,6 +21,8 @@ TASK_COLUMNS = [ ...@@ -21,6 +21,8 @@ TASK_COLUMNS = [
('data_table_type', "varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL", '数据表类型编码(如 budget_achievement)'), ('data_table_type', "varchar(50) COLLATE utf8mb4_unicode_ci NOT NULL", '数据表类型编码(如 budget_achievement)'),
('data_table_type_name', "varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT ''", '数据表类型中文名(如 预算达成数据)'), ('data_table_type_name', "varchar(100) COLLATE utf8mb4_unicode_ci DEFAULT ''", '数据表类型中文名(如 预算达成数据)'),
('month', "varchar(7) COLLATE utf8mb4_unicode_ci NOT NULL", '所属月份,格式 YYYY-MM'), ('month', "varchar(7) COLLATE utf8mb4_unicode_ci NOT NULL", '所属月份,格式 YYYY-MM'),
('period_start', 'date DEFAULT NULL', '所属周期-开始日期(need_period 类型使用,如 2026-08-01)'),
('period_end', 'date DEFAULT NULL', '所属周期-结束日期(need_period 类型使用,如 2026-08-31)'),
('status', "varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'PROCESSING'", '状态:PROCESSING处理中 / COMPLETED已完成 / FAILED失败'), ('status', "varchar(20) COLLATE utf8mb4_unicode_ci NOT NULL DEFAULT 'PROCESSING'", '状态:PROCESSING处理中 / COMPLETED已完成 / FAILED失败'),
('error_msg', "varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT ''", '失败原因(状态为 FAILED 时记录)'), ('error_msg', "varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT ''", '失败原因(状态为 FAILED 时记录)'),
('result_file_url', "varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT ''", '结果 Excel 的 OSS 链接(完成后回填)'), ('result_file_url', "varchar(500) COLLATE utf8mb4_unicode_ci DEFAULT ''", '结果 Excel 的 OSS 链接(完成后回填)'),
...@@ -105,6 +107,20 @@ def migrate(): ...@@ -105,6 +107,20 @@ def migrate():
# 回填已有数据的中文名 # 回填已有数据的中文名
cur.execute("UPDATE data_process_task SET data_table_type_name='预算达成数据' WHERE data_table_type='budget_achievement'") cur.execute("UPDATE data_process_task SET data_table_type_name='预算达成数据' WHERE data_table_type='budget_achievement'")
# ---- 唯一索引治理(2026-09-02 修订) ----
# 历史:原 uq_task_type_month 仅约束 (data_table_type, month),对"店效/产值"等
# 带所属周期的类型过严——同月份分周期上报会被误拒。改为 (4 维 + 软删感知):
# MariaDB 10.0 不支持 STORED 列上的索引(不支持函数索引),最终方案 = 删除 UNIQUE 约束,
# 仅靠应用层 (app.py task_create) 去重;校验已带 is_deleted=0 过滤,软删行不参与。
# 风险:极端并发下理论可能穿透,但实际用户手点操作可忽略。
cur.execute("SHOW INDEX FROM data_process_task WHERE Key_name LIKE 'uq_%'")
existing_uq = cur.fetchall()
for r in existing_uq:
kname = r[2]
cur.execute(f"ALTER TABLE data_process_task DROP INDEX {kname}")
print(f'[DROP UNIQUE] {kname}')
conn.commit() conn.commit()
print('迁移完成') print('迁移完成')
finally: finally:
......
...@@ -11,7 +11,8 @@ class DataProcessTask(db.Model): ...@@ -11,7 +11,8 @@ class DataProcessTask(db.Model):
"""数据处理任务单据表""" """数据处理任务单据表"""
__tablename__ = 'data_process_task' __tablename__ = 'data_process_task'
__table_args__ = ( __table_args__ = (
db.UniqueConstraint('data_table_type', 'month', name='uq_task_type_month'), db.UniqueConstraint('data_table_type', 'month', 'period_start', 'period_end',
name='uq_task_type_month_period'),
{'comment': '数据处理任务单据表'}, {'comment': '数据处理任务单据表'},
) )
...@@ -19,6 +20,11 @@ class DataProcessTask(db.Model): ...@@ -19,6 +20,11 @@ class DataProcessTask(db.Model):
data_table_type = db.Column(db.String(50), nullable=False, comment='数据表类型编码(如 budget_achievement)') data_table_type = db.Column(db.String(50), nullable=False, comment='数据表类型编码(如 budget_achievement)')
data_table_type_name = db.Column(db.String(100), default='', comment='数据表类型中文名(如 预算达成数据)') data_table_type_name = db.Column(db.String(100), default='', comment='数据表类型中文名(如 预算达成数据)')
month = db.Column(db.String(7), nullable=False, comment='所属月份,格式 YYYY-MM') month = db.Column(db.String(7), nullable=False, comment='所属月份,格式 YYYY-MM')
period_type = db.Column(db.String(10), nullable=False, default='month',
comment='周期粒度:month 按月 / week 按周')
week_num = db.Column(db.Integer, nullable=True, comment='按周时的周序号 1-5;按月时为 NULL')
period_start = db.Column(db.Date, nullable=True, comment='所属周期-开始日期(事实日期区间,两种粒度都填)')
period_end = db.Column(db.Date, nullable=True, comment='所属周期-结束日期(事实日期区间,两种粒度都填)')
status = db.Column(db.String(20), nullable=False, default='PROCESSING', comment='状态:PROCESSING处理中 / COMPLETED已完成 / FAILED失败') status = db.Column(db.String(20), nullable=False, default='PROCESSING', comment='状态:PROCESSING处理中 / COMPLETED已完成 / FAILED失败')
error_msg = db.Column(db.String(500), default='', comment='失败原因(状态为 FAILED 时记录)') error_msg = db.Column(db.String(500), default='', comment='失败原因(状态为 FAILED 时记录)')
result_file_url = db.Column(db.String(500), default='', comment='结果 Excel 的 OSS 链接(完成后回填)') result_file_url = db.Column(db.String(500), default='', comment='结果 Excel 的 OSS 链接(完成后回填)')
...@@ -35,6 +41,10 @@ class DataProcessTask(db.Model): ...@@ -35,6 +41,10 @@ class DataProcessTask(db.Model):
'data_table_type': self.data_table_type, 'data_table_type': self.data_table_type,
'data_table_type_name': self.data_table_type_name, 'data_table_type_name': self.data_table_type_name,
'month': self.month, 'month': self.month,
'period_type': self.period_type or 'month',
'week_num': self.week_num,
'period_start': self.period_start.strftime('%Y-%m-%d') if self.period_start else '',
'period_end': self.period_end.strftime('%Y-%m-%d') if self.period_end else '',
'status': self.status, 'status': self.status,
'error_msg': self.error_msg, 'error_msg': self.error_msg,
'result_file_url': self.result_file_url, 'result_file_url': self.result_file_url,
...@@ -215,3 +225,578 @@ class BizBudgetAchieve(db.Model): ...@@ -215,3 +225,578 @@ class BizBudgetAchieve(db.Model):
'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else '', 'created_at': self.created_at.strftime('%Y-%m-%d %H:%M:%S') if self.created_at else '',
'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else '', 'updated_at': self.updated_at.strftime('%Y-%m-%d %H:%M:%S') if self.updated_at else '',
} }
class DataProcessSubtask(db.Model):
"""
红黄门店盈利测算 - 子任务表。
一条主任务(store_effect_earnings)对应 4 条子任务,各自追踪 1 张输出表的处理状态。
调度器轮询时先查对应子任务状态:COMPLETED 则跳过,PENDING/FAILED 则处理。
"""
__tablename__ = 'data_process_subtask'
__table_args__ = (
db.UniqueConstraint('task_id', 'output_category',
name='uk_subtask_task_category'),
{'comment': '数据处理子任务表(追踪 4 张输出表的独立处理状态)'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
task_id = db.Column(db.Integer, db.ForeignKey('data_process_task.id'), nullable=False, comment='主任务ID')
output_category = db.Column(db.String(30), nullable=False,
comment='输出类别:warranty=延保 / equity=权益 / inshop=轻改店中店 / park=轻改园区店')
# 状态机:PENDING → PROCESSING → COMPLETED | FAILED
status = db.Column(db.String(20), nullable=False, default='PENDING',
comment='子任务状态:PENDING待处理 / PROCESSING处理中 / COMPLETED已完成 / FAILED失败')
error_msg = db.Column(db.String(500), default='', comment='失败时的错误信息')
row_count = db.Column(db.Integer, default=0, comment='实际写入行数(处理完成后更新)')
created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='最近更新时间')
is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除')
deleted_at = db.Column(db.DateTime, nullable=True, comment='删除时间')
# 与主任务关联
task = db.relationship('DataProcessTask', backref=db.backref('subtasks', cascade='all, delete-orphan'))
# ============================================================
# 红黄门店盈利测算 - 豪华品牌配置表
# ============================================================
class LuxuryBrandConfig(db.Model):
"""豪华品牌配置表:判断门店品牌属于豪华 or 非豪华"""
__tablename__ = 'luxury_brand_config'
__table_args__ = (
db.UniqueConstraint('brand_name', name='uk_luxury_brand_name'),
{'comment': '豪华品牌配置表'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
brand_name = db.Column(db.String(100), nullable=False, comment='品牌名称(如 问界/鸿蒙/奔驰/宝马 等)')
is_luxury = db.Column(db.Integer, nullable=False, default=0, comment='是否豪华品牌:1豪华 / 0非豪华')
remark = db.Column(db.String(200), default='', comment='备注')
created_at = db.Column(db.DateTime, default=datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
is_deleted = db.Column(db.Integer, nullable=False, default=0)
# ============================================================
# 红黄门店盈利测算 - 4 张输出表
# ============================================================
class ReportExtendedWarranty(db.Model):
"""延保盈利测算表(Excel Sheet「延保」39 列全量存储)"""
__tablename__ = 'report_extended_warranty'
__table_args__ = (
db.UniqueConstraint('task_id', 'period_start', 'period_end', 'store_name', 'brand',
name='uk_warranty_period_store_brand'),
{'comment': '红黄门店盈利测算-延保表'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
period_start = db.Column(db.Date, nullable=True, comment='统计周期开始日期')
period_end = db.Column(db.Date, nullable=True, comment='统计周期结束日期')
# --- 门店基础维度(9 列) ---
region_area = db.Column(db.String(50), default='', comment='片区')
province = db.Column(db.String(50), default='', comment='省份')
city = db.Column(db.String(50), default='', comment='城市')
region_manager = db.Column(db.String(50), default='', comment='区域运营')
training_supervisor = db.Column(db.String(50), default='', comment='培训督导')
biz_manager = db.Column(db.String(50), default='', comment='业务经理')
resident_type = db.Column(db.String(50), default='', comment='驻店类型')
store_name = db.Column(db.String(200), default='', comment='门店名')
brand = db.Column(db.String(50), default='', comment='品牌')
# --- 触客/成交(3 列) ---
delivery_cnt = db.Column(db.Integer, default=0, comment='交车')
touch_cnt = db.Column(db.Integer, default=0, comment='触客')
deal_cnt = db.Column(db.Integer, default=0, comment='成交数')
# --- 延保特有指标(8 列) ---
penetration_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='渗透率')
vehicle_warranty_cnt = db.Column(db.Integer, default=0, comment='整车延保成交数')
vehicle_warranty_penetration = db.Column(db.DECIMAL(10, 6), default=0, comment='整车延保渗透率')
vehicle_warranty_touch_convert = db.Column(db.DECIMAL(10, 6), default=0, comment='整车延保触客成交率')
battery_warranty_cnt = db.Column(db.Integer, default=0, comment='电池成交数')
battery_warranty_penetration = db.Column(db.DECIMAL(10, 6), default=0, comment='电池渗透率')
easy_bag_cnt = db.Column(db.Integer, default=0, comment='安心包成交数')
easy_bag_penetration = db.Column(db.DECIMAL(10, 6), default=0, comment='安心包渗透率')
# --- 产值/成本/费用/毛利(18 列) ---
store_output_value = db.Column(db.DECIMAL(15, 2), default=0, comment='门店产值')
upgrade_unit_price = db.Column(db.DECIMAL(15, 2), default=0, comment='升级客单价')
product_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='商品成本')
store_share = db.Column(db.DECIMAL(15, 2), default=0, comment='门店分成')
guarantee_amount = db.Column(db.DECIMAL(15, 2), default=0, comment='兜底金额')
gl_share = db.Column(db.DECIMAL(15, 2), default=0, comment='广联分成')
market_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='市场费')
market_fee_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='市场费占比')
marketing_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='营销费用')
marketing_fee_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='营销费用占比')
service_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='服务费用')
service_fee_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='服务费用占比')
total_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='成本总计')
cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='成本占比')
gross_profit = db.Column(db.DECIMAL(15, 2), default=0, comment='毛利测算')
gross_profit_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='预估毛利率')
gross_profit_status = db.Column(db.String(20), default='', comment='预估毛利情况')
gross_profit_rank = db.Column(db.Integer, default=0, comment='门店毛利排名')
created_at = db.Column(db.DateTime, default=datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
is_deleted = db.Column(db.Integer, nullable=False, default=0)
deleted_at = db.Column(db.DateTime, nullable=True)
class ReportEquityService(db.Model):
"""权益盈利测算表(Excel Sheet「权益」32 列全量存储)"""
__tablename__ = 'report_equity_service'
__table_args__ = (
db.UniqueConstraint('task_id', 'period_start', 'period_end', 'store_name', 'brand',
name='uk_equity_period_store_brand'),
{'comment': '红黄门店盈利测算-权益表'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
period_start = db.Column(db.Date, nullable=True, comment='统计周期开始日期')
period_end = db.Column(db.Date, nullable=True, comment='统计周期结束日期')
# --- 门店基础维度(9 列) ---
region_area = db.Column(db.String(50), default='', comment='片区')
province = db.Column(db.String(50), default='', comment='省份')
city = db.Column(db.String(50), default='', comment='城市')
region_manager = db.Column(db.String(50), default='', comment='区域运营')
training_supervisor = db.Column(db.String(50), default='', comment='培训督导')
biz_manager = db.Column(db.String(50), default='', comment='业务经理')
resident_type = db.Column(db.String(50), default='', comment='驻店类型')
store_name = db.Column(db.String(200), default='', comment='门店名')
brand = db.Column(db.String(50), default='', comment='品牌')
# --- 触客/成交(4 列) ---
delivery_cnt = db.Column(db.Integer, default=0, comment='交车')
touch_cnt = db.Column(db.Integer, default=0, comment='触客')
deal_cnt = db.Column(db.Integer, default=0, comment='成交数')
penetration_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='渗透率')
# --- 产值/成本/费用/毛利(18 列,与延保表一致) ---
store_output_value = db.Column(db.DECIMAL(15, 2), default=0, comment='门店产值')
upgrade_unit_price = db.Column(db.DECIMAL(15, 2), default=0, comment='升级客单价')
product_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='商品成本')
store_share = db.Column(db.DECIMAL(15, 2), default=0, comment='门店分成')
guarantee_amount = db.Column(db.DECIMAL(15, 2), default=0, comment='兜底金额')
gl_share = db.Column(db.DECIMAL(15, 2), default=0, comment='广联分成')
market_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='市场费')
market_fee_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='市场费占比')
marketing_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='营销费用')
marketing_fee_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='营销费用占比')
service_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='服务费用')
service_fee_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='服务费用占比')
total_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='成本总计')
cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='成本占比')
gross_profit = db.Column(db.DECIMAL(15, 2), default=0, comment='毛利测算')
gross_profit_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='预估毛利率')
gross_profit_status = db.Column(db.String(20), default='', comment='预估毛利情况')
gross_profit_rank = db.Column(db.Integer, default=0, comment='门店毛利排名')
created_at = db.Column(db.DateTime, default=datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
is_deleted = db.Column(db.Integer, nullable=False, default=0)
deleted_at = db.Column(db.DateTime, nullable=True)
class ReportLightReformInshop(db.Model):
"""轻改-店中店汇总表(Excel Sheet「店中店汇总」88 列全量存储)"""
__tablename__ = 'report_light_reform_inshop'
__table_args__ = (
db.UniqueConstraint('task_id', 'period_start', 'period_end', 'park_name', 'store_name',
name='uk_inshop_period_park_store'),
{'comment': '红黄门店盈利测算-轻改店中店汇总表'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
period_start = db.Column(db.Date, nullable=True, comment='统计周期开始日期')
period_end = db.Column(db.Date, nullable=True, comment='统计周期结束日期')
# --- 门店基础信息(13 列) ---
region_area = db.Column(db.String(50), default='', comment='大区名称')
province = db.Column(db.String(50), default='', comment='区域省')
city = db.Column(db.String(50), default='', comment='区域市')
park_type = db.Column(db.String(50), default='', comment='园区类型')
biz_line = db.Column(db.String(50), default='', comment='业务线')
operate_type = db.Column(db.String(50), default='', comment='经营属性')
region_manager = db.Column(db.String(50), default='', comment='区域经理')
park_name = db.Column(db.String(200), default='', comment='园区名称')
store_name = db.Column(db.String(200), default='', comment='门店名称')
brand = db.Column(db.String(50), default='', comment='品牌(问界/鸿蒙)')
brand_category = db.Column(db.String(50), default='', comment='品牌分类(豪华/非豪华)')
purchase_indicator = db.Column(db.String(200), default='', comment='采买/兜底指标')
# --- 销售端口(3 列) ---
sales_order_cnt = db.Column(db.Integer, default=0, comment='销售大定数')
sales_touch_cnt = db.Column(db.Integer, default=0, comment='销售触客数')
sales_touch_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='销售触客率')
# --- 交付端口(3 列) ---
delivery_cnt = db.Column(db.Integer, default=0, comment='交车数')
delivery_touch_cnt = db.Column(db.Integer, default=0, comment='交付触客数')
delivery_touch_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='交付触客率')
# --- 售后端口(6 列) ---
aftersales_baohui_cnt = db.Column(db.Integer, default=0, comment='售后首保回厂数')
aftersales_shigu_cnt = db.Column(db.Integer, default=0, comment='售后事故回厂数')
aftersales_touch_cnt = db.Column(db.Integer, default=0, comment='售后触客数')
aftersales_touch_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='售后触客率')
total_touch_cnt = db.Column(db.Integer, default=0, comment='总触客数')
total_deal_cnt = db.Column(db.Integer, default=0, comment='总成交数')
# --- 窗膜/车衣/精品(双列:原厂+副厂,各 4 列,共 12 列 + 踏板 1 列) ---
window_film_oe_cnt = db.Column(db.Integer, default=0, comment='窗膜成交数-原厂')
window_film_nonoe_cnt = db.Column(db.Integer, default=0, comment='窗膜成交数-副厂')
car_wrap_oe_cnt = db.Column(db.Integer, default=0, comment='车衣成交数-原厂')
car_wrap_nonoe_cnt = db.Column(db.Integer, default=0, comment='车衣成交数-副厂')
premium_oe_cnt = db.Column(db.Integer, default=0, comment='精品成交数-原厂')
premium_nonoe_cnt = db.Column(db.Integer, default=0, comment='精品成交数-副厂')
pedal_cnt = db.Column(db.Integer, default=0, comment='踏板')
# --- 产值(5 列) ---
store_output_value = db.Column(db.DECIMAL(15, 2), default=0, comment='门店总产值')
internal_settle_value = db.Column(db.DECIMAL(15, 2), default=0, comment='内部结算产值')
total_output_value = db.Column(db.DECIMAL(15, 2), default=0, comment='合计总产值')
oe_output_value = db.Column(db.DECIMAL(15, 2), default=0, comment='原厂总产值')
nonoe_output_value = db.Column(db.DECIMAL(15, 2), default=0, comment='副厂总产值')
# --- 客单/渗透(6 列) ---
avg_unit_price_delivery = db.Column(db.DECIMAL(15, 2), default=0, comment='平均客单价(交车)')
avg_price_target = db.Column(db.DECIMAL(15, 2), default=0, comment='平客目标值')
avg_price_diff = db.Column(db.DECIMAL(15, 2), default=0, comment='平客差值')
delivery_touch_unit_price = db.Column(db.DECIMAL(15, 2), default=0, comment='交付触客客单价')
upgrade_unit_price = db.Column(db.DECIMAL(15, 2), default=0, comment='升级客单价')
total_penetration_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='总订单渗透率')
window_film_penetration = db.Column(db.DECIMAL(10, 6), default=0, comment='窗膜渗透率')
car_wrap_penetration = db.Column(db.DECIMAL(10, 6), default=0, comment='车衣渗透率')
premium_penetration = db.Column(db.DECIMAL(10, 6), default=0, comment='精品渗透率')
# --- 成本-产品(7 列) ---
product_cost_finance = db.Column(db.DECIMAL(15, 2), default=0, comment='产品成本(财务列表)')
internal_settle_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='内部结算成本(财务列表)')
oe_product_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='原厂产品成本(财务列表)')
nonoe_product_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='副厂产品成本(财务列表)')
window_film_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='窗膜成本')
car_wrap_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='车衣成本')
premium_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='精品成本')
product_cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='产品总成本占比')
# --- 施工成本 ---
construction_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='施工成本合计(当前暂不用)')
construction_cost_oe = db.Column(db.DECIMAL(15, 2), default=0, comment='前置原厂施工成本')
construction_cost_nonoe = db.Column(db.DECIMAL(15, 2), default=0, comment='前置副厂施工成本')
construction_cost_post = db.Column(db.DECIMAL(15, 2), default=0, comment='后置施工成本(直营按商务政策, 服务商=0)')
construction_cost_post_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='后置施工成本占比(post/门店总产值)')
construction_cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='前置施工成本占比((oe+nonoe)/门店总产值)')
frontline_incentive = db.Column(db.DECIMAL(15, 2), default=0, comment='一线激励')
frontline_incentive_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='一线激励占比')
gross_profit_pre_share = db.Column(db.DECIMAL(15, 2), default=0, comment='进销差(未分成)')
gross_profit_pre_share_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='进销差占比')
store_share = db.Column(db.DECIMAL(15, 2), default=0, comment='门店分成')
store_share_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='门店分成占比(门店分成/门店总产值)')
store_share_per_car = db.Column(db.DECIMAL(15, 2), default=0, comment='门店单车利润')
guarantee_amount = db.Column(db.DECIMAL(15, 2), default=0, comment='兜底金额')
gl_share = db.Column(db.DECIMAL(15, 2), default=0, comment='广联分成')
gl_share_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='广联分成占比')
# --- 广联总分成/内部结算/施工收入(3 列) ---
construction_income = db.Column(db.DECIMAL(15, 2), default=0, comment='施工收入')
internal_settle_profit = db.Column(db.DECIMAL(15, 2), default=0, comment='内部结算')
gl_total_share = db.Column(db.DECIMAL(15, 2), default=0, comment='广联总分成')
# --- 营销/施工/市场/装修/房租/耗材/服务商(7 列) ---
marketing_personnel_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='营销人员成本')
marketing_personnel_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='营销人员成本占比')
market_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='市场费')
market_fee_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='市场费占比')
renovation_amortization = db.Column(db.DECIMAL(15, 2), default=0, comment='装修分摊')
rent_utilities = db.Column(db.DECIMAL(15, 2), default=0, comment='房租、水电费用')
store_consumables = db.Column(db.DECIMAL(15, 2), default=0, comment='门店耗材')
service_provider_share = db.Column(db.DECIMAL(15, 2), default=0, comment='服务商分成')
service_provider_share_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='服务商分成占比')
# --- 成本总计/毛利(5 列) ---
total_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='成本总计')
cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='总计占比')
gross_profit = db.Column(db.DECIMAL(15, 2), default=0, comment='毛利测算')
gross_profit_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='毛利率')
gross_profit_status = db.Column(db.String(20), default='', comment='毛利情况')
gross_profit_rank = db.Column(db.Integer, default=0, comment='门店毛利排名')
created_at = db.Column(db.DateTime, default=datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
is_deleted = db.Column(db.Integer, nullable=False, default=0)
deleted_at = db.Column(db.DateTime, nullable=True)
class SaasBusinessAchievement(db.Model):
"""产值达成表(data_table_type=output_value 的输出表,对应结果表 A~O 列)"""
__tablename__ = 'saas_business_achievement'
__table_args__ = (
db.UniqueConstraint('task_id', 'business_type', 'region_operator',
name='uk_saas_task_biz_operator'),
{'comment': '产值达成表'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='自增主键')
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
stat_month = db.Column(db.String(7), nullable=False, comment='统计月份 YYYY-MM')
start_date = db.Column(db.String(10), nullable=False, comment='统计周期开始时间 YYYY-MM-DD')
end_date = db.Column(db.String(10), nullable=False, comment='统计周期结束时间 YYYY-MM-DD')
business_type = db.Column(db.String(20), nullable=False, comment='业务类型(A列):2.1+2.3 或 1.1')
manager = db.Column(db.String(50), comment='大区经理(B列):由 C 列查关系表 E→D 得到')
region_operator = db.Column(db.String(50), nullable=False, comment='区域运营(C列):SAAS表区域运营')
online_operator = db.Column(db.String(50), comment='线上运营(D列):默认为空')
operated_stores = db.Column(db.Integer, default=0, comment='运营门店数(E列):按门店去重')
direct_stores = db.Column(db.Integer, default=0, comment='直营门店数(F列):驻店类型=直营,按门店去重')
daily_new_gmv = db.Column(db.DECIMAL(15, 2), comment='当日新增GMV(G列):接口获取,暂未接入')
existing_budget = db.Column(db.DECIMAL(15, 2), comment='存量门店预算(H列):存量明细的预估产值(纠偏)合计')
existing_actual = db.Column(db.DECIMAL(15, 2), comment='存量门店实际达成(I列):接口获取,暂未接入')
existing_rate = db.Column(db.DECIMAL(5, 2), comment='存量目标达成率%(J列)=I/H*100')
new_budget = db.Column(db.DECIMAL(15, 2), comment='新店预算(K列):新增明细的预估产值(纠偏)合计')
new_actual = db.Column(db.DECIMAL(15, 2), comment='新店实际达成(L列):接口获取,暂未接入')
new_rate = db.Column(db.DECIMAL(5, 2), comment='新店目标达成率%(M列)=L/K*100')
total_actual_gmv = db.Column(db.DECIMAL(15, 2), comment='实际达成GMV合计(N列)=I+L')
total_rate = db.Column(db.DECIMAL(5, 2), comment='总预算达成率%(O列)=(I+L)/(H+K)*100')
created_at = db.Column(db.DateTime, default=datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
def to_dict(self):
def _f(v):
return float(v) if v is not None else None
return {
'id': self.id,
'task_id': self.task_id,
'stat_month': self.stat_month,
'start_date': self.start_date,
'end_date': self.end_date,
'business_type': self.business_type,
'manager': self.manager,
'region_operator': self.region_operator,
'online_operator': self.online_operator,
'operated_stores': self.operated_stores,
'direct_stores': self.direct_stores,
'daily_new_gmv': _f(self.daily_new_gmv),
'existing_budget': _f(self.existing_budget),
'existing_actual': _f(self.existing_actual),
'existing_rate': _f(self.existing_rate),
'new_budget': _f(self.new_budget),
'new_actual': _f(self.new_actual),
'new_rate': _f(self.new_rate),
'total_actual_gmv': _f(self.total_actual_gmv),
'total_rate': _f(self.total_rate),
}
class ReportLightReformPark(db.Model):
"""轻改-园区店汇总表(Excel Sheet「园区店汇总」69 列全量存储)"""
__tablename__ = 'report_light_reform_park'
__table_args__ = (
db.UniqueConstraint('task_id', 'period_start', 'period_end', 'park_name', 'store_name',
name='uk_park_period_park_store'),
{'comment': '红黄门店盈利测算-轻改园区店汇总表'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
period_start = db.Column(db.Date, nullable=True, comment='统计周期开始日期')
period_end = db.Column(db.Date, nullable=True, comment='统计周期结束日期')
# --- 门店基础信息(11 列) ---
region_area = db.Column(db.String(50), default='', comment='大区名称')
province = db.Column(db.String(50), default='', comment='区域省')
city = db.Column(db.String(50), default='', comment='区域市')
park_type = db.Column(db.String(50), default='', comment='园区类型')
operate_type = db.Column(db.String(50), default='', comment='经营属性')
partner_store_cnt = db.Column(db.Integer, default=0, comment='合作门店数量')
region_manager = db.Column(db.String(50), default='', comment='区域经理')
park_name = db.Column(db.String(200), default='', comment='园区名称')
store_name = db.Column(db.String(200), default='', comment='门店名称')
brand = db.Column(db.String(50), default='', comment='品牌')
biz_type = db.Column(db.String(50), default='', comment='类型')
purchase_indicator = db.Column(db.String(200), default='', comment='采买/兜底指标(流量费)')
# --- 触客/交车/转化(10 列) ---
delivery_cnt = db.Column(db.Integer, default=0, comment='交车数')
arrival_cnt = db.Column(db.Integer, default=0, comment='到店数')
arrival_invalid_cnt = db.Column(db.Integer, default=0, comment='到店无效客户数')
invalid_arrival_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='无效到店率')
arrival_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='到店率')
deal_cnt = db.Column(db.Integer, default=0, comment='成交数')
conversion_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='转化率')
# --- 产值/客单/渗透率(8 列) ---
store_sales_output = db.Column(db.DECIMAL(15, 2), default=0, comment='门店销售产值')
internal_settle_value = db.Column(db.DECIMAL(15, 2), default=0, comment='内部结算产值')
total_output_value = db.Column(db.DECIMAL(15, 2), default=0, comment='合计总产值')
output_progress = db.Column(db.DECIMAL(10, 6), default=0, comment='产值达成进度')
avg_unit_price_arrival = db.Column(db.DECIMAL(15, 2), default=0, comment='平均客单价(到店)')
avg_price_target = db.Column(db.DECIMAL(15, 2), default=0, comment='平客目标值')
avg_price_diff = db.Column(db.DECIMAL(15, 2), default=0, comment='平客差值')
upgrade_unit_price = db.Column(db.DECIMAL(15, 2), default=0, comment='升级客单价')
# --- 窗膜/车衣/精品 成交+转化率(6 列) ---
window_film_cnt = db.Column(db.Integer, default=0, comment='窗膜成交数')
window_film_convert = db.Column(db.DECIMAL(10, 6), default=0, comment='窗膜转化率')
car_wrap_cnt = db.Column(db.Integer, default=0, comment='车衣成交数')
car_wrap_convert = db.Column(db.DECIMAL(10, 6), default=0, comment='车衣转化率')
premium_cnt = db.Column(db.Integer, default=0, comment='精品成交数')
premium_convert = db.Column(db.DECIMAL(10, 6), default=0, comment='精品转化率')
# --- 预算(3 列) ---
est_traffic = db.Column(db.Integer, default=0, comment='商务上架预估流量')
est_delivery_cnt = db.Column(db.Integer, default=0, comment='预估交车数')
est_output_value = db.Column(db.DECIMAL(15, 2), default=0, comment='预估总产值(预算目标)')
# --- 成本/分成/毛利核心字段(38 列) ---
product_cost_finance = db.Column(db.DECIMAL(15, 2), default=0, comment='产品成本(财务列表)')
product_cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='产品成本占比')
internal_settle_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='内部结算成本(财务列表)')
traffic_fee_finance = db.Column(db.DECIMAL(15, 2), default=0, comment='流量费(财务列表)')
traffic_fee_per_car = db.Column(db.DECIMAL(15, 2), default=0, comment='按单台计算流量/台')
traffic_fee_order = db.Column(db.DECIMAL(15, 2), default=0, comment='按台次计算流量费')
store_traffic_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='门店流量费')
traffic_fee_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='流量费率(列表测算)')
gl_share = db.Column(db.DECIMAL(15, 2), default=0, comment='广联分成')
gl_share_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='广联分成占比')
internal_settle_profit = db.Column(db.DECIMAL(15, 2), default=0, comment='内部结算')
gl_total_share = db.Column(db.DECIMAL(15, 2), default=0, comment='广联总分成')
personnel_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='人员成本')
personnel_cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='常规人员费率(加权参考)')
construction_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='施工成本')
construction_cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='施工成本占比')
market_fee_weighted = db.Column(db.DECIMAL(15, 2), default=0, comment='市场费(加权测算)')
market_fee_weighted_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='市场费费率(加权参考)')
service_fee = db.Column(db.DECIMAL(15, 2), default=0, comment='服务费(商务报表)')
service_fee_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='服务费费率(加权参考)')
renovation_amortization = db.Column(db.DECIMAL(15, 2), default=0, comment='装修分摊(商务报表)')
renovation_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='装修占比')
rent_utilities = db.Column(db.DECIMAL(15, 2), default=0, comment='房租、水电费用')
rent_utilities_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='房租、水电占比')
store_consumables = db.Column(db.DECIMAL(15, 2), default=0, comment='门店耗材')
store_consumables_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='门店耗材占比')
total_cost = db.Column(db.DECIMAL(15, 2), default=0, comment='成本总计')
cost_ratio = db.Column(db.DECIMAL(10, 6), default=0, comment='总计占比')
gross_profit = db.Column(db.DECIMAL(15, 2), default=0, comment='毛利测算')
gross_profit_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='毛利率')
gross_profit_status = db.Column(db.String(20), default='', comment='毛利情况')
gross_profit_rank = db.Column(db.Integer, default=0, comment='门店毛利排名')
created_at = db.Column(db.DateTime, default=datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
is_deleted = db.Column(db.Integer, nullable=False, default=0)
deleted_at = db.Column(db.DateTime, nullable=True)
class AvitaSpecialMonthData(db.Model):
"""阿维塔专项-月份明细数据表(data_table_type=avita_special 的主表,逐门店一行)"""
__tablename__ = 'avita_special_month_data'
__table_args__ = (
{'comment': '阿维塔专项-月份明细数据表(逐门店一行)'},
)
id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='自增主键')
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
stat_month = db.Column(db.String(7), nullable=False, comment='统计月份,格式YYYY-MM,如2026-08')
store_name = db.Column(db.String(255), nullable=False, comment='门店名称')
store_short_name = db.Column(db.String(255), comment='门店简称')
store_mode = db.Column(db.String(50), comment='门店模式')
entry_time = db.Column(db.String(10), comment='入驻时间')
regional_operation = db.Column(db.String(100), comment='区域运营')
resident_name = db.Column(db.String(100), comment='驻店姓名')
oem_delivery_count = db.Column(db.Integer, comment='主机厂数据-交付数')
oem_extended_warranty_deal_count = db.Column(db.Integer, comment='主机厂数据-延保成交数')
oem_worry_free_deal_count = db.Column(db.Integer, comment='主机厂数据-无忧成交数')
oem_revenue_per_vehicle = db.Column(db.DECIMAL(12, 2), comment='主机厂数据-门店单车收入(延保+无忧)')
oem_total_output = db.Column(db.DECIMAL(14, 2), comment='主机厂数据-门店总产值')
cutoff_gl_delivery_count = db.Column(db.Integer, comment='广联数据-交付数')
cutoff_gl_visit_count = db.Column(db.Integer, comment='广联数据-触客数')
cutoff_gl_extended_warranty_deal_count = db.Column(db.Integer, comment='广联数据-延保成交数')
cutoff_gl_worry_free_deal_count = db.Column(db.Integer, comment='广联数据-无忧成交数')
is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除(软删除)')
class AvitaSpecialMonthSummaryMetrics(db.Model):
"""阿维塔专项-汇总指标表(data_table_type=avita_special 的汇总行,单任务一行)"""
__tablename__ = 'avita_special_month_summary_metrics'
__table_args__ = (
{'comment': '阿维塔专项-汇总指标表(单任务一行)'},
)
id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='自增主键')
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
stat_month = db.Column(db.String(7), nullable=False, comment='统计月份,格式YYYY-MM,如2026-08')
project_name = db.Column(db.String(100), nullable=False, comment='项目')
brand = db.Column(db.String(100), nullable=False, comment='品牌')
store_count = db.Column(db.Integer, comment='门店数')
output_value = db.Column(db.DECIMAL(16, 2), comment='产值')
delivery_count = db.Column(db.Integer, comment='交付数')
pre_sales_visit_count = db.Column(db.Integer, comment='售前触客数')
pre_sales_visit_rate = db.Column(db.DECIMAL(10, 6), comment='售前触客率')
after_sales_store_count = db.Column(db.Integer, comment='售后门店数')
after_sales_scene_open_rate = db.Column(db.DECIMAL(10, 6), comment='售后场景开通率')
after_sales_order_count = db.Column(db.Integer, comment='售后订单数')
vehicle_extended_warranty_deal_count = db.Column(db.Integer, comment='整车延保成交数')
vehicle_extended_warranty_penetration_rate = db.Column(db.DECIMAL(10, 6), comment='整车延保渗透率')
oem_rights_deal_count = db.Column(db.Integer, comment='原厂权益成交数')
oem_rights_penetration_rate = db.Column(db.DECIMAL(10, 6), comment='原厂权益渗透率')
after_sales_scene_open_rate_mom = db.Column(db.DECIMAL(10, 6), comment='售后场景开通率环比')
pre_sales_visit_rate_mom = db.Column(db.DECIMAL(10, 6), comment='售前触客率环比')
vehicle_extended_warranty_penetration_rate_mom = db.Column(db.DECIMAL(10, 6), comment='整车延保渗透率环比')
oem_rights_penetration_rate_mom = db.Column(db.DECIMAL(10, 6), comment='原厂权益渗透率环比')
created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除(软删除)')
class ReportStoreEffectSummary(db.Model):
"""门店店效人效汇总表(整体合计,单任务一行;合并结果表第5个sheet)"""
__tablename__ = 'report_store_effect_summary'
__table_args__ = (
db.UniqueConstraint('task_id', 'period_start', 'period_end',
name='uk_store_effect_summary_task_period'),
{'comment': '门店店效人效汇总表(整体合计)'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True)
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
stat_month = db.Column(db.String(7), default='', comment='统计月份 YYYY-MM')
period_start = db.Column(db.Date, nullable=True, comment='统计周期开始')
period_end = db.Column(db.Date, nullable=True, comment='统计周期结束')
# --- 店效 ---
store_count = db.Column(db.Integer, default=0, comment='门店数(跨业务类型去重)')
delivery_total = db.Column(db.Integer, default=0, comment='交车数合计')
touch_total = db.Column(db.Integer, default=0, comment='触客数合计')
deal_total = db.Column(db.Integer, default=0, comment='成交数合计')
output_value_total = db.Column(db.DECIMAL(15, 2), default=0, comment='产值合计')
cost_total = db.Column(db.DECIMAL(15, 2), default=0, comment='成本合计')
gross_profit_total = db.Column(db.DECIMAL(15, 2), default=0, comment='毛利合计')
gross_profit_rate = db.Column(db.DECIMAL(10, 6), default=0, comment='毛利率')
# --- 人效 ---
labor_cost_total = db.Column(db.DECIMAL(15, 2), default=0, comment='人力成本合计')
headcount_total = db.Column(db.Integer, default=0, comment='人员数合计')
per_capita_output = db.Column(db.DECIMAL(15, 2), default=0, comment='人均产值')
per_capita_profit = db.Column(db.DECIMAL(15, 2), default=0, comment='人均毛利')
created_at = db.Column(db.DateTime, default=datetime.now)
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now)
is_deleted = db.Column(db.Integer, nullable=False, default=0)
deleted_at = db.Column(db.DateTime, nullable=True)
# -*- coding: utf-8 -*-
"""
产值达成表 独立处理器
====================
对应 ORM 表:saas_business_achievement
数据来源:SAAS门店预算分解表(sheet1=权益延保 2.1+2.3 / sheet2=轻改 1.1)+ 关系表
处理流程(对齐结果表《产值达成表.xlsx》「业务达成总览」口径):
Step1 下载附件(SAAS门店预算分解表、关系表)
Step2 解析 SAAS 表:按业务类型取对应 sheet 的明细
A列 业务类型:2.1+2.3 → sheet1(权益延保);1.1 → sheet2(轻改)
Step3 解析关系表:业务线 → {区域经理(E列): 大区经理(D列)}
Step4 按 C 列(区域运营)聚合:
B列 大区经理 = 关系表按 C 列查 E 列 → 取 D 列
E列 运营门店数 = 全部明细按「门店」去重计数
F列 直营门店数 = 驻店类型=直营 的明细按「门店」去重计数
H列 存量预算 = 存量/性质=存量 的「预估产值(纠偏)」合计
K列 新店预算 = 存量/性质=新增 的「预估产值(纠偏)」合计
Step5 入库 saas_business_achievement(按 task_id 先删后插,幂等)
接口列(已接入指标系统 http://dc.glsx.com.cn/data):
G列 当日新增GMV / I列 存量门店实际达成 / L列 新店实际达成
统一取自指标编码 A036(产值,非率不*100),按门店名(store_name) 匹配 API 返回的
merchantName 逐一求和;bizs 映射:2.1+2.3→[1,3]、1.1→[2],序列化为逗号字符串。
指标查询口径区分:G列「当日新增GMV」=统计周期最后一天(startDate=endDate=period_end,单日);
I列「存量门店实际达成」/L列「新店实际达成」=整周期累计(startDate=period_start→endDate=period_end)。
指标拉取成功但某门店名未匹配到 merchantName 时,G/I/L 该组填充 0(按用户口径缺数据显 0,不置空)。
依赖接口值的 J/M/N/O 达成率列由 G/I/L 与预算重算(实际为 0 → 达成率 0%)。
"""
import calendar
import logging
import os
import tempfile
from collections import defaultdict
from datetime import datetime
from decimal import Decimal, ROUND_HALF_UP
import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from oss_utils import upload_file
from config import Config
from report_utils import (
mark_task_failed, cleanup_tmp_dir, download_all_files,
parse_saas_achieve_details, parse_operator_relation,
fetch_indicator_data, safe_div_pct_decimal,
)
from models import DataProcessTask, SaasBusinessAchievement, db
logger = logging.getLogger('OutputValueProcessor')
OUTPUT_VALUE_TYPE = 'output_value'
# 业务类型 → (SAAS 表 sheet 关键字, sheet 索引回退, 关系表业务线关键字)
BIZ_SHEET_CONF = {
'2.1+2.3': (['权益延保', '门店'], 0, '权益延保'),
'1.1': (['轻改', '门店'], 1, '轻改'),
}
# 指标系统接口:产值达成表实际值(G/I/L 列)取自 A036(产值)。
# 用户确认:均非率类,不 *100;按门店名(store_name) 匹配 API 返回 merchantName 逐一求和。
INDICATOR_ITEM_CODES = ['A036']
# 业务类型 → 指标系统 bizs(多业务线序列化为逗号字符串,见 indicator_client):
# 2.1+2.3 → 延保(1) + 权益(3);1.1 → 轻改(2)
BIZS_MAP = {
'2.1+2.3': [1, 3],
'1.1': [2],
}
class OutputValueProcessor:
"""产值达成表独立处理器"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_output_value(self):
"""扫描 output_value 类型的 PROCESSING 任务并处理产值达成表"""
logger.info("[产值达成] 开始扫描 output_value 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=OUTPUT_VALUE_TYPE,
status='PROCESSING',
is_deleted=0,
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[产值达成] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[产值达成] 任务 {task.id} 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[产值达成] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[产值达成] 标记任务失败时出错: {mark_err}")
logger.info(f"[产值达成] 扫描完成,成功 {success_count},失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
# ============================================================
# 单任务处理
# ============================================================
def process(self, task):
"""处理单个任务的产值达成表输出"""
task_id = task.id
try:
row_count = self._process_output_value(task)
# 生成结果表 Excel 并上传到 OSS,回写 result_file_url
result_file_url = self.generate_result_excel(task)
task = DataProcessTask.query.filter_by(id=task_id).first()
task.status = 'COMPLETED'
task.result_file_url = result_file_url
task.error_msg = ''
db.session.commit()
logger.info(f"[产值达成] 任务 {task_id} 处理完成,写入 {row_count} 行,结果文件: {result_file_url}")
except Exception as e:
db.session.rollback()
mark_task_failed(task_id, str(e))
raise
def _process_output_value(self, task):
"""产值达成表完整处理流程,返回写入行数"""
task_id = task.id
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
stat_month = task.month or ''
logger.info(f"[产值达成] 开始处理 task_id={task_id}, 周期={start_str}~{end_str}")
# ========== Step1: 下载附件 ==========
tmp_dir = tempfile.mkdtemp(prefix=f"output_value_{task_id}_")
details_by_biz = {}
relation = {}
try:
file_map = download_all_files(task_id, tmp_dir)
saas_path = file_map.get('SAAS门店预算分解表')
if not saas_path:
raise Exception("缺少必需文件: SAAS门店预算分解表")
rel_path = file_map.get('关系表')
# ========== Step2: 解析 SAAS 明细(按业务类型取 sheet) ==========
for biz_type, (keywords, idx, _line) in BIZ_SHEET_CONF.items():
details_by_biz[biz_type] = parse_saas_achieve_details(saas_path, keywords, idx)
logger.info(f"[产值达成] 业务类型 {biz_type}: {len(details_by_biz[biz_type])} 行明细")
# ========== Step3: 解析关系表 ==========
if rel_path:
relation = parse_operator_relation(rel_path)
else:
logger.warning("[产值达成] 缺少关系表,B 列(大区经理)将为空")
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step3.5: 指标系统实际值(G / I / L)预拉取(按业务类型,bizs 不同) ==========
# 口径区分(按结果表列义):
# G 列「当日新增GMV」 = 统计周期【最后一天】单日值(startDate=endDate=period_end)
# I 列「存量门店实际达成」 = 统计周期【整周期】累计(startDate=period_start→endDate=period_end)
# L 列「新店实际达成」 = 统计周期【整周期】累计(同上)
# 故需分别拉取:整周期一份供 I/L,最后一天一份供 G。
indicator_period_by_biz = {} # 整周期:I/L
indicator_last_day_by_biz = {} # 最后一天:G
if end_str:
for biz_type, bizs in BIZS_MAP.items():
records = details_by_biz.get(biz_type)
if not records:
continue
# G 列:最后一天单日值
ind_last = fetch_indicator_data(end_str, end_str, bizs, INDICATOR_ITEM_CODES)
indicator_last_day_by_biz[biz_type] = ind_last
# I/L 列:整周期累计(需起止日齐全)
ind_period = {}
if start_str:
ind_period = fetch_indicator_data(start_str, end_str, bizs, INDICATOR_ITEM_CODES)
indicator_period_by_biz[biz_type] = ind_period
# 覆盖率日志:门店名(store_name) 与 API merchantName 匹配情况
store_names = {it['store_name'] for it in records if it['store_name']}
matched_last = len(store_names & set(ind_last.keys()))
matched_period = (len(store_names & set(ind_period.keys()))
if start_str else None)
logger.info(f"[产值达成] 业务类型 {biz_type} 指标拉取: "
f"整周期匹配 {matched_period}/{len(store_names)}"
+ f", 最后一天匹配 {matched_last}/{len(store_names)}")
else:
logger.warning("[产值达成] 缺少统计周期(start/end),跳过指标系统拉取(G/I/L 留空)")
# ========== Step4: 按区域运营聚合 ==========
rows_to_insert = []
for biz_type, (_kw, _idx, line_kw) in BIZ_SHEET_CONF.items():
records = details_by_biz.get(biz_type) or []
# 关系表:取该业务线对应的 区域经理 → 大区经理 映射
line_map = {}
for line, mapping in relation.items():
if line_kw and line_kw in str(line):
line_map.update(mapping)
if not line_map:
# 业务线未命中时回退:合并全部业务线(避免 B 列大面积为空)
for mapping in relation.values():
line_map.update(mapping)
group = defaultdict(list)
for r in records:
group[r['region_operator']].append(r)
for region_operator, items in group.items():
# E 列:全部明细按门店去重
store_set = {it['store_name'] for it in items if it['store_name']}
operated_stores = len(store_set)
# F 列:驻店类型=直营 的明细按门店去重
direct_set = {it['store_name'] for it in items
if it['store_name'] and it['resident_type'] == '直营'}
direct_stores = len(direct_set)
# H / K 列:按 存量/新增 汇总「预估产值(纠偏)」
existing_budget = sum((it['budget_corrected'] for it in items
if it['store_kind'] == '存量'), Decimal('0'))
new_budget = sum((it['budget_corrected'] for it in items
if it['store_kind'] == '新增'), Decimal('0'))
# 门店名集合(按 store_kind 区分,供 G/I/L 接口值按门店匹配求和)
existing_stores = [it['store_name'] for it in items
if it['store_name'] and it['store_kind'] == '存量']
new_stores = [it['store_name'] for it in items
if it['store_name'] and it['store_kind'] == '新增']
# B 列:关系表 E(区域经理) → D(大区经理)
manager = line_map.get(region_operator, '')
# 关系表哨兵值('/'、'nan'、'None')归一为空,结果表显示为空而非字面斜杠
if not manager or manager.strip() in ('/', 'nan', 'None', '无'):
manager = ''
# G / I / L 列:指标系统实际值(A036 产值),按门店名(store_name) 匹配 merchantName 求和
# I 列(存量实际) = 整周期累计:存量门店 A036 合计
# L 列(新店实际) = 整周期累计:新增门店 A036 合计
# G 列(当日新增GMV) = 最后一天单日:本组全部门店(存量+新增)A036 合计
ind_period = indicator_period_by_biz.get(biz_type) or {}
ind_last = indicator_last_day_by_biz.get(biz_type) or {}
existing_actual = self._sum_indicator(ind_period, existing_stores)
new_actual = self._sum_indicator(ind_period, new_stores)
# G:最后一天口径,按本组全部门店(存量+新增,去重)求和
all_stores = list(dict.fromkeys((existing_stores or []) + (new_stores or [])))
daily_new_gmv = self._sum_indicator(ind_last, all_stores)
# J / M / N / O 列:由 G/I/L 与预算重算。G/I/L 现为 0(未匹配)或实际值,
# 故达成率恒可计算(实际为 0 → 达成率 0%);预算为 0 时 safe_div 返回 0。
existing_rate = safe_div_pct_decimal(existing_actual, existing_budget)
new_rate = safe_div_pct_decimal(new_actual, new_budget)
total_actual_gmv = existing_actual + new_actual
total_rate = safe_div_pct_decimal(total_actual_gmv, existing_budget + new_budget)
rows_to_insert.append(SaasBusinessAchievement(
task_id=task_id,
stat_month=stat_month,
start_date=start_str,
end_date=end_str,
business_type=biz_type,
manager=manager or None,
region_operator=region_operator,
online_operator=None,
operated_stores=operated_stores,
direct_stores=direct_stores,
daily_new_gmv=daily_new_gmv,
existing_budget=existing_budget,
existing_actual=existing_actual,
existing_rate=existing_rate,
new_budget=new_budget,
new_actual=new_actual,
new_rate=new_rate,
total_actual_gmv=total_actual_gmv,
total_rate=total_rate,
))
logger.info(f"[产值达成] 业务类型 {biz_type}: 聚合 {len(group)} 个区域运营")
# ========== Step5: 入库(按 task_id 先删后插,幂等) ==========
SaasBusinessAchievement.query.filter_by(task_id=task_id).delete()
# 先 flush 删除,避免同事务内 insert 与未生效的 delete 触发唯一约束冲突
db.session.flush()
# 用 add_all 而非 bulk_save_objects:bulk 会省略 None 列,使 MySQL 套用列默认值 0.00,
# 导致接口列(G/I/L 及达成率)的 NULL 被误存为 0;add_all 会显式写入 NULL,
# 这样「0」才能唯一表示「接口已接入且真实为 0」,未接入则留空。
db.session.add_all(rows_to_insert)
db.session.commit()
logger.info(f"[产值达成] 入库完成:{len(rows_to_insert)} 行(task_id={task_id})")
return len(rows_to_insert)
# ============================================================
# 结果表 Excel 生成(任务完成后输出《产值达成表》结果文件)
# ============================================================
# 结果表「业务达成总览」列定义:(表头, ORM 属性, 类型)
# 对齐《产值达成表》模板:A 业务类型 / B=大区经理 / C=区域运营 / D 线上运营 / E~O 指标
# B 列取值:以 C 列(区域运营) 为键,查关系表 E(区域经理)→D(大区经理) 得到,库存于 manager 字段
RESULT_COLUMNS = [
('业务类型', 'business_type', 'text'),
('大区经理', 'manager', 'text'), # B:关系表 E(区域运营)→D(大区经理)
('区域运营', 'region_operator', 'text'), # C:SAAS 表区域运营
('线上运营', 'online_operator', 'text'),
('运营门店(家)', 'operated_stores', 'int'),
('直营门店(家)', 'direct_stores', 'int'),
('当日新增GMV', 'daily_new_gmv', 'amount'),
('存量门店预算', 'existing_budget', 'amount'),
('存量门店实际达成', 'existing_actual', 'amount'),
('存量目标达成率(%)', 'existing_rate', 'rate'),
('新店预算', 'new_budget', 'amount'),
('新店实际达成', 'new_actual', 'amount'),
('新店目标达成率(%)', 'new_rate', 'rate'),
('实际达成GMV合计', 'total_actual_gmv', 'amount'),
('总预算达成率(%)', 'total_rate', 'rate'),
]
# 统计行(小计/合计)需汇总的列:int/amount 求和,rate 由汇总值重算
_SUM_COLS = ['operated_stores', 'direct_stores', 'daily_new_gmv',
'existing_budget', 'existing_actual', 'new_budget', 'new_actual',
'total_actual_gmv']
@staticmethod
def _safe_none_sum(values):
"""对可空数值求和:全为空返回 None(保持「未接入」空白),否则忽略 None 求和"""
nums = [v for v in values if v is not None]
return sum(nums) if nums else None
@staticmethod
def _sum_indicator(ind_map, store_names, item_code='A036'):
"""按门店名逐一匹配指标系统返回 merchantName,对 item_code 的 itemValue 求和。
ind_map: {merchantName: {itemCode: value, ...}}(fetch_indicator_data 返回)
store_names: 本组需纳入求和的门店名列表(可空)
返回 Decimal:匹配到的门店 itemValue 累加;未匹配到任何门店(ind_map 为空、
门店名均不匹配、或门店列表为空)一律返回 Decimal('0'),以适配 G/I/L 缺数据显 0 的口径
(保证「未接入/无数据」与「真实为 0」在结果表均显示为 0,不再区分留空)。
"""
total = Decimal('0')
if not ind_map:
return total
for sn in store_names or []:
if not sn:
continue
v = ind_map.get(sn, {}).get(item_code)
if v is not None:
total += Decimal(str(v))
return total
@staticmethod
def _safe_rate_pct(num, den):
"""达成率(×100,与数据行一致):除数为空/0 时返回 None"""
if num is None or den is None or den == 0:
return None
return round(num / den * 100, 2)
@staticmethod
def _merge_same_vertical(ws, start_row, end_row, col, values, border):
"""在 [start_row, end_row] 行范围内,对 col 列中相邻相同的值做纵向合并,并补边框。
values 为按行顺序(相对 start_row)的值列表;合并后隐藏单元格的边框由
逐格补 border 保证显示完整边线(openpyxl 合并后仅顶/底可见单元格边框生效)。
"""
r = start_row
n = end_row - start_row + 1
while r <= end_row:
v = values[r - start_row] if (r - start_row) < len(values) else None
# 空值(None / 空串)不合并:仅逐格补边框,单列处理
if v is None or v == '':
ws.cell(row=r, column=col).border = border
r += 1
continue
run_start = r
while (r + 1 <= end_row
and (r + 1 - start_row) < len(values)
and values[r + 1 - start_row] == v):
r += 1
if r > run_start: # 存在 ≥2 个相邻相同值才合并
ws.merge_cells(start_row=run_start, start_column=col,
end_row=r, end_column=col)
for rr in range(run_start, r + 1):
ws.cell(row=rr, column=col).border = border
r += 1
def _aggregate(self, rows):
"""对一组明细行做汇总,返回各列汇总值(rate 列由汇总后的值重算)"""
agg = {c: self._safe_none_sum([getattr(r, c) for r in rows])
for c in self._SUM_COLS}
existing_budget = agg['existing_budget']
new_budget = agg['new_budget']
existing_actual = agg['existing_actual']
new_actual = agg['new_actual']
total_actual = agg['total_actual_gmv']
agg['existing_rate'] = self._safe_rate_pct(existing_actual, existing_budget)
agg['new_rate'] = self._safe_rate_pct(new_actual, new_budget)
denom = (existing_budget or 0) + (new_budget or 0)
agg['total_rate'] = (self._safe_rate_pct(total_actual, denom)
if total_actual is not None else None)
return agg
def _write_cell(self, ws, row, col, value, kind, font, border, align):
cell = ws.cell(row=row, column=col)
if value is None or value == '':
cell.value = ''
elif kind == 'int':
try:
cell.value = int(value)
cell.number_format = '#,##0'
except (ValueError, TypeError):
cell.value = ''
elif kind == 'amount':
try:
cell.value = float(value)
cell.number_format = '#,##0.00'
except (ValueError, TypeError):
cell.value = ''
elif kind == 'rate':
# 数据行/汇总值已是 ×100(如 75.50 表示 75.50%),
# 用 0.00"%" 仅追加 % 号、不缩放,与预算达成表口径一致
try:
cell.value = float(value)
cell.number_format = '0.00"%"'
except (ValueError, TypeError):
cell.value = ''
else:
cell.value = str(value)
cell.font = font
cell.border = border
cell.alignment = align
def generate_result_excel(self, task):
"""根据 saas_business_achievement 生成《产值达成表》结果 Excel 并上传,返回 URL。
结构对齐《产值达成表》模板(A~O 列):标题(行1,合并居中) / 表头(行2,B+C合并) /
各业务类型明细(行3+,A 列按业务类型纵向合并、B(大区经理)/C(区域运营) 列相同相邻值纵向合并) /
每业务类型小计(A:B合并) / 全部业务合计(A:B合并,C 补边框) /
模板末两行(二手车、总合计:A~L 合并加边框,M 标签,N/O 留空加边框)。
G/I/L 由指标系统接口填充;依赖它们的 J/M/N/O 达成率列在接口值非空时自动计算,
接口未匹配到数据(落 NULL)时仍留空。
"""
task_id = task.id
stat_month = task.month or ''
today_str = datetime.now().strftime('%Y%m%d')
type_name = task.data_table_type_name or task.data_table_type or 'result'
# 统计周期起止(页面参数「所属周期」的起止时间)
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
# 统计周期最后一天(截止日期),用所属周期的结束时间替换
end_date_str = period_end.strftime('%Y-%m-%d') if period_end else ''
# 时间进度 = 所属周期天数 / 统计月总天数 × 100%,四舍五入保留 2 位小数
time_progress_pct = None
if stat_month:
try:
y, m = (int(x) for x in stat_month.split('-'))
days_in_month = calendar.monthrange(y, m)[1]
if period_start and period_end and days_in_month:
days_in_period = (period_end - period_start).days + 1
time_progress_pct = round(days_in_period / days_in_month * 100, 2)
except (ValueError, TypeError):
time_progress_pct = None
# 业务类型排序:2.1+2.3 在前,1.1 在后
biz_order = ['2.1+2.3', '1.1']
rows = (SaasBusinessAchievement.query
.filter_by(task_id=task_id)
.order_by(SaasBusinessAchievement.business_type,
SaasBusinessAchievement.manager,
SaasBusinessAchievement.region_operator)
.all())
from collections import OrderedDict
groups = OrderedDict()
for r in rows:
groups.setdefault(r.business_type, []).append(r)
rows.sort(key=lambda r: (biz_order.index(r.business_type) if r.business_type in biz_order else 9,
r.manager or '', r.region_operator or ''))
# ---------- 构建工作簿 ----------
wb = openpyxl.Workbook()
ws = wb.active
ws.title = '业务达成总览'
header_font = Font(name='微软雅黑', size=11, bold=True, color='FFFFFF')
header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
title_font = Font(name='微软雅黑', size=12, bold=True)
cell_font = Font(name='微软雅黑', size=10)
center = Alignment(horizontal='center', vertical='center', wrap_text=True)
right = Alignment(horizontal='right', vertical='center')
thin = Border(left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin'))
# 行1:标题(合并 A1:M1 并居中显示)
title_cell = ws.cell(
row=1, column=1,
value=f'{stat_month}月SAAS+业务各区域预算达成率-运营(截止"{end_date_str}")')
title_cell.font = title_font
title_cell.alignment = center
ws.merge_cells('A1:M1')
# 行1:时间进度(N 列标签,O 列填实际计算结果)
n_cell = ws.cell(row=1, column=14, value='时间进度')
n_cell.font = title_font
n_cell.alignment = center
o_cell = ws.cell(row=1, column=15)
if time_progress_pct is not None:
o_cell.value = time_progress_pct
o_cell.number_format = '0.00"%"'
else:
o_cell.value = '(统计周期天数/统计月份总天数)×100%'
o_cell.font = title_font
o_cell.alignment = center
# 行2:表头(B=大区经理、C=区域运营,分列显示,不合并)
for c, (header, _attr, _kind) in enumerate(self.RESULT_COLUMNS, 1):
cell = ws.cell(row=2, column=c, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center
cell.border = thin
# 行3 起:明细 + 各业务类型小计
cur = 3
all_rows = []
for biz in biz_order:
grp = groups.get(biz) or []
if not grp:
continue
biz_start = cur
region_seq = [] # 本业务类型每行 C 列(区域运营) 值,供纵向相同合并
manager_seq = [] # 本业务类型每行 B 列(大区经理) 值,供纵向相同合并
for r in grp:
for c, (_header, attr, kind) in enumerate(self.RESULT_COLUMNS, 1):
# 数据行:B=大区经理、C=区域运营,各自为独立单元格(不横向合并)
self._write_cell(ws, cur, c, getattr(r, attr), kind, cell_font, thin,
right if kind in ('int', 'amount', 'rate') else center)
manager_seq.append(getattr(r, 'manager') or '')
region_seq.append(getattr(r, 'region_operator') or '')
cur += 1
biz_end = cur - 1
# 业务类型 A 列纵向合并(2.1+2.3 / 1.1 各合并为一格,对齐原产值达成表)
if biz_end > biz_start:
ws.merge_cells(start_row=biz_start, start_column=1, end_row=biz_end, end_column=1)
# B 列(大区经理)、C 列(区域运营):相同相邻值纵向合并(与原始产值达成表口径一致)
self._merge_same_vertical(ws, biz_start, biz_end, 2, manager_seq, thin)
self._merge_same_vertical(ws, biz_start, biz_end, 3, region_seq, thin)
# 业务类型小计(标签占 A:B 合并,B/C 均补边框)
sub = self._aggregate(grp)
a_cell = ws.cell(row=cur, column=1, value=f'{biz}小计')
a_cell.font = cell_font
a_cell.alignment = center
a_cell.border = thin
ws.cell(row=cur, column=2).border = thin # B 合并区补边框
ws.cell(row=cur, column=3).border = thin # C 单列补边框
for c, (_header, attr, kind) in enumerate(self.RESULT_COLUMNS, 1):
if c in (1, 2, 3): # A=标签(已写),B 合并区,C 已补边框
continue
self._write_cell(ws, cur, c, sub.get(attr), kind, cell_font, thin,
right if kind in ('int', 'amount', 'rate') else center)
ws.merge_cells(start_row=cur, start_column=1, end_row=cur, end_column=2)
cur += 1
all_rows.extend(grp)
# 全部业务合计(标签占 A:B 合并,B/C 均补边框)
gt = self._aggregate(all_rows)
a_cell = ws.cell(row=cur, column=1, value='合计')
a_cell.font = cell_font
a_cell.alignment = center
a_cell.border = thin
ws.cell(row=cur, column=2).border = thin
ws.cell(row=cur, column=3).border = thin
for c, (_header, attr, kind) in enumerate(self.RESULT_COLUMNS, 1):
if c in (1, 2, 3):
continue
self._write_cell(ws, cur, c, gt.get(attr), kind, cell_font, thin,
right if kind in ('int', 'amount', 'rate') else center)
ws.merge_cells(start_row=cur, start_column=1, end_row=cur, end_column=2)
cur += 1
# 模板末两行:二手车、总合计(A~L 合并+边框,M 标签,N/O 留空但加边框)
uc_row = cur
tc_row = cur + 1
for _row, _label in ((uc_row, '二手车'), (tc_row, '总合计')):
# 前面列 A~L 合并并加边框
for c in range(1, 13):
ws.cell(row=_row, column=c).border = thin
ws.merge_cells(start_row=_row, start_column=1, end_row=_row, end_column=12)
# M 列标签
m = ws.cell(row=_row, column=13, value=_label)
m.font = cell_font
m.alignment = center
m.border = thin
# N、O 列留空但加边框
ws.cell(row=_row, column=14).border = thin
ws.cell(row=_row, column=15).border = thin
# 列宽
widths = {
'业务类型': 12, '区域运营': 12, '线上运营': 14,
'运营门店(家)': 12, '直营门店(家)': 12, '当日新增GMV': 14,
'存量门店预算': 14, '存量门店实际达成': 14, '存量目标达成率(%)': 14,
'新店预算': 14, '新店实际达成': 14, '新店目标达成率(%)': 14,
'实际达成GMV合计': 14, '总预算达成率(%)': 14,
}
for c, (header, _a, _k) in enumerate(self.RESULT_COLUMNS, 1):
ws.column_dimensions[openpyxl.utils.get_column_letter(c)].width = widths.get(header, 12)
ws.freeze_panes = 'A3'
ws.row_dimensions[1].height = 24
ws.row_dimensions[2].height = 30
# ---------- 保存 + 上传 ----------
tmp_dir = tempfile.mkdtemp(prefix=f'output_value_result_{task_id}_')
try:
excel_path = os.path.join(tmp_dir, f'{type_name}_{today_str}.xlsx')
wb.save(excel_path)
object_key = (f"data-process/{today_str}"
f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key)
logger.info(f"[产值达成] 结果表已生成并上传: {file_url}({len(rows)} 行明细)")
return file_url
finally:
cleanup_tmp_dir(tmp_dir)
No preview for this file type
...@@ -61,6 +61,12 @@ REQUIRED_FORM_TYPES = ['市场费总表', '人力成本统计表', '外施施工 ...@@ -61,6 +61,12 @@ REQUIRED_FORM_TYPES = ['市场费总表', '人力成本统计表', '外施施工
# 该清洗负责建立 biz_budget_achieve 基础行与 GMV,供本脚本成本计算消费。 # 该清洗负责建立 biz_budget_achieve 基础行与 GMV,供本脚本成本计算消费。
CLEAN_DATA_TABLE_TYPE = 'budget_achievement' CLEAN_DATA_TABLE_TYPE = 'budget_achievement'
# 当前处理引擎支持的数据表类型白名单:
# 仅这些类型的 PROCESSING 任务会被调度器自动处理;
# 其余类型(如店效人效及盈利测算、产值达成表等新接入的报表)在单据层创建后
# 保持 PROCESSING 状态,等待对应处理引擎接入后再启用,避免被误判为处理失败。
SUPPORTED_PROCESS_TYPES = {CLEAN_DATA_TABLE_TYPE}
# 市场费 Title 与业务类型的映射关系 # 市场费 Title 与业务类型的映射关系
TITLE_TO_BIZ = { TITLE_TO_BIZ = {
"Title2": BIZ_TYPE_1_1, "Title2": BIZ_TYPE_1_1,
...@@ -204,12 +210,11 @@ def decrypt_excel_if_needed(file_path): ...@@ -204,12 +210,11 @@ def decrypt_excel_if_needed(file_path):
office_file = msoffcrypto.OfficeFile(f) office_file = msoffcrypto.OfficeFile(f)
if office_file.is_encrypted(): if office_file.is_encrypted():
office_file.load_key(password=password) office_file.load_key(password=password)
decrypted = office_file.decrypt()
# 写入临时文件 # 写入临时文件(新版 API: decrypt(outfile=文件对象))
tmp_fd, tmp_path = tempfile.mkstemp(suffix='.xlsx', prefix='decrypted_') tmp_fd, tmp_path = tempfile.mkstemp(suffix='.xlsx', prefix='decrypted_')
with os.fdopen(tmp_fd, 'wb') as tmp_f: with os.fdopen(tmp_fd, 'wb') as tmp_f:
tmp_f.write(decrypted) office_file.decrypt(outfile=tmp_f)
logger.info(f"[解密] 成功解密文件,密码: {password}") logger.info(f"[解密] 成功解密文件,密码: {password}")
return tmp_path, True return tmp_path, True
...@@ -1309,6 +1314,8 @@ class DataProcessor: ...@@ -1309,6 +1314,8 @@ class DataProcessor:
def scan_processing_tasks(self): def scan_processing_tasks(self):
""" """
查询 data_process_task 表中 status='PROCESSING' 且 is_deleted=0 的任务列表。 查询 data_process_task 表中 status='PROCESSING' 且 is_deleted=0 的任务列表。
仅返回当前引擎支持的数据表类型(SUPPORTED_PROCESS_TYPES);
其余类型(新接入报表等)暂不自动处理,保持 PROCESSING 待对应引擎接入。
返回:任务列表(按创建时间升序) 返回:任务列表(按创建时间升序)
""" """
logger.info("[扫描] 开始扫描待处理任务...") logger.info("[扫描] 开始扫描待处理任务...")
...@@ -1316,8 +1323,13 @@ class DataProcessor: ...@@ -1316,8 +1323,13 @@ class DataProcessor:
DataProcessTask.status == 'PROCESSING', DataProcessTask.status == 'PROCESSING',
DataProcessTask.is_deleted == 0 DataProcessTask.is_deleted == 0
).order_by(DataProcessTask.created_at.asc()).all() ).order_by(DataProcessTask.created_at.asc()).all()
logger.info(f"[扫描] 共发现 {len(tasks)} 个待处理任务") supported = [t for t in tasks if getattr(t, 'data_table_type', None) in SUPPORTED_PROCESS_TYPES]
return tasks skipped = [t for t in tasks if getattr(t, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES]
if skipped:
logger.info(f"[扫描] 跳过 {len(skipped)} 个暂不支持自动处理的类型任务: "
f"{sorted({getattr(t, 'data_table_type_name', None) or getattr(t, 'data_table_type', '') for t in skipped})}")
logger.info(f"[扫描] 共发现 {len(tasks)} 个待处理任务,本次处理 {len(supported)} 个")
return supported
def _run_clean_pipeline(self, task): def _run_clean_pipeline(self, task):
""" """
...@@ -1412,6 +1424,42 @@ class DataProcessor: ...@@ -1412,6 +1424,42 @@ class DataProcessor:
if not task: if not task:
raise Exception(f"任务不存在: {task_id}") raise Exception(f"任务不存在: {task_id}")
# 按 data_table_type 路由到对应处理器,避免非预算任务误跑预算达成流水线
if getattr(task, 'data_table_type', None) == 'output_value':
from output_value_processor import OutputValueProcessor
logger.info(f"[处理任务] 路由 output_value 任务 {task_id} 至 OutputValueProcessor")
OutputValueProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == 'store_effect_earnings':
from store_effect_summary_processor import StoreEffectSummaryProcessor
logger.info(f"[处理任务] 路由 store_effect_earnings 任务 {task_id} 至 StoreEffectSummaryProcessor")
StoreEffectSummaryProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == 'avita_special':
from avita_special_processor import AvitaSpecialProcessor
logger.info(f"[处理任务] 路由 avita_special 任务 {task_id} 至 AvitaSpecialProcessor")
AvitaSpecialProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == 'voyah_special':
from voyah_processor import VoyahProcessor
logger.info(f"[处理任务] 路由 voyah_special 任务 {task_id} 至 VoyahProcessor")
VoyahProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == 'leapmotor_special':
from leapmotor_processor import LeapmotorProcessor
logger.info(f"[处理任务] 路由 leapmotor_special 任务 {task_id} 至 LeapmotorProcessor")
LeapmotorProcessor(app=self.app).process(task)
return
# 类型白名单保护:当前引擎仅支持 SUPPORTED_PROCESS_TYPES
if getattr(task, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES:
raise Exception(
f"数据表类型「{task.data_table_type_name or task.data_table_type}」的处理引擎尚未接入,暂不支持自动处理")
logger.info(f"[处理任务] 任务: {task.month} ({task.data_table_type_name})") logger.info(f"[处理任务] 任务: {task.month} ({task.data_table_type_name})")
# ========== 步骤 a: 将关联文件的 clean_status 从 1 更新为 2(清洗中) ========== # ========== 步骤 a: 将关联文件的 clean_status 从 1 更新为 2(清洗中) ==========
......
This diff could not be displayed because it is too large.
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
作者:数据处理引擎 作者:数据处理引擎
""" """
import os
import threading import threading
import logging import logging
import sys import sys
...@@ -56,6 +57,56 @@ class TaskScheduler: ...@@ -56,6 +57,56 @@ class TaskScheduler:
self._is_processing = False self._is_processing = False
self._last_run_time = None self._last_run_time = None
self._last_run_result = None self._last_run_result = None
# 跨进程互斥: 文件锁 (Windows 用 msvcrt, Linux 用 fcntl)
self._lock_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.scheduler.lock')
self._lock_file = None
def _acquire_file_lock(self):
"""
尝试获取跨进程文件锁。
返回 True = 获取成功 (本进程可以启动调度器)
返回 False = 另一个进程已持有锁
"""
try:
self._lock_file = open(self._lock_path, 'w')
if sys.platform.startswith('win'):
import msvcrt
msvcrt.locking(self._lock_file.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(self._lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
self._lock_file.write(str(os.getpid()))
self._lock_file.flush()
return True
except (IOError, OSError) as e:
logger.warning(f"[调度器] 跨进程锁获取失败 (另一实例已在运行): {e}")
if self._lock_file:
self._lock_file.close()
self._lock_file = None
return False
def _release_file_lock(self):
"""释放跨进程文件锁。"""
if self._lock_file:
try:
import sys as _sys
if _sys.platform.startswith('win'):
import msvcrt
msvcrt.locking(self._lock_file.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(self._lock_file.fileno(), fcntl.LOCK_UN)
except Exception:
pass
try:
self._lock_file.close()
except Exception:
pass
self._lock_file = None
try:
os.remove(self._lock_path)
except Exception:
pass
def start(self): def start(self):
""" """
...@@ -70,6 +121,12 @@ class TaskScheduler: ...@@ -70,6 +121,12 @@ class TaskScheduler:
logger.info("[调度器] 定时任务未启用 (SCHEDULER_ENABLED=false),跳过启动") logger.info("[调度器] 定时任务未启用 (SCHEDULER_ENABLED=false),跳过启动")
return return
# ===== 跨进程互斥: 文件锁 =====
# 多人同时启动 Flask 时, 只有第一个能拿到文件锁, 其余直接跳过
if not self._acquire_file_lock():
logger.warning("[调度器] ⚠️ 另一个调度器实例已在运行 (PID 见 .scheduler.lock),本实例跳过启动")
return
interval = Config.SCHEDULER_INTERVAL_SECONDS interval = Config.SCHEDULER_INTERVAL_SECONDS
try: try:
...@@ -113,6 +170,9 @@ class TaskScheduler: ...@@ -113,6 +170,9 @@ class TaskScheduler:
except Exception as e: except Exception as e:
logger.error(f"[调度器] 停止 APScheduler 时出错: {str(e)}") logger.error(f"[调度器] 停止 APScheduler 时出错: {str(e)}")
# ===== 释放跨进程文件锁 =====
self._release_file_lock()
logger.info("[调度器] 调度器已完全停止") logger.info("[调度器] 调度器已完全停止")
def get_status(self): def get_status(self):
...@@ -174,3 +234,357 @@ class TaskScheduler: ...@@ -174,3 +234,357 @@ class TaskScheduler:
finally: finally:
self._is_processing = False self._is_processing = False
self._lock.release() self._lock.release()
# ============================================================
# 红黄门店盈利测算 - 4 张输出表独立调度器
# ============================================================
class NewReportScheduler:
"""
红黄门店盈利测算独立调度器基类(模板方法)。
4 个调度器统一扫描 store_effect_earnings 类型的 PROCESSING 任务,
但根据 OUTPUT_CATEGORY 只处理对应的输出表。
"""
# 子类必覆盖:输出类别 'warranty' / 'equity' / 'inshop' / 'park'
OUTPUT_CATEGORY = None
JOB_NAME = 'new_report_scan'
def __init__(self, app=None):
self.app = app
self._scheduler = None
self._lock = threading.Lock()
self._running = False
self._is_processing = False
self._last_run_time = None
self._last_run_result = None
def start(self):
if self._running:
logger.warning(f"[{self.JOB_NAME}] 已在运行中,忽略 start() 调用")
return
if not Config.SCHEDULER_ENABLED:
logger.info(f"[{self.JOB_NAME}] 定时任务未启用,跳过启动")
return
interval = Config.SCHEDULER_INTERVAL_SECONDS
try:
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.interval import IntervalTrigger
self._scheduler = BackgroundScheduler(daemon=True)
self._scheduler.add_job(
self._execute_scan,
trigger=IntervalTrigger(seconds=interval),
id=self.JOB_NAME,
name=self.JOB_NAME,
replace_existing=True,
)
self._scheduler.start()
self._running = True
logger.info(f"[{self.JOB_NAME}] APScheduler 已启动,执行间隔: {interval}秒, category={self.OUTPUT_CATEGORY}")
except ImportError:
logger.warning(f"[{self.JOB_NAME}] APScheduler 未安装,使用 threading 后备方案")
self._running = True
self._thread_timer(interval)
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 启动失败: {str(e)}")
raise
def stop(self):
if not self._running:
return
self._running = False
if self._scheduler:
try:
self._scheduler.shutdown(wait=False)
logger.info(f"[{self.JOB_NAME}] APScheduler 已停止")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 停止时出错: {str(e)}")
def get_status(self):
return {
'job_name': self.JOB_NAME,
'output_category': self.OUTPUT_CATEGORY,
'enabled': Config.SCHEDULER_ENABLED,
'running': self._running,
'is_processing': self._is_processing,
'last_run_time': self._last_run_time.strftime('%Y-%m-%d %H:%M:%S') if self._last_run_time else None,
'last_run_result': self._last_run_result,
}
def _thread_timer(self, interval):
if not self._running:
return
self._execute_scan()
if self._running:
timer = threading.Timer(interval, self._thread_timer, args=[interval])
timer.daemon = True
timer.start()
def _execute_scan(self):
if not self._lock.acquire(blocking=False):
logger.debug(f"[{self.JOB_NAME}] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 store_effect_earnings 待处理任务, category={self.OUTPUT_CATEGORY}")
with self.app.app_context():
# 4 个输出类别各自对应独立的 Processor 模块
from earnings_report_processor import WarrantyProcessor
from equity_processor import EquityProcessor
from light_reform_inshop_processor import LightReformInshopProcessor
from light_reform_park_processor import LightReformParkProcessor
_CATEGORY_CLS = {
'warranty': WarrantyProcessor,
'equity': EquityProcessor,
'inshop': LightReformInshopProcessor,
'park': LightReformParkProcessor,
}
cls = _CATEGORY_CLS.get(self.OUTPUT_CATEGORY)
if not cls:
raise ValueError(f"未知的 output_category: {self.OUTPUT_CATEGORY}")
processor = cls(app=self.app)
result = processor.scan_store_effect_earnings(self.OUTPUT_CATEGORY)
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 扫描完成:成功 {result.get('success', 0)} 个,失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()
class WarrantyReportScheduler(NewReportScheduler):
"""延保盈利测算独立调度器"""
OUTPUT_CATEGORY = 'warranty'
JOB_NAME = 'warranty_report_scan'
class EquityReportScheduler(NewReportScheduler):
"""权益盈利测算独立调度器"""
OUTPUT_CATEGORY = 'equity'
JOB_NAME = 'equity_report_scan'
class LightReformInshopScheduler(NewReportScheduler):
"""轻改-店中店汇总独立调度器"""
OUTPUT_CATEGORY = 'inshop'
JOB_NAME = 'light_reform_inshop_scan'
class LightReformParkScheduler(NewReportScheduler):
"""轻改-园区店汇总独立调度器"""
OUTPUT_CATEGORY = 'park'
JOB_NAME = 'light_reform_park_scan'
class OutputValueScheduler(NewReportScheduler):
"""产值达成表独立调度器(扫描 output_value 类型任务)"""
OUTPUT_CATEGORY = 'output_value'
JOB_NAME = 'output_value_scan'
def _execute_scan(self):
if not self._lock.acquire(blocking=False):
logger.debug(f"[{self.JOB_NAME}] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 output_value 待处理任务")
with self.app.app_context():
from output_value_processor import OutputValueProcessor
processor = OutputValueProcessor(app=self.app)
result = processor.scan_output_value()
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 扫描完成:成功 {result.get('success', 0)} 个,"
f"失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()
class CommonEquityScheduler(NewReportScheduler):
"""通用+权益独立调度器(扫描 common_equity 类型任务)"""
OUTPUT_CATEGORY = 'common_equity'
JOB_NAME = 'common_equity_scan'
def _execute_scan(self):
if not self._lock.acquire(blocking=False):
logger.debug(f"[{self.JOB_NAME}] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 common_equity 待处理任务")
with self.app.app_context():
from common_equity_processor import CommonEquityProcessor
processor = CommonEquityProcessor(app=self.app)
result = processor.scan_common_equity()
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 扫描完成:成功 {result.get('success', 0)} 个,"
f"失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()
class StoreEffectSummaryScheduler(NewReportScheduler):
"""门店店效人效汇总表独立调度器(扫描 store_effect_earnings 类型任务,整体合计一行,第5个sheet)"""
OUTPUT_CATEGORY = 'store_effect_summary'
JOB_NAME = 'store_effect_summary_scan'
def _execute_scan(self):
if not self._lock.acquire(blocking=False):
logger.debug(f"[{self.JOB_NAME}] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 store_effect_earnings 待处理任务, "
f"category={self.OUTPUT_CATEGORY}")
with self.app.app_context():
from store_effect_summary_processor import StoreEffectSummaryProcessor
processor = StoreEffectSummaryProcessor(app=self.app)
result = processor.scan_store_effect_summary(self.OUTPUT_CATEGORY)
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 扫描完成:成功 {result.get('success', 0)} 个,"
f"失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()
class AvitaSpecialScheduler(NewReportScheduler):
"""阿维塔专项独立调度器(扫描 avita_special 类型任务,交给 AvitaSpecialProcessor 处理)"""
OUTPUT_CATEGORY = 'avita_special'
JOB_NAME = 'avita_special_scan'
def _execute_scan(self):
if not self._lock.acquire(blocking=False):
logger.debug(f"[{self.JOB_NAME}] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 avita_special 待处理任务")
with self.app.app_context():
from avita_special_processor import AvitaSpecialProcessor
processor = AvitaSpecialProcessor(app=self.app)
result = processor.scan_avita_special()
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 扫描完成:成功 {result.get('success', 0)} 个,"
f"失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()
class VoyahScheduler(NewReportScheduler):
"""岚图专项报表独立调度器(扫描 voyah_special 类型任务)"""
OUTPUT_CATEGORY = 'voyah_special'
JOB_NAME = 'voyah_special_scan'
def _execute_scan(self):
if not self._lock.acquire(blocking=False):
logger.debug(f"[{self.JOB_NAME}] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 voyah_special 待处理任务")
with self.app.app_context():
from voyah_processor import VoyahProcessor
processor = VoyahProcessor(app=self.app)
result = processor.scan_voyah()
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 扫描完成:成功 {result.get('success', 0)} 个,"
f"失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()
class LeapmotorScheduler(NewReportScheduler):
"""零跑专项报表独立调度器(扫描 leapmotor_special 类型任务)"""
OUTPUT_CATEGORY = 'leapmotor_special'
JOB_NAME = 'leapmotor_special_scan'
def _execute_scan(self):
if not self._lock.acquire(blocking=False):
logger.debug(f"[{self.JOB_NAME}] 上一轮处理尚未完成,跳过本轮扫描")
return
self._is_processing = True
self._last_run_time = datetime.now()
try:
logger.info(f"[{self.JOB_NAME}] 开始扫描 leapmotor_special 待处理任务")
with self.app.app_context():
from leapmotor_processor import LeapmotorProcessor
processor = LeapmotorProcessor(app=self.app)
result = processor.scan_leapmotor()
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 扫描完成:成功 {result.get('success', 0)} 个,"
f"失败 {result.get('failed', 0)} 个")
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 扫描执行异常: {str(e)}")
self._last_run_result = {'error': str(e)}
finally:
self._is_processing = False
self._lock.release()
\ No newline at end of file \ No newline at end of file
...@@ -390,6 +390,17 @@ tbody tr:hover { background: #f8fafd; } ...@@ -390,6 +390,17 @@ tbody tr:hover { background: #f8fafd; }
.modal-file .tip { flex: 1 1 100%; padding-top: 0; } .modal-file .tip { flex: 1 1 100%; padding-top: 0; }
} }
/* 所属周期选择器 */
.period-picker { display: flex; align-items: center; gap: 8px; }
.period-picker input[type=date] {
height: 32px; padding: 0 8px;
border: 1px solid #d0d3da; border-radius: 4px; outline: none;
font-size: 13px; background: #fff;
}
.period-picker input[type=date]:focus { border-color: #185fa5; }
.period-sep { color: #999; font-size: 13px; }
.period-hint { margin-top: 4px; font-size: 12px; color: #999; }
/* 上传 Loading 遮罩 */ /* 上传 Loading 遮罩 */
.loading-mask { .loading-mask {
position: fixed; inset: 0; position: fixed; inset: 0;
...@@ -413,3 +424,29 @@ tbody tr:hover { background: #f8fafd; } ...@@ -413,3 +424,29 @@ tbody tr:hover { background: #f8fafd; }
animation: spin .8s linear infinite; animation: spin .8s linear infinite;
} }
@keyframes spin { to { transform: rotate(360deg); } } @keyframes spin { to { transform: rotate(360deg); } }
/* 周期粒度分段按钮(按月/按周 切换) */
.seg-group {
display: inline-flex;
border: 1px solid #dcdfe6;
border-radius: 4px;
overflow: hidden;
background: #fff;
}
.seg-group .seg-btn {
padding: 4px 12px;
font-size: 13px;
border: none;
background: #fff;
color: #606266;
cursor: pointer;
border-right: 1px solid #dcdfe6;
transition: all .15s;
white-space: nowrap;
}
.seg-group .seg-btn:last-child { border-right: none; }
.seg-group .seg-btn:hover { color: #185fa5; }
.seg-group .seg-btn.active {
background: #185fa5;
color: #fff;
}
...@@ -5,6 +5,8 @@ ...@@ -5,6 +5,8 @@
var modalMode = ''; // '' | 'create' | 'regenerate' var modalMode = ''; // '' | 'create' | 'regenerate'
var editingTaskId = null; var editingTaskId = null;
var formFiles = {}; // form_type -> { file, fileName, size, oldUrl } var formFiles = {}; // form_type -> { file, fileName, size, oldUrl }
var modalPeriodType = 'month'; // 'month' | 'week'
var modalWeekNum = null; // 1~5
// ---------- 通用 ---------- // ---------- 通用 ----------
function api(url, opts) { function api(url, opts) {
...@@ -130,10 +132,18 @@ ...@@ -130,10 +132,18 @@
var tr = document.createElement('tr'); var tr = document.createElement('tr');
var canDownload = item.status === 'COMPLETED'; var canDownload = item.status === 'COMPLETED';
var canRegen = item.status === 'COMPLETED' || item.status === 'FAILED'; var canRegen = item.status === 'COMPLETED' || item.status === 'FAILED';
// 所属周期:按周时显示 "W3 (2026-08-17~2026-08-23)",否则显示日期区间或整月
var periodText = '-';
if (item.period_type === 'week' && item.week_num && item.period_start && item.period_end) {
periodText = 'W' + item.week_num + ' (' + item.period_start + ' ~ ' + item.period_end + ')';
} else if (item.period_start && item.period_end) {
periodText = item.period_start + ' ~ ' + item.period_end;
}
tr.innerHTML = tr.innerHTML =
'<td>' + (++seq) + '</td>' + '<td>' + (++seq) + '</td>' +
'<td>' + (item.data_table_type_name || item.data_table_type) + '</td>' + '<td>' + (item.data_table_type_name || item.data_table_type) + '</td>' +
'<td>' + item.month + '</td>' + '<td>' + item.month + '</td>' +
'<td>' + periodText + '</td>' +
'<td>' + (item.creator || '-') + '</td>' + '<td>' + (item.creator || '-') + '</td>' +
'<td>' + item.created_at + '</td>' + '<td>' + item.created_at + '</td>' +
'<td>' + (item.updater || '-') + '</td>' + '<td>' + (item.updater || '-') + '</td>' +
...@@ -157,6 +167,11 @@ ...@@ -157,6 +167,11 @@
if (fMonth.value) params.set('month', fMonth.value); if (fMonth.value) params.set('month', fMonth.value);
if (fCreator.value) params.set('creator', fCreator.value.trim()); if (fCreator.value) params.set('creator', fCreator.value.trim());
if (fStatus.value) params.set('status', fStatus.value); if (fStatus.value) params.set('status', fStatus.value);
// 周期粒度筛选(取按钮组当前 active 的 data-type)
var activePeriodBtn = document.querySelector('#fPeriodTypeGroup .seg-btn.active');
if (activePeriodBtn && activePeriodBtn.dataset.type) {
params.set('periodType', activePeriodBtn.dataset.type);
}
api('/api/tasks?' + params.toString()).then(function (res) { api('/api/tasks?' + params.toString()).then(function (res) {
if (res.code !== 0) { toast(res.msg, true); return; } if (res.code !== 0) { toast(res.msg, true); return; }
state.total = res.data.total; state.total = res.data.total;
...@@ -230,21 +245,218 @@ ...@@ -230,21 +245,218 @@
function onTypeChange() { function onTypeChange() {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; }); var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
renderFileInputs(cfg ? cfg.forms : []); renderFileInputs(cfg ? cfg.forms : []);
togglePeriodTypeRow(cfg); // 按 support_week 控制粒度切换行显示
togglePeriodRow(cfg);
}
// ---------- 所属周期(日期区间)----------
var mPeriodRow = document.getElementById('mPeriodRow');
var mPeriodStart = document.getElementById('mPeriodStart');
var mPeriodEnd = document.getElementById('mPeriodEnd');
var mPeriodHint = document.getElementById('mPeriodHint');
// 计算某月最后一天
function lastDayOfMonth(monthVal) {
if (!monthVal) return null;
var parts = monthVal.split('-');
var y = parseInt(parts[0], 10), m = parseInt(parts[1], 10);
return new Date(y, m, 0).getDate();
}
// 月份值 YYYY-MM → YYYY-MM-DD(day=1)
function monthToDate(monthVal) {
if (!monthVal) return '';
return monthVal + '-01';
}
function setPeriodDefault(monthVal) {
// 已手动改过周期的不覆盖;仅在自动初始化时使用
if (!monthVal) { mPeriodStart.value = ''; mPeriodEnd.value = ''; return; }
var last = lastDayOfMonth(monthVal);
var start = monthToDate(monthVal);
var end = monthVal + '-' + String(last).padStart(2, '0');
mPeriodStart.value = start;
mPeriodEnd.value = end;
}
function togglePeriodRow(cfg) {
var need = cfg && cfg.need_period;
var isWeek = modalPeriodType === 'week';
if (isWeek || need) {
// 按周:无论 need_period 是什么,都显示周期行且 disabled
// 按月 + need_period=True:显示,可编辑(现有行为)
mPeriodRow.style.display = '';
if (isWeek) {
mPeriodStart.disabled = true;
mPeriodEnd.disabled = true;
// 按周时自动填入日期(如果已有 weekNum)
if (modalWeekNum) applyWeekPeriod(modalWeekNum);
} else {
mPeriodStart.disabled = false;
mPeriodEnd.disabled = false;
if (!mPeriodStart.value || !mPeriodEnd.value) setPeriodDefault(mMonth.value);
}
} else {
// need_period=False 且按月:隐藏
mPeriodRow.style.display = 'none';
}
}
// 前端周计算函数(与后端 compute_week_period 规则一致)
// 规则:该月第一个周一为 W1 起始日,每周周一至周日
function computeWeekOptions(monthVal) {
if (!monthVal) return [];
var parts = monthVal.split('-');
var y = parseInt(parts[0], 10), m = parseInt(parts[1], 10);
// 该月第一天
var firstDay = new Date(y, m - 1, 1); // JS Date: month 0-indexed
// firstDay.getDay(): 周日=0, 周一=1, ..., 周六=6
// 转换为:周一=0, 周日=6(与 Python weekday() 对齐)
var jsDay = firstDay.getDay(); // 0=周日 .. 6=周六
var pyWeekday = (jsDay === 0 ? 6 : jsDay - 1); // 周一=0, 周日=6
// 该月第一个周一 = 若月初就是周一则当天,否则往后推到下一个周一
// 例:2026-08-01 周六 pyWeekday=5 → offset=(7-5)%7=2 → 8/1+2天=8/3(正确)
var offset = (7 - pyWeekday) % 7;
var firstMonday = new Date(y, m - 1, 1 + offset);
// 生成 W1~W5
var options = [];
for (var w = 1; w <= 5; w++) {
var start = new Date(firstMonday);
start.setDate(firstMonday.getDate() + (w - 1) * 7);
var end = new Date(start);
end.setDate(start.getDate() + 6);
// 如果周的起始日已经不在该月范围内(极端情况),跳过
if (start.getMonth() + 1 !== m && w > 1) break;
var startStr = fmtDate(start);
var endStr = fmtDate(end);
options.push({
week: w,
label: 'W' + w + ' (' + (start.getMonth() + 1) + '/' + start.getDate() + '-' + (end.getMonth() + 1) + '/' + end.getDate() + ')',
start: startStr,
end: endStr
});
// 如果 start 已经跨到下个月,停止(不生成超出月份的周)
if (start.getMonth() + 1 !== m) break;
}
return options;
}
// Date 对象 → 'YYYY-MM-DD'
function fmtDate(d) {
var y = d.getFullYear();
var mo = String(d.getMonth() + 1).padStart(2, '0');
var da = String(d.getDate()).padStart(2, '0');
return y + '-' + mo + '-' + da;
}
// 渲染周选择下拉框
function renderWeekSelect(monthVal) {
var sel = document.getElementById('mWeekSelect');
sel.innerHTML = '';
var opts = computeWeekOptions(monthVal);
if (!opts.length) { sel.style.display = 'none'; return; }
opts.forEach(function (o) {
var opt = document.createElement('option');
opt.value = o.week;
opt.textContent = o.label;
sel.appendChild(opt);
});
sel.style.display = '';
// 选中已有的 weekNum(重新生成回填时),否则默认 W1
if (modalWeekNum) {
sel.value = String(modalWeekNum);
applyWeekPeriod(modalWeekNum);
} else {
modalWeekNum = opts[0].week;
applyWeekPeriod(opts[0].week);
}
}
// 根据周序号自动填入 period start/end
function applyWeekPeriod(weekNum) {
var opts = computeWeekOptions(mMonth.value);
var found = null;
for (var i = 0; i < opts.length; i++) {
if (opts[i].week === weekNum) { found = opts[i]; break; }
}
if (!found) return;
mPeriodStart.value = found.start;
mPeriodEnd.value = found.end;
modalWeekNum = weekNum;
}
// 周期粒度行:仅 support_week=true 的类型(通用+权益)才显示
// 其他类型(整月、月份+自定义日期)统一隐藏,用户不可切换按月/按周
function togglePeriodTypeRow(cfg) {
var row = document.getElementById('mPeriodTypeRow');
var show = cfg && cfg.support_week;
row.style.display = show ? '' : 'none';
// 防御:若当前 period_type 为 week 但新类型不支持,强制重置为 month
if (!show && modalPeriodType === 'week') {
modalPeriodType = 'month';
modalWeekNum = null;
document.getElementById('mWeekSelect').style.display = 'none';
}
}
// 周期提示:结束日期 ≤ 月份最后一天;开始默认1号
function updatePeriodHint() {
if (!mPeriodRow || mPeriodRow.style.display === 'none') return;
if (!mMonth.value) { if (mPeriodHint) mPeriodHint.textContent = ''; return; }
var last = lastDayOfMonth(mMonth.value);
var maxEnd = mMonth.value + '-' + String(last).padStart(2, '0');
mPeriodStart.max = maxEnd;
mPeriodEnd.max = maxEnd;
if (mPeriodStart.value && !mPeriodStart.value.startsWith(mMonth.value + '-')) {
// 开始日期强制该月1号
mPeriodStart.value = monthToDate(mMonth.value);
}
if (mPeriodHint) {
mPeriodHint.textContent = '默认当月 1 号至月末,可调整结束日期(≤' + maxEnd + ')';
}
} }
function openModal(mode, task) { function openModal(mode, task) {
modalMode = mode; modalMode = mode;
editingTaskId = task ? task.id : null; editingTaskId = task ? task.id : null;
// 初始化周期粒度状态(regenerate 时从任务回填,否则默认 month)
modalPeriodType = (task && task.period_type) ? task.period_type : 'month';
modalWeekNum = (task && task.week_num) ? task.week_num : null;
document.getElementById('modalTitle').textContent = mode === 'regenerate' ? '重新生成' : '新增数据'; document.getElementById('modalTitle').textContent = mode === 'regenerate' ? '重新生成' : '新增数据';
fillModalTypes(); fillModalTypes();
mType.value = task ? task.data_table_type : ''; mType.value = task ? task.data_table_type : '';
mMonth.value = task ? task.month : ''; mMonth.value = task ? task.month : '';
// 周期默认值(编辑态回填任务周期,否则按月份初始化)
if (task && task.period_start && task.period_end) {
mPeriodStart.value = task.period_start;
mPeriodEnd.value = task.period_end;
} else {
setPeriodDefault(mMonth.value);
}
mMonth.dispatchEvent(new Event('change')); // 更新 placeholder 显示 mMonth.dispatchEvent(new Event('change')); // 更新 placeholder 显示
var locked = mode === 'regenerate'; var locked = mode === 'regenerate';
mType.disabled = locked; mType.disabled = locked;
mMonth.disabled = locked; mMonth.disabled = locked;
var cfg = typeConfigs.find(function (t) { return t.code === (task ? task.data_table_type : '') }); // 周期框 disabled 由 togglePeriodRow 统一控制(按周时 disabled,按月时 need_period=True 可编辑)
var cfg = typeConfigs.find(function (t) { return t.code === (task ? task.data_table_type : ''); });
// 防御:若原 task 的 period_type 为 week 但当前类型不支持,强制重置
if (cfg && !cfg.support_week && modalPeriodType === 'week') {
modalPeriodType = 'month';
modalWeekNum = null;
}
renderFileInputs(cfg ? cfg.forms : []); renderFileInputs(cfg ? cfg.forms : []);
togglePeriodTypeRow(cfg); // 按 support_week 控制粒度切换行显示
togglePeriodRow(cfg); // 根据粒度 + need_period 控制周期行显示/disabled
updatePeriodHint();
// 初始化粒度按钮组 active 状态
var btns = document.querySelectorAll('#mPeriodTypeGroup .seg-btn');
btns.forEach(function (b) {
if (b.dataset.type === modalPeriodType) b.classList.add('active');
else b.classList.remove('active');
});
// 按周时渲染周选择下拉
if (modalPeriodType === 'week') {
renderWeekSelect(mMonth.value);
} else {
document.getElementById('mWeekSelect').style.display = 'none';
}
// 编辑态:用原文件回填文件名 // 编辑态:用原文件回填文件名
if (locked && task && task.files) { if (locked && task && task.files) {
task.files.forEach(function (f) { task.files.forEach(function (f) {
...@@ -266,6 +478,7 @@ ...@@ -266,6 +478,7 @@
function closeModal() { function closeModal() {
modal.style.display = 'none'; modal.style.display = 'none';
modalMode = ''; editingTaskId = null; formFiles = {}; modalMode = ''; editingTaskId = null; formFiles = {};
modalPeriodType = 'month'; modalWeekNum = null;
// 防御性:清理可能残留的 loading 遮罩与「确定」按钮禁用态 // 防御性:清理可能残留的 loading 遮罩与「确定」按钮禁用态
var lm = document.getElementById('loadingMask'); var lm = document.getElementById('loadingMask');
if (lm) lm.style.display = 'none'; if (lm) lm.style.display = 'none';
...@@ -309,6 +522,18 @@ ...@@ -309,6 +522,18 @@
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; }); var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
if (!cfg) { toast('请选择数据表类型', true); return; } if (!cfg) { toast('请选择数据表类型', true); return; }
if (!mMonth.value) { toast('请选择所属月份', true); return; } if (!mMonth.value) { toast('请选择所属月份', true); return; }
// 周期校验:
// 按周 → 必须有 week_num(后端会根据 month+week_num 重算日期,这里只是前端兜底检查)
// 按月 + need_period=True → 必须选 period_start/end
// 按月 + need_period=False → 不需要周期(如预算达成数据)
var isWeek = modalPeriodType === 'week';
if (isWeek) {
if (!modalWeekNum) { toast('请选择第几周', true); return; }
} else if (cfg.need_period) {
var ps = mPeriodStart.value || '', pe = mPeriodEnd.value || '';
if (!ps || !pe) { toast('请选择所属周期(开始日期~结束日期)', true); return; }
if (pe < ps) { toast('所属周期结束日期不能早于开始日期', true); return; }
}
// 必填:新增模式所有附件必填;重新生成未上传视为保留原文件(通过 formFiles.oldUrl 标记) // 必填:新增模式所有附件必填;重新生成未上传视为保留原文件(通过 formFiles.oldUrl 标记)
var missing = []; var missing = [];
var toUpload = []; // 需要直传的新文件 var toUpload = []; // 需要直传的新文件
...@@ -349,7 +574,18 @@ ...@@ -349,7 +574,18 @@
filesPayload.push({ form_type: ft, file_name: old.fileName, file_url: old.oldUrl, file_size: old.size }); filesPayload.push({ form_type: ft, file_name: old.fileName, file_url: old.oldUrl, file_size: old.size });
} }
}); });
var payload = { data_table_type: mType.value, month: mMonth.value, files: filesPayload }; var payload = {
data_table_type: mType.value,
month: mMonth.value,
period_type: modalPeriodType,
week_num: modalWeekNum,
files: filesPayload
};
// 周期日期:按周时也填上(后端会根据 week_num 重算做双重保险)
if (isWeek || cfg.need_period) {
payload.period_start = mPeriodStart.value;
payload.period_end = mPeriodEnd.value;
}
var url = modalMode === 'regenerate' var url = modalMode === 'regenerate'
? '/api/tasks/' + editingTaskId + '/regenerate' ? '/api/tasks/' + editingTaskId + '/regenerate'
: '/api/tasks'; : '/api/tasks';
...@@ -400,6 +636,86 @@ ...@@ -400,6 +636,86 @@
}); });
mType.addEventListener('change', onTypeChange); mType.addEventListener('change', onTypeChange);
mMonth.addEventListener('change', function () {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
if (modalPeriodType === 'week') {
// 按周:月份变了重新生成周选项
modalWeekNum = null;
renderWeekSelect(mMonth.value);
} else {
// 按月:原有逻辑
setPeriodDefault(mMonth.value);
}
togglePeriodRow(cfg);
updatePeriodHint();
});
mPeriodStart.addEventListener('change', function () {
if (mMonth.value && mPeriodStart.value && !mPeriodStart.value.startsWith(mMonth.value + '-')) {
// 开始日期只能取该月1号,自动纠正
mPeriodStart.value = monthToDate(mMonth.value);
}
if (mPeriodEnd.value && mPeriodStart.value && mPeriodEnd.value < mPeriodStart.value) {
toast('结束日期不能早于开始日期', true);
}
updatePeriodHint();
});
mPeriodEnd.addEventListener('change', function () {
if (mPeriodEnd.value && mPeriodStart.value && mPeriodEnd.value < mPeriodStart.value) {
toast('结束日期不能早于开始日期', true);
mPeriodEnd.value = mPeriodStart.value;
}
updatePeriodHint();
});
// ---------- 弹窗:周期粒度切换 ----------
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (btn) {
btn.addEventListener('click', function () {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
// 防御:当前类型不支持按周时忽略点击(理论上行已隐藏,用户不可达)
if (!cfg || !cfg.support_week) return;
modalPeriodType = btn.dataset.type;
// 更新按钮组 active 状态
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (b) {
if (b === btn) b.classList.add('active');
else b.classList.remove('active');
});
// 切换粒度时重置 weekNum
modalWeekNum = null;
if (modalPeriodType === 'week') {
// 按周:渲染周下拉 + 自动计算日期
document.getElementById('mWeekSelect').style.display = '';
if (mMonth.value) renderWeekSelect(mMonth.value);
} else {
// 按月:隐藏周下拉 + 恢复默认
document.getElementById('mWeekSelect').style.display = 'none';
setPeriodDefault(mMonth.value);
}
togglePeriodRow(cfg);
updatePeriodHint();
});
});
// 弹窗:周选择下拉 change
var mWeekSelect = document.getElementById('mWeekSelect');
if (mWeekSelect) {
mWeekSelect.addEventListener('change', function () {
var w = parseInt(mWeekSelect.value, 10);
if (w >= 1) applyWeekPeriod(w);
});
}
// ---------- 列表筛选:粒度切换 ----------
var fPeriodTypeBtns = document.querySelectorAll('#fPeriodTypeGroup .seg-btn');
fPeriodTypeBtns.forEach(function (btn) {
btn.addEventListener('click', function () {
fPeriodTypeBtns.forEach(function (b) {
if (b === btn) b.classList.add('active');
else b.classList.remove('active');
});
state.page = 1;
loadList();
});
});
document.getElementById('btnCancel').onclick = closeModal; document.getElementById('btnCancel').onclick = closeModal;
document.getElementById('modalClose').onclick = closeModal; document.getElementById('modalClose').onclick = closeModal;
// 不移除:点击弹窗外区域不关闭弹窗,只能通过取消按钮或关闭按钮关闭 // 不移除:点击弹窗外区域不关闭弹窗,只能通过取消按钮或关闭按钮关闭
......
...@@ -53,6 +53,14 @@ ...@@ -53,6 +53,14 @@
</div> </div>
</div> </div>
<div class="filter-item"> <div class="filter-item">
<label>粒度</label>
<div class="seg-group" id="fPeriodTypeGroup">
<button type="button" class="seg-btn active" data-type="">全部</button>
<button type="button" class="seg-btn" data-type="month">按月</button>
<button type="button" class="seg-btn" data-type="week">按周</button>
</div>
</div>
<div class="filter-item">
<label>创建人</label> <label>创建人</label>
<input id="fCreator" maxlength="20" placeholder="请输入"> <input id="fCreator" maxlength="20" placeholder="请输入">
</div> </div>
...@@ -78,6 +86,7 @@ ...@@ -78,6 +86,7 @@
<th style="width:60px">序号</th> <th style="width:60px">序号</th>
<th>数据表类型</th> <th>数据表类型</th>
<th>所属月份</th> <th>所属月份</th>
<th>所属周期</th>
<th>创建人</th> <th>创建人</th>
<th>创建时间</th> <th>创建时间</th>
<th>更新人</th> <th>更新人</th>
...@@ -146,6 +155,29 @@ ...@@ -146,6 +155,29 @@
</div> </div>
</div> </div>
</div> </div>
<div class="modal-row" id="mPeriodTypeRow" style="display:none">
<label>周期粒度</label>
<div class="modal-control">
<div class="seg-group" id="mPeriodTypeGroup">
<button type="button" class="seg-btn active" data-type="month">按月</button>
<button type="button" class="seg-btn" data-type="week">按周</button>
</div>
<select id="mWeekSelect" style="display:none; margin-left:10px; min-width:140px;">
<!-- 由 JS 动态渲染 W1~W5 -->
</select>
</div>
</div>
<div class="modal-row" id="mPeriodRow" style="display:none">
<label class="required">所属周期</label>
<div class="modal-control">
<div class="period-picker">
<input type="date" id="mPeriodStart">
<span class="period-sep">至</span>
<input type="date" id="mPeriodEnd">
</div>
<div class="period-hint" id="mPeriodHint"></div>
</div>
</div>
<div id="mFiles"></div> <div id="mFiles"></div>
</div> </div>
</div> </div>
......
# -*- coding: utf-8 -*-
"""
门店店效人效汇总表 独立处理器(整体合计,单任务一行;合并结果表第5个sheet)
============================================================================
数据来源(与红黄门店盈利测算三表同源):
SAAS门店预算分解表(延保 2.3 / 权益 2.1 / 轻改 1.1)
+ 关系表 + 主机厂数据表(鸿蒙/广联) + 预算达成数据(商务)
+ 园区店交车触客表 + 商务政策表(园区店) + 人力成本表
+ 指标系统 API(biz 1/3/2)+ 业务系统 SQL(嘀加 dj_smartcarlife)
口径(用户确认 2026-09-07):
- 整体合计,不按维度分组(无门店明细)。
- 从源数据重新计算(不读 4 张报告表)。
- 先出骨架,数字待校准:业务系统 SQL 字段在 Config.BIZ_SQL_ENABLED=false 时
恒为 0(fetch_biz_sql_aggregated / fetch_park_daily_report 返回 {})。
指标取值:
- 延保/权益 产值=A036、成交=A075、触客=A084、交车=主机厂数据表;
- 轻改 产值=业务SQL store_output_value(0 待校准)、成交=A075、交车=日报 delivery_cnt;
- 成本/毛利:延保/权益 用 市场费+营销费+服务费(营销费占比来自商务预算 labor_ratio);
轻改 用 人力+施工+市场+服务+装修分摊+房租水电+门店耗材(施工/市场待校准为 0)。
- 人效:轻改 人力成本=直营(headcount*3500+产值*4%) / 人员数=人力成本表 headcount;
延保/权益 暂无人力口径 → 0(待校准)。
"""
import calendar
import logging
import os
import tempfile
from collections import OrderedDict
from datetime import datetime, date, timedelta
from decimal import Decimal, ROUND_HALF_UP
import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from oss_utils import upload_file
from config import Config
from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_WARRANTY, BIZ_TYPE_EQUITY, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
get_subtask_status,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files,
parse_saas_base, parse_saas_base_sheet2, parse_saas_base_sheet2_exclude,
parse_region_map, parse_delivery_table,
parse_budget_achieve_excel, extract_budget_ratio, parse_labor_cost,
fetch_biz_sql_aggregated, fetch_park_daily_report,
fetch_indicator_data, fuzzy_match_store, exact_match_store, safe_div_pct_decimal, prorate_by_period,
)
from models import ReportStoreEffectSummary, DataProcessTask, db
logger = logging.getLogger('StoreEffectSummaryProcessor')
SUMMARY_CATEGORY = 'store_effect_summary'
# 总看板(第5个 sheet)必须在以下前 4 张 sheet 全部 COMPLETED 后才能执行,
# 否则读到的源数据不全(前 4 张表尚未落库或仍是旧快照)。
PRECEDING_CATEGORIES = ['warranty', 'equity', 'inshop', 'park']
# 各业务类型 → (解析函数, 文件/sheet 参数, 指标 biz 键, 指标编码)
BIZ_PLAN = [
('warranty', BIZ_TYPE_WARRANTY, INDICATOR_BIZ_MAP.get('warranty'),
['A036', 'A075', 'A084', 'A066', 'A070', 'A086']),
('equity', BIZ_TYPE_EQUITY, INDICATOR_BIZ_MAP.get('equity'),
['A036', 'A075', 'A084']),
('inshop', '1.1', INDICATOR_BIZ_MAP.get('light_reform'),
['A075']),
('park', '1.1', INDICATOR_BIZ_MAP.get('light_reform'),
['A075']),
]
class StoreEffectSummaryProcessor:
"""门店店效人效汇总表独立处理器(整体合计一行)"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_store_effect_summary(self, output_category=SUMMARY_CATEGORY):
from models import DataProcessTask
logger.info(f"[店效人效汇总] 开始扫描 store_effect_earnings 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=STORE_EFFECT_EARNINGS_TYPE,
status='PROCESSING',
is_deleted=0,
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[店效人效汇总] 扫描到 {len(tasks)} 个待处理任务")
success_count = 0
fail_count = 0
for task in tasks:
try:
self.process(task)
success_count += 1
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[店效人效汇总] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception:
pass
logger.info(f"[店效人效汇总] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def _preceding_sheets_all_completed(self, task_id):
"""总看板闸门:前 4 张 sheet(warranty/equity/inshop/park)是否全部 COMPLETED。
返回 (all_completed, pending_list):
- all_completed=True → 总看板可以执行;
- all_completed=False → pending_list 列出尚未就绪的 category=status,
供日志提示。任一未 COMPLETED(PENDING/PROCESSING/None/FAILED)都视为未就绪,
总看板返回等待,自身子任务保持 PENDING,由下一轮调度重试。
"""
pending = []
for cat in PRECEDING_CATEGORIES:
st = get_subtask_status(task_id, cat)
if st != SUBTASK_COMPLETED:
pending.append(f"{cat}={st}")
return (len(pending) == 0, pending)
def process(self, task):
task_id = task.id
# 幂等:自身子任务已 COMPLETED 则跳过(防止调度器重复扫描重算)
if is_subtask_completed(task_id, SUMMARY_CATEGORY):
logger.info(f"[店效人效汇总] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
# 闸门:总看板必须在前 4 张 sheet(延保/权益/店中店/园区店)全部 COMPLETED 后执行,
# 否则读到的是未落库/旧的前置数据(如 2.3交车数会偏旧)。
# 前置未就绪时直接返回(自身子任务保持 PENDING,等下一轮调度重试),不置 FAILED。
all_done, pending = self._preceding_sheets_all_completed(task_id)
if not all_done:
logger.info(f"[店效人效汇总] 任务 {task_id} 前 4 张 sheet 尚未全部完成,"
f"总看板暂缓执行,等待下一轮:未完成任务={pending}")
return
update_subtask(task_id, SUMMARY_CATEGORY, SUBTASK_PROCESSING)
db.session.commit()
row_count = 0
board_m = None
try:
row_count = self._process_summary(task)
update_subtask(task_id, SUMMARY_CATEGORY, SUBTASK_COMPLETED, row_count=row_count)
db.session.commit()
self._finalize_main_task(task_id)
logger.info(f"[店效人效汇总] 任务 {task_id} 处理完成,{row_count} 行")
except Exception as e:
db.session.rollback()
update_subtask(task_id, SUMMARY_CATEGORY, SUBTASK_FAILED, error_msg=str(e))
db.session.commit()
promote_subtask_failure_to_main_task(task_id)
raise
def _finalize_main_task(self, task_id):
"""
把主任务收敛到终态 COMPLETED:补齐 result_file_url、清空 error_msg。
这是修复「计算完成但主任务一直显示处理中」的关键——原设计只更新子任务状态,
主任务依赖未实现的 finalize_all_subtasks_done() 才会置 COMPLETED。
"""
task = DataProcessTask.query.filter_by(id=task_id).first()
if not task:
return
if task.status != 'PROCESSING':
return
# 若 result_file_url 为空,用已入库的汇总行重新生成兜底
if not task.result_file_url:
row = ReportStoreEffectSummary.query.filter_by(task_id=task_id).first()
if row:
try:
task.result_file_url = self.generate_result_excel(task, row)
except Exception as e:
logger.error(f"[店效人效汇总] 兜底重新生成结果文件失败: {e}")
task.status = 'COMPLETED'
task.error_msg = ''
task.updater = task.updater or task.creator
db.session.commit()
logger.info(f"[店效人效汇总] 主任务 {task_id} → COMPLETED")
# ============================================================
# 核心:解析源数据 → 逐店计算 → 整体合计
# ============================================================
def _process_summary(self, task):
task_id = task.id
stat_month = task.month or ''
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
start_str = period_start.strftime('%Y-%m-%d') if period_start else ''
end_str = period_end.strftime('%Y-%m-%d') if period_end else ''
logger.info(f"[店效人效汇总] 开始, task_id={task_id}, period={start_str}~{end_str}")
# ========== Step1: 下载附件 ==========
budget_warranty = budget_equity = budget_light = {}
all_store_names = []
base_records = [] # (biz_tag, rec)
tmp_dir = tempfile.mkdtemp(prefix=f"store_effect_{task_id}_")
try:
file_map = download_all_files(task_id, tmp_dir)
saas_path = file_map.get('SAAS门店预算分解表')
if not saas_path:
# 骨架模式:允许不带源文件先出结果(全部指标/SQL 取 0),保证结果表始终可生成
logger.warning("[店效人效汇总] 未找到 SAAS门店预算分解表 附件,将以骨架(0)输出汇总表")
rel_path = file_map.get('关系表')
delivery_map = {}
for ftype in ('鸿蒙主机厂数据表', '广联主机厂数据表'):
fpath = file_map.get(ftype)
if fpath:
part = parse_delivery_table(fpath)
for k, v in part.items():
delivery_map[k] = delivery_map.get(k, 0) + v
# 商务预算(延保/权益 marketing_fee_ratio;轻改 装修/租/耗/服务费占比)
# 注意:下载文件位于 tmp_dir,必须在 cleanup 之前完成解析
budget_path = file_map.get('预算达成数据(商务)') or file_map.get('预算达成数据(商务)')
if budget_path:
budget_warranty = parse_budget_achieve_excel(budget_path, biz_type='2.3')
budget_equity = parse_budget_achieve_excel(budget_path, biz_type='2.1')
budget_light = parse_budget_achieve_excel(budget_path, biz_type='1.1')
# 人力成本表(轻改 headcount)
labor_map = {}
lc_path = file_map.get('人力成本表')
if lc_path:
labor_map = parse_labor_cost(lc_path, biz_type='1.1')
# 关系表(暂不用于分组,仅保解析以对齐源口径)
if rel_path:
parse_region_map(rel_path)
# SAAS 门店预算分解表(逐业务解析,必须在 cleanup 之前完成!)
if saas_path:
for biz_tag, biz_filter, _ind_biz, _codes in BIZ_PLAN:
try:
if biz_tag == 'warranty':
recs = parse_saas_base(saas_path, biz_filter)
elif biz_tag == 'equity':
recs = parse_saas_base(saas_path, biz_filter)
elif biz_tag == 'inshop':
recs = parse_saas_base_sheet2(saas_path)
else: # park
recs = parse_saas_base_sheet2_exclude(saas_path)
except Exception as e:
logger.error(f"[店效人效汇总] 解析 SAAS({biz_tag}) 失败,跳过该业务: {e}")
recs = []
for r in recs:
base_records.append((biz_tag, r))
if r.get('store_name'):
all_store_names.append(r['store_name'])
else:
logger.warning("[店效人效汇总] saas_path 为空,base_records 为空(骨架输出)")
# 双列看板(总看板):从任务附件目录重算,必须在 cleanup 之前(compute_metrics 需读 tmp_dir)
try:
from build_store_effect_board import compute_metrics
# 流失门店统计月份:优先用任务统计月(task.month),回退到周期起止
_m_start = _m_end = None
if stat_month:
try:
_y, _mo = map(int, stat_month.split('-'))
_m_start = date(_y, _mo, 1)
_m_end = date(_y + 1, 1, 1) if _mo == 12 else date(_y, _mo + 1, 1)
except Exception:
_m_start = _m_end = None
if _m_start is None and period_start:
_m_start = period_start
_m_end = (period_end + timedelta(days=1)) if period_end else None
board_m = compute_metrics(tmp_dir, period_start, period_end, _m_start, _m_end)
logger.info(f"[店效人效汇总] 双列看板指标计算完成,共 {len(board_m)} 项 "
f"(流失门店统计月={_m_start}~{_m_end})")
except Exception as e:
import traceback
logger.error(f"[店效人效汇总] 双列看板计算失败,结果表回退单行: {e}")
logger.error(traceback.format_exc())
finally:
cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统(按业务类型分别拉取,失败降级为 {}) ==========
def _safe_indicator(biz_code, item_codes):
if not (start_str and end_str):
return {}
try:
return fetch_indicator_data(start_str, end_str, biz_code, item_codes) or {}
except Exception as e:
logger.warning(f"[店效人效汇总] 指标拉取失败({item_codes}): {e}")
return {}
ind_warranty = _safe_indicator(INDICATOR_BIZ_MAP.get('warranty'),
['A036', 'A075', 'A084', 'A066', 'A070', 'A086'])
ind_equity = _safe_indicator(INDICATOR_BIZ_MAP.get('equity'), ['A036', 'A075', 'A084'])
ind_light = _safe_indicator(INDICATOR_BIZ_MAP.get('light_reform'), ['A075'])
# ========== Step3: 业务系统 SQL(聚合 + 日报;BIZ_SQL_ENABLED=false 时返回 {}) ==========
# 注:SAAS 已在 Step1(cleanup 之前)完成解析,all_store_names/base_records 已就绪
def _safe_sql(fn):
if not (period_start and period_end):
return {}
try:
return fn() or {}
except Exception as e:
logger.warning(f"[店效人效汇总] 业务SQL拉取失败: {e}")
return {}
# SAAS 已在 Step1(cleanup 之前)完成解析,此处不再解析,避免 temp 已被清理导致失败
biz_sql_warranty = _safe_sql(lambda: fetch_biz_sql_aggregated(period_start, period_end, '2.3', all_store_names))
biz_sql_equity = _safe_sql(lambda: fetch_biz_sql_aggregated(period_start, period_end, '2.1', all_store_names))
biz_sql_light = _safe_sql(lambda: fetch_biz_sql_aggregated(period_start, period_end, '1.1', all_store_names))
park_daily = _safe_sql(lambda: fetch_park_daily_report(period_start, period_end, scene_type=1))
# ========== Step4: 逐店计算并累加为整体合计 ==========
store_set = set()
delivery_total = touch_total = deal_total = 0
output_value_total = Decimal('0')
cost_total = Decimal('0')
gross_profit_total = Decimal('0')
labor_cost_total = Decimal('0')
headcount_total = 0
for biz_tag, rec in base_records:
store_name = rec.get('store_name', '')
if not store_name:
continue
store_set.add(store_name)
resident = rec.get('resident_type') or rec.get('operate_type') or ''
is_direct = (resident == '直营')
if biz_tag in ('warranty', 'equity'):
if biz_tag == 'warranty':
ind = ind_warranty.get(store_name) or exact_match_store(store_name, ind_warranty) or {}
biz = exact_match_store(store_name, biz_sql_warranty) or {}
budget_ratio_map = budget_warranty
else: # equity
ind = ind_equity.get(store_name) or exact_match_store(store_name, ind_equity) or {}
biz = exact_match_store(store_name, biz_sql_equity) or {}
budget_ratio_map = budget_equity
output_value = Decimal(str(ind.get('A036', 0)))
deal = int(Decimal(str(ind.get('A075', 0))))
touch = int(Decimal(str(ind.get('A084', 0))))
delivery = int(delivery_map.get(store_name, 0))
product_cost = Decimal(str(biz.get('product_cost', 0)))
market_fee = Decimal(str(biz.get('market_fee', 0)))
store_share = Decimal(str(biz.get('shop_traffic_money', 0)))
service_fee = Decimal('0') if is_direct else Decimal(str(biz.get('service_fee', 0)))
mkt_ratio = extract_budget_ratio(budget_ratio_map, store_name, 'labor_ratio')
marketing_fee = (output_value * mkt_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
gl_share = output_value - product_cost - store_share
total_cost = market_fee + marketing_fee + service_fee
gross_profit = gl_share - total_cost
labor_cost = Decimal('0')
headcount = 0
else: # 轻改 inshop / park
ind = ind_light.get(store_name) or exact_match_store(store_name, ind_light) or {}
biz1 = exact_match_store(store_name, biz_sql_light) or {}
park_dr = exact_match_store(store_name, park_daily) or {}
output_value = Decimal(str(biz1.get('store_output_value', 0)))
deal = int(Decimal(str(ind.get('A075', 0))))
delivery = int(park_dr.get('delivery_cnt', 0))
touch = 0 # 待校准
product_cost = Decimal(str(biz1.get('product_cost', 0)))
store_traffic_fee = Decimal(str(biz1.get('shop_traffic_money', 0)))
gl_share = output_value - product_cost - store_traffic_fee
headcount = labor_map.get(store_name, 0)
personnel_cost = ((Decimal(str(headcount)) * Decimal('3500') + output_value * Decimal('0.04'))
.quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
if is_direct else Decimal('0'))
sp_ratio = (Decimal('0') if is_direct
else extract_budget_ratio(budget_light, store_name, 'service_provider_share_ratio'))
service_fee = (output_value * sp_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
renovation = prorate_by_period(extract_budget_ratio(budget_light, store_name, 'renovation_amortization'),
period_start, period_end)
rent = prorate_by_period(extract_budget_ratio(budget_light, store_name, 'rent_utilities'),
period_start, period_end)
consumables = prorate_by_period(extract_budget_ratio(budget_light, store_name, 'store_consumables'),
period_start, period_end)
construction = Decimal('0') # 待校准(需窗膜/车衣/精品成交数)
market_fee_weighted = Decimal('0') # 待校准
total_cost = (personnel_cost + construction + market_fee_weighted
+ service_fee + renovation + rent + consumables)
gross_profit = gl_share - total_cost
labor_cost = personnel_cost
delivery_total += delivery
touch_total += touch
deal_total += deal
output_value_total += output_value
cost_total += total_cost
gross_profit_total += gross_profit
labor_cost_total += labor_cost
headcount_total += int(headcount) if isinstance(headcount, (int, float, Decimal)) else 0
# ========== Step5: 汇总指标 ==========
store_count = len(store_set)
gross_profit_rate = safe_div_pct_decimal(gross_profit_total, output_value_total)
per_capita_output = (output_value_total / Decimal(str(headcount_total))).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP) if headcount_total else Decimal('0')
per_capita_profit = (gross_profit_total / Decimal(str(headcount_total))).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP) if headcount_total else Decimal('0')
# ========== Step6: 先生成结果 Excel(保证结果表一定产出,不依赖 DB 写入成败) ==========
row = ReportStoreEffectSummary(
task_id=task_id, stat_month=stat_month,
period_start=period_start, period_end=period_end,
store_count=store_count,
delivery_total=delivery_total, touch_total=touch_total, deal_total=deal_total,
output_value_total=output_value_total, cost_total=cost_total,
gross_profit_total=gross_profit_total, gross_profit_rate=gross_profit_rate,
labor_cost_total=labor_cost_total, headcount_total=headcount_total,
per_capita_output=per_capita_output, per_capita_profit=per_capita_profit,
)
result_file_url = self.generate_result_excel(task, row, board_metrics=board_m)
logger.info(f"[店效人效汇总] 结果文件已生成: {result_file_url}")
# ========== Step7: 入库(单任务一行,先删后插;失败不影响已生成的文件) ==========
try:
ReportStoreEffectSummary.query.filter_by(task_id=task_id).delete()
db.session.flush()
db.session.add(row)
db.session.commit()
logger.info(f"[店效人效汇总] 入库 1 行:门店数={store_count}, 产值={output_value_total}, "
f"毛利={gross_profit_total}, 人员数={headcount_total}")
task = DataProcessTask.query.filter_by(id=task_id).first()
if task:
task.result_file_url = result_file_url
db.session.commit()
except Exception as db_err:
logger.error(f"[店效人效汇总] 入库/回填失败(结果文件已生成): {db_err}")
db.session.rollback()
return 1
# ============================================================
# 结果 Excel 生成(单 sheet「门店店效人效汇总表」)
# ============================================================
RESULT_COLUMNS = [
('门店数', 'store_count', 'int'),
('交车数', 'delivery_total', 'int'),
('触客数', 'touch_total', 'int'),
('成交数', 'deal_total', 'int'),
('产值合计', 'output_value_total', 'amount'),
('成本合计', 'cost_total', 'amount'),
('毛利合计', 'gross_profit_total', 'amount'),
('毛利率', 'gross_profit_rate', 'rate'),
('人力成本', 'labor_cost_total', 'amount'),
('人员数', 'headcount_total', 'int'),
('人均产值', 'per_capita_output', 'amount'),
('人均毛利', 'per_capita_profit', 'amount'),
]
def generate_result_excel(self, task, row, board_metrics=None, local_only=False):
stat_month = task.month or ''
today_str = datetime.now().strftime('%Y%m%d')
type_name = task.data_table_type_name or task.data_table_type or 'result'
period_end = getattr(task, 'period_end', None)
period_start = getattr(task, 'period_start', None)
end_date_str = period_end.strftime('%Y-%m-%d') if period_end else ''
# 完整 6 sheet 模式:延保 + 权益 + 店中店 + 园区店 + 总看板 + 字段说明
try:
from export_red_yellow_report import export_red_yellow_report
# 生成本地临时文件(6 sheet)
local_path = export_red_yellow_report(
period_start, period_end,
task_id=task.id,
metrics=board_metrics,
)
logger.info(f"[店效人效汇总] 6 sheet 红黄门店盈利测算已生成: {local_path}")
if local_only:
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True)
final_path = os.path.join(out_dir, f'{type_name}_{today_str}.xlsx')
import shutil
shutil.copy2(local_path, final_path)
logger.info(f"[店效人效汇总] 6 sheet 本地文件: {final_path}")
return final_path
object_key = (f"data-process/{today_str}"
f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(local_path, object_key)
logger.info(f"[店效人效汇总] 6 sheet 已上传 OSS: {file_url}")
return file_url
except Exception as e:
import traceback
logger.error(f"[店效人效汇总] export_red_yellow_report 失败,回退单行: {e}")
logger.error(traceback.format_exc())
# 回退到旧的单行 12 列模式
return self._generate_single_sheet_excel(task, row)
def _generate_single_sheet_excel(self, task, row):
"""回退:单行 12 列汇总表(兼容旧行为,直接上传 OSS)"""
stat_month = task.month or ''
period_end = getattr(task, 'period_end', None)
end_date_str = period_end.strftime('%Y-%m-%d') if period_end else ''
wb = openpyxl.Workbook()
ws = wb.active
ws.title = '门店店效人效汇总表'
header_font = Font(name='微软雅黑', size=11, bold=True, color='FFFFFF')
header_fill = PatternFill(start_color='4472C4', end_color='4472C4', fill_type='solid')
title_font = Font(name='微软雅黑', size=12, bold=True)
cell_font = Font(name='微软雅黑', size=10)
center = Alignment(horizontal='center', vertical='center', wrap_text=True)
right = Alignment(horizontal='right', vertical='center')
thin = Border(left=Side(style='thin'), right=Side(style='thin'),
top=Side(style='thin'), bottom=Side(style='thin'))
title_cell = ws.cell(
row=1, column=1,
value=f'{stat_month}月门店店效人效汇总表(整体合计,截止"{end_date_str}")')
title_cell.font = title_font
title_cell.alignment = center
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=len(self.RESULT_COLUMNS))
for c, (header, _attr, _kind) in enumerate(self.RESULT_COLUMNS, 1):
cell = ws.cell(row=2, column=c, value=header)
cell.font = header_font
cell.fill = header_fill
cell.alignment = center
cell.border = thin
for c, (_header, attr, kind) in enumerate(self.RESULT_COLUMNS, 1):
val = getattr(row, attr)
cell = ws.cell(row=3, column=c)
if kind == 'int':
try:
cell.value = int(val); cell.number_format = '#,##0'
except (ValueError, TypeError): cell.value = ''
elif kind == 'amount':
try:
cell.value = float(val); cell.number_format = '#,##0.00'
except (ValueError, TypeError): cell.value = ''
elif kind == 'rate':
try:
cell.value = float(val); cell.number_format = '0.00"%"'
except (ValueError, TypeError): cell.value = ''
else:
cell.value = str(val) if val is not None else ''
cell.font = cell_font; cell.border = thin
cell.alignment = right if kind in ('int', 'amount', 'rate') else center
note = ws.cell(row=4, column=1,
value='注:整体合计,不分组;业务系统SQL字段在 BIZ_SQL_ENABLED=false 时为0,数字待校准。')
note.font = Font(name='微软雅黑', size=9, italic=True, color='999999')
note.alignment = Alignment(horizontal='left', vertical='center')
ws.merge_cells(start_row=4, start_column=1, end_row=4, end_column=len(self.RESULT_COLUMNS))
for c in range(1, len(self.RESULT_COLUMNS) + 1):
ws.column_dimensions[openpyxl.utils.get_column_letter(c)].width = 13
ws.freeze_panes = 'A3'
tmp_dir = tempfile.mkdtemp(prefix=f'store_effect_result_{task.id}_')
try:
excel_path = os.path.join(tmp_dir, f'{type_name}_{today_str}.xlsx')
wb.save(excel_path)
object_key = (f"data-process/{today_str}"
f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key)
logger.info(f"[店效人效汇总] 回退单行已上传: {file_url}")
return file_url
finally:
cleanup_tmp_dir(tmp_dir)
# -*- coding: utf-8 -*-
"""
岚图专项报表 独立处理器
=======================
对应数据表类型:voyah_special(岚图专项,无需上传附件,need_period=True)
功能:查询"岚图"品牌(pg_group_info.group_name='岚图')旗下门店的延保业务经营数据,
按模板 exporttemplete/岚图专项.xlsx 渲染表头与正文,生成结果 Excel 上传 OSS 并回填
task.result_file_url。设计见《岚图专项报表设计文档.md》(项目根目录,2026-09-17 已确认)。
处理流程:
Step1 业务库(dj_smartcarlife)查询:门店清单 / 省份 / 区域运营 / 驻店人员
Step2 指标系统查询(fetch_by_merchant_ids,按商户号取值):
- 上月整月 A062/A084/A075(G/H/I 列)
- 当前周期 A036/A062/A084/A075(E/M/N/O 列、末列产值)
- 每个评灯节点(周期内每周一/周四 + endDate)按 1号~节点日 累计 A075/A084
Step3 加载模板渲染:前三行表头复用模板样式;正文第 4 行合计行 A4:F4 合并"合计"、
其后留空(不计算);第 5 行起每商户一行(按门店清单 id 倒序)
Step4 上传 OSS(object_key: data-process/YYYYMMDD/岚图专项_{起}-{止}_{时间戳}.xlsx),
回填 task.result_file_url,任务置 COMPLETED
关键口径(已与需求方确认):
- 指标返回粒度:商户 × 指标,每商户每 itemCode 各一条,按 (merchant_id, item_code) 取值
- 评灯阈值:<40% 红 / [40%,50%) 黄 / >=50% 绿(对应模板"总部指标"sheet 标准值0.4/优秀值0.5)
- 所有单元格写计算值,不写 Excel 公式
- 百分比列写小数比率 + '0%' 格式(Excel 展示自动四舍五入到整数百分比)
- 若 endDate 恰为某评灯节点,日期列与"截止目前"列重复展示
"""
import logging
import os
import tempfile
from copy import copy
from datetime import date, datetime, timedelta
from decimal import Decimal
import openpyxl
from openpyxl.styles import PatternFill
from openpyxl.utils import get_column_letter
from sqlalchemy import text, bindparam
from config import Config
from indicator_client import IndicatorClient
from oss_utils import upload_file
from report_utils import mark_task_failed, cleanup_tmp_dir, _get_biz_sql_conn
from models import DataProcessTask, db
logger = logging.getLogger('VoyahProcessor')
VOYAH_TYPE = 'voyah_special'
GROUP_NAME = '岚图'
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
TEMPLATE_PATH = os.path.join(BASE_DIR, 'exporttemplete', '岚图专项.xlsx')
TEMPLATE_SHEET = '展示表'
# 指标编码:A036 产值 / A062 交付数 / A084 引荐台数 / A075 成交数(biz=1 延保)
CODE_OUTPUT = 'A036'
CODE_DELIVERY = 'A062'
CODE_REFER = 'A084'
CODE_DEAL = 'A075'
# ---------- 模板布局常量(列号 1 起) ----------
FIXED_COLS = 18 # A~R 固定列
DATE_COL_START = 19 # S 列起为动态日期(评灯)列
TEMPLATE_DATE_COLS = 7 # 模板现有动态列数(S~Y)
TEMPLATE_LAST_COL = 27 # 模板末列 AA
# 截止目前列 = DATE_COL_START + n_dates;产值列 = 截止目前列 + 1
# 评灯底色(浅红 / 浅黄 / 浅绿)
RATE_FILL = {
'红色': 'FFC7CE',
'黄色': 'FFEB9C',
'绿色': 'C6EFCE',
}
# 正文行各百分比列(J/K/P/Q/R)列号:写小数比率 + '0%' 格式
PCT_COLS = (10, 11, 16, 17, 18)
# 省份简称映射(含直辖市/自治区/特别行政区)
PROVINCE_ABBR = {
'北京市': '北京', '天津市': '天津', '上海市': '上海', '重庆市': '重庆',
'河北省': '河北', '山西省': '山西', '辽宁省': '辽宁', '吉林省': '吉林',
'黑龙江省': '黑龙江', '江苏省': '江苏', '浙江省': '浙江', '安徽省': '安徽',
'福建省': '福建', '江西省': '江西', '山东省': '山东', '河南省': '河南',
'湖北省': '湖北', '湖南省': '湖南', '广东省': '广东', '海南省': '海南',
'四川省': '四川', '贵州省': '贵州', '云南省': '云南', '陕西省': '陕西',
'甘肃省': '甘肃', '青海省': '青海',
'内蒙古自治区': '内蒙古', '广西壮族自治区': '广西', '西藏自治区': '西藏',
'宁夏回族自治区': '宁夏', '新疆维吾尔自治区': '新疆',
'香港特别行政区': '香港', '澳门特别行政区': '澳门',
'台湾省': '台湾',
}
def shorten_province(name):
"""省份全称 → 简称:广西壮族自治区→广西 / 上海市→上海 / 湖北省→湖北。
先查枚举映射,未命中按去『省/市』后缀兜底;空值原样返回空。"""
if not name:
return ''
name = str(name).strip()
if name in PROVINCE_ABBR:
return PROVINCE_ABBR[name]
for suffix in ('省', '市'):
if name.endswith(suffix) and len(name) > len(suffix):
return name[:-len(suffix)]
return name
def generate_stat_nodes(period_start, period_end):
"""评灯日期列节点:统计周期内的每个周一、周四(去重升序)。
注意(2026-09-17 联调修复):endDate 不作为日期列——需求示例口径为
日期列只取周一/周四(9/1~9/26 → 9月3日 9月7日 9月10日 9月14日 9月17日
9月21日 9月24日 共 7 列),endDate 通过固定的"截止目前"列体现;
仅当 endDate 恰为周一/周四时,该日期列与"截止目前"列重复展示。
"截止目前"列的取数日期由 collect_data 单独补充(节点 ∪ {endDate})。"""
nodes = set()
d = period_start
while d <= period_end:
if d.weekday() in (0, 3): # 0=周一 3=周四
nodes.add(d)
d += timedelta(days=1)
return sorted(nodes)
def rating_text(deal, refer):
"""触客转化率评灯:成交/引荐 → 红色(<40%) / 黄色([40%,50%)) / 绿色(>=50%)。
无数据(成交/引荐为空,或引荐=0)返回空字符串。"""
if deal is None or refer is None:
return ''
try:
deal_d = Decimal(str(deal))
refer_d = Decimal(str(refer))
except Exception:
return ''
if refer_d == 0:
return ''
pct = deal_d / refer_d * 100
if pct < 40:
return '红色'
if pct < 50:
return '黄色'
return '绿色'
def _pct(num, den):
"""比率(小数),供 '0%' 格式单元格展示(Excel 自动四舍五入到整数百分比)。
分母为空/0 或分子为空时返回 None(单元格留空)。"""
if num is None or den is None:
return None
try:
num_d, den_d = Decimal(str(num)), Decimal(str(den))
except Exception:
return None
if den_d == 0:
return None
return float(num_d / den_d)
def _pct_int_str(num, den):
"""四舍五入取整的百分比整数(如 41),用于校验/日志;展示层用 _pct + '0%' 格式。"""
r = _pct(num, den)
if r is None:
return None
return int(Decimal(str(r)) * 100 + Decimal('0.5')) if r >= 0 else None
class VoyahProcessor:
"""岚图专项报表处理器(调度扫描 + 单任务处理 + Excel 渲染)"""
def __init__(self, app=None):
self.app = app
# ============================================================
# 调度器入口
# ============================================================
def scan_voyah(self):
"""扫描 voyah_special 类型的 PROCESSING 任务并逐个处理"""
logger.info("[岚图专项] 开始扫描 voyah_special 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type=VOYAH_TYPE,
status='PROCESSING',
is_deleted=0,
).order_by(DataProcessTask.id.asc()).all()
logger.info(f"[岚图专项] 扫描到 {len(tasks)} 个待处理任务")
success_count, fail_count = 0, 0
for task in tasks:
try:
self.process(task)
success_count += 1
logger.info(f"[岚图专项] 任务 {task.id} 处理成功")
except Exception as e:
import traceback
fail_count += 1
logger.error(f"[岚图专项] 任务 {task.id} 处理失败: {str(e)}")
logger.error(traceback.format_exc())
try:
mark_task_failed(task.id, str(e))
except Exception as mark_err:
logger.error(f"[岚图专项] 标记任务失败时出错: {mark_err}")
logger.info(f"[岚图专项] 扫描完成,成功 {success_count},失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
# ============================================================
# 单任务处理
# ============================================================
def process(self, task):
"""处理单个岚图专项任务:取数 → 渲染 Excel → 上传 OSS → 回填任务状态"""
task_id = task.id
try:
period_start = getattr(task, 'period_start', None)
period_end = getattr(task, 'period_end', None)
if not period_start or not period_end:
raise Exception("缺少所属周期(period_start/period_end),无法处理")
# 周期校验:开始/结束必须同月(不能跨月)
if (period_start.year, period_start.month) != (period_end.year, period_end.month):
raise Exception(
f"所属周期不能跨月: {period_start} ~ {period_end}")
logger.info(f"[岚图专项] 开始处理 task_id={task_id}, "
f"周期={period_start}~{period_end}")
# Step1+2: 取数
data = self.collect_data(period_start, period_end)
logger.info(f"[岚图专项] 取数完成: {len(data['stores'])} 个门店, "
f"{len(data['nodes'])} 个评灯节点")
# Step3: 渲染 Excel
# 文件名:岚图专项_{开始日期}-{结束日期}_{时间戳}.xlsx
# (日期 YYYYMMDD,时间戳到秒避免重名)
period_start = self._as_date(period_start)
period_end = self._as_date(period_end)
ts = datetime.now().strftime('%Y%m%d%H%M%S')
file_name = (f"岚图专项_{period_start.strftime('%Y%m%d')}"
f"-{period_end.strftime('%Y%m%d')}_{ts}.xlsx")
tmp_dir = tempfile.mkdtemp(prefix=f'voyah_{task_id}_')
try:
excel_path = os.path.join(tmp_dir, file_name)
self.build_workbook(data, period_start, period_end, excel_path)
# Step4: 上传 OSS + 回填任务
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
f"/{file_name}")
file_url = upload_file(excel_path, object_key)
finally:
cleanup_tmp_dir(tmp_dir)
task = DataProcessTask.query.filter_by(id=task_id).first()
task.status = 'COMPLETED'
task.result_file_url = file_url
task.error_msg = ''
db.session.commit()
logger.info(f"[岚图专项] 任务 {task_id} 处理完成,结果文件: {file_url}")
except Exception as e:
db.session.rollback()
mark_task_failed(task_id, str(e))
raise
# ============================================================
# 数据采集(业务库 SQL + 指标系统)
# ============================================================
def collect_data(self, period_start, period_end):
"""采集正文全部数据,返回渲染所需的字典。独立于任务,便于单测/脚本复用。
返回:
{
'stores': [{merchant_id, merchant_name}, ...] 按 pgr.id 倒序,
'province': {mid: 简称},
'directors': {mid: 'a/b'},
'staff': {mid: 'x/y'},
'ind_cur': {mid: {item_code: Decimal}}, # 当前周期 A036/A062/A084/A075
'ind_prev': {mid: {item_code: Decimal}}, # 上月整月 A062/A084/A075
'nodes': [date, ...], # 评灯节点(升序)
'node_ratings': {date: {mid: '红色'/'黄色'/'绿色'/''}},
}
"""
period_start = self._as_date(period_start)
period_end = self._as_date(period_end)
start_str = period_start.strftime('%Y-%m-%d')
end_str = period_end.strftime('%Y-%m-%d')
# ---------- Step1: 业务库 SQL ----------
conn = _get_biz_sql_conn()
if conn is None:
raise Exception("业务库(dj_smartcarlife)连接失败")
try:
# 门店清单(按 pgr.id 倒序)
rows = conn.execute(text(
"select pgr.merchant_id, pgr.merchant_name "
"from pg_group_info pg "
"inner join pg_group_store_rel pgr on pg.id = pgr.group_id "
" and pgr.deleted_flag = 'N' "
"where pg.deleted_flag = 'N' and pg.group_name = :gname "
"order by pgr.id desc"
), {'gname': GROUP_NAME}).fetchall()
stores = [{'merchant_id': str(r[0]), 'merchant_name': r[1]} for r in rows]
mids = [s['merchant_id'] for s in stores]
logger.info(f"[岚图专项] 门店清单: {len(mids)} 家({GROUP_NAME})")
if not mids:
return {'stores': [], 'province': {}, 'directors': {}, 'staff': {},
'ind_cur': {}, 'ind_prev': {},
'nodes': generate_stat_nodes(period_start, period_end),
'node_ratings': {period_end: {}}}
# 省份(批量)
province = {}
for r in conn.execute(text(
"select merchant_id, province_name from dj_car_life_service_merchant "
"where deleted_flag = 'N' and merchant_id in :mids"
).bindparams(bindparam('mids', expanding=True)), {'mids': mids}):
province[str(r[0])] = shorten_province(r[1])
# 区域运营(批量,多 director_name 用 / 分割,去重保序)
directors = {}
for r in conn.execute(text(
"select merchant_id, director_name "
"from dj_car_life_shop_merchant_director_config "
"where deleted_flag = 'N' and director_type = 9 "
" and merchant_id in :mids"
).bindparams(bindparam('mids', expanding=True)), {'mids': mids}):
mid = str(r[0])
seen = directors.setdefault(mid, [])
if r[1] and r[1] not in seen:
seen.append(r[1])
directors = {k: '/'.join(v) for k, v in directors.items()}
# 今日延保驻店人员(日报 ∪ 开单,按商户 GROUP_CONCAT 去重,'/' 分割)
staff = {}
end_dt_str = period_end.strftime('%Y-%m-%d 23:59:59')
staff_rows = conn.execute(text(
"select t.merchant_id, "
" group_concat(distinct si.staff_name order by si.staff_name separator '/') as staff_names "
"from ( "
" select merchant_id, staff_uuid from dj_car_life_staff_daily_report "
" where deleted_flag = 'N' and scene_type = 0 "
" and template_type in (1, 2) "
" and merchant_id in :mids1 "
" and report_date >= :sdate and report_date <= :edate "
" union "
" select merchant_id, seller_user_id as staff_uuid "
" from dj_car_life_goods_order "
" where deleted_flag = 'N' and scene_type = 0 and business_type = 2 "
" and merchant_id in :mids2 "
" and order_time >= :sdt and order_time <= :edt "
") t "
"inner join dj_car_life_staff_info si "
" on si.staff_uuid = t.staff_uuid and si.deleted_flag in ('N', 'I') "
"group by t.merchant_id"
).bindparams(
bindparam('mids1', expanding=True), bindparam('mids2', expanding=True),
), {
'mids1': mids, 'mids2': mids,
'sdate': start_str, 'edate': end_str,
'sdt': f'{start_str} 00:00:00', 'edt': end_dt_str,
}).fetchall()
for r in staff_rows:
staff[str(r[0])] = r[1] or ''
finally:
conn.close()
# ---------- Step2: 指标系统 ----------
client = IndicatorClient()
# 当前周期:A036/A062/A084/A075(E 展业状态、M/N/O、产值 一次取齐)
ind_cur = client.fetch_by_merchant_ids(
start_str, end_str,
[CODE_OUTPUT, CODE_DELIVERY, CODE_REFER, CODE_DEAL], mids)
# 上月整月:A062/A084/A075(G/H/I)
prev_first, prev_last = self._prev_month_range(period_start)
ind_prev = client.fetch_by_merchant_ids(
prev_first.strftime('%Y-%m-%d'), prev_last.strftime('%Y-%m-%d'),
[CODE_DELIVERY, CODE_REFER, CODE_DEAL], mids)
logger.info(f"[岚图专项] 指标拉取完成: 当前周期 {len(ind_cur)} 商户, "
f"上月({prev_first}~{prev_last}) {len(ind_prev)} 商户")
# 评灯取数日期集合:周期内周一/周四(日期列)∪ endDate("截止目前"列),
# 各按 1号~该日 累计 A075/A084。endDate 非节点时多查一次。
nodes = generate_stat_nodes(period_start, period_end)
rating_dates = sorted(set(nodes) | {period_end})
month_first = date(period_start.year, period_start.month, 1)
node_ratings = {}
for d in rating_dates:
ind_node = client.fetch_by_merchant_ids(
month_first.strftime('%Y-%m-%d'), d.strftime('%Y-%m-%d'),
[CODE_DEAL, CODE_REFER], mids)
node_ratings[d] = {
mid: rating_text((ind_node.get(mid) or {}).get(CODE_DEAL),
(ind_node.get(mid) or {}).get(CODE_REFER))
for mid in mids
}
logger.info(f"[岚图专项] 评灯取数 {d} 完成({len(ind_node)} 商户)")
return {
'stores': stores,
'province': province,
'directors': directors,
'staff': staff,
'ind_cur': ind_cur,
'ind_prev': ind_prev,
'nodes': nodes,
'node_ratings': node_ratings,
}
# ============================================================
# Excel 渲染(加载模板 → 动态列调整 → 清样例 → 写正文)
# ============================================================
def build_workbook(self, data, period_start, period_end, out_path):
"""按模板渲染岚图专项报表并保存到 out_path。
data 为 collect_data() 的返回结构。前三行表头复用模板样式;
正文第 4 行合计行 A4:F4 合并"合计"、其后留空;第 5 行起每商户一行。
"""
period_start = self._as_date(period_start)
period_end = self._as_date(period_end)
stores = data.get('stores') or []
nodes = data.get('nodes') or generate_stat_nodes(period_start, period_end)
node_ratings = data.get('node_ratings') or {}
n_dates = len(nodes)
last_col = FIXED_COLS + n_dates + 2 # 截止目前 + 产值
wb = openpyxl.load_workbook(TEMPLATE_PATH)
ws = wb[TEMPLATE_SHEET]
# ---------- 0) 清空模板条件格式 ----------
# 模板自带 15 组条件格式(I/K/R 列 colorScale 渐变、S~Y 列 cellIs),
# 若不清空会残留作用于新数据行:I/K/R 被自动上色(colorScale 按
# 相对排名渐变,颜色与数值大小无直接关系)。评灯底色由代码按阈值填充。
from openpyxl.formatting.formatting import ConditionalFormattingList
ws.conditional_formatting = ConditionalFormattingList()
# ---------- 1) 解除模板全部合并(结束后按最终列数重建) ----------
for rng in [str(r) for r in ws.merged_cells.ranges]:
ws.unmerge_cells(rng)
# ---------- 2) 动态列数调整(仅作用在日期列区间内) ----------
# 模板动态列 S~Y 共 7 列(19~25),截止目前 Z(26)、产值 AA(27)。
# 增加列:在 26 前插入(Z/AA 右移,黄底"截止目前"样式随列平移);
# 减少列:从日期列区右端(25)删除,保证 Z/AA 的表头样式不丢失。
delta = n_dates - TEMPLATE_DATE_COLS
if delta > 0:
src_style = {} # 以模板 S 列(19) 行1~5 样式为蓝本
for r in range(1, 6):
src_style[r] = copy(ws.cell(row=r, column=DATE_COL_START)._style)
src_width = ws.column_dimensions[get_column_letter(DATE_COL_START)].width
for _ in range(delta):
ws.insert_cols(26)
for r in range(1, 6):
ws.cell(row=r, column=26)._style = copy(src_style[r])
ws.column_dimensions[get_column_letter(26)].width = src_width
elif delta < 0:
# 从日期列区右端(25=Y)起、位置逐次左移删除,只删多余日期列,
# "截止目前"(Z)/"产值"(AA) 列样式(含黄底)随列平移保留
pos = 25
for _ in range(-delta):
ws.delete_cols(pos)
pos -= 1
# ---------- 3) 捕获正文行样式(模板第 5 行样例,按列捕获) ----------
row_styles = {}
for col in range(1, last_col + 1):
c = ws.cell(row=5, column=col)
row_styles[col] = copy(c._style)
# ---------- 4) 清除模板样例正文(第 5 行起全部删除) ----------
if ws.max_row >= 5:
ws.delete_rows(5, ws.max_row - 4)
# ---------- 5) 重建表头 ----------
# 行1:标题(周期结束时间动态渲染)
ws.cell(row=1, column=1,
value=f'岚图专项截止{period_end.month}月{period_end.day}日数据')
ws.merge_cells(start_row=1, start_column=1, end_row=1, end_column=last_col)
# 行2:四个合并区块
ws.cell(row=2, column=1, value='门店基础信息')
ws.merge_cells(start_row=2, start_column=1, end_row=2, end_column=6)
ws.cell(row=2, column=7, value='上月数据')
ws.merge_cells(start_row=2, start_column=7, end_row=2, end_column=11)
ws.cell(row=2, column=12, value='本月数据')
ws.merge_cells(start_row=2, start_column=12, end_row=2, end_column=18)
ws.cell(row=2, column=DATE_COL_START, value='门店评灯等级')
ws.merge_cells(start_row=2, start_column=DATE_COL_START,
end_row=2, end_column=last_col)
# 行3:A~R 固定表头模板已有;S 列起写动态日期 + 截止目前 + 产值
for i, node in enumerate(nodes):
ws.cell(row=3, column=DATE_COL_START + i,
value=f'{node.month}月{node.day}日')
zhici_col = DATE_COL_START + n_dates
ws.cell(row=3, column=zhici_col, value='截止目前')
ws.cell(row=3, column=zhici_col + 1, value='产值')
# 行4:合计行 —— A4:F4 合并"合计",G4 及之后全部留空(不计算)。
# 注意:openpyxl 的 cell(row, col, value=None) 传 None 只读取不赋值,
# 必须用 cell.value = None 直接赋值才能真正清空模板残留数据/公式。
ws.cell(row=4, column=1, value='合计')
ws.merge_cells(start_row=4, start_column=1, end_row=4, end_column=6)
for col in range(7, last_col + 1):
ws.cell(row=4, column=col).value = None
# ---------- 6) 写正文(第 5 行起,每商户一行) ----------
province = data.get('province') or {}
directors = data.get('directors') or {}
staff = data.get('staff') or {}
ind_cur = data.get('ind_cur') or {}
ind_prev = data.get('ind_prev') or {}
for idx, store in enumerate(stores):
r = 5 + idx
mid = store['merchant_id']
cur = ind_cur.get(mid) or {}
prev = ind_prev.get(mid) or {}
values = {
1: store['merchant_name'], # A 门店
2: None, # B 精准门店信息(留空)
3: province.get(mid, '') or None, # C 省份
4: directors.get(mid, '') or None, # D 区域运营
5: '展业中' if (cur.get(CODE_OUTPUT) or 0) > 0 else None, # E
6: staff.get(mid, '') or None, # F 驻店人员
7: prev.get(CODE_DELIVERY), # G 上月交付
8: prev.get(CODE_REFER), # H 上月引荐
9: prev.get(CODE_DEAL), # I 上月成交
10: _pct(prev.get(CODE_DEAL), prev.get(CODE_DELIVERY)), # J
11: _pct(prev.get(CODE_DEAL), prev.get(CODE_REFER)), # K
12: None, # L 本月目标(留空)
13: cur.get(CODE_DELIVERY), # M 本月交车
14: cur.get(CODE_REFER), # N 本月引荐
15: cur.get(CODE_DEAL), # O 本月成交
16: _pct(cur.get(CODE_DEAL), cur.get(CODE_DELIVERY)), # P
17: _pct(cur.get(CODE_REFER), cur.get(CODE_DELIVERY)), # Q 触客率
18: _pct(cur.get(CODE_DEAL), cur.get(CODE_REFER)), # R
}
# 动态评灯列 + 截止目前(endDate 口径与最后一节点相同,重复展示)
for i, node in enumerate(nodes):
values[DATE_COL_START + i] = (node_ratings.get(node) or {}).get(mid) or None
values[zhici_col] = (node_ratings.get(period_end) or {}).get(mid) or None
values[zhici_col + 1] = cur.get(CODE_OUTPUT) # 产值
ws.row_dimensions[r].height = 20
for col in range(1, last_col + 1):
cell = ws.cell(row=r, column=col)
cell._style = copy(row_styles.get(col))
val = values.get(col)
cell.value = val if val is not None else None
if col in PCT_COLS:
cell.number_format = '0%'
fill_color = RATE_FILL.get(val) if isinstance(val, str) else None
if fill_color:
cell.fill = PatternFill(start_color=fill_color,
end_color=fill_color, fill_type='solid')
wb.save(out_path)
logger.info(f"[岚图专项] Excel 已生成: {out_path}({len(stores)} 门店, "
f"{n_dates} 评灯节点, 共 {last_col} 列)")
return out_path
# ============================================================
# 工具
# ============================================================
@staticmethod
def _as_date(val):
"""date/datetime/字符串 统一转 date"""
if isinstance(val, datetime):
return val.date()
if isinstance(val, date):
return val
return datetime.strptime(str(val)[:10], '%Y-%m-%d').date()
@staticmethod
def _prev_month_range(period_start):
"""给定周期(某月内),返回上个月的第一天与最后一天"""
first = date(period_start.year, period_start.month, 1)
last_of_prev = first - timedelta(days=1)
first_of_prev = date(last_of_prev.year, last_of_prev.month, 1)
return first_of_prev, last_of_prev
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!