Commit ce59bee5 by zhouhaibao

Merge branch 'v1.2' of http://192.168.3.233:8090/data_report/data-report into v1.2

# Conflicts:
#	data-process/processor.py
2 parents 59a3feaa 4eae55d3
Showing 58 changed files with 7665 additions and 801 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/
...@@ -6,3 +6,43 @@ ...@@ -6,3 +6,43 @@
- 处理引擎未接入:`process_task` 白名单(SUPPORTED_PROCESS_TYPES)会拦截并提示"引擎尚未接入"(与 future_expansion 一致),不会误跑预算流水线、不崩溃。 - 处理引擎未接入:`process_task` 白名单(SUPPORTED_PROCESS_TYPES)会拦截并提示"引擎尚未接入"(与 future_expansion 一致),不会误跑预算流水线、不崩溃。
- 改动仅 config.py;前端按 DATA_TABLE_TYPES 动态渲染上传区,重启后端后上传页出现"阿维塔专项"选项。 - 改动仅 config.py;前端按 DATA_TABLE_TYPES 动态渲染上传区,重启后端后上传页出现"阿维塔专项"选项。
- need_period 已按用户要求改为 False(阿维塔专项不需要所属周期项)。仍待确认:是否需重启后端(PID 13536)让前端生效。 - 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-20
## 新增 北汽专项(baic_special)数据表类型
- 用户已手动建好 3 张 MySQL 表(不再依赖 db.create_all):`baic_special_month_data`(明细,逐门店一行,PK=store_id)、`baic_special_monthly_business`(逐门店×业务 延保/权益,本轮不落)、`baic_special_month_summary_metrics`(单任务一行)。ORM 必须逐列对齐真实表(曾踩坑 Unknown column)。
- 接线点(参考 avita_special):`config.DATA_TABLE_TYPES['baic_special']`(name=北汽专项,need_period=False,forms=['北汽专项源数据表']);`models.py` 新增 3 个 ORM 类;`baic_special_processor.py`(BaicSpecialProcessor: process/_parse/_save/scan_baic_special/generate_result_excel);`scheduler.py` 新增 `BaicSpecialScheduler`(OUTPUT_CATEGORY='baic_special',JOB_NAME='baic_special_scan');`app.py` import+实例化+加入 ALL_SCHEDULERS(**并补回此前缺失的 avita_special_scheduler 接线**);`processor.py` 白名单前路由 baic_special→BaicSpecialProcessor。
- 源文件「北汽专项源数据表」仅 5 列 → DB 映射:门店名称→store_name、品牌→brand、兜底门店→underwriting_rule、交车数核对(一店一群)→delivery_check_group_cnt、触客数核对(一店一群)→visit_check_group_cnt。`region`/`store_type`(NOT NULL,来源D+)本轮占位空串;其余列留 NULL;monthly_business 本轮不落。
- 源文件结构:行1主表头+行2子表头,行3起逐门店(隔行空白占位),共 23 家;末尾 r52-54 是「北汽品牌汇总/售后门店数/售后场景开通率」纯标签段(无数值),解析须跳过。
- 结果模板 `exporttemplete/baic_special_report_template.xlsx` 已复制(用户「北汽专项-展示表字段取值说明(模板版)」)。模板自带 7月 23 家门店的 5 列值。结果表生成:复制模板→按 store_name 用 DB 源值覆盖 D门店名/E品牌/J兜底/AB一店一群交车/AE一店一群触客→品牌汇总本月段(r59) A=北汽 B=北汽 C=门店数;其余系统列保留模板原样(框架轮口径)。截止日期规则同 avita(所属月内取今日,否则取月末封账)。OSS object_key `data-process/YYYYMMDD/baic_special_{month}_{task}.xlsx`。
- **端到端验证通过**(临时脚本 _verify_baic.py 已清理):解析 23 家、落库 23 明细+1 汇总、结果表 5 列与 r59 校验一致。后端重启(backend_baic1.log),avita_special_scan 与 baic_special_scan 调度均生效。
- 已知缺口(待 D+ 系统接入):区域/驻店类型/产值/交付/触客/渗透/评灯/周趋势/产值表核对/差异/品牌汇总(产值交付渗透售后环比) 全来自 D+ 系统,当前代码无该数据源;monthly_business(延保/权益订单) 同理。汇总表 brand 框架轮填固定值「北汽」(D+ 接入后改「极狐/越野」)。
## 北汽专项结果表改用「精简骨架模板」+ 门店行动态展开(2026-09-20 下午)
- 用户替换模板:`北汽专项-展示表字段取值说明(模板版).xlsx` 去掉大量说明行,改**骨架版**(仅 16 行):r1 标题、r2 大分类表头、r3 32 列子表头、r4/r5 合计行(延保/权益)、**r6/r7 单个示例门店块**(延保/权益两行)、r10-12 品牌汇总本月段、r14-16 上月段。**不再预填 23 家门店**。
- 已复制覆盖 `exporttemplete/baic_special_report_template.xlsx`。
- 用户拍板:导出时门店**每家拆 2 行(延保/权益)**,参照示例块 r6/r7 结构。
- `generate_result_excel` 重写:①标题日期;②`ws.insert_rows(EX2+1, (n-1)*2)` 一次性插入额外行;③逐块填写:第 i 家(0-based)占 r_a=6+2i(延保)/r_b=r_a+1(权益),i≥1 时复制示例块样式(逐列 `cell._style=copy(...)`)并按 delta=2i 重建两行合并;④合计行清空计算列;⑤品牌汇总本月/上月段动态定位(扫描含「本月」/「上月」的行)后更新标签与本月数据行(A=北汽/B=北汽/C=门店数,D..R 清空);⑥上月段数据行保留模板原样。
- 源文件字段列位置:D门店名(4)/E品牌(5)/I业务(9)/J兜底(10)/AB一店一群交车(28)/AE一店一群触客(31)。其余 D+ 列清空。
- **两个 openpyxl 大坑(务必记住)**:
1. **合并区只有锚点(左上)单元格可写**,写非锚点抛 `AttributeError: 'MergedCell' object attribute 'value' is read-only`。示例块 r6/r7 的 A/B/C/D/E/F/G/H/J/K..AF 均为两行合并(仅 I(业务)、Q、R 非合并)→ 所有值/清空只写 r_a(延保行),r_b 仅写 I(权益)/Q/R。合计行 r4/r5 同构(Q/R 非合并需单独清 r5)。
2. **`ws.insert_rows()` 只移动单元格值、不移动已合并区域**!模板的 `A10:AF10`/`A14:AF14`(品牌汇总标签行合并)不随插入下移,会压住新门店行,导致该行取值落入合并非锚点而“静默丢失”。**解法**:插入前先 `unmerge` 掉所有 `min_row>=8` 的合并区,插入后按 extra 偏移用 `get_column_letter` 重建。
- 端到端验证通过(临时脚本已清理):23 家 × 2 行=46 行正确展开(含 r10/r14 曾丢失已修复)、顺序/品牌(北汽极狐/北京越野)/兜底/一店一群值正确、示例块 D+ 列已清空、品牌汇总本月段 A=北汽 B=北汽 C=23 其余清空、合计行计算列清空、合并单元格 707 个。
- 样例结果表留存:`data-process/outputs/baic_special_2026-09_sample.xlsx`。后端重启(backend_baic2.log),baic_special_scan 调度正常。
## 修正:源文件末尾「售后门店数 / 售后场景开通率」汇总段(2026-09-20 下午)
- **更正上面第 7 条的判断**:源文件末尾 r52-54 **不是「纯标签段」**,而是品牌级汇总段,**带数值**:
r52 A='北汽品牌汇总'(品牌标签);r53 A='售后门店数' B=11;r54 A='售后场景开通率' B=22。
源文件「字段字典」页 r44/r45:两者均为**线上运营手工上传(品牌级,不按门店)**;售后场景开通率「运营直接上传比率值」。
- **单位口径**:结果模板该列格式为 `0.0%`(存小数),故源文件 `22` 需按百分数归一 → `0.22`。新增 `_to_rate()`:`|v|>1` 时 `÷100`,`|v|<=1` 原样。→ 落库 `after_sale_scene_open_rate=0.22000000`。
- **真实数据 bug(任务 900002 / month=2026-08 暴露)**:真实附件里这两行的「品牌」列位置有值('11'/'22'),旧守卫「brand 为空才跳过标签行」**拦不住** → 被当作门店落库(明细 25 行 = 23 店 + 2 条假门店,且 brand 写成 '11'/'22')。
- **正确解法**:在 `_parse` 里**标签优先**——先 `label == BRAND_SUMMARY_LABEL` / `label in SUMMARY_LABELS` 分支处理,再走门店行分支;末尾兜底守卫保留。常量:`BRAND_SUMMARY_LABEL='北汽品牌汇总'`、`SUMMARY_LABELS={'售后门店数':'after_sale_store_cnt','售后场景开通率':'after_sale_scene_open_rate','售后订单数':'after_sale_order_cnt'}`、`RATE_SUMMARY_ATTRS={'after_sale_scene_open_rate'}`。`_parse` 返回 `(detail_rows, (brand, summary_vals))`。
- `_save`:汇总行填 `after_sale_store_cnt` / `after_sale_scene_open_rate` / `after_sale_order_cnt`(源文件仅前两项有值)。
- `generate_result_excel`:品牌汇总本月段数据行**先清空 D..R,再回填 H(col8)=售后门店数 / I(col9)=售后场景开通率**(`0.0%` 格式自然保留)。注意清空范围 `range(4,19)` 含 8/9,必须**在清空之后**写入。
- **端到端验证通过(重跑真实任务 900002)**:明细 23 行(假门店已剔除)、汇总 `after_sale_store_cnt=11` / `after_sale_scene_open_rate=0.22`、结果表 r56 H=11 / I=0.22(格式 0.0%)、门店业务行 46=23×2。结果表留存 `outputs/baic_special_2026-08_task900002.xlsx`。后端重启(backend_baic3.log,端口 5001),两个专项调度正常。
## 北汽专项接入 D+ 门店基础信息(2026-09-20 傍晚)
- 用户提供 dj_smartcarlife 查询 SQL(`pg_group_store_rel` + `pg_group_info.group_name='北汽'` 为门店全集),本轮回填 5 个字段:门店编码 / 区域 / 驻店类型 / 业务开展 / 区域运营。
- **用户原 SQL 两处修正(已实施,需向其说明)**:
1. 「区域运营」子查询原**硬编码 `merchant_id=44214970`** → 所有门店都返回同一人「刘淑君」;改为按 `a.merchant_id` 关联(与 avita 的 `fetch_regional_operation` 同口径,director_type=9)。
2. 弃用 `DATE_FORMAT(x,'%Y-%m-%d')`——SQLAlchemy `text()` 参数化时 `%` 会与驱动绑定冲突;改为 `MIN(order_time)` 取原值,Python 侧 `_to_date()` 格式化(`_to_date` 已改为 datetime→`.date()`,避免 DATETIME 写 DATE 列)。
- 实现:`baic_special_processor.py` 新增 `_get_biz_engine()`(懒加载 `Config.BIZ_SQL_DATABASE_URL`)、`BAIC_STORE_INFO_SQL`、`fetch_baic_store_info()`(返回 `{merchant_name: {store_code,region,store_type,business_start_date,operator_name}}`);常量 `BAIC_GROUP_NAME='北汽'`、`DIRECT_SALE_PARTNER_ID=44206988`(partner_merchant_id 等于该值→直营,否则服务商)。
- `_parse` 末尾按**门店名称精确匹配**补充 D+ 字段并记录匹配率/未匹配名单;`_save` 写 `store_code/region/store_type/business_start_date/operator_name`(region/store_type 未匹配仍占位空串,NOT NULL);`generate_result_excel` 的 `KEEP` 扩为 `{1,2,3,4,5,6,7,9,10,28,31}`,回填 B 区域(2)/C 驻店类型(3)/F 运营(6)/G 业务开展(7)。
- **匹配率 19/23**(D+ 北汽组返回 24 家):源文件 4 家未命中——`乌海市新拓`/`沈阳鹏升` 在 `pg_group_store_rel` 中 `deleted_flag='D'`(被 `a.deleted_flag='N'` 过滤);`乌鲁木齐疆野`/`石河子隆庆` **未挂载到北汽项目组**(rel 无记录,但商户表存在)。反向有 5 家 D+ 有、源文件无:`新乡途悦`/`内蒙古林源致`/`新乡汇通达`/`宁夏金和信`/`伊犁金腾`(疑似新开店)。→ 已反馈用户,属业务数据待确认。
- 验证:抽样 4 家(山西瑞狐=山西省/直营/尚媛珍/2025-03-01/code 44214230;北京博瑞祥弘=北京市/服务商/王峰;北京真浩泰=直营/王峰;成都鹏龙兴元=四川省/直营/陈晓文)全部一致;结果表 r6/r8/r18/r20 的 B/C/F/G 正确、4 家未匹配行留空。
- **生产路径验证通过**:把 900002 置 PROCESSING,运行中的调度器 16:59:03 自动处理为 COMPLETED(明细 23、region 填充 19)→ 证明线上服务已加载新代码。
- **重要环境坑(务必记住)**:沙箱内 `kill` **无法终止**由**其它会话**启动的后台进程(报 `No such process`);本次发现 **3 个历史遗留后端实例同时 LISTENING 在 0.0.0.0:5001**(werkzeug 默认 SO_REUSEADDR 允许多进程绑同端口 → 请求可能命中旧代码)。清理方式:用 `TaskStop` 停掉自己启动的后台任务(旧的会以 task-notification failed 形式回执),确认 `netstat -ano | grep ":5001 "` 只剩自己的实例后再启动;宿主机侧 `Stop-Process` 看不到沙箱内进程。后端重启后建议用「置任务 PROCESSING + 看日志/DB 是否按新代码变化」来确认线上代码版本。
## 北汽专项接入 SCRM「驻店人员」(2026-09-20 傍晚)
- 数据源确认:`platform_*` 系列表在 **`scrm_account` 库**(`Config.SCRM_DATABASE_URL`,read_scrm_account @ 192.168.5.1:3310),**不在 dj_smartcarlife**。首次误用 BIZ_SQL 报 `Table 'dj_smartcarlife.platform_merchant_staff' doesn't exist`。
- **关键坑:驻店人员角色配在「园区店」商户上,不在品牌门店商户上。** 直接拿北汽门店编码(如 44214230)按用户原 SQL 查 → **恒为空**(北汽门店在 scrm 只挂「超级管理员/系统默认角色」);用户示例编码 44218107 在 scrm 里根本不存在。
正确链路:北汽门店 `merchant_id` → `dj_car_life_scene_merchant_ref.sub_merchant_id`(main_merchant_type=2, sub_merchant_type IN (6,8), scene=0)= **园区店** → 到 scrm_account 按 `platform_merchant.merchantNo` 查 `role_name='驻店人员'`。
验证:24 家门店全部有对应园区店、园区店编码 100% 命中 scrm、共 74 人次;「驻店人员」角色全库配在 2314 个商户上(8175 条关联)。
- 实现:`baic_special_processor.py` 新增 `_get_scrm_engine()`、`RESIDENT_STAFF_SQL`、`fetch_resident_staff(park_codes)`(返回 `{park_code: [name,...]}`,跨库查询,失败仅告警返回 `{}`);`BAIC_STORE_INFO_SQL` **新增 `park_merchant_ids` 子查询列**(`GROUP_CONCAT(DISTINCT d.sub_merchant_id)`,原 left join d/e 保持不动以免影响 store_type);`fetch_baic_store_info` 聚合 park codes → 调 `fetch_resident_staff` → 回填 `resident_staff`(**多人以「/」分隔**,字段字典口径;截断 255 适配列长)。
- `_save` 写 `resident_staff`(该列 `varchar(255)` 已存在于真实表);`generate_result_excel` 的 `KEEP` 扩为 `{1,2,3,4,5,6,7,8,9,10,28,31}`,`_set_cell(ws, r_a, 8, d.resident_staff)` 回填 **H 列驻店人员**(字段字典 r9:原表 J → 模板 H)。
- **端到端验证通过(重跑真实任务 900002 / 2026-08)**:明细 23 行、`resident_staff` 非空 **18 行**(5 家未匹配门店无 code → 无驻店人员);结果表 r6..r50 的 H 列正确(如 山西瑞狐=马梅子、上海昊府=上官飞、成都鹏龙兴元=陈晓文/何明勇/胡泽涛/王曦)。
- **生产路径验证通过**:置 900002 为 PROCESSING,调度器 17:10:03 自动处理,日志含 `SCRM 驻店人员:24 个园区店编码 → 命中 22 个、共 74 人次`。后端重启(backend_baic5.log,PID 16240,端口 5001),两个专项调度正常。
- 数据质量问题(保留原值未清洗,需用户确认):宁夏荣越达的驻店人员里混入一个 `1`(staff_name='1',脏数据);秦皇岛昱拓有 store_code 但园区店未配驻店人员 → 留空。
# 2026-09-21 工作记录
## 北汽专项:新增广联报表(dj.glsx.com.cn)取数源
- 新增 `fetch_glsx_report(stat_month)`(baic_special_processor.py):`queryAllExcel?filename={月}&business_type=yanbao&report_type=yanbaoMerAndPerRanking` 取 filename 含「通用品牌」的 key → `download?key=` 取 `data.list[0].url` → GET 下载 xlsx 解析 Sheet1(表头 col0=='业务类型')。
- 报表结构:每个门店分段 = 业务行(如 2.3延保, C列带门店名, H/K/O 带值) → 多条人员行(仅 O 有值, C 空) → 延保小计/权益小计 小计行(A 标签, H/K/O 带值, C 可能空 → 门店名从上一业务行**向前携带**)。
- 取值口径(按门店名精确匹配源文件):
- `output_target_wan`(K产值目标) ← 延保小计行 H(8月目标产值(万元))
- `new_delivery_cnt`(N新车交付数) ← 非小计行 K(累计交付数(台)),同店多条取 max
- `visit_cnt`(O触客数) ← 非小计行 O(实际售前触客数),同店多条取 max
- `delivery_check_output_cnt`(AA交车数核对-产值表) ← 延保小计行 K
- `visit_check_output_cnt`(AD触客数核对-产值表) ← 延保小计行 O
- DB 列(baic_special_month_data)早已存在(output_target_wan/new_delivery_cnt/visit_cnt/delivery_check_output_cnt/visit_check_output_cnt),本次仅接线填充;结果表模板 r3 对应 K/N/O/AA/AD 列,KEEP 集合加入 {11,14,15,27,30}。
- 验证(重跑真实任务 900002 / 2026-08):广联报表解析 214 门店,北汽 19/23 精确匹配(源全名一致);落库 output_target_wan 非空 18(石河子市隆庆在报表但其延保小计 H 为空→目标 NULL,符合数据)、其余 4 列非空 19;未匹配 4 家(北京博瑞祥弘/沈阳鹏升/乌鲁木齐疆野/濮阳市欣驰,业务数据缺口)留 NULL。生产路径已验证(置 PROCESSING,调度器 12:08 自动处理含广联报表日志)。
- ✅ 口径已确认(用户 2026-09-21 13:43 明确):**visit_cnt(触客数系统)= 单人 max**(非小计人员行 O 取最大值,即同店单人最大触客数);**visit_check_output_cnt(触客数核对-产值表)= 门店合计**(延保小计行 O)。两者本就语义不同,正是预期(成都鹏龙兴元 4 / 119;山西瑞狐 34 / 34)。原有实现已正确,无需改代码。
- 后端重启(backend_baic6.log,PID 12472,端口 5001),旧实例 16240 已清理。
## 北汽专项:结果表「差异」列(AC/AF)
- 口径(用户 2026-09-21 明确):**交车数核对-差异(AC) = 交车数核对-产值表(AA) − 交车数核对-一店一群(AB)**;**触客数核对-差异(AF) = 触客数核对-产值表(AD) − 触客数核对-一店一群(AE)**。任一侧为空则差异留空。
- 列索引(1-based):AA=27(delivery_check_output_cnt) AB=28(delivery_check_group_cnt) **AC=29(差异)** AD=30(visit_check_output_cnt) AE=31(visit_check_group_cnt) **AF=32(差异)**;表头为三行结构(行1大类/行2子字段/行3+数据),门店名在 col4(D)。
- 实现:新增 `_diff(a,b)`(任一侧 None → None),`_fill_block` 在写完 AA/AB/AD/AE 后写 29/32;`KEEP` 加入 29、32(否则被「非 KEEP 列清空」循环抹掉)。
- 验证(重跑 900002/2026-08):23 家明细,差异与「产值表−一店一群」逐行一致(26 行含重复业务行,0 不符)。样例:成都鹏龙兴元 交车 94−83=11、触客 119−83=36;包头欢腾 11/45;山西瑞狐 −7/−5。
- ⚠️ 踩坑记录(重要):
1. `generate_result_excel` 内部是 `from oss_utils import upload_file` 的**局部名**,猴子补丁必须重绑 `baic_special_processor.upload_file`,只改 `oss_utils.upload_file` 无效。
2. 本地预览文件名不统一:处理器 OSS object_key 为 `baic_special_{YYYY-MM}_{task_id}.xlsx`(无 task),而预览文件是 `baic_special_{YYYY-MM}_task{task_id}.xlsx`(有 task)。曾因此验证读到旧文件误判「差异写入失败」。**本地输出统一用 `_task{id}.xlsx`**。
3. 验证 openpyxl 需带 `data_only=True`;带/不带结果一致。
- 后端重启(backend_baic7.log,FLASK_PORT=5001,新代码),旧实例 12472 已清理;调度器扫描 0 个待处理(900002 已 COMPLETED)。
## 北汽专项:差异值落库 baic_special_month_data(补漏)
- 用户反馈「baic_special_month_data 表差异值未保存」。根因:`_save` 只写了 `delivery_check_output_cnt/group_cnt`、`visit_check_output_cnt/group_cnt`,**从未给 `delivery_check_diff` / `visit_check_diff` 赋值**(差异只在 `generate_result_excel` 里用 `_diff()` 临时算,不落库)。真实表两列已存在(`int(11)`,注释「交车数核对差异=产值表-一店一群」/「触客数核对差异=产值表-一店一群」)。
- 修复:`_save` 循环内先 `_to_int` 归一 4 个核对值(dc_output/dc_group/vc_output/vc_group),ORM 用归一值,并写 `delivery_check_diff=_diff(dc_output, dc_group)`、`visit_check_diff=_diff(vc_output, vc_group)`。与结果表 AC/AF 列同一 `_diff` 口径,保证 DB 与 Excel 一致。
- 验证(重跑 900002):活跃明细 23 行,`delivery_check_diff`/`visit_check_diff` **非空各 19/23**(4 家产值表未匹配→留 NULL,符合口径),逐行 = 产值表−一店一群,**0 不符**;本地预览 `outputs/baic_special_2026-08_task900002.xlsx` 同步刷新且与 DB 一致。
- 注意:`baic_special_month_data` 用软删除,每次重跑会累积 is_deleted=1 的历史行(900002 累计 604 行 → 活跃 23 行),读表必须 `filter_by(is_deleted=0)`。
- 后端重启(backend_baic8.log,PID 11892,端口 5001);发现同时存在两个 `app.py` 实例(30304/34604,疑为 Flask debug reloader 父子进程),已一并清理后启单实例,调度器扫描 0 个待处理。
## 北汽专项:评灯标准(优秀值/标准值/预警值)按品牌取值
- 用户口径(2026-09-21):**品牌=北汽极狐 → 0.5 / 0.3 / 0.3;品牌=北京越野 → 0.5 / 0.4 / 0.4**(源文件与系统均不提供,固定规则)。
- 新增模块常量 `LIGHT_STANDARD_BY_BRAND` + `_light_standard(brand)`(品牌未匹配返回 (None,None,None))。
- 落库:`_save` 按 `rec['brand']` 写 `excellent_value` / `standard_value` / `warning_value`(DECIMAL(10,6),经 `_to_dec`)。
- 结果表:`_fill_block` 写 col24(X 优秀值)/25(Y 标准值)/26(Z 预警值),**`KEEP` 必须含 24、25、26**(否则被「非 KEEP 列清空」抹掉)。列位置:row2 大类「评灯标准」在 col24,row3 子表头 col24=优秀值/25=标准值/26=预警值。
- 验证(重跑 900002):`brand` 分布 北汽极狐 12 家 / 北京越野 11 家;DB 23/23 取值正确、**0 不符**;Excel X/Y/Z 与 DB 逐行一致 23/23。
- 后端:debug reloader 已自动重载新代码,但文件最终写入晚于最后一次 reload → 做干净重启(backend_baic9.log,PID 12136,端口 5001)。**坑**:停旧实例后其 reloader 子进程会变孤儿继续占端口(本次为 33356),需按 `ParentProcessId` 找孤儿并清掉,最终确认只剩 1 对父子进程、netstat 仅 1 个 LISTENING。
## 北汽专项:截止目前产值 + 达成率(D+ 支付成功金额)
- 用户口径(2026-09-21):截止目前产值 = 指定 SQL 的 `SUM(b.actual_money)`(`dj_car_life_goods_order a` LEFT JOIN `dj_car_life_pay_order b` ON `b.order_code=a.order_code AND b.deleted_flag='N' AND b.pay_status=2`,条件 `a.deleted_flag='N' AND a.merchant_id=门店编码 AND a.scene_type=0 AND a.business_type=2 AND b.success_date ∈ [周期起, 周期止+1天)`);**merchant_id = 门店 D+ 编码(store_code)**、success_date = 任务周期,其余参数不变。**达成率 = 截止目前产值 ÷ 产值目标**。
- 量纲:`actual_money` 是**元**,写入「截止目前产值(万)」需 **/10000**(实测 山西瑞狐 66037 元→6.6037 万,目标 9.6 万→达成率 68.8%,量级吻合)。模板 col12 `0.00`(万元)、col13 `0.0%`(小数比率),模板示例 8.0988/12=0.6749 正好印证公式。
- 实现:`BAIC_OUTPUT_CURRENT_SQL`(改为 `GROUP BY a.merchant_id` + `IN :merchant_ids` 一次查全,SQLAlchemy 2.0 需 `bindparam('merchant_ids', expanding=True)`)+ `fetch_output_current(period_start, period_end, merchant_ids)`(元→万元,4 位 Decimal);新增 `_task_period(task)`(优先 period_start/period_end,缺失按 month 推整月);`_parse` 在 D+ 基础信息与广联报表**之后**补产值(依赖 store_code 与 output_target_wan);`_save` 写 `output_current_wan` / `achievement_rate`;`_fill_block` 写 col12/13,**`KEEP` 补入 12、13**。`from datetime import ... timedelta`、`from sqlalchemy import ... bindparam` 已补。
- 验证(重跑 900002,周期 2026-08-01~2026-08-31):门店 23 家、有 store_code 19 家,产值**命中 18/19**(仅濮阳欣驰无数据,且它也无产值目标);**DB 23/23 一致 0 不符**(达成率逐行 = 产值/目标);Excel L/M 列与 DB 逐行一致 23/23,格式 `0.00`/`0.0%` 保留。无数据门店留 NULL(不臆造 0)。
- 后端:改为 **`FLASK_DEBUG=false` 单进程启动**(backend_baic10.log,PID 36132,端口 5001)——此前 debug reloader 反复重启会在端口上留下**孤儿 app.py 进程**(同一 5001 出现 2 个 LISTENING、调度器重复扫描),关掉 reloader 后 netstat 仅 1 个 LISTENING。**注意**:关闭后改代码必须手动重启后端才会生效。
## 北汽专项:触客率(= 触客数 ÷ 新车交付数)
- 用户口径(2026-09-21):**触客率 = 触客数(visit_cnt) ÷ 新车交付数(new_delivery_cnt)**,均为广联报表口径(非小计行,同店取 max)。附:这两个值本就是非小计行,所以触客率实际就是「单人最高触客数 ÷ 门店新车交付数」。
- 实现:新增 `_ratio(a, b)`(任一侧为空或分母 0 → NULL,返回 Decimal 无量纲小数,模板 `0.0%` 格式);`_parse` 在广联报表匹配**之后**逐行算 `rec['visit_rate']`;`_save` 写 `visit_rate`(真实列 `decimal(18,8)`);`_fill_block` 写 col16,**`KEEP` 补入 16**。
- 验证(重跑 900002):**DB 23/23 校验一致 0 不符**(=触客数/新车交付数);Excel P 列与 DB 逐行一致;**非空 18/23**,留空 5 家=广联未匹配 4 家(北京博瑞祥弘/沈阳鹏升/乌鲁木齐疆野/濮阳欣驰)+ 石河子隆庆(新车交付=0,防除零)。样例:山西瑞狐 34/48=70.8%、通辽惠都 132/135=97.8%、包头欢腾 3/84=3.6%、秦皇岛昱拓 24/19=126.3%。
- **踩坑记录(重要)**:并行对**同一文件**发多个 Edit 会互相覆盖——本次 `_ratio` 定义与 `KEEP` 补 16 两个编辑均静默丢失(Edit 返回成功但内容未落盘),必须先 grep 回读确认再继续。另外,`baic_special_month_data` **主键是 `store_id`**(不是 id)。
- 后端重启(backend_baic11.log,PID 35956,端口 5001,`FLASK_DEBUG=false` 单进程),旧实例 36132 已清理。
# 2026-09-22 工作日志
## 北汽专项(data-report / baic_special)
- 接入「触客率」:`触客率 = 触客数(visit_cnt) ÷ 新车交付数(new_delivery_cnt)`,量纲为无量纲小数(模板 `0.0%`)。
- 新增 `_ratio(a, b)`(任一侧为空或分母 0 → NULL);`_parse` 在广联报表匹配后逐行计算;`_save` 写 `visit_rate`;`_fill_block` 写 col16 且 `KEEP` 补 16。
- 重跑 900002 验证:DB 23/23 一致 0 不符;Excel P 列与 DB 逐行一致;非空 18/23(留空=广联未匹配 4 家 + 石河子隆庆新车交付数=0)。
- **坑记录(重要)**:同一文件在同一批次并行发多个 Edit 会**静默互相覆盖**(返回成功但未落盘)——本次 `_ratio` 定义与 `KEEP` 补 16 两次编辑均丢失,需 grep 回读复查。另:`baic_special_month_data` 主键为 `store_id`(非 id)。
- 后端:`backend_baic11.log`(PID 35956,端口 5001,`FLASK_DEBUG=false` 单进程)。
## 店效人效及盈利测算:豪华品牌判定行为核实(只读排查,未改代码)
- 用户问:`config_brand_category` 里一行写 `阿维塔、长安、长城、哈弗、欧拉、坦克`,是否按分隔符拆开匹配。
- 结论:**不拆分**,整行作为 1 个 key;但 `brand_category()` 用**双向子串包含**,门店品牌是该整串子串 → 仍判为豪华(歪打正着)。详见 `MEMORY.md` 新增条目(含最长匹配抢占风险、两条链路口径不一致、`哈弗` 仅靠该串兜底等)。
## 店效人效 board(task 32 / 2026-08)非豪华门店排查
- 用户称「非豪华门店数量=1」。实测当前 board 输出 `门店店效人效汇总表_2026-08.xlsx`:**非豪华门店数量=2**(不是 1),**非豪华直营门店数=1**。
- 2 家非豪华均为品牌=宝马:`内蒙古新弗汽车服务有限公司`(直营/存量)、`文山德宝通汽车销售服务有限公司`(空驻店/新增)。
- 唯一=1 的"非豪华*"指标是 **非豪华直营门店数=1 → 内蒙古新弗汽车服务有限公司(宝马/直营/存量)**。
- 根因:`config_brand_category` 现已 69 行,但**无"宝马/BMW"**,故宝马默认判非豪华。宝马属豪华品牌,疑似漏配,需补入配置。
- **大小写 vs 子串澄清**:`brand_category()` 精确 key 区分大小写("奇瑞icar" 不命中 "奇瑞ICAR");但配置另有更短 key "奇瑞"(category=豪华),"奇瑞" 是 "奇瑞ICAR" 的子串 → 模糊命中判豪华。所以"奇瑞ICAR"判豪华**不是因为不区分大小写,而是被"奇瑞"前缀 key 兜住**。`config_brand_category` 69 行 category 全为"豪华"(含奇瑞/大众/比亚迪/广汽丰田/长安等走量品牌),属"豪华清单"语义;真正的非豪华缺口仅宝马缺失。
## 北汽专项:截止目前产值 SQL 新增条件(2026-09-22 改码)
- `BAIC_OUTPUT_CURRENT_SQL`(`baic_special_processor.py`)WHERE 新增 `AND a.status = 4`(a=dj_car_life_goods_order,仅 status=4 的订单计入「截止目前产值」)。同步更新文件头注释口径说明。
- 影响:仅对 status≠4 的 goods_order 行剔除,会**降低**部分门店「截止目前产值」及达成率。需重跑任务 900002(并重启后端单进程 backend_baic11)才生效落库。
## 北汽专项:订单数统计(延保/权益)接入(2026-09-22 改码)
- 新增 `BAIC_ORDER_COUNT_SQL` + `fetch_order_count`(dj_smartcarlife,按 merchant_id + goods_type_name 分组):
`dj_car_life_goods_sub_order gso` LEFT JOIN `dj_car_life_goods_order a`(deleted_flag=N) LEFT JOIN `dj_car_life_pay_order b`(deleted_flag=N, pay_status=2);
WHERE `gso.deleted_flag='N' AND a.merchant_id IN :ids AND a.scene_type=0 AND a.business_type=2 AND a.status=4 AND b.success_date ∈ [周期起, 周期止+1天)`;
映射 `整车延保`→延保(业务类型1)、`原厂权益`→权益(业务类型2),其余忽略。
- 落库:`baic_special_monthly_business`(预留表,逐门店×业务:store_id 外键 + business_type + order_cnt)。`_save` 在 `add_all(detail_objs)` 后 `flush` 拿 store_id,再先按本任务旧 store_id 删旧业务行、插新行(物理删,因该表无 is_deleted);并在写前 `BaicSpecialMonthlyBusiness.__table__.create(db.engine, checkfirst=True)` 兜底建表。
- 结果表(模板 Q=17 订单数):每家拆延保行(r_a)/权益行(r_b),Q 列分别写整车延保/原厂权益订单数;合计行 r4(延保)/r5(权益) 按业务类型求和。KEEP 集合补 17。
- 业务类型编码常量:`BAIC_BIZ_EXT_WARRANTY=1 / BAIC_BIZ_RIGHTS=2`,映射 `ORDER_CNT_TYPE_MAP`、标签 `BIZ_TYPE_LABEL`。
## 北汽专项:订单数未显示(重跑踩坑,已修复 2026-09-22)
- 用户重跑后「结果表订单数未显示」。根因有两层:
1. **孤儿后端**:重跑命中旧后端进程(PID 35956,09-21 启动,不含订单数代码)。`netstat` 在 5001 上出现 35956+35148 两个 LISTENING(Windows SO_REUSEADDR 允许多实例绑同端口)。已 `taskkill` 两个孤儿,重启单进程后端 `backend_baic12.log`(PID 26288,`FLASK_DEBUG=false`)。
2. **本地预览文件名不匹配**:`generate_result_excel` 原来只上传 OSS(object_key `baic_special_{month}_{task_id}.xlsx`,不带 _task);本地预览文件实为 `baic_special_{month}_task{task_id}.xlsx`(带 _task,用户正在预览)。新增的本地落盘最初也写成了不带 _task 的名字 → 预览文件未更新。已改为本地落盘写 `baic_special_{month}_task{task_id}.xlsx`(与预览对齐),OSS object_key 维持不带 _task。
- 验证:重跑 900002 后,预览文件 Q 列(订单数)已正确显示——合计 延保=157 / 权益=222;山西瑞狐 延保=7 权益=10;北京博瑞祥弘 延保=49;逐门店合计与合计行一致。DB `baic_special_monthly_business` 29 行(18 家命中,延保有值 14 家 / 权益有值 15 家)。
- **环境要点**:flask 装在用户 site-packages `C:/Users/66/AppData/Roaming/Python/Python314/site-packages`,沙箱会剥离该路径导致 `import flask` 失败;独立重跑脚本须 `dangerouslyDisableSandbox=true` 或 `PYTHONPATH=...` 该路径并以 `C:/Python314/python.exe` 运行。后端即以此 python 启动。
## 北汽专项:渗透率(交车渗透率 R=18 / 综合渗透 S=19)接入(2026-09-22 改码)
- 新增 `_penetration(order_cnt, delivery)`(分母空/0/非数→NULL;分子缺失按 0)。
- 口径:**交车渗透率(R=18) = 本行订单数 ÷ 新车交付数(N=14)**;**综合渗透(S=19) = (延保订单数 + 权益订单数) ÷ 新车交付数**(门店级,两行同值)。
- `_fill_block`:延保行(r_a)写 R=`_penetration(ext_cnt, new_delivery)`、S=`_penetration(ext+rights, new_delivery)`;权益行(r_b)写 R=`_penetration(rights_cnt, new_delivery)`(S 不写,见下坑)。合计行 r4=延保、r5=权益:R 各写本业务合计÷总交付,S 仅写 r4(锚点)。KEEP 补 18、19。
- **坑:MergedCell 只读**。模板 S 列(19) 是「延保/权益两行合并」的只读格(`r6/r7` 与 `r4/r5` 合并范围均含 col19,不含 col17/18)。往 r_b/r5(被合并行)写 S 触发 `'MergedCell' object attribute 'value' is read-only`。修复:S 只写锚点行 r_a/r4,合并区在 Excel 中自动把门店级同值显示到 r_b/r5。R(18) 不在合并,两行都可写。
- **坑:OSS 上传崩溃阻断本地落盘**。原 `generate_result_excel` 末尾 `url = upload_file(...)` 若抛异常(如本次临时 OSS 抖动)导致 `return url` 处 `url` 未绑定 → UnboundLocalError → `process` 标记任务 FAILED 且本地副本未刷新。已改为:**本地落盘 `baic_special_{month}_task{task_id}.xlsx` 移到 upload_file 之前且不再 try 包裹**;upload_file 包 try(失败仅 warn,不阻断),函数仍 return(url 默认 '')。
- 重跑 900002(直接 `BaicSpecialProcessor().process(task)` 独立重跑,非靠后端)验证通过:山西瑞狐 延保 R=0.1458 S=0.3542、权益 R=0.2083;合计 R=0.1809 S=0.4366;北京博瑞祥弘因广联未匹配 N 为空 → R/S 留空(符合预期)。文件 mtime 已更新至 15:02。
# 2026-09-24
## 北汽报表新增周度评灯(W1/W2/W3/截止目前)
- 分支:v1.2(北汽代码在 v1.2 分支,`baic_special_processor.py` 在切分支后才在磁盘出现)。
- 需求:结果表「门店等级」四列 T/U/V/W(20/21/22/23)=截止目前/W1/W2/W3。按门店当月该周**综合渗透**判灯:
综合渗透 > 优秀值(X,小数)→绿(#C6EFCE);> 标准值(Y,小数)→黄(#FFEB9C);否则→红(#FFC7CE)。
**关键坑(用户明确提醒)**:评灯标准显示是小数非百分比,与综合渗透同为单位小数,**直接比较、勿×100/勿÷100**。
- 综合渗透(节点) = 当月累计(延保+权益)订单数 ÷ 新车交付数(全月分母固定);
W1/W2/W3 订单数取「截止到当前周」累计(窗口起点=当月1号,上界=各周结束日+1天),截止目前上界=cutoff_date。
- 实现(`baic_special_processor.py`):
- 新增 `fetch_order_count_window(period_start, period_end, codes)`(复用 BAIC_ORDER_COUNT_SQL);
- `compute_baic_week_ends(month, cutoff_date)` 周规则=当月首个周一起 W1,每周一~周日(与 app.compute_week_period 一致)→ W1/W2/W3 结束日;
- `_baic_light(pen, exc, std)` 判灯(std 为 None 或无渗透率 → 返回 None 不显灯);
- `generate_result_excel` 在 `_fill_block` 写 T/U/V/W(绿/黄/红文字+底色),**无灯时显式 `PatternFill(fill_type='none')` 清模板残留底色**(否则 None 门店会误显模板黄底);合计行 r4 写各节点聚合综合渗透(数值、无灯色)。
- 验证:task 900002 重跑(`regen_baic900002.py`,沙箱外 `dangerouslyDisableSandbox`),结果表 outputs/baic_special_2026-08_task900002.xlsx:
合计 r4 聚合综合渗透 T=0.437/U=0.138/V=0.236/W=0.323(W1<W2<W3<截止目前,符合累计);门店灯 绿11/黄13/红48,None 无残留底色。OSS 已上传(20260924 路径)。
- 模板 exporttemplete/baic_special_report_template.xlsx 列位:X/Y/Z(24/25/26)=优秀/标准/预警值;T/U/V/W(20-23)=周度灯(列头已存在,代码接入填充)。
## 北汽周度数据定时快照(W1/W2/W3 订单数+新车交付数落库)
- 需求:W1/W2/W3 的**订单数**和**新车交付数**新增为 `baic_special_month_data` 持久化字段,由**每周最后一天(周日)定时任务**去产值报表拉取保存(渲染仍现算,落库仅为快照)。
- 已对齐口径:仅 6 个周度字段;写「本月最新一条」baic_special 任务(month=当前月、最新 id、有明细);周日触发;渲染不改读存储字段。
- 改动:
- `models.py` BaicSpecialMonthData 新增 6 列:`w1/w2/w3_order_cnt`、`w1/w2/w3_new_delivery_cnt`(INT 可空)。
- 真实表已 ALTER ADD 这 6 列(data_report.baic_special_month_data,`tmp_alter_baic_wk.py` 先查后加,幂等)。
- `baic_special_processor.py` 新增 `scan_baic_weekly()`:today→算 week_n(1-3,基于当月首个周一;>3 或 <1 跳过);拉 `fetch_glsx_report`(交付,门店名匹配) + `fetch_order_count_window(当月1号, 本周日, codes)`(订单);写 `w{n}_order_cnt`(延保+权益累计) / `w{n}_new_delivery_cnt`;db.commit。
- `scheduler.py` 新增 `BaicWeeklySnapshotScheduler(NewReportScheduler)`:CronTrigger(day_of_week='sun', hour=23, minute=0),`_execute_scan` 调 `scan_baic_weekly()`;无 apscheduler 时后备每日线程检查周日。
- `app.py` import + 实例化 `baic_weekly_snapshot_scheduler` + 注册进 `ALL_SCHEDULERS`(后端 `__main__` 块自动 start 全部调度器)。
- 关键坑(已修):订单窗口上界公式初写 `6*(n-1)+6` 算成 W2=08-15/W3=08-21,**各少 1 天**(漏算当周周日订单);正确为 `7*(n-1)+6`(W2=08-16/W3=08-23),与 `compute_baic_week_ends` 节点结束日一致。
- 验证:py_compile 全过;周N逻辑自测(8/9→W1, 8/16→W2, 8/23→W3, 8/30→跳过);实跑 scan_baic_weekly(当前 2026-09 无任务→安全 skip no_task);对 900002 做 rollback 不提交演练(23 行、广联报表命中214/订单窗口18家,各店 w3 值正确如 山西瑞狐 订单15/交付48)。
- 运维:改了 scheduler.py/app.py,需重启后端(当前 5001 空闲,原 PID 26288 的后台任务已被沙箱回收)新调度器才生效。
## 广联日快照基础表(每日拉取「门店产值及个人成交排名」的延保小计/权益小计)
- 需求:新增**每日定时任务**,每天拉取**昨天**的广联「门店产值及个人成交排名」数据,仅保存**延保小计/权益小计**数据。
- 用户口径确认(关键):①**与任何报表类型/任务无关,是独立基础表**(不挂 DataProcessTask);②保存**粒度=仅按门店**;③保存**全部数据**(延保小计/权益小计两小计行的全量字段,非单一指标)。
- 数据源:`dj.glsx.com.cn/reportExport`,`business_type=yanbao&report_type=yanbaoMerAndPerRanking`,取 filename 含「通用品牌」的报表(**月文件**,故「昨天」→ 用**昨天所在月**做 filename,月初跨月自动取上月)。报表为**门店分段**结构:业务类型行 → 人员行 → `延保小计`/`权益小计` 小计行。
- **报表真实结构(2026-09 实测,表头列位)**:业务类型(0)/区域省份(1)/门店(2)/…/`9月目标产值(万元)`(7)/`实际完成产值(万元)`(8)/`累计交付数(台)`(10)/`实际售前触客数`(14)/…/`整车延保成交数`(21)/`原厂权益成交数`(25)/`广联权益成交数`(27)。
- ⚠ 门店小计行的 **`目标产值`(col7) 为空**,实为 **`实际完成产值`(col8)** 有值 → 故存 `actual_output_wan`(实际完成产值),不存目标产值。
- `延保小计` 行带 `整车延保成交数`(21) + `原厂权益成交数`(25);`权益小计` 行带 `广联权益成交数`(27) → 两个「权益」口径都存。
- 改动:
- `models.py` 新增独立基础表 `GlsxDailyDealSubtotal`(`glsx_daily_deal_subtotal`)列:`stat_date` / `store_name` / `ext_warranty_deal_count`(整车延保成交数) / `rights_deal_count`(原厂权益成交数) / `gl_rights_deal_count`(广联权益成交数) / `actual_output_wan`(实际完成产值万) / `delivery_cnt`(累计交付数) / `visit_cnt`(实际售前触客数) / `is_deleted` / `created_at` / `updated_at`。
- 真实表已建(`__table__.create(checkfirst=True)`),并 ALTER 把 `output_target_wan` CHANGE 为 `actual_output_wan` + ADD `gl_rights_deal_count`。
- 新模块 `glsx_daily_processor.py`(**独立、不耦合 baic/avita**):`_download_glsx_rows(月)`(列表→定位通用品牌→下载→返回 rows+表头行)、`fetch_daily_deal_subtotals(月)`(**按列名归一后定位**,不依赖固定列号;门店名靠 `门店` 列向前携带;延保小计行取 ext/rights/actual/交付/触客,权益小计行取广联权益)、`scan_glsx_daily()`(昨天=今-1天;月=昨天所在月;按 `stat_date` **先软删旧行再插新行** 幂等)。
- `scheduler.py` 新增 `GlsxDailyScheduler(NewReportScheduler)`:`CronTrigger(hour=2, minute=0)` **每日 02:00**,`_execute_scan` 调 `scan_glsx_daily()`;无 apscheduler 时后备每日线程。
- `app.py` import + 实例化 `glsx_daily_scheduler` + 注册 `('glsx_daily', ...)` 进 `ALL_SCHEDULERS`。
- 验证:py_compile 全过;`scan_glsx_daily()` 实跑 → **2026-09-23 落库 184 家门店**(幂等:软删旧 184 行后重插);字段非空命中 ext/rights/gl_rights/交付/触客=184/184,实际产值 128/184(其余小计行无产值);合计 延保成交=1146、原厂权益=272、广联权益=679、实际产值=795.10万、交付=4981、触客=3644。预览导出 `outputs/glsx_daily_deal_subtotal_2026-09-23.xlsx`。
- 注:`scan_glsx_daily()` **内部 commit**,故「dry-run」会真实落库(本次即留下 2026-09-23 的 184 行——即真实快照,幂等重跑会刷新)。
- 运维:改了 scheduler.py/app.py/models.py,**需重启后端**新调度器(每日 02:00)才生效。
## 北汽周度综合渗透分母改取日快照(W1/W2/W3)
- 需求(用户 2026-09-24):W1/W2/W3 综合渗透公式中——**分子订单数实时查 D+**(不变),**分母新车交付数(累计交付数) 改从 `glsx_daily_deal_subtotal` 表查**。
- 已对齐口径:①**T(截止目前) 保持全月实时 `new_delivery_cnt`**,只改 W1/W2/W3;②快照缺失(该周结束日无日快照)→ 该周渗透**留空且不评灯**(不显任何底色)。
- 实现(`baic_special_processor.py`):
- import 增加 `GlsxDailyDealSubtotal`;
- 新增 `fetch_delivery_snapshot_by_dates(stat_dates)` → `{stat_date: {store_name: delivery_cnt}}`(filter `stat_date IN ds AND is_deleted=0`;缺失日期不出现在结果中;异常返回 `{}` 不致命);
- `generate_result_excel`:`week_nodes` 后构造 `week_delivery_by_node`(j=0 为 None=用全月实时值,j≥1 为该周结束日快照 dict);
- `_fill_block`:`node_delivery = new_delivery if j==0 else _snap.get(d.store_name)` → `_penetration(comb_node, node_delivery)`;
- 合计行 r4:`node_delivery_total = total_delivery if j==0 else sum(_snap.get(d.store_name) or 0 for d in details)`。
- 验证:py_compile 过;`fetch_delivery_snapshot_by_dates([2026-08-09/16/23])` → `{}`(无 8 月快照);`[2026-09-23]` → 184 家。
- **关键发现(门店名匹配)**:北汽明细 23 家中仅 **17 家**能命中「通用品牌」报表快照,6 家不在该报表内(北京博瑞祥弘/乌海市新拓/沈阳鹏升/乌鲁木齐疆野/石河子市隆庆/濮阳市欣驰)→ 这些门店 W1/W2/W3 将永久留空(与既有"通用品牌报表不含全部北汽门店"一致)。
- 重跑 900002 实测:合计 T=0.4366(不变)、**U/V/W 均 None**(8 月无日快照 → 留空,符合约定);门店 T 绿5/黄5/红8、W1/W2/W3 全 None 且无底色。
- 注入假快照演练(patch `fetch_delivery_snapshot_by_dates` + `upload_file` 为 no-op,验后还原文件):U=0.1948/V=0.3328/W=0.4545,灯色 绿/黄/红齐现,6 家无快照门店正确留空 → 主路径正常。
- ⚠ 遗留不一致(待用户定夺):`scan_baic_weekly()` 落库的 `w{n}_new_delivery_cnt` 仍取 `fetch_glsx_report` 的**全月** `new_delivery_cnt`,与本次新渲染口径(周快照)已不一致。
- ⚠ 运维:改了 `baic_special_processor.py`,**需重启后端**(前端触发或调度才用新码)。
## 北汽 W1/W2/W3 合计行口径 BUG 修复(用户 8 月真实数据验证时暴露)
- 背景:用户往 `glsx_daily_deal_subtotal` 手插一条 `stat_date=2026-08-09`(8月W1周结束日)的快照用于验证,第一次门店名写成「岚图汽车销售服务有限公司武汉分公司」(非北汽门店 → 精确匹配 0 家,W1 仍留空);改名「山西瑞狐汽车销售有限公司」(900002 第1家, store_code=44214230, 交付=10)后生效。
- **暴露的 BUG**:合计行 r4 的 U(W1) 算出 **12**(渗透率 >1 显然错误)。根因——**分子分母门店集合不一致**:
- 分子 `ec_total/rc_total` 统计**所有有 store_code 的门店**(19 家,W1订单合计=120);
- 分母 `node_delivery_total` 只统计**该周有快照的门店**(1 家,交付=10)→ 120÷10=12。
- **修复**(`baic_special_processor.py` 合计行 r4 循环):W1/W2/W3 分子分母统一取「该周结束日**有快照 delivery_cnt** 且**有 store_code**」的门店集合 `_univ`;T(j=0) 维持原口径(分子=有 store_code 的门店、分母=全月交付合计,二者均遍历全部 details → 自洽,无需改)。
- **口径备忘**:合计行 Q/R/S/T 的 Q=R/S/T 分子分母都遍历**全部 details**(无值按 0),因此自洽;只有"按周快照"引入的分母是子集,必须同步收缩分子。
- 验证(重跑 `regen_baic900002.py`):合计 `U(W1)=0.7`(=山西瑞狐 7÷10);门店行 山西瑞狐 `U='绿'`(7÷10=0.7 > 优秀值0.5);T 仍 0.4366(379÷868)不变;U(W1) 灯色统计 绿1/空22;V/W 全空(无 08-16/08-23 快照)。
- 山西瑞狐 8月数据参考:月交付 48、截止订单 17(延保7+权益10)→ S/T=0.3542 黄;W1 订单 7(延保4+权益3)÷ 快照交付10 = 0.7 → 绿。
## 北汽 W1/W2/W3 结果表生成时回写落库(用户反馈"W1数据未保存")
- 现象:`baic_special_month_data` 的 `w1/w2/w3_order_cnt`、`w{n}_new_delivery_cnt`、`w{n}_comprehensive_penetration`、`w{n}_light_level` **全为 NULL**(全表 `w1_order_cnt` 非空=0)。
- 根因:此前**只有周日定时任务 `scan_baic_weekly()` 会落库**,且它只处理**当前月**任务 → 8 月(900002)永远不会被回填;`generate_result_excel` 渲染时**只写 Excel、不回写 DB**。
- 修复(`baic_special_processor.py`):
- `_fill_block` 的 W1/W2/W3 节点循环内(j≥1),把该节点算出的值 `setattr` 到明细 ORM 对象 `d`:
`w{j}_order_cnt`(无 store_code→None)/ `w{j}_new_delivery_cnt`(快照交付,无快照→None)/
`w{j}_comprehensive_penetration` / `w{j}_light_level`;j=0(截止目前)无 w0 列 → 跳过。
- 合计行之后统一 `db.session.commit()`(try/except 包住,失败仅告警不影响 Excel 与 OSS)。
- 验证(重跑 `regen_baic900002.py`):日志 `周度字段(W1/W2/W3)已回写 baic_special_month_data:23 行`;
库内 900002:`w1_order_cnt` 非空 19 行、`w1_new_delivery_cnt` 1 行(山西瑞狐=10)、
`w1_comprehensive_penetration`=0.7 + `w1_light_level`='绿'(仅山西瑞狐);`w2/w3_order_cnt` 各 19 行;Excel 与库值一致(合计 U=0.7、山西瑞狐 U='绿')。
- ⚠ **待用户拍板的口径冲突**:渲染现在写这 4 个周度列,而周日定时任务 `scan_baic_weekly()` 只写 `w{n}_order_cnt`(D+,口径一致 ✓)与 `w{n}_new_delivery_cnt`(**广联报表全月累计**,与渲染的"该周结束日快照"口径 ✗)→ 两者会互相覆盖。另有定时时序问题:周日 23:00 执行时,"该周日"的日快照要次日 02:00 才由日任务生成 → 若改成快照口径,当周取不到分母。
- ⚠ 运维:改了 `baic_special_processor.py`,**需重启后端**(前端触发才用新码)。
## 北汽周度任务定位修正:周日任务改为「只写 glsx_daily_deal_subtotal 基础表」
- 用户拍板(2026-09-24,原话):**「周日定时任务只写 glsx_daily_deal_subtotal 表,不做其他逻辑」** → 消除了渲染与定时任务互相覆盖 `w{n}` 列的口径冲突。
- 改动:
- `glsx_daily_processor.py`:抽出通用落库函数 **`snapshot_glsx(stat_date)`**(报表月 = stat_date 所在月;按 stat_date 幂等:先软删旧行再插新行);`scan_glsx_daily()` 收缩为一行 `return snapshot_glsx(date.today() - timedelta(days=1))`;模块 docstring 补每日/每周两个触发口。
- `baic_special_processor.py` 的 `scan_baic_weekly()` **重写**:只 `from glsx_daily_processor import snapshot_glsx` → `snapshot_glsx(date.today())`(今天=周日=该周结束日)。**删掉**了原先的"定位本月最新任务 / 算 week_n / 查 D+ 订单窗口 / 写 w{n}_order_cnt 与 w{n}_new_delivery_cnt"全部逻辑。
- `scheduler.py` 的 `BaicWeeklySnapshotScheduler` docstring 同步(Cron 周日 23:00 不变)。类名/JOB_NAME 仍叫 baic_weekly_snapshot(未改名,避免动 app.py 接线;属命名遗留)。
- 验证:实跑 `scan_baic_weekly()` → `{'success':1,'stat_date':'2026-09-24','stores':184,'deleted_old':0}`;**baic_special_month_data 的 w1_order_cnt 非空数前=19 后=19(未被动过)**;glsx 表新增 stat_date=2026-09-24 184 行。
实跑 `scan_glsx_daily()` → stat_date=2026-09-23、软删旧 184 插 184(重构后仍幂等正常)。
- 现有快照日期:2026-08-09(用户手插 1 家,山西瑞狐)、2026-09-23、2026-09-24(各 184 家)。**2026-08-16 / 2026-08-23 仍无快照 → 8 月 W2/W3 仍会留空。**
- 最终一致性核对:DB 山西瑞狐 `w1_order=7 / w1_deliv=10 / w1_pen=0.7 / w1_light=绿`;Excel 合计 `T=0.4366 / U(W1)=0.7 / V=W=None`;900002 共 23 行、w1_order_cnt 非空 19 行。
## 下线北汽周日定时任务(只保留每日快照任务)
- 用户拍板(2026-09-24 16:36):`glsx_daily_deal_subtotal` 写入口「只需要保留每日快照任务就可以了」。
- 改动:
- `scheduler.py`:**整类删除** `BaicWeeklySnapshotScheduler`(含 CronTrigger 周日 23:00 与 threading 后备 `_thread_timer_daily`)。
- `app.py`:移除 import `BaicWeeklySnapshotScheduler`、实例化 `baic_weekly_snapshot_scheduler`、`ALL_SCHEDULERS` 中的 `('baic_weekly_snapshot', ...)` 行。
- `baic_special_processor.py`:`scan_baic_weekly()` **保留**,降级为**手动补数入口**(docstring 已改:原为周日定时任务,现定时任务已移除,仅手动调用;行为不变 = `snapshot_glsx(date.today())`)。
- 注释同步去掉"每周任务/周日"表述:`glsx_daily_processor` 模块 docstring(触发口改为「每日 Cron + 手动补数」)、`snapshot_glsx` docstring、`models.py` 周度快照注释(改为"由 generate_result_excel 渲染时按同口径回写")。
- 验证:`py_compile` 5 文件全过;`import app` → JOBS 列表无 `baic_weekly_snapshot`、`hasattr(app,'baic_weekly_snapshot_scheduler')=False`、`scheduler.BaicWeeklySnapshotScheduler` 不存在;全项目 grep `baic_weekly|BaicWeeklySnapshot` 仅剩 `scan_baic_weekly` 方法定义 1 处。
- ⚠ 时序副作用(告知用户):某周日的 stat_date 快照改由**次日 02:00** 每日任务补写(stat_date = 昨天 = 该周日)→ 周日当晚查不到该日快照;周一 02:00 后完整。W1/W2/W3 分母依赖该日快照,若周日当天就要出表,须手动 `snapshot_glsx(该周日)`(或调 `scan_baic_weekly()` 的日期参数入口)。
- ⚠ 改的是 scheduler.py/app.py → **需重启后端**(当前后端未运行,5001 空闲)新调度配置才生效。
# 2026-09-28
## 广联日快照定时任务执行时间调整:02:00 → 07:00
- 需求(用户 2026-09-28):`glsx_daily_deal_subtotal` 对应的定时任务(`GlsxDailyScheduler` / JOB_NAME=`glsx_daily_snapshot`)改为**每天早上 7 点**执行。
- 改动:
- `scheduler.py` `GlsxDailyScheduler`:`CRON_HOUR 2 → 7`(`CRON_MINUTE=0` 不变);类 docstring、常量注释、`_thread_timer_daily` docstring 中「02:00」字样同步为 07:00。
- `glsx_daily_processor.py` 模块 docstring:触发口「每日 Cron(默认 02:00)」→「(07:00)」。
- `baic_special_processor.py` `scan_baic_weekly()` docstring:「GlsxDailyScheduler,每日 02:00」→ 07:00。
- 验证:`py_compile` 过;`import app` → `dict(ALL_SCHEDULERS)['glsx_daily'].CRON_HOUR == 7`、`CRON_MINUTE == 0`;全项目 grep `02:00` 无残留。
- **环境事实(本次实测,重要)**:本机**未安装 apscheduler** —— `C:/Users/66/AppData/Roaming/Python/Python314/site-packages` 与 `C:/Python314/Lib/site-packages` 均无该包(`pip list` 只有 Flask/Flask-SQLAlchemy/SQLAlchemy/openpyxl 等)。
→ 所有 `NewReportScheduler` 子类**实际走 threading 后备路径**:`start()` 触发 ImportError 分支 → `_thread_timer_daily()` 每 **60 秒**轮询一次,命中 `now.hour == CRON_HOUR and now.minute == CRON_MINUTE` 才执行 → 实际触发窗口为 **07:00:00–07:00:59**(日志会打「APScheduler 未安装,使用 threading 后备方案」而非「APScheduler(Cron) 已启动」)。
- ⚠ 风险:60s `threading.Timer` 有累积漂移(每轮叠加执行耗时),后端长期不重启理论上可整体偏移 >60s → 可能漏掉整分钟窗口。若要精确:装 apscheduler,或把轮询间隔改成对齐分钟边界(`threading.Timer(60 - datetime.now().second, ...)`)。
- ⚠ 结论:`CRON_HOUR` 是类属性、`start()` 时才读取 → **改完必须重启后端**才生效。
- 时序含义未变:仍写 `stat_date = 昨天`;某**周日**的数据仍由**次日(周一)07:00** 写入。
## 北汽结果表合计行(r4)新增 12 项求和
- 需求(用户 2026-09-28):合计行补「产值目标 / 截止目前产值 / 达成率 / 新车交付数 / 触客数 / 触客率 / 交车数核对-产值表 / 交车数核对-一店一群 / 交车数核对-差异 / 触客数核对-产值表 / 触客数核对-一店一群 / 触客数核对-差异」合计统计。
- 改动:`baic_special_processor.py` `generate_result_excel` 合计行段(原 S 列写入之后、周度聚合之前)新增 12 列求和并写回 r4(K/L/M/N/O/P/AA/AB/AC/AD/AE/AF 均为 r4/r5 两行合并锚点,写 r4 即在合并区显示)。
- 比率列**不简单加和**:达成率(M)=合计截止目前产值÷合计产值目标;触客率(P)=合计触客数÷合计新车交付数。
- 差异列=对应「产值表」合计 −「一店一群」合计(=逐店差异之和)。
- None 计 0 参与求和;分母为 0 → 比率留空。
- 验证:`verify_total_row.py` 重跑 task 900002 并读本地副本 r4;DB 级 `SUM()` 与 Excel 完全一致:K=156.27 / L=124.9329 / M=0.7995 / N=868 / O=438 / P=0.5046 / AA=868 / AB=1006 / AC=-138 / AD=745 / AE=702 / AF=43。(临时脚本已删)
## 合计行差异列(AC/AF)合计口径修正(用户指出不正确)
- **根因**:AC/AF 原按 `差异 = 合计产值表 − 合计一店一群` 计算(即 `diff(Σout, Σgrp)`)。但 4 家门店(北京博瑞祥弘/沈阳鹏升/乌鲁木齐疆野/濮阳市欣驰)**产值表为空(通用品牌报表未命中→None)而一店一群有值**,被当成 0 相减,凭空计入负差,使合计差异偏离逐店可见差异之和。
- **修正**:差异列合计改为「**逐店差异之和**」,即对每店 `_diff(out, grp)` 求和,任一为空→该店差异留空、不计入合计。`sum((_diff(out,grp) or 0) for d in details)`。
- 验证(task 900002 重跑):AC=**6**(原 −138)、AF=**163**(原 43);与逐店 displayed 差异之和一致(delivery 非None差之和=6、visit=163;4 家 None 门店已排除)。AA/AB/AD/AE 列合计仍按「Σ(非空或0)」列求和,保持不变。
## 北汽结果表品牌汇总·本月段(data_row)数据写入
- 需求(用户 2026-09-28,「品牌汇总 数据写入」):品牌汇总本月段数据行此前只填 项目/品牌/门店数 + 售后门店数/售后场景开通率,且用 `for c in range(4,19): _set_cell(None)` **清空 D~R**;现改为与合计行同口径聚合填充。
- 改动(`baic_special_processor.py` `generate_result_excel`,品牌汇总本月 data_row = 本月标题行+2):
- D(4)=total_current(截止目前产值合计) / E(5)=total_delivery(交付合计) / F(6)=total_visit(触客合计) / G(7)=_visit_rate_total(合计触客率) / H(8)=summary.after_sale_store_cnt / I(9)=summary.after_sale_scene_open_rate(→_dec_to_float) / J(10)=_combined_total(售后订单数=延保+权益成交合计) / K(11)=ext_total(整车延保成交合计) / L(12)=_penetration(ext_total,total_delivery) / M(13)=rights_total(原厂权益成交合计) / N(14)=_penetration(rights_total,total_delivery)。
- ⚠ 关键修复:原本清空 D~R 会把模板示例的**7月 环比样例值**(P/Q/R=0.0105/-0.0145/0.0258)保留进正式输出 → 改完后**显式清空 O(15)~R(18) 环比**(当前管线无上月同口径数据,模板示例值属占位、不得泄漏)。
- 验证(task 900002 重跑):品牌汇总本月段 D=124.9329 / E=868 / F=438 / G=0.5046 / H=11 / I=0.22 / J=379 / K=157 / L=0.1809 / M=222 / N=0.2558;与合计行 L/N/O/P 及合计延保/权益订单数完全一致;O~R=None(已清空)。上月段数据行仍保留模板原样(框架轮参考,不重写)。
# 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 列表)。
# 2026-10-08 工作日志
## 店效人效及盈利测算 · 汇总表强制限定父任务 task_id(防跨月串数据)
- 需求:用户要求汇总表(门店店效人效汇总表/总看板)数据查询**限制与父任务同一个 taskId**,不要"周期匹配或最新 task_id"的旧回退。
- 根因确认:`store_effect_earnings` 主任务派生 5 个 `DataProcessSubtask`(状态记录,共享父 task_id),子处理器(warranty/equity/inshop/park)把 `task_id=task.id`(=父任务)写进 `report_extended_warranty` 等子结果表 → 子表 task_id 即父任务 id。
- 改动 `build_store_effect_board.py`:
- `_lr_sum_one(which,col_attr,period_start,period_end,task_id=None)`:传 task_id 时精确 `SUM(... WHERE task_id==task_id)`,否则回退旧逻辑(原样保留供 CLI)。
- `fetch_light_reform_11_sum / _11_sum_one / fetch_equity_21_sum / fetch_extended_warranty_23_sum` 各加 `task_id=None` 透传。
- `compute_metrics(..., task_id=None)`:用 `functools.partial` 把 task_id 绑定到上述 4 个包装函数(module global 重绑,else 分支还原),调用点无需逐处改。
- CLI `main()` 加 `--task-id`,传给 compute_metrics。
- 改动 `store_effect_summary_processor.py`:`_process_summary` 调 `compute_metrics(..., task_id=task_id)`(task_id=父任务 id)。
- 验证(DB 实测 task32):
- 子表存在 task_id=32 行:延保 419 / 店中店 32 / 园区店 20 / 权益 133。
- 新精确过滤 vs DB 直查完全一致:延保交车 17525 / 权益 3465 / 店中店 1695 / 园区店 887。
- **旧回退(max task_id)错取 task36**(延保/权益/店中店),返回错误值 15415/3300/985 → 证实"跨月串数据"bug,新逻辑已根治。
- partial 绑定路径单测通过;`py_compile` 两文件 OK。
- ⚠ 改的是处理器代码,前端「数据处理」走新逻辑需**重启后端**(当前 5001 空闲)。
# 项目长期约定(data-report / 预算达成数据处理) # 项目长期约定(data-report)
## 数据表类型与调度分工 ## 数据表类型与路由
- `config.DATA_TABLE_TYPES` 共 5 类:`budget_achievement`(7表单) / `store_effect_earnings`(11表单, need_period) / `output_value`(2表单: SAAS门店预算分解表+关系表, need_period) / `future_expansion`(占位) / `avita_special`(1表单: 主机厂数据表[附件表名为暂定,后续可能改名,改名只改 config forms], need_period=False, 引擎未接入占位)。 - `config.DATA_TABLE_TYPES` 6 类:`budget_achievement`(7表单) / `store_effect_earnings`(11表单,need_period) / `output_value`(2表单:SAAS门店预算分解表+关系表) / `future_expansion`(占位) / `avita_special`(1表单 主机厂数据表,need_period=False) / `baic_special`(1表单 北汽专项源数据表,need_period=False)。表单名暂定,改名只改 config 的 `forms`。
- 流水线分工: - `DataProcessor.process_task` 在白名单 `SUPPORTED_PROCESS_TYPES` **之前**按 data_table_type 显式路由:output_value→OutputValueProcessor、store_effect_earnings→StoreEffectSummaryProcessor、avita_special→AvitaSpecialProcessor、baic_special→BaicSpecialProcessor(各自置 COMPLETED 后 return);非白名单类型(future_expansion)抛"引擎尚未接入"。process_all 只处理 budget_achievement。
- `budget_achievement`:`processor.process_all` 编排(先 clean 后 processor)。 - 调度独立:`OutputValueScheduler` / `BaicSpecialScheduler`(扫描 PROCESSING 任务);另有 `GlsxDailyScheduler`(**每日 07:00**,写 stat_date=昨天) 是 `glsx_daily_deal_subtotal` 的**唯一定时写入者**。原 `BaicWeeklySnapshotScheduler`(周日 23:00) 已于 2026-09-24 整类删除;`BaicSpecialProcessor.scan_baic_weekly()` 保留仅作手动补数。
- `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 先删后插,幂等)。 ## 广联报表接口(dj.glsx.com.cn/reportExport,**无需鉴权**)
- `DataProcessor.process_task` 已按 `data_table_type` 路由(2026-09-04 补):`output_value` → `OutputValueProcessor`(手动单任务触发亦可处理);其余非 `SUPPORTED_PROCESS_TYPES` 类型(`store_effect_earnings`/`future_expansion`/`avita_special`)白名单拦截抛"引擎尚未接入",不再误跑预算流水线。`process_all` 仍只处理 `budget_achievement`。 三步链路:
1. `GET /queryAllExcel?pageSize=10&currentPage=1&filename={YYYY-MM}&business_type=yanbao&report_type=yanbaoMerAndPerRanking&key=` → 取 `data.list` 中 `filename` 含**「通用品牌」**那条的 `key`。
## output_value 产值达成表(2026-09-04 实现) 2. `GET /download?key={key}` → `data.list[0].url`。
- 结果表列 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总达成率。 3. `GET 该 url` 下载 xlsx。
- 映射规则(用户拍板):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 留空)。 解析要点:表头行 = col0=='业务类型'(表头含换行,须归一 `_norm_header`);门店名在 col2,**小计行 col2 为空 → 从上一业务行向前携带**。行标签 `延保小计` 带:整车延保成交数 / 原厂权益成交数 / **实际完成产值(万元)** / 累计交付数 / 实际售前触客数;行标签 `权益小计` 带:广联权益成交数。⚠ 门店小计行的「目标产值」列**为空**(真实值是「实际完成产值」)。
- 关系表哨兵 `/`、`nan`、`None`、`无` 归一为空。 三处同源实现:`baic_special_processor.fetch_glsx_report` / `avita_special_processor.fetch_glsx_deal_counts` / `glsx_daily_processor._download_glsx_rows`。
- 解析复用 `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(精品业务达成/省份透视)依赖接口数据,暂未生成。 ## 广联日快照基础表(2026-09-24)
- **接口列必须存 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 留空。 - `glsx_daily_deal_subtotal`(**独立基础表,不关联任何 DataProcessTask**):stat_date / store_name / ext_warranty_deal_count(延保小计-整车延保成交数) / rights_deal_count(延保小计-原厂权益成交数) / gl_rights_deal_count(权益小计-广联权益成交数) / actual_output_wan(延保小计-实际完成产值万) / delivery_cnt / visit_cnt / is_deleted / created_at / updated_at。
- `glsx_daily_processor.scan_glsx_daily()`:昨天 = today-1,报表月 = 昨天所在月;按 stat_date **先软删旧行再插**(幂等);**内部 commit**(验证时别指望 rollback)。
## 共享解析库 report_utils 关键函数 - 写入者只有一个定时任务:`GlsxDailyScheduler`(**每日 07:00**,2026-09-28 由 02:00 调整)。⚠ 后果:某**周日**的 stat_date 数据要等**次日(周一)07:00** 才落库;W1/W2/W3 分母依赖该日快照,周日当天出表须手动 `snapshot_glsx(该周日)`。
`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
## 导出 Excel 列格式约定 - `avita_special_processor.py`:process 下载附件→解析→按 task_id **软删**旧行(is_deleted=1) + 插新行 → COMPLETED、`result_file_url=''`。
- 占比/毛利率列(`processor.py RATIO_COLS`)用 `number_format='0.00"%"'`(表内已×100,禁用以 `0.00%` 会再放大100倍)。 - ORM:`AvitaSpecialMonthData`(明细,**真实表无 created_at/updated_at**) / `AvitaSpecialMonthSummaryMetrics`(**只有 created_at**)。读表须 `filter_by(is_deleted=0)`。写 ORM 必须逐列对齐真实表,多声明列 INSERT 报 `Unknown column`。
- 遗留问题:表头含 `\n` 的金额列(K成本GMV/N流量费GMV/T成本收入/U流量费收入/AI房租水电)因换行与 AMOUNT_COLS 不匹配,导出为文本串,需 strip('\n') 修复。 - 源文件:跳过前 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 家命中)。
## 标准名/别名映射
- `merchant_4s`/`merchant_yq` 字典表 + `to_standard(raw, kind)`:别名→标准名(园区店带 D+ 前缀)。 ## 北汽专项 baic_special
- 合并键6维(业务类型+主体+流量方标准名+品牌+园区店标准名+服务商),**必须在解析器分组阶段用标准名**而非事后归一(否则同标准名多别名拆多行)。 - 3 张表(用户手建,均带 `is_deleted`):`baic_special_month_data`(明细,**PK=store_id 非 id**,无 updated_at,created_at NOT NULL DEFAULT CURRENT_TIMESTAMP) / `baic_special_monthly_business`(逐门店×业务: store_id/business_type/order_cnt) / `baic_special_month_summary_metrics`(单任务一行,**列名与 avita 不同**:store_cnt / output_wan(万) / pre_sale_visit_cnt / vehicle_ext_warranty_deal_cnt / original_rights_deal_cnt,环比后缀 `_mom_pp`,brand/project_name 固定「北汽」)。
- 装修摊销两侧 `to_standard`+`strip_if_dplus`;门店耗材保留 D+。 - 源文件 5 列:门店名称 / 品牌 / 兜底门店(→underwriting_rule,无填「无」) / 交车数核对(一店一群) / 触客数核对(一店一群);行1主表头+行2子表头+行3起逐门店。末尾品牌级汇总段(北汽品牌汇总 / 售后门店数 / 售后场景开通率)**必须「标签优先」识别**,否则被当门店落库。开通率为比率值,`_to_rate()`:|v|>1 时 ÷100。
- 已接入数据源:区域/驻店类型/运营/业务开展(dj_smartcarlife `BAIC_STORE_INFO_SQL`)、驻店人员(scrm_account)、广联报表(产值目标/新车交付数/触客数/交车数核对/触客数核对)、截止目前产值+达成率(D+ `dj_car_life_pay_order.actual_money`,元→万元 /10000)、订单数(D+ `dj_car_life_goods_sub_order`,整车延保→延保行 / 原厂权益→权益行)、评灯标准(北汽极狐 0.5/0.3/0.3、北京越野 0.5/0.4/0.4)、触客率=触客数÷新车交付数、差异=产值表−一店一群。
## 装修摊销 / 门店耗材匹配 - 结果表列位:L(12)截止目前产值 / M(13)达成率 / P(16)触客率 / S(19)综合渗透 / T-U-V-W(20-23)灯(截止目前/W1/W2/W3)/ X-Y-Z(24-26)评灯标准 / AA(27)交车核对产值表 / AB(28)一店一群 / AC(29)交车差异 / AD(30)触客核对产值表 / AE(31)一店一群 / AF(32)触客差异。**KEEP 必须含所有要写的列**,否则被"非 KEEP 列清空"循环抹掉。
- 装修摊销:装修费用明细(business_type='1.1'),基数=合同金额/36,仅验收次月起36月内;先 F(门店名称)→traffic_name 池,F空未命中才 G(系统园区店)→park_store 池;单条不双重命中;`distribute_by_weight`+`reconcile_total` 保证池合计==明细总额。 - 周度评灯:综合渗透 = 当月累计(延保+权益)订单数 ÷ **全月**新车交付数;> 优秀值→绿 `#C6EFCE`、> 标准值→黄 `#FFEB9C`、否则红 `#FFC7CE`(**小数直接比,不 ×100**);周界 = 当月首个周一 +6/13/20 天(`compute_baic_week_ends`);W1/W2/W3 窗口起点均为当月 1 号、上界=本周日+1天(半开);合计行 r4 写聚合综合渗透数值。
- 门店耗材:耗材明细表,按明细自身业务类型匹配,F/G候选去重、保留D+,只取同月。 - 周度快照:`baic_special_month_data.w1/w2/w3_order_cnt` + `w1/w2/w3_new_delivery_cnt`(2026-09-24 ALTER 加)。⚠ 落库方=**`generate_result_excel` 渲染时按 Excel 同口径回写**(`w{n}_order_cnt`/`w{n}_new_delivery_cnt`/`w{n}_comprehensive_penetration`/`w{n}_light_level`);**已无定时任务写这 4 组列**(原周日 23:00 任务 2026-09-24 删除,`scan_baic_weekly()` 现仅手动补基础表)。
- `gmv_ratio`=本行GMV/同业务类型+同流量方合计;`gmv_ratio_park`=/同园区店合计;末行 `1-其余` 回填,组合计精确=1。 - D+ 基础信息两个 SQL 坑:① 子查询勿硬编码 merchant_id,须按 `a.merchant_id` 关联;② SQLAlchemy `text()` 里勿写 `DATE_FORMAT(x,'%Y-%m-%d')`(`%` 与驱动绑定冲突),取原值后 Python 侧格式化。
- SCRM 驻店人员两个坑:① `platform_*` 表在 **scrm_account 库**(非 dj_smartcarlife);② `role_name='驻店人员'` 配在**园区店**商户上,须经 `dj_car_life_scene_merchant_ref.sub_merchant_id`(main_merchant_type=2, sub_merchant_type IN (6,8), scene=0) 取园区店编码再查。多人以「/」分隔。
## 两条流水线架构(clean vs processor) - 结果表 openpyxl 两个大坑:① 合并区**仅锚点(左上)可写**,写非锚点抛 `MergedCell ... read-only`;② `insert_rows()` **不移动已合并区域** → 插入前 unmerge `min_row>=8`,插入后按偏移重建。
- `clean_budget_achievement`:DELETE+INSERT 全量重写,8维唯一键,写26列+装修摊销/门店耗材,独立 pymysql 自提交。 - 预览文件名坑:OSS key `baic_special_{month}_{task}.xlsx`(无 `task`),本地预览 `outputs/baic_special_{month}_task{task}.xlsx`(**有 `task`**),务必对齐。
- `processor.py`:仅 UPDATE 成本列(5维键,只读不插),强依赖 clean 先跑(读其 GMV 做市场费分摊分母)。
- 风险:①顺序 clean→processor;②唯一键粒度不一致(8 vs 5)会让多行同成本值;③processor 只UPDATE不INSERT。 ## output_value 产值达成表
- 结果表 A~O:A业务类型 / 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);B ← 关系表「E区域经理→D大区经理」;C ← SAAS 表「区域运营」;E/F 按门店去重;H/K ← 预估产值(纠偏) 按存量/新增汇总;G/I/L 来自接口。
- 手动回填:`python clean_budget_achievement.py -t budget_achievement -m YYYY-MM [--force] [--dry-run]`。 - **接口列必须存 NULL(关键坑)**:DECIMAL 列 DB 端默认 `0.00`,`bulk_save_objects` 会省略 None → 落 0,把"未接入"误读成"已接入且为 0"。写入须用 `db.session.add_all`。
- 店效 4 处理器「业务系统 SQL」仍 `biz_sql_data={}` 占位(BIZ_SQL_ENABLED 默认 false),产值/成本类字段恒为 0;需接指标 API 或业务 SQL 才有真实值。
## 店效人效看板 build_store_effect_board.py
- 指标 API:`fetch_indicator_data` / `indicator_client.py`(A0018 全国经营总产值 / A036 产值 / A075 成交 / A084 触客)。`(w)` 万元标签输出需 ÷10000。
- **`IndicatorClient.fetch` 的 `biz=None` 曾被序列化成 `bizs="None"` → API 当无效业务线 → 返回空 → 看板求和算成 0**(2026-09-22 已修:`biz is None` 时省略 `bizs` 键)。A0018 2026-08 全量实测 **98,255,112.51**(不传 bizs,499 条);实时计算值,随业务回写变动。
- **门店名匹配要精确**(`match_any` / `in_stores` 已改 exact-only,禁用包含);但**品牌名匹配 `brand_category()` 仍是双向子串包含**(走 `config_brand_category`,命多取最长 key),两者别混。改品牌配置须同时评估 `is_luxury_brand()`(`luxury_brand_config`,纯精确相等)侧。
- **汇总表(门店店效人效汇总表/总看板)子表聚合必须限定父任务 task_id**(2026-10-08 改造):`build_store_effect_board._lr_sum_one` 现接受 `task_id`,传入则 `SUM(...) WHERE task_id==父task_id`(report_* 子结果表 task_id 与父 store_effect_earnings 任务一致,因子任务仅 `DataProcessSubtask` 状态记录、复用父 task_id 写库);未传则回退旧逻辑(周期匹配优先,否则 max(task_id)——**该回退会跨月串数据,勿依赖**)。`compute_metrics` 经 `functools.partial` 把 task_id 绑定到 4 个 `fetch_*_sum` 包装函数;生产路径 `StoreEffectSummaryProcessor._process_summary` 传 `task_id=task.id`,CLI 加 `--task-id`。验证:task32 旧回退错取 task36 数据(延保交车 15415 vs 正确 17525),新精确过滤与 DB 直查一致。
## 共享解析库 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` / `is_luxury_brand`。新报表优先复用。
## 流水线 & 格式约定
- `clean_budget_achievement`:DELETE+INSERT 全量重写、8 维唯一键、独立 pymysql 自提交;`processor.py` 仅 UPDATE 成本列(5 维键,只读不插)→ **必须先 clean 后 processor**。手动回填:`python clean_budget_achievement.py -t budget_achievement -m YYYY-MM [--force] [--dry-run]`。
- 占比/毛利率列(`processor.py RATIO_COLS`)用 `0.00"%"`(表内已 ×100,禁用 `0.00%` 会再放大 100 倍);模板 `0.0%` 列存小数。
- 装修摊销:基数=合同金额/36,仅验收次月起 36 月内;F(门店名)→traffic_name 池,F 空才走 G(系统园区店)→park_store 池。`gmv_ratio`=本行GMV/同业务类型+同流量方合计;`gmv_ratio_park`=/同园区店合计。
## 运行 & 环境
- 改 `config.py` / `processor.py` / `scheduler.py` / `app.py` / `models.py` 后需**重启后端**才生效。
- 后端 Flask 跑在用户 site-packages `C:/Users/66/AppData/Roaming/Python/Python314/site-packages`;沙箱外重跑须 `dangerouslyDisableSandbox=true` + `PYTHONPATH=该路径` + `C:/Python314/python.exe`。Windows `SO_REUSEADDR` 允许多实例绑同端口 → 重跑前先 `taskkill` 清孤儿进程。
- **⚠ 本机未装 apscheduler**(2026-09-28 实测:上述 site-packages 与 `C:/Python314/Lib/site-packages` 均无)→ 所有 `NewReportScheduler` 子类实际走 **threading 后备**(`_thread_timer_daily` 每 60s 轮询命中 `hour==CRON_HOUR and minute==CRON_MINUTE`,触发窗口 = 该分钟 0~59 秒;日志打「APScheduler 未安装」)。60s Timer 有累积漂移风险;`CRON_HOUR/CRON_MINUTE` 为类属性、`start()` 时才读 → **改时间必须重启后端**。
- **⚠ 同一文件并行发多条 Edit 会静默丢写**(返回成功但内容未落盘)→ 改完必须 grep 回读确认。
...@@ -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 ----------
...@@ -33,5 +33,5 @@ INIT_NICKNAME=系统管理员 ...@@ -33,5 +33,5 @@ INIT_NICKNAME=系统管理员
# ---------- 服务 ---------- # ---------- 服务 ----------
FLASK_HOST=0.0.0.0 FLASK_HOST=0.0.0.0
FLASK_PORT=5001 FLASK_PORT=5000
FLASK_DEBUG=true FLASK_DEBUG=true
...@@ -4,3 +4,8 @@ __pycache__/ ...@@ -4,3 +4,8 @@ __pycache__/
*.pyc *.pyc
uploads/ uploads/
data/ data/
.idea
.idea/*
.venv/
/.scheduler.lock
"""扫店中店模板 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()
...@@ -32,6 +32,12 @@ from scheduler import ( ...@@ -32,6 +32,12 @@ from scheduler import (
LightReformParkScheduler, LightReformParkScheduler,
OutputValueScheduler, OutputValueScheduler,
StoreEffectSummaryScheduler, StoreEffectSummaryScheduler,
AvitaSpecialScheduler,
VoyahScheduler,
LeapmotorScheduler,
CommonEquityScheduler,
BaicSpecialScheduler,
GlsxDailyScheduler,
) )
app = Flask(__name__, static_folder='static', static_url_path='') app = Flask(__name__, static_folder='static', static_url_path='')
...@@ -126,6 +132,11 @@ def parse_period(data, tcfg): ...@@ -126,6 +132,11 @@ def parse_period(data, tcfg):
if period_type not in ('month', 'week'): if period_type not in ('month', 'week'):
raise ValueError(f'period_type 仅支持 month / week,当前值:{period_type}') 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': if period_type == 'week':
# 按周:强校验 week_num,后端计算权威日期区间 # 按周:强校验 week_num,后端计算权威日期区间
try: try:
...@@ -251,7 +262,8 @@ def meta_task_types(): ...@@ -251,7 +262,8 @@ 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)} '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)
...@@ -652,6 +664,12 @@ light_reform_inshop_scheduler = LightReformInshopScheduler(app=app) ...@@ -652,6 +664,12 @@ light_reform_inshop_scheduler = LightReformInshopScheduler(app=app)
light_reform_park_scheduler = LightReformParkScheduler(app=app) light_reform_park_scheduler = LightReformParkScheduler(app=app)
output_value_scheduler = OutputValueScheduler(app=app) output_value_scheduler = OutputValueScheduler(app=app)
store_effect_summary_scheduler = StoreEffectSummaryScheduler(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)
avita_special_scheduler = AvitaSpecialScheduler(app=app)
baic_special_scheduler = BaicSpecialScheduler(app=app)
glsx_daily_scheduler = GlsxDailyScheduler(app=app)
ALL_SCHEDULERS = [ ALL_SCHEDULERS = [
('budget_achievement', scheduler), ('budget_achievement', scheduler),
...@@ -661,6 +679,12 @@ ALL_SCHEDULERS = [ ...@@ -661,6 +679,12 @@ ALL_SCHEDULERS = [
('light_reform_park', light_reform_park_scheduler), ('light_reform_park', light_reform_park_scheduler),
('output_value', output_value_scheduler), ('output_value', output_value_scheduler),
('store_effect_summary', store_effect_summary_scheduler), ('store_effect_summary', store_effect_summary_scheduler),
('voyah_special', voyah_scheduler),
('leapmotor_special', leapmotor_scheduler),
('common_equity', common_equity_scheduler),
('avita_special', avita_special_scheduler),
('baic_special', baic_special_scheduler),
('glsx_daily', glsx_daily_scheduler),
] ]
......
# -*- 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 -*-
"""
北汽专项 独立处理器
====================
对应 ORM 表:baic_special_month_data(明细,逐门店一行)
baic_special_monthly_business(逐门店×业务:延保/权益;D+系统订单,本轮暂不落)
baic_special_month_summary_metrics(汇总指标,单任务一行)
数据来源:北汽专项源数据表(Excel,线上运营手工上传 5 列)。
源文件结构(经核对,以实际附件为准):
- 行1(主表头):门店名称 | 品牌 | 兜底门店 | 交车数核对 | 触客数核对
- 行2(子表头): | | | 一店一群 | 一店一群
- 行3 起 :逐门店明细(每店一行,隔行为空占位)
- 末尾汇总段:'北汽品牌汇总'(品牌标签) + 售后门店数 + 售后场景开通率
(品牌级线上运营手工上传;A 列标签 / B 列数值。
售后场景开通率按百分数上传,如 22 表示 22% → 落库 0.22)
即:col0=门店名称 col1=品牌 col2=兜底门店 col3=交车数核对(一店一群) col4=触客数核对(一店一群)
字段字典(字段取值说明)口径映射:
- 门店名称 -> store_name
- 品牌 -> brand(如:北汽极狐 / 北京越野)
- 兜底门店 -> underwriting_rule(无兜底填「无」;有兜底填规则原文)
- 交车数核对(一店一群) -> delivery_check_group_cnt(交车数核对-一店一群交车数,手工上传)
- 触客数核对(一店一群) -> visit_check_group_cnt(触客数核对-一店一群触客数,手工上传)
评灯标准(优秀值/标准值/预警值)按品牌固定取值(用户 2026-09-21 明确,见 LIGHT_STANDARD_BY_BRAND):
- 北汽极狐 -> 0.5 / 0.3 / 0.3 ;北京越野 -> 0.5 / 0.4 / 0.4
落库 excellent_value / standard_value / warning_value;结果表 X/Y/Z 列(24/25/26);品牌未匹配留 NULL。
截止目前产值 / 达成率(用户 2026-09-21 明确,见 BAIC_OUTPUT_CURRENT_SQL / fetch_output_current):
- 截止目前产值 output_current_wan = SUM(dj_car_life_pay_order.actual_money) / 10000(万元)
条件:goods_order.deleted_flag='N' AND merchant_id=门店编码 AND scene_type=0 AND business_type=2 AND status=4
AND pay_order.deleted_flag='N' AND pay_status=2 AND success_date ∈ [周期起, 周期止+1天)
- 达成率 achievement_rate = 截止目前产值 ÷ 产值目标(同万元,比值为小数,模板 0.0% 格式)
落库 output_current_wan / achievement_rate;结果表 L/M 列(12/13);无数据(如门店无支付成功单)留 NULL。
订单数(延保/权益,用户 2026-09-22 明确,见 BAIC_ORDER_COUNT_SQL / fetch_order_count):
- 订单数 order_cnt = COUNT(0) FROM dj_car_life_goods_sub_order(LEFT JOIN goods_order / pay_order)
条件:sub_order.deleted_flag='N' AND goods_order.deleted_flag='N' AND merchant_id=门店编码
AND scene_type=0 AND business_type=2 AND status=4
AND pay_order.deleted_flag='N' AND pay_status=2 AND success_date ∈ [周期起, 周期止+1天)
映射:upgrade_secondary_goods_type_name='整车延保' → 延保(业务类型1);'原厂权益' → 权益(业务类型2);其余忽略。
- 落库 baic_special_monthly_business(逐门店×业务,store_id 外键 + business_type + order_cnt,按 task 先删后插幂等);
结果表 Q 列(17):延保行=整车延保订单数、权益行=原厂权益订单数;合计行 r4/r5 按业务类型求和。无数据留 NULL。
其余列中:
- 触客率 P(16):系统计算(见上)。
- 周度评灯 T/U/V/W(20/21/22/23):【已接入】按当月累计(延保+权益)订单数 ÷ 新车交付数得综合渗透,
与 X/Y(优秀/标准值, 小数) 比较判灯色——>优秀值绿(#C6EFCE)/ >标准值黄(#FFEB9C)/ 否则红(#FFC7CE);
W1/W2/W3 取「截止到当前周」累计订单数(实时查 D+),分母新车交付数取该周结束日快照
(基础表 glsx_daily_deal_subtotal.delivery_cnt,见 fetch_delivery_snapshot_by_dates);
截止目前节点分母仍用全月实时 new_delivery_cnt、上界=cutoff_date。
快照缺失 → 该周渗透留空且不评灯。合计行(r4)写各节点聚合综合渗透(数值)。
- 周趋势/品牌汇总等其余系统列:源文件不含 → 占位留 NULL(后续接入)。
广联报表来源(dj.glsx.com.cn 报表导出,见 fetch_glsx_report / _GLSX_BASE):
- 产值目标 output_target_wan <- 延保小计行 H(8月目标产值(万元))
- 新车交付数 new_delivery_cnt <- 非小计行 K(累计交付数(台)),同店多条取最大值
- 触客数 visit_cnt <- 非小计行 O(实际售前触客数),同店多条取最大值
- 交车数核对-产值表 delivery_check_output_cnt <- 延保小计行 K(累计交付数(台))
- 触客数核对-产值表 visit_check_output_cnt <- 延保小计行 O(实际售前触客数)
报表取「通用品牌」一份(queryAllExcel 按 filename=报表月 过滤),门店名与源文件精确匹配;未匹配留 NULL。
触客率 visit_rate(用户 2026-09-21 明确,系统计算):
- 触客率 = 触客数(visit_cnt) ÷ 新车交付数(new_delivery_cnt),无量纲小数(模板 0.0% 格式)
- 任一侧为空或新车交付数为 0 → 留 NULL
落库 visit_rate;结果表 P 列(16)。
核对结果表的「差异」列(AC/F 列,系统计算,任一侧为空则留空):
- 交车数核对-差异 = 交车数核对-产值表(delivery_check_output_cnt) - 交车数核对-一店一群(delivery_check_group_cnt)
- 触客数核对-差异 = 触客数核对-产值表(visit_check_output_cnt) - 触客数核对-一店一群(visit_check_group_cnt)
注:触客数(系统,O列)=单人max,触客数核对-产值表=门店合计,两者语义本就不同(用户 2026-09-21 确认)。
D+ 系统来源(dj_smartcarlife,见 fetch_baic_store_info / BAIC_STORE_INFO_SQL):
- 门店编码 store_code <- pg_group_store_rel.merchant_id(北汽项目组)
- 区域 region <- dj_car_life_service_merchant.province_name
- 驻店类型 store_type <- dj_car_life_yqmerchant_config.partner_merchant_id=44206988 ? 直营 : 服务商
- 业务开展 business_start_date <- dj_car_life_goods_order MIN(order_time)(scene_type=0)
- 运营 operator_name <- dj_car_life_shop_merchant_director_config.director_name(director_type=9)
按「门店名称」与源文件精确匹配;未匹配则上述字段留空。
SCRM 来源(scrm_account,见 fetch_resident_staff / RESIDENT_STAFF_SQL):
- 驻店人员 resident_staff <- platform_merchant_staff.staff_name(角色 role_name='驻店人员',多人「/」分隔)
⚠ 该角色在 D+ 里配在**园区店**商户上,不在品牌门店商户上:须先用门店在
dj_car_life_scene_merchant_ref 的 sub_merchant_id(type 6/8, scene=0)换算出园区店编码,
再到 scrm_account 按 platform_merchant.merchantNo 查询。直接拿品牌门店编码查会全部为空。
落库:按 task_id 先逻辑删除(旧行置 is_deleted=1)后插入新行(is_deleted=0),幂等。
结果表生成:复制用户模板(exporttemplete/baic_special_report_template.xlsx),按 store_name 用
DB 源值覆盖 5 列 + 品牌汇总本月段项目/品牌/门店数;系统列保留模板原样。生成后上传 OSS 并回填
result_file_url。
"""
import io
import logging
import os
import re
import tempfile
import requests
from calendar import monthrange
from copy import copy
from datetime import datetime, date, timedelta
from decimal import Decimal, InvalidOperation
import openpyxl
from openpyxl.styles import PatternFill
from openpyxl.utils import get_column_letter
from sqlalchemy import create_engine, text, bindparam
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,
BaicSpecialMonthData, BaicSpecialMonthlyBusiness, BaicSpecialMonthSummaryMetrics,
GlsxDailyDealSubtotal,
)
# 结果表生成模板(由用户提供的「北汽专项-展示表字段取值说明(模板版)」复制而来,作为布局基线)
BAIC_TEMPLATE_PATH = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'exporttemplete', 'baic_special_report_template.xlsx')
logger = logging.getLogger('BaicSpecialProcessor')
BAIC_TYPE = 'baic_special'
# 源文件明细行列索引(0-based)
SRC_STORE_NAME = 0
SRC_BRAND = 1
SRC_UNDERWRITING = 2
SRC_DELIVERY_GROUP = 3
SRC_VISIT_GROUP = 4
# 源文件末尾汇总段(品牌级,A 列标签 / B 列数值)
BRAND_SUMMARY_LABEL = '北汽品牌汇总'
SUMMARY_LABELS = {
'售后门店数': 'after_sale_store_cnt',
'售后场景开通率': 'after_sale_scene_open_rate',
'售后订单数': 'after_sale_order_cnt',
}
# 需按百分数归一为小数比率的汇总字段(源文件以「22」表示 22%)
RATE_SUMMARY_ATTRS = {'after_sale_scene_open_rate'}
# ---------- 评灯标准(优秀值/标准值/预警值)----------
# 源文件与系统均未提供,按品牌固定取值(用户 2026-09-21 明确):
# 北汽极狐 -> 0.5 / 0.3 / 0.3 ; 北京越野 -> 0.5 / 0.4 / 0.4
# 落库 excellent_value / standard_value / warning_value;结果表 X/Y/Z 列(24/25/26);品牌未匹配留 NULL。
# 注意:评灯标准「显示是小数、非百分比」(如 0.5 即 50%),与综合渗透(同为小数比率)直接比较,
# **切勿**把综合渗透 ×100 再比,也**切勿**把标准值当百分数 ÷100。
LIGHT_STANDARD_BY_BRAND = {
'北汽极狐': (0.5, 0.3, 0.3),
'北京越野': (0.5, 0.4, 0.4),
}
# ---------- 周度评灯底色(绿/黄/红)与结果表列位 ----------
# 结果表「门店等级」四列:T(20)=截止目前(灯)、U(21)=W1、V(22)=W2、W(23)=W3
# 单元格显示灯色文字(绿/黄/红)+ 对应浅色底;列顺序与 compute_baic_week_ends 返回的节点顺序一致。
BAIC_LIGHT_FILL = {
'绿': 'C6EFCE', # 综合渗透 > 优秀值
'黄': 'FFEB9C', # 综合渗透 > 标准值(且 ≤ 优秀值)
'红': 'FFC7CE', # 综合渗透 ≤ 标准值
}
BAIC_LIGHT_COLS = [20, 21, 22, 23] # [截止目前, W1, W2, W3] 对应 T/U/V/W
# ---------- 业务类型编码(对应 baic_special_monthly_business.business_type)----------
# 1=延保(整车延保)/ 2=权益(原厂权益)
BAIC_BIZ_EXT_WARRANTY = 1
BAIC_BIZ_RIGHTS = 2
# 订单数 SQL:goods_type_name -> 业务类型编码(其余类型忽略)
ORDER_CNT_TYPE_MAP = {
'整车延保': BAIC_BIZ_EXT_WARRANTY,
'原厂权益': BAIC_BIZ_RIGHTS,
}
BIZ_TYPE_LABEL = {BAIC_BIZ_EXT_WARRANTY: '延保', BAIC_BIZ_RIGHTS: '权益'}
def _light_standard(brand):
"""按品牌返回评灯标准 (优秀值, 标准值, 预警值);品牌未匹配返回 (None, None, None)。"""
return LIGHT_STANDARD_BY_BRAND.get((brand or '').strip(), (None, None, None))
def _task_period(task):
"""取任务的统计周期 (start_date, end_date),两端均含当天。
优先用任务的 period_start / period_end;缺失时按 month(YYYY-MM)推算整月,
用于「截止目前产值」按 success_date 区间汇总(SQL 上界取 end_date + 1 天)。
"""
ps = getattr(task, 'period_start', None)
pe = getattr(task, 'period_end', None)
if ps and pe:
return ps, pe
month = (getattr(task, 'month', None) or '')
if len(month) >= 7 and month[4] == '-':
try:
y, m = int(month[:4]), int(month[5:7])
return date(y, m, 1), date(y, m, monthrange(y, m)[1])
except (ValueError, IndexError):
logger.warning(f"[北汽] 任务月份无法解析为周期: {month!r}")
return ps, pe
# ---------- D+ 系统(dj_smartcarlife)门店基础信息 ----------
BAIC_GROUP_NAME = '北汽' # pg_group_info.group_name
DIRECT_SALE_PARTNER_ID = 44206988 # partner_merchant_id 等于该值 -> 直营,否则 服务商
_BIZ_ENGINE = None
def _get_biz_engine():
"""业务系统 SQL 引擎(嘀加 dj_smartcarlife),懒加载单例。"""
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
# ---------- SCRM 系统(scrm_account)驻店人员 ----------
_SCRM_ENGINE = None
def _get_scrm_engine():
"""SCRM 账号库(scrm_account)引擎,懒加载单例。"""
global _SCRM_ENGINE
if _SCRM_ENGINE is None:
_SCRM_ENGINE = create_engine(Config.SCRM_DATABASE_URL, echo=False, pool_pre_ping=True)
return _SCRM_ENGINE
# 驻店人员:按「园区店编码」(platform_merchant.merchantNo) 查角色 role_name='驻店人员' 的员工姓名
# 注意:D+ 的「驻店人员」配在**园区店**商户上(店面配置-人员管理),
# 不是品牌门店商户本身;故须先用门店关联的 sub_merchant_id 换算出园区店编码再查本表。
RESIDENT_STAFF_SQL = """
SELECT pm.merchantNo AS merchant_no, st.staff_name AS staff_name
FROM platform_merchant_staff st
LEFT JOIN platform_merchant_role_staff_relation pr
ON st.id = pr.staff_id AND pr.del_flag = 0
LEFT JOIN platform_merchant_role ro
ON pr.role_id = ro.id AND ro.del_flag = 0
LEFT JOIN platform_merchant pm
ON st.merchant_id = pm.id AND pm.del_flag = 0
WHERE st.del_flag = 0
AND ro.role_name = '驻店人员'
AND pm.merchantNo IN :park_codes
"""
def fetch_resident_staff(park_codes):
"""按园区店编码批量查询驻店人员(scrm_account 单次查询)。
park_codes: 园区店编码可迭代对象(platform_merchant.merchantNo)
返回 {园区店编码(str): ['张三','李四', ...]};查询失败/无数据返回 {}(不致命)。
"""
codes = tuple({str(c).strip() for c in (park_codes or []) if c not in (None, '')})
if not codes:
return {}
engine = _get_scrm_engine()
result = {}
try:
with engine.connect() as conn:
rows = conn.execute(text(RESIDENT_STAFF_SQL), {'park_codes': codes}).fetchall()
except Exception as e:
logger.warning(f"[北汽] SCRM 驻店人员查询失败: {e}")
return {}
for no, name in rows:
key = str(no).strip() if no is not None else ''
val = str(name).strip() if name not in (None, '') else ''
if not key or not val:
continue
bucket = result.setdefault(key, [])
if val not in bucket:
bucket.append(val)
logger.info(f"[北汽] SCRM 驻店人员:{len(codes)} 个园区店编码 → 命中 {len(result)} 个、共 "
f"{sum(len(v) for v in result.values())} 人次")
return result
# ===================================================================
# 广联报表(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(C列),业务类型标签在 col0(A列)
# - 每个门店分段:业务类型行(如 '2.3延保', C=门店名, H/K/O 带值)
# → 多条人员行(仅 O 有值, C 空) → '延保小计'/'权益小计' 小计行
# (A 标签, H/K/O 带值, C 可能空 → 门店名从上一业务行向前携带)
# 取值(按门店名称匹配):
# - output_target_wan : '延保小计' 行 H 列(8月目标产值(万元))
# - new_delivery_cnt : 非小计行 K 列(累计交付数(台)),同一门店多条取最大值
# - visit_cnt : 非小计行 O 列(实际售前触客数),同一门店多条取最大值
# - delivery_check_output_cnt: '延保小计' 行 K 列(累计交付数(台))
# - visit_check_output_cnt : '延保小计' 行 O 列(实际售前触客数)
# 失败返回 {}(不致命,仅告警留空)。
# ===================================================================
_GLSX_BASE = 'https://dj.glsx.com.cn/reportExport'
_GLSX_TIMEOUT = (30, 120)
def _norm_glsx_header(s):
"""报表表头单元格归一:去空格/换行,便于按列名定位(如 '8月目标产值\n(万元)'→'8月目标产值(万元)')"""
return ''.join(str(s).split()) if s is not None else ''
def _glsx_to_int(v):
"""单元格转 int:空/非数字 → None(用于交付/触客计数聚合与取值)"""
if v is None or v == '':
return None
s = str(v).strip().replace(',', '')
if s in ('-', 'None'):
return None
try:
return int(Decimal(s))
except (InvalidOperation, ValueError):
return None
def _diff(a, b):
"""差异 = 产值表 - 一店一群:任一侧为空则差异为空(NULL)。用于交车数核对/触客数核对差异列。"""
if a is None or b is None:
return None
return a - b
def _ratio(a, b):
"""比率 = a ÷ b:任一侧为空或分母为 0 则留空(NULL)。返回无量纲小数(模板 0.0% 格式)。"""
if a is None or b in (None, 0):
return None
return Decimal(str(a)) / Decimal(str(b))
def _penetration(order_cnt, delivery):
"""渗透率 = 订单数(order_cnt) ÷ 新车交付数(delivery)。
- 分母 delivery 为空 / 0 / 非数字 → 留空(NULL,无法计算);
- 分子 order_cnt 缺失(None)→ 按 0 参与计算(门店未售该业务即渗透 0)。
返回无量纲小数(模板百分比格式)。
"""
if delivery is None:
return None
try:
dv = float(delivery)
except (TypeError, ValueError):
return None
if dv <= 0:
return None
oc = order_cnt if order_cnt is not None else 0
try:
oc = float(oc)
except (TypeError, ValueError):
return None
return oc / dv
def fetch_glsx_report(stat_month):
"""从广联报表导出接口获取各门店的 产值目标/新车交付数/触客数系统/交车数核对-产值表/触客数核对-产值表。
返回 {门店名称: {'output_target_wan','new_delivery_cnt','visit_cnt',
'delivery_check_output_cnt','visit_check_output_cnt'}};
任何失败返回空 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_glsx_header(row[0]) == '业务类型'), None)
if hidx is None:
logger.warning('[北汽] 广联报表:未找到表头行(业务类型)')
return {}
SUB = ('延保小计', '权益小计')
stores = {}
cur = None # 向前携带的当前门店名(人员行 C 为空)
for row in rows[hidx + 1:]:
a = _norm_glsx_header(row[0]) if row and row[0] is not None else ''
c = str(row[2]).strip() if len(row) > 2 and row[2] is not None else ''
h = row[7] if len(row) > 7 else None # H 8月目标产值(万元)
k = row[10] if len(row) > 10 else None # K 累计交付数(台)
o = row[14] if len(row) > 14 else None # O 实际售前触客数
if not a and not c:
continue
if c:
cur = c
if not cur:
continue
s = stores.setdefault(cur, {'h': None, 'kl': [], 'ol': [], 'ek': None, 'eo': None})
if a in SUB:
if a == '延保小计':
if h not in (None, ''):
s['h'] = _to_dec(h)
kv = _glsx_to_int(k)
if kv is not None:
s['ek'] = kv
ov = _glsx_to_int(o)
if ov is not None:
s['eo'] = ov
else:
kv = _glsx_to_int(k)
if kv is not None:
s['kl'].append(kv)
ov = _glsx_to_int(o)
if ov is not None:
s['ol'].append(ov)
result = {}
for name, s in stores.items():
result[name] = {
'output_target_wan': s['h'],
'new_delivery_cnt': max(s['kl']) if s['kl'] else None,
'visit_cnt': max(s['ol']) if s['ol'] else None,
'delivery_check_output_cnt': s['ek'],
'visit_check_output_cnt': s['eo'],
}
logger.info(f'[北汽] 广联报表:解析到 {len(result)} 个门店的产值/交付/触客数据')
return result
except Exception as e:
logger.warning(f'[北汽] 广联报表获取失败(stat_month={stat_month}): {e}')
return {}
# 北汽项目组门店基础信息:门店编码 / 门店名称 / 区域(省) / 驻店类型 / 业务开展 / 区域运营 / 关联园区店
# 注意:
# 1) 「区域运营」须按 a.merchant_id 关联(原 SQL 硬编码单个 merchant_id 会让所有门店返回同一人);
# 2) 不用 DATE_FORMAT('%Y-%m-%d')——SQLAlchemy 参数化语句下 '%' 会与驱动绑定冲突,
# 改为取 MIN(order_time) 原值,在 Python 侧用 _to_date() 格式化;
# 3) park_merchant_ids 为门店关联的园区店商户编码(type 6/8, scene=0),供 SCRM 查「驻店人员」用。
BAIC_STORE_INFO_SQL = """
SELECT
a.merchant_id AS merchant_id,
a.merchant_name AS merchant_name,
c.province_name AS province_name,
IF(e.partner_merchant_id = :direct_partner_id, '直营', '服务商') AS store_type,
(
SELECT MIN(o.order_time)
FROM dj_car_life_goods_order o
WHERE o.deleted_flag = 'N'
AND o.scene_type = 0
AND o.merchant_id = a.merchant_id
) AS business_start_date,
(
SELECT GROUP_CONCAT(DISTINCT director_name)
FROM dj_car_life_shop_merchant_director_config
WHERE deleted_flag = 'N'
AND merchant_id = a.merchant_id
AND director_type = 9
) AS operator_name,
(
SELECT GROUP_CONCAT(DISTINCT d.sub_merchant_id)
FROM dj_car_life_scene_merchant_ref d
WHERE d.deleted_flag = 'N'
AND d.main_merchant_id = a.merchant_id
AND d.main_merchant_type = 2
AND d.sub_merchant_type IN (6, 8)
AND d.scene = 0
) AS park_merchant_ids
FROM pg_group_store_rel a
LEFT JOIN pg_group_info b
ON b.id = a.group_id AND b.deleted_flag = 'N'
LEFT JOIN dj_car_life_service_merchant c
ON c.merchant_id = a.merchant_id AND c.deleted_flag = 'N'
LEFT JOIN dj_car_life_scene_merchant_ref d
ON d.main_merchant_id = a.merchant_id AND d.deleted_flag = 'N'
AND d.main_merchant_type = 2 AND d.sub_merchant_type IN (6, 8) AND d.scene = 0
LEFT JOIN dj_car_life_yqmerchant_config e
ON d.sub_merchant_id = e.merchant_id AND e.deleted_flag = 'N'
WHERE a.deleted_flag = 'N'
AND b.group_name = :group_name
"""
def fetch_baic_store_info(group_name=BAIC_GROUP_NAME):
"""查询北汽项目组下门店的 D+ 基础信息(dj_smartcarlife 单次查询)。
返回 {merchant_name: {'store_code','region','store_type','business_start_date',
'operator_name','resident_staff'}};
其中驻店人员由关联园区店编码到 scrm_account 二次查询(见 fetch_resident_staff),
多人以「/」分隔(字段字典口径)。
查询失败/无数据返回 {}(不致命,调用方仅告警)。
"""
engine = _get_biz_engine()
result = {}
try:
with engine.connect() as conn:
rows = conn.execute(
text(BAIC_STORE_INFO_SQL),
{'direct_partner_id': DIRECT_SALE_PARTNER_ID,
'group_name': group_name},
).fetchall()
except Exception as e:
logger.warning(f"[北汽] D+ 门店基础信息查询失败: {e}")
return result
for r in rows:
mid, name, province, stype, start_date, operator, park_ids = (
r[0], r[1], r[2], r[3], r[4], r[5], r[6])
name = (str(name).strip() if name not in (None, '') else '')
if not name:
continue
item = result.setdefault(name, {
'store_code': str(mid) if mid is not None else None,
'region': (str(province).strip() if province not in (None, '') else None),
'store_type': (str(stype).strip() if stype not in (None, '') else None),
'business_start_date': _to_date(start_date),
'operator_name': (str(operator).strip() if operator not in (None, '') else None),
'park_merchant_ids': [],
'resident_staff': None,
})
# 同一门店可能关联多个园区店(join 出多行)→ 合并去重
for code in str(park_ids or '').split(','):
code = code.strip()
if code and code not in item['park_merchant_ids']:
item['park_merchant_ids'].append(code)
# ---- 按园区店编码到 SCRM 查「驻店人员」(跨库二次查询)----
all_codes = {c for v in result.values() for c in v['park_merchant_ids']}
staff_map = fetch_resident_staff(all_codes)
for v in result.values():
names = []
for code in v['park_merchant_ids']:
for nm in staff_map.get(code, []):
if nm not in names:
names.append(nm)
v['resident_staff'] = ('/'.join(names))[:255] if names else None
v.pop('park_merchant_ids', None)
logger.info(f"[北汽] D+ 门店基础信息:北汽组查询到 {len(result)} 家门店(group_name={group_name})"
f",其中 {sum(1 for v in result.values() if v['resident_staff'])} 家有驻店人员")
return result
# ---------- D+ 系统:截止目前产值(dj_smartcarlife) ----------
# 用户提供口径(2026-09-21):按门店 merchant_id + 周期 success_date 区间汇总支付成功金额。
# merchant_id <- 门店 D+ 编码(即 store_code,来自 pg_group_store_rel.merchant_id)
# success_date <- 任务周期([period_start, period_end + 1 天))
# 原 SQL 为单店标量查询,此处改为按 merchant_id 分组一次查全,谓词完全一致。
# 注意:actual_money 单位为「元」,写入「截止目前产值(万)」需 /10000。
BAIC_OUTPUT_CURRENT_SQL = """
SELECT a.merchant_id AS merchant_id,
SUM(b.actual_money) AS output_amount
FROM dj_car_life_goods_order a
LEFT JOIN dj_car_life_pay_order b
ON b.order_code = a.order_code
AND b.deleted_flag = 'N'
AND b.pay_status = 2
WHERE a.deleted_flag = 'N'
AND a.merchant_id IN :merchant_ids
AND a.scene_type = 0
AND a.business_type = 2
AND a.status = 4
AND b.success_date >= :date_from
AND b.success_date < :date_to
GROUP BY a.merchant_id
"""
def fetch_output_current(period_start, period_end, merchant_ids):
"""查询各门店「截止目前产值」(dj_smartcarlife,单次分组查询)。
:param period_start: 周期开始日期(date)
:param period_end: 周期结束日期(date,含当天 → 查询上界取次日)
:param merchant_ids: 门店 D+ 编码集合(store_code)
:return: {merchant_id(str): 截止目前产值(万元, Decimal 4 位)};失败/无数据返回 {}(不致命)。
"""
result = {}
ids = [int(c) for c in {str(c).strip() for c in merchant_ids if c not in (None, '')}
if str(c).strip().isdigit()]
if not ids or not period_start or not period_end:
return result
date_from = period_start.strftime('%Y-%m-%d')
date_to = (period_end + timedelta(days=1)).strftime('%Y-%m-%d')
engine = _get_biz_engine()
try:
with engine.connect() as conn:
stmt = text(BAIC_OUTPUT_CURRENT_SQL).bindparams(
bindparam('merchant_ids', expanding=True))
rows = conn.execute(
stmt,
{'merchant_ids': ids, 'date_from': date_from, 'date_to': date_to},
).fetchall()
except Exception as e:
logger.warning(f"[北汽] 截止目前产值查询失败: {e}")
return result
for r in rows:
mid, amt = r[0], r[1]
if mid is None or amt is None:
continue
# 元 -> 万元(对齐 output_current_wan DECIMAL(18,4))
result[str(mid)] = (Decimal(str(amt)) / Decimal('10000')).quantize(Decimal('0.0001'))
logger.info(f"[北汽] 截止目前产值:周期 [{date_from}, {date_to}) 命中 {len(result)}/{len(ids)} 家门店")
return result
# 订单数统计(用户 2026-09-22 明确,见 fetch_order_count):按门店 + 业务类型(延保/权益)分组。
# 口径:sub_order.deleted_flag='N' AND goods_order.deleted_flag='N' AND merchant_id=门店编码
# AND scene_type=0 AND business_type=2 AND status=4
# AND pay_order.deleted_flag='N' AND pay_status=2 AND success_date ∈ [周期起, 周期止+1天)
# 映射:upgrade_secondary_goods_type_name='整车延保' -> 延保(1);'原厂权益' -> 权益(2);其余忽略。
BAIC_ORDER_COUNT_SQL = """
SELECT a.merchant_id AS merchant_id,
gso.upgrade_secondary_goods_type_name AS goods_type_name,
COUNT(0) AS order_cnt
FROM dj_car_life_goods_sub_order gso
LEFT JOIN dj_car_life_goods_order a
ON a.order_code = gso.order_code AND a.deleted_flag = 'N'
LEFT JOIN dj_car_life_pay_order b
ON b.order_code = a.order_code AND b.deleted_flag = 'N' AND b.pay_status = 2
WHERE gso.deleted_flag = 'N'
AND a.merchant_id IN :merchant_ids
AND a.scene_type = 0
AND a.business_type = 2
AND a.status = 4
AND b.success_date >= :date_from
AND b.success_date < :date_to
GROUP BY a.merchant_id, gso.upgrade_secondary_goods_type_name
"""
def fetch_order_count(period_start, period_end, merchant_ids):
"""查询各门店「延保/权益订单数」(dj_smartcarlife,按门店+业务类型分组一次查全)。
:param period_start: 周期开始日期(date)
:param period_end: 周期结束日期(date,含当天 → 查询上界取次日)
:param merchant_ids: 门店 D+ 编码集合(store_code)
:return: {merchant_id(str): {业务类型编码(int): 订单数(int)}};失败/无数据返回 {}(不致命)。
"""
result = {}
ids = [int(c) for c in {str(c).strip() for c in merchant_ids if c not in (None, '')}
if str(c).strip().isdigit()]
if not ids or not period_start or not period_end:
return result
date_from = period_start.strftime('%Y-%m-%d')
date_to = (period_end + timedelta(days=1)).strftime('%Y-%m-%d')
engine = _get_biz_engine()
try:
with engine.connect() as conn:
stmt = text(BAIC_ORDER_COUNT_SQL).bindparams(
bindparam('merchant_ids', expanding=True))
rows = conn.execute(
stmt,
{'merchant_ids': ids, 'date_from': date_from, 'date_to': date_to},
).fetchall()
except Exception as e:
logger.warning(f"[北汽] 订单数查询失败: {e}")
return result
for r in rows:
mid, gtn, cnt = r[0], (r[1] or '').strip(), r[2]
if mid is None or cnt is None:
continue
biz = ORDER_CNT_TYPE_MAP.get(gtn)
if biz is None:
continue
result.setdefault(str(mid), {})[biz] = int(cnt)
logger.info(f"[北汽] 订单数:周期 [{date_from}, {date_to}) 命中 {len(result)}/{len(ids)} 家门店"
f"(仅统计整车延保/原厂权益)")
return result
def fetch_order_count_window(period_start, period_end, merchant_ids):
"""查询各门店『截止 period_end(含当天)累计』的延保/权益订单数。
与 fetch_order_count 同口径(同样的 BAIC_ORDER_COUNT_SQL 谓词),仅成功日期上界不同,
用于周度评灯 / 截止目前 的「截止到当前周累计」订单数:
success_date ∈ [period_start, period_end + 1 天)
返回 {merchant_id(str): {业务类型编码(int): 订单数(int)}};失败/无数据返回 {}(不致命)。
"""
result = {}
ids = [int(c) for c in {str(c).strip() for c in merchant_ids if c not in (None, '')}
if str(c).strip().isdigit()]
if not ids or not period_start or not period_end:
return result
date_from = period_start.strftime('%Y-%m-%d')
date_to = (period_end + timedelta(days=1)).strftime('%Y-%m-%d')
engine = _get_biz_engine()
try:
with engine.connect() as conn:
stmt = text(BAIC_ORDER_COUNT_SQL).bindparams(
bindparam('merchant_ids', expanding=True))
rows = conn.execute(
stmt,
{'merchant_ids': ids, 'date_from': date_from, 'date_to': date_to},
).fetchall()
except Exception as e:
logger.warning(f"[北汽] 累计订单数查询失败(窗口 {date_from}~{date_to}): {e}")
return result
for r in rows:
mid, gtn, cnt = r[0], (r[1] or '').strip(), r[2]
if mid is None or cnt is None:
continue
biz = ORDER_CNT_TYPE_MAP.get(gtn)
if biz is None:
continue
result.setdefault(str(mid), {})[biz] = int(cnt)
logger.info(f"[北汽] 累计订单数(窗口 {date_from}~{date_to}) 命中 {len(result)}/{len(ids)} 家门店")
return result
def compute_baic_week_ends(month, cutoff_date):
"""计算北汽报表周度评灯节点的结束日期(与 app.compute_week_period 同一套周规则)。
规则:当月第一个周一为 W1 起始日,每周周一~周日。
W1 结束 = 第一个周一 + 6 天;W2 = +13;W3 = +20。
返回 [(label, end_date), ...],列顺序固定为 [截止目前, W1, W2, W3],
对应结果表 T/U/V/W 四列(BAIC_LIGHT_COLS)。
end_date 为 date;month 非法时 W1/W2/W3 返回 None。
"""
w1 = w2 = w3 = None
if len(month) >= 7 and month[4] == '-':
try:
y, m = int(month[:4]), int(month[5:7])
first = date(y, m, 1)
offset = (7 - first.weekday()) % 7 # 周一=0 → offset 0;周六=5 → +2 天到周一
first_monday = first + timedelta(days=offset)
w1 = first_monday + timedelta(days=6)
w2 = first_monday + timedelta(days=13)
w3 = first_monday + timedelta(days=20)
except (ValueError, IndexError):
w1 = w2 = w3 = None
return [
('截止目前', cutoff_date),
('W1', w1),
('W2', w2),
('W3', w3),
]
def fetch_delivery_snapshot_by_dates(stat_dates):
"""从基础表 glsx_daily_deal_subtotal 批量取各门店的「累计交付数(delivery_cnt)」快照。
背景(用户 2026-09-24 明确):北汽结果表 W1/W2/W3 的综合渗透公式中,
分子「订单数」实时查 D+;分母「新车交付数(累计交付数)」改从本基础表按
**该周结束日的 stat_date** 取(日快照,由 GlsxDailyScheduler 每日产出)。
:param stat_dates: 可迭代的 date 集合(各周结束日);None/空 → 返回 {}
:return: {stat_date(date): {store_name: delivery_cnt}};
缺失的日期不出现在返回 dict 中(调用方据此判「无快照 → 无法评估」)。
任何异常返回 {}(不致命,仅告警),保证结果表生成不因缺快照而失败。
"""
ds = [d for d in (stat_dates or []) if d]
if not ds:
return {}
try:
rows = (GlsxDailyDealSubtotal.query
.filter(GlsxDailyDealSubtotal.stat_date.in_(ds),
GlsxDailyDealSubtotal.is_deleted == 0)
.all())
out = {}
for r in rows:
if r.stat_date is None:
continue
out.setdefault(r.stat_date, {})[r.store_name] = r.delivery_cnt
logger.info(f'[北汽] 周度交付数快照:查询 {len(ds)} 个日期,命中 '
f'{len(out)} 个({ {str(k): len(v) for k, v in out.items()} })')
return out
except Exception as e:
logger.warning(f'[北汽] 读取 glsx_daily_deal_subtotal 交付数快照失败: {e}')
return {}
def _baic_light(penetration, excellent, standard):
"""按综合渗透与评灯标准判定门店等级灯色。
:param penetration: 综合渗透小数(如 0.4363)或 None(无法计算)
:param excellent: 优秀值小数(X 列)或 None(品牌未匹配)
:param standard: 标准值小数(Y 列)或 None(品牌未匹配)
:return: (灯色文字, 底色 hex) ;无法计算(渗透率为 None 或无标准值)返回 (None, None)
规则:综合渗透 > 优秀值 → 绿;> 标准值 → 黄;否则 → 红。
注意:渗透率为小数、标准值亦为小数,直接比较(勿 ×100 / 勿 ÷100)。
"""
if penetration is None or standard is None:
return None, None
try:
p = float(penetration)
std = float(standard)
exc = float(excellent) if excellent is not None else None
except (TypeError, ValueError):
return None, None
if exc is not None and p > exc:
return '绿', BAIC_LIGHT_FILL['绿']
if p > std:
return '黄', BAIC_LIGHT_FILL['黄']
return '红', BAIC_LIGHT_FILL['红']
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_rate(v):
"""比率值归一为小数比率。
源文件汇总段的「售后场景开通率」由线上运营以**百分数**形式上传
(如 22 表示 22%),而结果模板该列为 0.0% 格式、DB 列为 DECIMAL 小数,
故 |v| > 1 时按百分数 ÷100;已是小数(|v| <= 1)则原样返回。
"""
d = _to_dec(v)
if d is None:
return None
try:
return (d / Decimal(100)) if abs(d) > 1 else d
except (InvalidOperation, TypeError):
return None
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):
"""business_start_date:DATE/DATETIME/字符串(YYYY-MM-DD) -> date;空 -> None"""
if v is None:
return None
if isinstance(v, datetime):
return v.date()
if isinstance(v, 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 BaicSpecialProcessor:
"""北汽专项独立处理器"""
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(基于用户模板:源文件 5 列覆盖 + 品牌汇总固定项)
try:
url = self.generate_result_excel(task)
except Exception as ge:
logger.warning(f"[北汽] 结果表生成失败(task {task_id}): {ge}")
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_baic_special(self):
"""扫描 baic_special 类型的 PROCESSING 任务并逐个处理(供 BaicSpecialScheduler 调用)。"""
logger.info("[北汽] 开始扫描 baic_special 待处理任务")
tasks = DataProcessTask.query.filter_by(
data_table_type='baic_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 scan_baic_weekly(self):
"""手动补数入口:**只写 glsx_daily_deal_subtotal 基础表,不做其他逻辑**。
口径(用户 2026-09-24 明确,2026-09-24 晚已下线对应定时任务):
- 原为「每周日 23:00」定时任务,现该定时任务已移除,改为**仅保留每日快照任务**
(GlsxDailyScheduler,每日 07:00 写 stat_date=昨天),本方法仅保留作手动补数用;
- 本方法**不写** baic_special_month_data 的任何字段(w{n}_order_cnt /
w{n}_new_delivery_cnt / w{n}_comprehensive_penetration / w{n}_light_level 均由
结果表生成 generate_result_excel 按渲染口径回写);
- 本方法**不查** D+ 订单数。
动作:把「今天」的通用品牌报表快照落库基础表
(glsx_daily_processor.snapshot_glsx(stat_date=今天),按 stat_date 幂等)。
该日快照即北汽 W1/W2/W3 综合渗透「新车交付数」分母的来源。
"""
today = date.today()
try:
from glsx_daily_processor import snapshot_glsx
except Exception as e:
logger.error(f"[北汽周快照] 导入 snapshot_glsx 失败: {e}")
return {'success': 0, 'error': str(e)}
result = snapshot_glsx(today)
logger.info(f"[北汽周快照] 基础表快照(stat_date={today})结果: {result}")
return result
# ============================================================
# 解析
# ============================================================
def _parse(self, task):
task_id = task.id
tmp_dir = tempfile.mkdtemp(prefix=f'baic_{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 行起取门店明细;
# 末尾汇总段(如 r52「北汽品牌汇总」+ r53 售后门店数 + r54 售后场景开通率)单独解析。
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:
attr = SUMMARY_LABELS[label]
val = row[1] if len(row) > 1 else None
summary_vals[attr] = _to_rate(val) if attr in RATE_SUMMARY_ATTRS else val
continue
rec = {
'store_name': str(a).strip(),
'brand': (str(row[SRC_BRAND]).strip()
if len(row) > SRC_BRAND and row[SRC_BRAND] not in (None, '') else None),
'underwriting_rule': (str(row[SRC_UNDERWRITING]).strip()
if len(row) > SRC_UNDERWRITING and row[SRC_UNDERWRITING] not in (None, '') else None),
'delivery_check_group_cnt': (_to_int(row[SRC_DELIVERY_GROUP])
if len(row) > SRC_DELIVERY_GROUP else None),
'visit_check_group_cnt': (_to_int(row[SRC_VISIT_GROUP])
if len(row) > SRC_VISIT_GROUP else None),
}
# 跳过纯标签/汇总段行(品牌与数值均为空),仅保留真实门店行
if (rec['brand'] is None
and rec['delivery_check_group_cnt'] is None
and rec['visit_check_group_cnt'] is None):
continue
detail_rows.append(rec)
if not detail_rows:
logger.warning(f"[北汽] 任务 {task_id} 未解析到任何明细门店行")
logger.info(f"[北汽] 任务 {task_id} 汇总段解析:{summary_vals}")
# ---- 补充 D+ 系统基础信息(门店编码/区域/驻店类型/业务开展/区域运营)----
store_info = fetch_baic_store_info()
matched = 0
unmatched = []
for rec in detail_rows:
info = store_info.get(rec['store_name'])
if info:
matched += 1
rec.update(info)
else:
unmatched.append(rec['store_name'])
rec.update({'store_code': None, 'region': None, 'store_type': None,
'business_start_date': None, 'operator_name': None,
'resident_staff': None})
logger.info(f"[北汽] 任务 {task_id} D+ 基础信息匹配:{matched}/{len(detail_rows)} 家"
+ (f";未匹配 {unmatched}" if unmatched else ""))
# ---- 补充广联报表(产值目标/新车交付数/触客数系统/交车数核对-产值表/触客数核对-产值表)----
stat_month = (getattr(task, 'month', None) or '')
glsx_map = fetch_glsx_report(stat_month)
glsx_matched = 0
glsx_unmatched = []
for rec in detail_rows:
g = glsx_map.get(rec['store_name'])
if g:
glsx_matched += 1
rec.update(g)
else:
glsx_unmatched.append(rec['store_name'])
rec.update({'output_target_wan': None, 'new_delivery_cnt': None,
'visit_cnt': None, 'delivery_check_output_cnt': None,
'visit_check_output_cnt': None})
logger.info(f"[北汽] 任务 {task_id} 广联报表匹配:{glsx_matched}/{len(detail_rows)} 家"
+ (f";未匹配 {glsx_unmatched}" if glsx_unmatched else ""))
# ---- 触客率 = 触客数 ÷ 新车交付数(两者同为广联报表口径,均取非小计行)----
rate_hit = 0
for rec in detail_rows:
rec['visit_rate'] = _ratio(_to_int(rec.get('visit_cnt')),
_to_int(rec.get('new_delivery_cnt')))
if rec['visit_rate'] is not None:
rate_hit += 1
logger.info(f"[北汽] 任务 {task_id} 触客率计算:{rate_hit}/{len(detail_rows)} 家"
f"(新车交付数为空或 0 的门店留空)")
# ---- 补充「截止目前产值」(D+ 支付成功金额汇总)与「达成率」----
# 需在 D+ 基础信息(拿 store_code)与广联报表(拿产值目标)之后执行。
p_start, p_end = _task_period(task)
code_recs = {}
for rec in detail_rows:
code = rec.get('store_code')
if code:
code_recs.setdefault(str(code), []).append(rec)
current_map = fetch_output_current(p_start, p_end, code_recs.keys())
cur_hit = 0
for code, recs in code_recs.items():
wan = current_map.get(code)
if wan is None:
for rec in recs:
rec['output_current_wan'] = None
rec['achievement_rate'] = None
continue
cur_hit += 1
for rec in recs:
rec['output_current_wan'] = wan
target = _to_dec(rec.get('output_target_wan'))
# 达成率 = 截止目前产值 ÷ 产值目标(同为万元,比值为无量纲小数)
rec['achievement_rate'] = ((Decimal(str(wan)) / target)
if target else None)
logger.info(f"[北汽] 任务 {task_id} 截止目前产值:{cur_hit}/{len(code_recs)} 家"
f"(共 {len(detail_rows)} 家门店,{len(detail_rows) - len(code_recs)} 家无门店编码)")
# ---- 补充「延保/权益订单数」(D+ 子订单 dj_car_life_goods_sub_order)----
# 需在 D+ 基础信息(拿 store_code)之后执行;按门店编码匹配,写入 rec 待 _save 落库。
order_map = fetch_order_count(p_start, p_end, code_recs.keys())
for code, recs in code_recs.items():
om = order_map.get(code, {})
ew = om.get(BAIC_BIZ_EXT_WARRANTY)
rt = om.get(BAIC_BIZ_RIGHTS)
for rec in recs:
rec['ext_warranty_order_cnt'] = ew
rec['rights_order_cnt'] = rt
logger.info(f"[北汽] 任务 {task_id} 订单数:{len(order_map)}/{len(code_recs)} 家门店命中"
f"(整车延保/原厂权益)")
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 ''))
# ---------- 明细 ----------
# 逻辑删除(软删除):将本任务旧行置 is_deleted=1,再插入新行(is_deleted=0)
BaicSpecialMonthData.query.filter_by(task_id=task_id, is_deleted=0).update(
{BaicSpecialMonthData.is_deleted: 1}, synchronize_session=False)
db.session.flush()
detail_objs = []
for rec in detail_rows:
# 核对值先归一为 int,再据此计算差异,保证落库与结果表口径完全一致
dc_output = _to_int(rec.get('delivery_check_output_cnt'))
dc_group = _to_int(rec.get('delivery_check_group_cnt'))
vc_output = _to_int(rec.get('visit_check_output_cnt'))
vc_group = _to_int(rec.get('visit_check_group_cnt'))
# 评灯标准按品牌固定取值(北汽极狐 0.5/0.3/0.3;北京越野 0.5/0.4/0.4)
lv_excellent, lv_standard, lv_warning = _light_standard(rec.get('brand'))
detail_objs.append(BaicSpecialMonthData(
task_id=task_id,
is_deleted=0,
stat_month=stat_month,
store_name=rec.get('store_name') or '',
brand=rec.get('brand'),
# 区域 / 驻店类型来自 D+ 系统(NOT NULL,未匹配时占位空串)
region=rec.get('region') or '',
store_type=rec.get('store_type') or '',
store_code=rec.get('store_code'),
business_start_date=_to_date(rec.get('business_start_date')),
operator_name=rec.get('operator_name'),
# 驻店人员来自 SCRM(园区店「驻店人员」角色,多人以「/」分隔)
resident_staff=rec.get('resident_staff'),
underwriting_rule=rec.get('underwriting_rule'),
delivery_check_group_cnt=dc_group,
visit_check_group_cnt=vc_group,
# 广联报表(dj.glsx.com.cn 延保+权益门店产值及个人成交排名·通用品牌):
# output_target_wan <- 延保小计行 H(8月目标产值(万元))
# new_delivery_cnt <- 非小计行 K(累计交付数(台))同店取 max
# visit_cnt <- 非小计行 O(实际售前触客数)同店取 max
# delivery_check_output_cnt <- 延保小计行 K(交车数核对-产值表)
# visit_check_output_cnt <- 延保小计行 O(触客数核对-产值表)
# 以上 5 项按门店名从报表匹配;未匹配门店留 NULL。
output_target_wan=_to_dec(rec.get('output_target_wan')),
# 截止目前产值(万,D+ 支付成功金额/10000)与达成率(=截止目前产值 ÷ 产值目标)
output_current_wan=_to_dec(rec.get('output_current_wan')),
achievement_rate=_to_dec(rec.get('achievement_rate')),
new_delivery_cnt=_to_int(rec.get('new_delivery_cnt')),
visit_cnt=_to_int(rec.get('visit_cnt')),
# 触客率 = 触客数 ÷ 新车交付数(无量纲小数,任一侧为空或分母 0 → NULL)
visit_rate=_to_dec(rec.get('visit_rate')),
delivery_check_output_cnt=dc_output,
visit_check_output_cnt=vc_output,
# 差异 = 产值表 - 一店一群(任一侧为空则留 NULL),与结果表 AC/AF 列同口径
delivery_check_diff=_diff(dc_output, dc_group),
visit_check_diff=_diff(vc_output, vc_group),
# 评灯标准(优秀值/标准值/预警值):按品牌固定取值,未匹配品牌留 NULL
excellent_value=_to_dec(lv_excellent),
standard_value=_to_dec(lv_standard),
warning_value=_to_dec(lv_warning),
))
db.session.add_all(detail_objs)
# flush 以拿到自增 store_id,供下方业务行(baic_special_monthly_business)外键引用
db.session.flush()
# 确保业务表存在(首次部署时按 ORM 定义补建,checkfirst 幂等;不删除任何数据)
BaicSpecialMonthlyBusiness.__table__.create(db.engine, checkfirst=True)
# ---------- 业务(逐门店×业务:延保/权益)----------
# 订单数来自 D+ 子订单(dj_car_life_goods_sub_order),经 fetch_order_count 计算后挂在 rec 上。
# 幂等:先按本任务主表明细 store_id 删除旧业务行,再插入新行(该表无 is_deleted 列,物理删除)。
old_biz_ids = [r.store_id for r in BaicSpecialMonthData.query.filter_by(task_id=task_id).all()]
if old_biz_ids:
BaicSpecialMonthlyBusiness.query.filter(
BaicSpecialMonthlyBusiness.store_id.in_(old_biz_ids)).delete(synchronize_session=False)
db.session.flush()
biz_objs = []
for rec, obj in zip(detail_rows, detail_objs):
sid = obj.store_id
ew = _to_int(rec.get('ext_warranty_order_cnt'))
rt = _to_int(rec.get('rights_order_cnt'))
if ew is not None:
biz_objs.append(BaicSpecialMonthlyBusiness(
store_id=sid, business_type=BAIC_BIZ_EXT_WARRANTY, order_cnt=ew))
if rt is not None:
biz_objs.append(BaicSpecialMonthlyBusiness(
store_id=sid, business_type=BAIC_BIZ_RIGHTS, order_cnt=rt))
db.session.add_all(biz_objs)
# ---------- 汇总(单任务一行)----------
# 逻辑删除(软删除)旧汇总行,再插入新行
BaicSpecialMonthSummaryMetrics.query.filter_by(task_id=task_id, is_deleted=0).update(
{BaicSpecialMonthSummaryMetrics.is_deleted: 1}, synchronize_session=False)
db.session.flush()
brand, summary_vals = summary_tuple if summary_tuple else (None, {})
sum_obj = BaicSpecialMonthSummaryMetrics(
task_id=task_id,
is_deleted=0,
stat_month=stat_month,
project_name='北汽',
brand='北汽',
store_cnt=len(detail_objs),
# 源文件末尾汇总段(品牌级手工上传):售后门店数 / 售后场景开通率
after_sale_store_cnt=_to_int(summary_vals.get('after_sale_store_cnt')),
after_sale_scene_open_rate=_to_dec(summary_vals.get('after_sale_scene_open_rate')),
after_sale_order_cnt=_to_int(summary_vals.get('after_sale_order_cnt')),
# 其余列(产值/交付/触客/渗透/环比)来自 D+ 系统或系统计算,本轮留空
)
db.session.add(sum_obj)
db.session.commit()
logger.info(f"[北汽] 落库完成:明细 {len(detail_objs)} 行 + 汇总 1 行(task_id={task_id},"
f"售后门店数={sum_obj.after_sale_store_cnt},"
f"售后场景开通率={sum_obj.after_sale_scene_open_rate})")
# ============================================================
# 结果表生成(基于模板 exporttemplete/baic_special_report_template.xlsx)
# ============================================================
def generate_result_excel(self, task):
"""根据 task 生成「北汽专项报表」结果 Excel:
- 复制模板布局;标题月份 / 截止日期 / 品牌汇总段月份标签占位替换;
- 按 store_name 用 DB 源值覆盖 5 列(门店名称/品牌/兜底门店/一店一群交车/一店一群触客);
- 品牌汇总本月段(r59)项目/品牌/门店数 覆盖;其余系统列保留模板原样;
- 生成后上传 OSS 并回填 result_file_url。
返回 OSS 可访问 URL(失败抛异常)。"""
task_id = task.id
month = getattr(task, 'month', None) or ''
# 报表月标签 / 上月标签
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 = '', ''
# 截止日期规则:用报表所属月;若当前时间已在所属月之后 → 取所属月最后一天(封账)
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 = BaicSpecialMonthData.query.filter_by(
task_id=task_id, is_deleted=0).order_by(BaicSpecialMonthData.store_id).all()
# 汇总表(单任务一行):售后门店数 / 售后场景开通率 来源于源文件汇总段
summary = BaicSpecialMonthSummaryMetrics.query.filter_by(
task_id=task_id, is_deleted=0).order_by(
BaicSpecialMonthSummaryMetrics.id.desc()).first()
# 业务订单数(逐门店×业务):store_id -> {业务类型编码: 订单数}(来自 baic_special_monthly_business)
store_ids = [d.store_id for d in details]
biz_rows = (BaicSpecialMonthlyBusiness.query.filter(
BaicSpecialMonthlyBusiness.store_id.in_(store_ids)).all()
if store_ids else [])
biz_map = {}
for br in biz_rows:
biz_map.setdefault(br.store_id, {})[br.business_type] = br.order_cnt
# ---- 周度评灯取数:各节点(截止目前/W1/W2/W3)当月累计订单数 ----
# 综合渗透(节点) = 当月累计(延保+权益)订单数 ÷ 新车交付数;
# · 分子:W1/W2/W3 取「截止到当前周」累计(窗口起点=当月1号,上界=各周结束日+1天),实时查 D+
# · 分母:W1/W2/W3 取该周结束日快照(glsx_daily_deal_subtotal.delivery_cnt,见下方 week_delivery_by_node)
# · 截止目前节点:分子上界=cutoff_date(封账后=当月最后一天),分母用全月实时 new_delivery_cnt
month_start_obj = None
if len(month) >= 7 and month[4] == '-':
try:
month_start_obj = date(int(month[:4]), int(month[5:7]), 1)
except (ValueError, IndexError):
month_start_obj = None
cutoff_date_obj = _to_date(cutoff_date)
week_nodes = compute_baic_week_ends(month, cutoff_date_obj)
store_codes = [d.store_code for d in details if d.store_code]
window_biz_by_node = [] # 与 week_nodes 同序:{store_code(str): {biz: cnt}}
for (_lbl, _end) in week_nodes:
if month_start_obj and _end:
window_biz_by_node.append(
fetch_order_count_window(month_start_obj, _end, store_codes))
else:
window_biz_by_node.append({})
logger.info(f"[北汽] 周度评灯节点: {[(lbl, (d.strftime('%Y-%m-%d') if d else None)) for lbl, d in week_nodes]}"
f";门店编码 {len(store_codes)} 个")
# ---- 周度分母取数:W1/W2/W3 的「新车交付数」改从基础表 glsx_daily_deal_subtotal 取 ----
# (用户 2026-09-24 明确:综合渗透公式的分子订单数实时查 D+,
# 分母新车交付数(累计交付数) 从 glsx_daily_deal_subtotal 按该周结束日 stat_date 查)
# 截止目前(T) 仍用全月实时 new_delivery_cnt(本次不改)。
# 快照缺失(该日期无日快照)→ 该门店该周分母 None → 渗透留空且不评灯。
_week_ends = [end for (_lbl, end) in week_nodes[1:] if end]
_snap_delivery = fetch_delivery_snapshot_by_dates(_week_ends)
week_delivery_by_node = [
None if j == 0 else _snap_delivery.get(_end, {})
for j, (_lbl, _end) in enumerate(week_nodes)
]
if not os.path.exists(BAIC_TEMPLATE_PATH):
raise Exception(f'北汽结果表模板不存在:{BAIC_TEMPLATE_PATH}')
wb = openpyxl.load_workbook(BAIC_TEMPLATE_PATH)
ws = wb[wb.sheetnames[0]]
# ---- 标题 ----
ws['A1'] = f"北汽专项报表 ·「{month_label}」页签 · 数据截止 {cutoff_date}"
# ---- 明细门店:动态展开(每家拆 延保/权益 两行,参照示例块 r6/r7)----
EX1, EX2 = 6, 7 # 示例块:r6=延保行, r7=权益行
n = len(details)
if n == 0:
raise Exception('北汽明细数据为空,无法生成结果表')
# 示例块的两行合并(rows 6/7),用于新块复制
example_merges = [str(r) for r in ws.merged_cells.ranges
if r.min_row == EX1 and r.max_row == EX2]
# 可写入的列:源文件字段 + D+ 基础信息(区域/驻店类型/运营/业务开展/驻店人员)
# + 广联报表(产值目标/新车交付数/触客数/交车数核对-产值表/触客数核对-产值表)
# 12/13 = 截止目前产值(万)/ 达成率(D+);24/25/26 = 评灯标准(按品牌固定取值)
# 20/21/22/23 = 周度评灯(截止目前/W1/W2/W3),由代码按综合渗透+评灯标准填灯色+底色
KEEP = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19,
20, 21, 22, 23,
24, 25, 26, 27, 28, 29, 30, 31, 32}
def _fill_block(r_a, r_b, idx, d):
# r_a 为两行合并的锚点行:可写入/清空本块所有列(合并区显示锚点值)
_set_cell(ws, r_a, 1, idx) # A 序号
_set_cell(ws, r_a, 2, d.region or None) # B 区域(D+)
_set_cell(ws, r_a, 3, d.store_type or None) # C 驻店类型(D+:直营/服务商)
_set_cell(ws, r_a, 4, d.store_name) # D 门店名称
_set_cell(ws, r_a, 5, d.brand) # E 品牌
_set_cell(ws, r_a, 6, d.operator_name) # F 运营(D+ 区域运营)
_set_cell(ws, r_a, 7, d.business_start_date) # G 业务开展(D+)
_set_cell(ws, r_a, 8, d.resident_staff) # H 驻店人员(SCRM,多人「/」分隔)
_set_cell(ws, r_a, 9, '延保') # I 业务
_set_cell(ws, r_a, 10, d.underwriting_rule or '无') # J 兜底门店
_set_cell(ws, r_a, 11, _dec_to_float(d.output_target_wan)) # K 产值目标(万,广联报表)
_set_cell(ws, r_a, 12, _dec_to_float(d.output_current_wan)) # L 截止目前产值(万,D+)
_set_cell(ws, r_a, 13, _dec_to_float(d.achievement_rate)) # M 达成率(=L/K)
_set_cell(ws, r_a, 14, d.new_delivery_cnt) # N 新车交付数(广联报表)
_set_cell(ws, r_a, 15, d.visit_cnt) # O 触客数(广联报表)
_set_cell(ws, r_a, 16, _dec_to_float(d.visit_rate)) # P 触客率(=触客数÷新车交付数)
# 评灯标准(按品牌固定取值:北汽极狐 0.5/0.3/0.3;北京越野 0.5/0.4/0.4)
_set_cell(ws, r_a, 24, _dec_to_float(d.excellent_value)) # X 优秀值
_set_cell(ws, r_a, 25, _dec_to_float(d.standard_value)) # Y 标准值
_set_cell(ws, r_a, 26, _dec_to_float(d.warning_value)) # Z 预警值
_set_cell(ws, r_a, 27, d.delivery_check_output_cnt) # AA 交车数核对-产值表(广联报表)
_set_cell(ws, r_a, 28, d.delivery_check_group_cnt) # AB 一店一群交车数
_set_cell(ws, r_a, 30, d.visit_check_output_cnt) # AD 触客数核对-产值表(广联报表)
_set_cell(ws, r_a, 31, d.visit_check_group_cnt) # AE 一店一群触客数
# 差异列 = 产值表 - 一店一群(任一侧为空则差异为空)
_set_cell(ws, r_a, 29, _diff(d.delivery_check_output_cnt, d.delivery_check_group_cnt)) # AC 交车数核对-差异
_set_cell(ws, r_a, 32, _diff(d.visit_check_output_cnt, d.visit_check_group_cnt)) # AF 触客数核对-差异
# 订单数(D+ 子订单,按业务类型)与渗透率
new_delivery = d.new_delivery_cnt # N 新车交付数
ext_cnt = biz_map.get(d.store_id, {}).get(BAIC_BIZ_EXT_WARRANTY) # 整车延保订单数
rights_cnt = biz_map.get(d.store_id, {}).get(BAIC_BIZ_RIGHTS) # 原厂权益订单数
# Q 订单数
_set_cell(ws, r_a, 17, ext_cnt) # Q 延保订单数
# R 交车渗透率 = 本行订单数 ÷ 新车交付数
_set_cell(ws, r_a, 18, _penetration(ext_cnt, new_delivery))
# S 综合渗透 = (延保订单数 + 权益订单数) ÷ 新车交付数(门店级,两行同值)
_combined = ((ext_cnt if ext_cnt is not None else 0)
+ (rights_cnt if rights_cnt is not None else 0))
_set_cell(ws, r_a, 19, _penetration(_combined, new_delivery))
# ---- 周度评灯(截止目前/W1/W2/W3):T/U/V/W 列(BAIC_LIGHT_COLS)----
# 综合渗透(节点) = 当月累计(延保+权益)订单数 ÷ 新车交付数
# · 分子:W1/W2/W3 订单数取「截止到当前周」累计(见 window_biz_by_node),实时查 D+
# · 分母:W1/W2/W3 用该周结束日快照(glsx_daily_deal_subtotal.delivery_cnt,
# 见 week_delivery_by_node);截止目前(T) 仍用全月实时 new_delivery_cnt
# · 分母缺失(该周结束日无日快照 / 交付数为 0)→ 渗透 None → 该格留空且不评灯
# 灯色:综合渗透 > 优秀值(X) → 绿;> 标准值(Y) → 黄;否则 → 红(底色见 BAIC_LIGHT_FILL)
# 评灯标准为小数(如 0.5=50%),与综合渗透(小数)直接比较,切勿 ×100。
scode = str(d.store_code) if d.store_code is not None else None
for j, (_lbl, _end) in enumerate(week_nodes):
wb_node = window_biz_by_node[j] if j < len(window_biz_by_node) else {}
ec = wb_node.get(scode, {}).get(BAIC_BIZ_EXT_WARRANTY) if scode else None
rc = wb_node.get(scode, {}).get(BAIC_BIZ_RIGHTS) if scode else None
comb_node = ((ec if ec is not None else 0)
+ (rc if rc is not None else 0))
# 分母:j=0(截止目前)用全月实时新车交付数;W1/W2/W3 用该周结束日快照
if j == 0:
node_delivery = new_delivery
else:
_snap = week_delivery_by_node[j] if j < len(week_delivery_by_node) else {}
node_delivery = _snap.get(d.store_name)
pen_node = _penetration(comb_node, node_delivery)
light_txt, light_fill = _baic_light(pen_node, d.excellent_value, d.standard_value)
col = BAIC_LIGHT_COLS[j]
_set_cell(ws, r_a, col, light_txt) # 绿/黄/红 文字(None=无法评估,留空)
# 显式清/设底色:有灯色则填充;无灯色(无法评估,如门店无编码/无标准值)
# 必须清除模板示例块/插入行的残留底色,避免误显为某色灯。
ws.cell(r_a, col).fill = (
PatternFill(start_color=light_fill, end_color=light_fill, fill_type='solid')
if light_fill else PatternFill(fill_type='none'))
# ---- 回写 baic_special_month_data:W1/W2/W3 周度字段(与 Excel 同口径)----
# j=0 为「截止目前」节点,无对应 w0 列 → 跳过;j=1/2/3 → w1/w2/w3。
# w{n}_order_cnt 该周累计(延保+权益)订单数(无门店编码→None,无法统计)
# w{n}_new_delivery_cnt 该周结束日快照交付数(无快照→None)
# w{n}_comprehensive_penetration 综合渗透(分母缺失→None)
# w{n}_light_level 灯级(绿/黄/红;无法评估→None)
if j >= 1:
setattr(d, f'w{j}_order_cnt', (comb_node if scode else None))
setattr(d, f'w{j}_new_delivery_cnt',
(int(node_delivery) if node_delivery is not None else None))
setattr(d, f'w{j}_comprehensive_penetration', pen_node)
setattr(d, f'w{j}_light_level', light_txt)
# 其余列(截止目前产值/达成率/触客率/周趋势等)来自 D+ 或系统计算,尚未接入 → 清空
for c in range(1, 33):
if c not in KEEP:
_set_cell(ws, r_a, c, None)
# r_b(权益行)仅非合并列可写:业务(I) + Q/R/S
_set_cell(ws, r_b, 9, '权益')
_set_cell(ws, r_b, 17, rights_cnt) # Q 权益订单数
_set_cell(ws, r_b, 18, _penetration(rights_cnt, new_delivery)) # R 交车渗透率
# 注:S(19) 综合渗透为两行合并的只读格,仅写在 r_a 锚点行(见上),
# 合并区会自动把门店级同值显示到本行。
# 一次性在示例块之后插入 (n-1)*2 行。
# 注意:openpyxl 的 insert_rows 只移动单元格值、不移动已合并区域,
# 故先解除「示例块之后」的合并(品牌汇总段标签行 A10:AF10 / A14:AF14),
# 插入后按偏移重建,避免标签合并区压住门店行导致取值丢失。
extra = (n - 1) * 2
shift_merges = [(rng.min_col, rng.min_row, rng.max_col, rng.max_row)
for rng in ws.merged_cells.ranges if rng.min_row >= EX2 + 1]
for (_c1, _r1, _c2, _r2) in shift_merges:
ws.unmerge_cells(f"{get_column_letter(_c1)}{_r1}:{get_column_letter(_c2)}{_r2}")
if extra > 0:
ws.insert_rows(EX2 + 1, extra)
for (_c1, _r1, _c2, _r2) in shift_merges:
ws.merge_cells(
f"{get_column_letter(_c1)}{_r1 + extra}:"
f"{get_column_letter(_c2)}{_r2 + extra}")
# 逐块填写:第 i 家(0-based)占 r_a=6+2i(延保)/ r_b=r_a+1(权益)
for i in range(n):
r_a = EX1 + 2 * i
r_b = r_a + 1
if i > 0:
# 复制示例块样式并重建两行合并单元格
for c in range(1, 33):
ws.cell(r_a, c)._style = copy(ws.cell(EX1, c)._style)
ws.cell(r_b, c)._style = copy(ws.cell(EX2, c)._style)
delta = 2 * i
for mr in example_merges:
L, R = mr.split(':')
m_l = re.match(r'([A-Z]+)(\d+)', L)
m_r = re.match(r'([A-Z]+)(\d+)', R)
new_mr = (f"{m_l.group(1)}{int(m_l.group(2)) + delta}:"
f"{m_r.group(1)}{int(m_r.group(2)) + delta}")
try:
ws.merge_cells(new_mr)
except Exception:
pass
_fill_block(r_a, r_b, i + 1, details[i])
# ---- 合计行(r4/r5):订单数按业务类型汇总 + 渗透率 ----
# r4 为两行合并的锚点行,写 r4 即可清空合并区显示;
# Q/R/S(订单数/交车渗透率/综合渗透)为非合并列,需对 r5 单独写。
ext_total = sum((biz_map.get(d.store_id, {}).get(BAIC_BIZ_EXT_WARRANTY) or 0) for d in details)
rights_total = sum((biz_map.get(d.store_id, {}).get(BAIC_BIZ_RIGHTS) or 0) for d in details)
total_delivery = sum((d.new_delivery_cnt or 0) for d in details) # 全门店新车交付数合计
# 清空 r4 的 11~32 计算列(保留 R/S 后续单独填)
for c in range(11, 33):
if c in (18, 19):
continue
_set_cell(ws, 4, c, None)
_set_cell(ws, 5, 17, None)
# 订单数列(Q=17):r4=延保合计,r5=权益合计(D+ 子订单统计)
_set_cell(ws, 4, 17, ext_total)
_set_cell(ws, 5, 17, rights_total)
# 交车渗透率(R=18):本业务订单数合计 ÷ 全门店新车交付数合计
_set_cell(ws, 4, 18, _penetration(ext_total, total_delivery))
_set_cell(ws, 5, 18, _penetration(rights_total, total_delivery))
# 综合渗透(S=19):(延保合计 + 权益合计) ÷ 全门店新车交付数合计。
# S 列为两行合并只读格,仅写 r4 锚点行,合并区显示到 r5。
_combined_total = ext_total + rights_total
_set_cell(ws, 4, 19, _penetration(_combined_total, total_delivery))
# ---- 合计行:产值目标/截止目前产值/达成率/新车交付数/触客数/触客率/交车·触客核对(12 项求和)----
# 合计行 r4 为两行合并锚点(K/L/M/N/O/P/AA/AB/AC/AD/AE/AF 均为合并列),写 r4 即在合并区显示。
# 比率列(达成率 M、触客率 P)按「合计分子 ÷ 合计分母」计算,不做简单比率加和(比率相加无意义);
# 差异列合计 = 逐店「差异」之和(仅累计两列均有值、差异非空的门店;任一为空的门店差异本身留空,不计入合计)。
# 不可直接「合计产值表 − 合计一店一群」:后者会把「产值表缺失(通用品牌报表未命中)」的门店当 0 相减,
# 使合计差异偏离逐店可见差异之和(如 4 家门店产值表为空但一店一群有值,会凭空计入负差)。
total_target = sum((_dec_to_float(d.output_target_wan) or 0) for d in details) # K 产值目标合计(万)
total_current = sum((_dec_to_float(d.output_current_wan) or 0) for d in details) # L 截止目前产值合计(万)
total_visit = sum((d.visit_cnt or 0) for d in details) # O 触客数合计
# 达成率(合计) = 合计截止目前产值 ÷ 合计产值目标
_ach_total = (total_current / total_target) if total_target else None
# 触客率(合计) = 合计触客数 ÷ 合计新车交付数
_visit_rate_total = (total_visit / total_delivery) if total_delivery else None
total_deliv_check_out = sum((d.delivery_check_output_cnt or 0) for d in details) # AA 交车数核对-产值表 合计
total_deliv_check_grp = sum((d.delivery_check_group_cnt or 0) for d in details) # AB 交车数核对-一店一群 合计
total_visit_check_out = sum((d.visit_check_output_cnt or 0) for d in details) # AD 触客数核对-产值表 合计
total_visit_check_grp = sum((d.visit_check_group_cnt or 0) for d in details) # AE 触客数核对-一店一群 合计
# 差异列合计 = 逐店差异之和(任一列为空 → 该店差异留空、不计入合计)
total_deliv_diff = sum((_diff(d.delivery_check_output_cnt, d.delivery_check_group_cnt) or 0)
for d in details) # AC 交车数核对-差异 合计
total_visit_diff = sum((_diff(d.visit_check_output_cnt, d.visit_check_group_cnt) or 0)
for d in details) # AF 触客数核对-差异 合计
_set_cell(ws, 4, 11, total_target) # K 产值目标(万)合计
_set_cell(ws, 4, 12, total_current) # L 截止目前产值(万)合计
_set_cell(ws, 4, 13, _ach_total) # M 达成率 合计(=合计L÷合计K)
_set_cell(ws, 4, 14, total_delivery) # N 新车交付数 合计
_set_cell(ws, 4, 15, total_visit) # O 触客数 合计
_set_cell(ws, 4, 16, _visit_rate_total) # P 触客率 合计(=合计O÷合计N)
_set_cell(ws, 4, 27, total_deliv_check_out) # AA 交车数核对-产值表 合计
_set_cell(ws, 4, 28, total_deliv_check_grp) # AB 交车数核对-一店一群 合计
_set_cell(ws, 4, 29, total_deliv_diff) # AC 交车数核对-差异 合计(逐店差异之和)
_set_cell(ws, 4, 30, total_visit_check_out) # AD 触客数核对-产值表 合计
_set_cell(ws, 4, 31, total_visit_check_grp) # AE 触客数核对-一店一群 合计
_set_cell(ws, 4, 32, total_visit_diff) # AF 触客数核对-差异 合计(逐店差异之和)
# ---- 周度评灯节点聚合综合渗透(T/U/V/W 列,r4 锚点行,写数值不写灯色)----
# 各节点综合渗透 = Σ门店该节点累计(延保+权益)订单数 ÷ Σ门店该节点新车交付数
# ⚠ 分子与分母必须同口径(同一门店集合),否则会出现 >1 的无意义值:
# 截止目前(T):门店集合 = 有 store_code 的门店;分母 = 全月新车交付数合计
# W1/W2/W3 :门店集合 = 该周结束日「有快照交付数」且有 store_code 的门店;
# 分母 = 该集合的快照 delivery_cnt 合计(无快照门店不参与分子分母)
for j, (_lbl, _end) in enumerate(week_nodes):
wb_node = window_biz_by_node[j] if j < len(window_biz_by_node) else {}
if j == 0:
_univ = [d for d in details if d.store_code]
node_delivery_total = total_delivery
else:
_snap = week_delivery_by_node[j] if j < len(week_delivery_by_node) else {}
_univ = [d for d in details
if d.store_code and _snap.get(d.store_name) is not None]
node_delivery_total = sum((_snap.get(d.store_name) or 0) for d in _univ)
ec_total = sum((wb_node.get(str(d.store_code), {}).get(BAIC_BIZ_EXT_WARRANTY) or 0)
for d in _univ)
rc_total = sum((wb_node.get(str(d.store_code), {}).get(BAIC_BIZ_RIGHTS) or 0)
for d in _univ)
comb_total = ec_total + rc_total
_set_cell(ws, 4, BAIC_LIGHT_COLS[j], _penetration(comb_total, node_delivery_total))
# ---- 回写落库:把本次渲染算出的 W1/W2/W3 周度字段持久化 ----
# 说明:_fill_block 已把 w{n}_order_cnt / w{n}_new_delivery_cnt /
# w{n}_comprehensive_penetration / w{n}_light_level 设到各 details 对象上,
# 此处统一提交;失败仅告警,不影响 Excel 生成与 OSS 上传。
try:
db.session.commit()
logger.info(f"[北汽] 周度字段(W1/W2/W3)已回写 baic_special_month_data:{len(details)} 行"
f"(task {task_id})")
except Exception as we:
db.session.rollback()
logger.warning(f"[北汽] 周度字段回写失败(task {task_id},不影响结果表): {we}")
# ---- 品牌汇总 本月/上月段:插入门店行后位置下移,动态定位 ----
cur_month_row = cur_prev_row = None
for r in range(1, ws.max_row + 1):
v = ws.cell(r, 1).value
if v and '本月' in str(v):
cur_month_row = r
elif v and '上月' in str(v):
cur_prev_row = r
if cur_month_row is not None:
lbl = ws.cell(cur_month_row, 1).value
if lbl and '本月' in str(lbl):
ws.cell(cur_month_row, 1).value = re.sub(
r'本月\s*\S*', f'本月 {month_label}', str(lbl))
data_row = cur_month_row + 2
_set_cell(ws, data_row, 1, '北汽') # 项目
_set_cell(ws, data_row, 2, '北汽') # 品牌(框架轮填北汽;D+ 接入后改极狐/越野)
_set_cell(ws, data_row, 3, n) # 门店数
# 品牌汇总本月段:与合计行同口径聚合(D~N 系统/计算列均填,O~R 环比框架轮留空)
_set_cell(ws, data_row, 4, total_current) # D 产值(万)= 截止目前产值合计
_set_cell(ws, data_row, 5, total_delivery) # E 交付数 = 新车交付数合计
_set_cell(ws, data_row, 6, total_visit) # F 售前触客数 = 触客数合计
_set_cell(ws, data_row, 7, _visit_rate_total) # G 售前触客率 = 合计触客率
# H 售后门店数 / I 售后场景开通率(源文件末尾汇总段,经汇总表落库后回填)
if summary:
_set_cell(ws, data_row, 8, summary.after_sale_store_cnt)
_set_cell(ws, data_row, 9, _dec_to_float(summary.after_sale_scene_open_rate))
_set_cell(ws, data_row, 10, _combined_total) # J 售后订单数 = 延保+权益成交合计
_set_cell(ws, data_row, 11, ext_total) # K 整车延保成交数 = 延保订单合计
_set_cell(ws, data_row, 12, _penetration(ext_total, total_delivery)) # L 整车延保渗透率
_set_cell(ws, data_row, 13, rights_total) # M 原厂权益成交数 = 权益订单合计
_set_cell(ws, data_row, 14, _penetration(rights_total, total_delivery)) # N 原厂权益渗透率
# O(15)~R(18) 环比:当前管线无上月同口径数据,显式清空(避免残留模板示例值)
for c in range(15, 19):
_set_cell(ws, data_row, c, None)
if cur_prev_row is not None:
lbl = ws.cell(cur_prev_row, 1).value
if lbl and '上月' in str(lbl):
ws.cell(cur_prev_row, 1).value = re.sub(
r'上月\s*\S*', f'上月 {prev_month_label}', str(lbl))
# 上月段数据行保留模板原样(作为固定参考,框架轮不重写)
# ---- sheet 重命名(月份占位替换)----
try:
ws.title = f"{month_label}页签-字段取值说明"
except Exception:
pass
# ---- 保存 + 上传 OSS ----
tmp = tempfile.mktemp(suffix='.xlsx')
wb.save(tmp)
# 本地预览副本:与用户正在预览的文件对齐(带 _task)。
# 放在 OSS 上传之前,确保即便上传失败本地预览仍能更新。
_local_out = os.path.join(
os.path.dirname(os.path.abspath(__file__)),
'outputs', f'baic_special_{month}_task{task_id}.xlsx')
os.makedirs(os.path.dirname(_local_out), exist_ok=True)
wb.save(_local_out)
logger.info(f"[北汽] 结果表本地副本已保存:{_local_out}")
# OSS 上传(失败不影响本地预览)
url = ''
try:
object_key = f"data-process/{datetime.now().strftime('%Y%m%d')}/baic_special_{month}_{task_id}.xlsx"
url = upload_file(tmp, object_key)
logger.info(f"[北汽] 结果表已上传 OSS:task {task_id} -> {url}")
except Exception as ue:
logger.warning(f"[北汽] OSS 上传失败(本地副本已保留,不影响预览): {ue}")
try:
os.remove(tmp)
except Exception:
pass
return url
...@@ -554,9 +554,14 @@ def parse_hr(src, password='2026'): ...@@ -554,9 +554,14 @@ def parse_hr(src, password='2026'):
# 指标计算 # 指标计算
# ============================================================ # ============================================================
def _lr_sum_one(which, col_attr, period_start, period_end): def _lr_sum_one(which, col_attr, period_start, period_end, task_id=None):
"""单表某数值列之和;which='inshop'|'park'|'equity';条件:同 task_id, is_deleted=0。返回 Decimal。 """单表某数值列之和;which='inshop'|'park'|'equity'|'warranty';条件:is_deleted=0。返回 Decimal。
task_id 解析:优先与汇总同周期(period_start>=/period_end<=),否则取最新(最大) task_id。
task_id 限定(2026-10-08 改造:精确隔离到父任务):
- 传入 task_id 时,精确过滤到该父任务(report_* 子结果表的 task_id 与父任务一致),
即只 SUM(task_id == task_id) 的行,彻底避免跨月/跨任务串数据。
- 未传入(兼容旧 CLI)时,回退旧逻辑:优先与汇总同周期(period_start>=/period_end<=),
否则取最新(最大) task_id。
""" """
from app import app, db from app import app, db
from models import (ReportLightReformInshop, ReportLightReformPark, from models import (ReportLightReformInshop, ReportLightReformPark,
...@@ -569,6 +574,10 @@ def _lr_sum_one(which, col_attr, period_start, period_end): ...@@ -569,6 +574,10 @@ def _lr_sum_one(which, col_attr, period_start, period_end):
tag = ('轻改' if which in ('inshop', 'park') tag = ('轻改' if which in ('inshop', 'park')
else '权益' if which == 'equity' else '延保') else '权益' if which == 'equity' else '延保')
with app.app_context(): with app.app_context():
if task_id is not None:
selected = task_id
logger.info(f"[{tag}] 限制父任务 task_id={task_id}({which}){col_attr} 之和")
else:
q = db.session.query(model_cls.task_id).filter(model_cls.is_deleted == 0) q = db.session.query(model_cls.task_id).filter(model_cls.is_deleted == 0)
if period_start and period_end: if period_start and period_end:
q = q.filter(model_cls.period_start >= period_start, q = q.filter(model_cls.period_start >= period_start,
...@@ -581,46 +590,46 @@ def _lr_sum_one(which, col_attr, period_start, period_end): ...@@ -581,46 +590,46 @@ def _lr_sum_one(which, col_attr, period_start, period_end):
if not tids: if not tids:
logger.info(f"[{tag}] 未找到结果 task_id,{which}.{col_attr}=0") logger.info(f"[{tag}] 未找到结果 task_id,{which}.{col_attr}=0")
return Decimal('0') return Decimal('0')
task_id = max(tids) selected = max(tids)
logger.info(f"[{tag}] 取 task_id={selected}({which}){col_attr} 之和")
col = getattr(model_cls, col_attr) 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( 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 model_cls.task_id == selected, model_cls.is_deleted == 0).scalar() or 0
return Decimal(str(float(s))) return Decimal(str(float(s)))
def fetch_light_reform_11_sum(col_attr, period_start, period_end): def fetch_light_reform_11_sum(col_attr, period_start, period_end, task_id=None):
"""轻改结果表(inshop + park)某数值列之和;条件:同 task_id, is_deleted=0。返回 Decimal。""" """轻改结果表(inshop + park)某数值列之和;条件:同 task_id, is_deleted=0。返回 Decimal。"""
try: try:
return _lr_sum_one('inshop', col_attr, period_start, period_end) \ return _lr_sum_one('inshop', col_attr, period_start, period_end, task_id) \
+ _lr_sum_one('park', col_attr, period_start, period_end) + _lr_sum_one('park', col_attr, period_start, period_end, task_id)
except Exception as e: except Exception as e:
logger.warning(f"[轻改] 读取失败,{col_attr} 置0: {e}") logger.warning(f"[轻改] 读取失败,{col_attr} 置0: {e}")
return Decimal('0') return Decimal('0')
def fetch_light_reform_11_sum_one(which, col_attr, period_start, period_end): def fetch_light_reform_11_sum_one(which, col_attr, period_start, period_end, task_id=None):
"""轻改单表某数值列之和(安全包装,失败置0);which='inshop'|'park'。""" """轻改单表某数值列之和(安全包装,失败置0);which='inshop'|'park'。"""
try: try:
return _lr_sum_one(which, col_attr, period_start, period_end) return _lr_sum_one(which, col_attr, period_start, period_end, task_id)
except Exception as e: except Exception as e:
logger.warning(f"[轻改] 读取失败,{which}.{col_attr} 置0: {e}") logger.warning(f"[轻改] 读取失败,{which}.{col_attr} 置0: {e}")
return Decimal('0') return Decimal('0')
def fetch_equity_21_sum(col_attr, period_start, period_end): def fetch_equity_21_sum(col_attr, period_start, period_end, task_id=None):
"""权益服务结果表(report_equity_service)某数值列之和;同 task_id, is_deleted=0。返回 Decimal。""" """权益服务结果表(report_equity_service)某数值列之和;同 task_id, is_deleted=0。返回 Decimal。"""
try: try:
return _lr_sum_one('equity', col_attr, period_start, period_end) return _lr_sum_one('equity', col_attr, period_start, period_end, task_id)
except Exception as e: except Exception as e:
logger.warning(f"[权益] 读取失败,{col_attr} 置0: {e}") logger.warning(f"[权益] 读取失败,{col_attr} 置0: {e}")
return Decimal('0') return Decimal('0')
def fetch_extended_warranty_23_sum(col_attr, period_start, period_end): def fetch_extended_warranty_23_sum(col_attr, period_start, period_end, task_id=None):
"""延保盈利测算结果表(report_extended_warranty)某数值列之和;同 task_id, is_deleted=0。返回 Decimal。""" """延保盈利测算结果表(report_extended_warranty)某数值列之和;同 task_id, is_deleted=0。返回 Decimal。"""
try: try:
return _lr_sum_one('warranty', col_attr, period_start, period_end) return _lr_sum_one('warranty', col_attr, period_start, period_end, task_id)
except Exception as e: except Exception as e:
logger.warning(f"[延保] 读取失败,{col_attr} 置0: {e}") logger.warning(f"[延保] 读取失败,{col_attr} 置0: {e}")
return Decimal('0') return Decimal('0')
...@@ -752,7 +761,21 @@ def fetch_new_stores(month_start, month_end_excl, exact_map, keys): ...@@ -752,7 +761,21 @@ def fetch_new_stores(month_start, month_end_excl, exact_map, keys):
return total, lux, nonlux return total, lux, nonlux
def compute_metrics(src, period_start, period_end, month_start=None, month_end_excl=None): def compute_metrics(src, period_start, period_end, month_start=None, month_end_excl=None, task_id=None):
# 限定子表聚合到「本父任务」task_id:report_* 子结果表的 task_id 与父任务一致,
# 精确过滤可彻底避免跨月/跨任务串数据。未传则回退旧逻辑(周期匹配优先,否则最新 task_id)。
global fetch_light_reform_11_sum, fetch_light_reform_11_sum_one, fetch_equity_21_sum, fetch_extended_warranty_23_sum
from functools import partial
_lr11, _lr11o, _eq, _ex = (fetch_light_reform_11_sum, fetch_light_reform_11_sum_one,
fetch_equity_21_sum, fetch_extended_warranty_23_sum)
if task_id is not None:
fetch_light_reform_11_sum = partial(_lr11, task_id=task_id)
fetch_light_reform_11_sum_one = partial(_lr11o, task_id=task_id)
fetch_equity_21_sum = partial(_eq, task_id=task_id)
fetch_extended_warranty_23_sum = partial(_ex, task_id=task_id)
else:
fetch_light_reform_11_sum, fetch_light_reform_11_sum_one = _lr11, _lr11o
fetch_equity_21_sum, fetch_extended_warranty_23_sum = _eq, _ex
exact_map, keys = load_brand_category() exact_map, keys = load_brand_category()
s1, s2 = parse_saas(src) s1, s2 = parse_saas(src)
allrows = s1 + s2 allrows = s1 + s2
...@@ -887,12 +910,10 @@ def compute_metrics(src, period_start, period_end, month_start=None, month_end_e ...@@ -887,12 +910,10 @@ def compute_metrics(src, period_start, period_end, month_start=None, month_end_e
logger.warning(f"[指标] 拉取失败,产值/成交/触客置 0: {e}") logger.warning(f"[指标] 拉取失败,产值/成交/触客置 0: {e}")
def match_any(name, stores): def match_any(name, stores):
"""指标系统商户名 ↔ SAAS 门店名 匹配(精确优先,再双向包含)""" """指标系统商户名 ↔ SAAS 门店名 匹配(精确匹配,不使用包含)"""
if not name: if not name:
return False return False
if name in stores: return name in stores
return True
return any(s and (s in name or name in s) for s in stores)
def ind_sum(ind_map, stores, code): def ind_sum(ind_map, stores, code):
t = Decimal('0') t = Decimal('0')
...@@ -969,16 +990,14 @@ def compute_metrics(src, period_start, period_end, month_start=None, month_end_e ...@@ -969,16 +990,14 @@ def compute_metrics(src, period_start, period_end, month_start=None, month_end_e
m['全国直营店均人数'] = safe_div(m['全国直营营销人数'], m['全国直营门店总数']) m['全国直营店均人数'] = safe_div(m['全国直营营销人数'], m['全国直营门店总数'])
m['全国人均产值(w)'] = safe_div(m['全国经营总产值'], m['全国直营营销人数']) m['全国人均产值(w)'] = safe_div(m['全国经营总产值'], m['全国直营营销人数'])
# 豪华/非豪华:按「入驻门店」映射门店集合(精确优先,再包含匹配) # 豪华/非豪华:按「入驻门店」映射门店集合(精确匹配,不使用包含)
lux_stores = {r['store'] for r in allrows if r['category'] == '豪华'} lux_stores = {r['store'] for r in allrows if r['category'] == '豪华'}
nonlux_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): def in_stores(hs, stores):
if not hs: if not hs:
return False return False
if hs in stores: return hs in stores
return True
return any(s and (s in hs or hs in s) for s in stores)
lux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], lux_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)} nonlux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], nonlux_stores)}
...@@ -1179,7 +1198,7 @@ FIELD_NOTES = [ ...@@ -1179,7 +1198,7 @@ FIELD_NOTES = [
('全国经营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有门店明细按门店名称去重计算总数'), ('全国经营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有门店明细按门店名称去重计算总数'),
('经管预算目标', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(预算目标)"之和'), ('经管预算目标', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(预算目标)"之和'),
('全国经营总预算', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(纠偏)"之和'), ('全国经营总预算', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(纠偏)"之和'),
('全国经营总产值', '指标系统 A0018(含二手车业务),不传bizs全量求和、不做门店匹配;2026-08=97,681,597.64'), ('全国经营总产值', '指标系统 A0018(含二手车业务),biz=None 不传bizs查全量、不做门店匹配;2026-08 全量(不传bizs)实测=98,255,112.51(注:97,681,597.64 为历史快照,数据随业务回写变动)'),
('全国直营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有驻店类型=直营 的门店明细去重计算总数'), ('全国直营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有驻店类型=直营 的门店明细去重计算总数'),
('全国直营总人数', '人力成本表:AF列检核=TRUE、过滤岗位=离职,按工号去重【人力表加密无法读取,当前0】'), ('全国直营总人数', '人力成本表:AF列检核=TRUE、过滤岗位=离职,按工号去重【人力表加密无法读取,当前0】'),
('全国直营营销人数', '人力成本表:检核=TRUE、岗位=门店销售,按工号去重【人力表加密无法读取,当前0】'), ('全国直营营销人数', '人力成本表:检核=TRUE、岗位=门店销售,按工号去重【人力表加密无法读取,当前0】'),
...@@ -1263,6 +1282,7 @@ def main(): ...@@ -1263,6 +1282,7 @@ def main():
ap.add_argument('--period-start', default='') ap.add_argument('--period-start', default='')
ap.add_argument('--period-end', default='') ap.add_argument('--period-end', default='')
ap.add_argument('--out', default='') ap.add_argument('--out', default='')
ap.add_argument('--task-id', default='', help='父任务 task_id,指定后子表聚合精确限定到该任务')
args = ap.parse_args() args = ap.parse_args()
ps = excel_serial_to_date(args.period_start) if args.period_start else None ps = excel_serial_to_date(args.period_start) if args.period_start else None
...@@ -1287,7 +1307,8 @@ def main(): ...@@ -1287,7 +1307,8 @@ def main():
month_start = ps month_start = ps
month_end_excl = (pe + timedelta(days=1)) if pe else None month_end_excl = (pe + timedelta(days=1)) if pe else None
m = compute_metrics(args.src, ps, pe, month_start, month_end_excl) m = compute_metrics(args.src, ps, pe, month_start, month_end_excl,
task_id=int(args.task_id) if getattr(args, 'task_id', None) else None)
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs', 'store_effect_summary') out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True) os.makedirs(out_dir, exist_ok=True)
......
# -*- 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)
...@@ -94,6 +94,10 @@ class Config: ...@@ -94,6 +94,10 @@ class Config:
INDICATOR_BIZ_LIGHT_REFORM = 2 INDICATOR_BIZ_LIGHT_REFORM = 2
INDICATOR_BIZ_EQUITY = 3 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 库)---------- # ---------- 业务系统 SQL 数据源(嘀加 dj_smartcarlife 库)----------
BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'true').lower() == 'true' BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'true').lower() == 'true'
BIZ_SQL_DATABASE_URL = os.getenv( BIZ_SQL_DATABASE_URL = os.getenv(
...@@ -129,6 +133,7 @@ class Config: ...@@ -129,6 +133,7 @@ class Config:
'budget_achievement': { 'budget_achievement': {
'name': '预算达成数据', 'name': '预算达成数据',
'need_period': False, 'need_period': False,
'support_week': False,
'forms': [ 'forms': [
'结算数据汇总表', '结算数据汇总表',
'市场费总表', '市场费总表',
...@@ -142,6 +147,7 @@ class Config: ...@@ -142,6 +147,7 @@ class Config:
'store_effect_earnings': { 'store_effect_earnings': {
'name': '店效人效及盈利测算', 'name': '店效人效及盈利测算',
'need_period': True, 'need_period': True,
'support_week': False,
'forms': [ 'forms': [
'SAAS门店预算分解表', 'SAAS门店预算分解表',
'关系表', '关系表',
...@@ -159,18 +165,17 @@ class Config: ...@@ -159,18 +165,17 @@ class Config:
'output_value': { 'output_value': {
'name': '产值达成表', 'name': '产值达成表',
'need_period': True, 'need_period': True,
'support_week': False,
'forms': [ 'forms': [
'SAAS门店预算分解表', 'SAAS门店预算分解表',
'关系表', '关系表',
], ],
}, },
'future_expansion': { # 阿维塔专项:当前仅需上传主机厂数据表(表名暂定,后续若改名只改下方 forms)。
'name': '未来拓展', # 注意:此「主机厂数据表」为阿维塔专项独立数据表,格式不保证与现有
'need_period': False, # 「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,切勿复用
'forms': [], # report_utils.parse_delivery_table(鸿蒙/广联共用结构);
}, # 后续接入引擎时须按用户实际提供的附件字段解析并写入阿维塔专属结果表。
# 阿维塔专项:当前仅需上传主机厂数据表;
# forms[0] 的附件表名为暂定,后续若改名只需改此处。
'avita_special': { 'avita_special': {
'name': '阿维塔专项', 'name': '阿维塔专项',
'need_period': False, 'need_period': False,
...@@ -178,34 +183,40 @@ class Config: ...@@ -178,34 +183,40 @@ class Config:
'主机厂数据表', '主机厂数据表',
], ],
}, },
# 阿维塔专项:当前仅需上传主机厂数据表; # 北汽专项:当前仅需上传源数据表(表名暂定,后续若改名只改下方 forms)。
# forms[0] 的附件表名为暂定,后续若改名只需改此处。 # 注意:源文件「北汽专项源数据表」仅含线上运营手工上传类字段
'avita_special': { # (门店名称/品牌/兜底门店/一店一群交车数/一店一群触客数),
'name': '阿维塔专项', # 结果模板其余字段(区域/产值/订单/渗透/评灯/周趋势等)均来自 D+ 系统取数,
# 当前代码无 D+ 系统数据源,待后续接入后填充。
'baic_special': {
'name': '北汽专项',
'need_period': False, 'need_period': False,
'forms': [ 'forms': [
'主机厂数据表', '北汽专项源数据表',
], ],
}, },
# 零跑专项 / 岚图专项:无需上传 Excel,need_period=True 需要所属周期 # 零跑专项 / 岚图专项:无需上传 Excel,need_period=True 需要所属周期
'leapmotor_special': { 'leapmotor_special': {
'name': '零跑专项', 'name': '零跑专项',
'need_period': True, 'need_period': True,
'support_week': False,
'forms': [], 'forms': [],
}, },
'voyah_special': { 'voyah_special': {
'name': '岚图专项', 'name': '岚图专项',
'need_period': True, 'need_period': True,
'support_week': False,
'forms': [], 'forms': [],
}, },
# 通用+权益:支持按月/按周粒度,含 3 个附件 # 通用+权益:支持按月/按周粒度,含 3 个附件
'common_equity': { # 'common_equity': {
'name': '通用+权益', # 'name': '通用+权益',
'need_period': True, # 'need_period': True,
'forms': [ # 'support_week': True,
'区域维度数据', # 'forms': [
'汇总区数据', # '区域维度数据',
'红黄门店数据', # '汇总区数据',
], # '红黄门店数据',
}, # ],
# },
} }
...@@ -25,7 +25,7 @@ from report_utils import ( ...@@ -25,7 +25,7 @@ from report_utils import (
download_all_files, download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps, parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps,
parse_budget_achieve_excel, extract_budget_ratio, parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, exact_match_store,
fetch_indicator_data, fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio, safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
) )
...@@ -175,9 +175,10 @@ class WarrantyProcessor: ...@@ -175,9 +175,10 @@ class WarrantyProcessor:
indicator_data = {} indicator_data = {}
# ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ========== # ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
store_names_for_sql = [r.get('store_name', '') for r in base_records if r.get('store_name')] # 不传 store_names 过滤(419 个 OR LIKE 会导致 MySQL 优化器异常丢 50% 门店)
# 后续用 fuzzy_match_store 在 Python 层做精确模糊匹配
# BIZ_TYPE_WARRANTY='2.3' → scene_type=0, business_type=2 # 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, store_names_for_sql) biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_WARRANTY)
# ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ========== # ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========
...@@ -190,13 +191,12 @@ class WarrantyProcessor: ...@@ -190,13 +191,12 @@ class WarrantyProcessor:
resident_type = rec.get('resident_type', '') resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {}) ind = indicator_data.get(store_name, {})
# Excel 门店名 → 业务表 merchant_name 模糊匹配 # 业务系统 SQL — 精确匹配,避免模糊误匹配(如"广西河池中达"误匹配到其他"中达"门店)
biz_data = fuzzy_match_store(store_name, biz_sql_map) or {} biz_data = exact_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表"厅店名称"/"基础信息-门店名称" # 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表(两边都是 Excel,命名可能不同 → 模糊保留)
# Excel 未匹配时,系统日报 scene_type=0 兜底
delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0 delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0
if delivery_cnt == 0 and system_delivery_map: if delivery_cnt == 0 and system_delivery_map:
_sys_entry = fuzzy_match_store(store_name, system_delivery_map) or {} _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 delivery_cnt = _sys_entry.get('delivery_cnt', 0) if isinstance(_sys_entry, dict) else 0
# 指标系统取值 # 指标系统取值
...@@ -218,8 +218,21 @@ class WarrantyProcessor: ...@@ -218,8 +218,21 @@ class WarrantyProcessor:
# —— 业务系统 SQL 取值(已在 L172 用 fuzzy_match_store 拿到 biz_data)—— # —— 业务系统 SQL 取值(已在 L172 用 fuzzy_match_store 拿到 biz_data)——
product_cost = biz_data.get('product_cost', Decimal('0')) product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', 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')) service_fee = Decimal('0') if resident_type != '服务商' else biz_data.get('service_fee', Decimal('0'))
# 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录)
# —— 门店分成:普通品牌取系统流量费 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')) store_share = biz_data.get('shop_traffic_money', Decimal('0'))
guarantee_amount = Decimal('0') guarantee_amount = Decimal('0')
gl_share = store_output_value - product_cost - store_share - guarantee_amount gl_share = store_output_value - product_cost - store_share - guarantee_amount
......
...@@ -25,7 +25,7 @@ from report_utils import ( ...@@ -25,7 +25,7 @@ from report_utils import (
download_all_files, download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps, parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps,
parse_budget_achieve_excel, extract_budget_ratio, parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, exact_match_store,
fetch_indicator_data, fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio, safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
) )
...@@ -177,9 +177,10 @@ class EquityProcessor: ...@@ -177,9 +177,10 @@ class EquityProcessor:
indicator_data = {} indicator_data = {}
# ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ========== # ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
store_names_for_sql = [r.get('store_name', '') for r in base_records if r.get('store_name')] # 不传 store_names 过滤(419 个 OR LIKE 会导致 MySQL 优化器异常丢 50% 门店)
# 后续用 fuzzy_match_store 在 Python 层做精确模糊匹配
# BIZ_TYPE_EQUITY='2.1' → scene_type=0, business_type=1 # 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, store_names_for_sql) biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_EQUITY)
# ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ========== # ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========
...@@ -192,14 +193,13 @@ class EquityProcessor: ...@@ -192,14 +193,13 @@ class EquityProcessor:
resident_type = rec.get('resident_type', '') resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {}) ind = indicator_data.get(store_name, {})
# Excel 门店名 → 业务表 merchant_name 模糊匹配 # 业务系统 SQL — 精确匹配
biz_data = fuzzy_match_store(store_name, biz_sql_map) or {} biz_data = exact_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表"厅店名称"/"基础信息-门店名称" # 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表(Excel → Excel 保留模糊)
# Excel 未匹配时,系统日报 scene_type=0 兜底
delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0 delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0
if delivery_cnt == 0 and system_delivery_map: if delivery_cnt == 0 and system_delivery_map:
# system_delivery_map value 是 dict{delivery_cnt, equity_to_shop_count, ...} # system_delivery_map value 是 dict{delivery_cnt, equity_to_shop_count, ...}
_sys_entry = fuzzy_match_store(store_name, system_delivery_map) or {} _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 delivery_cnt = _sys_entry.get('delivery_cnt', 0) if isinstance(_sys_entry, dict) else 0
# 指标系统取值 # 指标系统取值
...@@ -214,7 +214,7 @@ class EquityProcessor: ...@@ -214,7 +214,7 @@ class EquityProcessor:
# —— 业务系统 SQL 取值 —— # —— 业务系统 SQL 取值 ——
product_cost = biz_data.get('product_cost', Decimal('0')) product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', 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')) service_fee = Decimal('0') if resident_type != '服务商' else biz_data.get('service_fee', Decimal('0'))
# 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录) # 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录)
store_share = biz_data.get('shop_traffic_money', Decimal('0')) store_share = biz_data.get('shop_traffic_money', Decimal('0'))
guarantee_amount = Decimal('0') guarantee_amount = Decimal('0')
......
# -*- 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))
...@@ -405,8 +405,9 @@ def _fix_number_format(fmt, attr_name): ...@@ -405,8 +405,9 @@ def _fix_number_format(fmt, attr_name):
if not fmt or '%' not in fmt: if not fmt or '%' not in fmt:
return fmt return fmt
if _is_ratio_field(attr_name): if _is_ratio_field(attr_name):
# 真正的比例字段 → 转字面百分号(DB 已存 1-100,不应再自动乘 100) # 真正的比例字段 → 统一保留 2 位小数 + 字面 "%"
return fmt.replace('%', '"%"') # 防模板整数百分比格式(0%)四舍五入:DB 存 1.5 显示成 2%
return '0.00"%"'
else: else:
# 金额/数值字段被误配 % → 去掉百分号字符,保留数字精度 # 金额/数值字段被误配 % → 去掉百分号字符,保留数字精度
cleaned = fmt.replace('%', '').strip() cleaned = fmt.replace('%', '').strip()
......
-- ============================================================
-- 红黄门店盈利测算 - 4 张输出表 DDL (MySQL 5.7+, utf8mb4)
-- 生成方式:由 SQLAlchemy ORM Model 反推,与 db.create_all() 等价
-- 使用:在目标库 data_process 中直接执行即可
-- ============================================================
-- ---------- 表 1:延保盈利测算表 ----------
DROP TABLE IF EXISTS `report_extended_warranty`;
CREATE TABLE `report_extended_warranty` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '所属任务单据ID',
`period_start` DATE DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` DATE DEFAULT NULL COMMENT '统计周期结束日期',
-- 门店基础维度(9 列)
`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 '品牌',
-- 触客/成交(3 列)
`delivery_cnt` INT DEFAULT 0 COMMENT '交车',
`touch_cnt` INT DEFAULT 0 COMMENT '触客',
`deal_cnt` INT DEFAULT 0 COMMENT '成交数',
-- 延保特有指标(8 列)
`penetration_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '渗透率',
`vehicle_warranty_cnt` INT DEFAULT 0 COMMENT '整车延保成交数',
`vehicle_warranty_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '整车延保渗透率',
`vehicle_warranty_touch_convert` DECIMAL(10,6) DEFAULT 0 COMMENT '整车延保触客成交率',
`battery_warranty_cnt` INT DEFAULT 0 COMMENT '电池成交数',
`battery_warranty_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '电池渗透率',
`easy_bag_cnt` INT DEFAULT 0 COMMENT '安心包成交数',
`easy_bag_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '安心包渗透率',
-- 产值/成本/费用/毛利(18 列)
`store_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '门店产值',
`upgrade_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '升级客单价',
`product_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '商品成本',
`store_share` DECIMAL(15,2) DEFAULT 0 COMMENT '门店分成',
`guarantee_amount` DECIMAL(15,2) DEFAULT 0 COMMENT '兜底金额',
`gl_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联分成',
`market_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '市场费',
`market_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '市场费占比',
`marketing_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '营销费用',
`marketing_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '营销费用占比',
`service_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '服务费用',
`service_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '服务费用占比',
`total_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '成本总计',
`cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '成本占比',
`gross_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '毛利测算',
`gross_profit_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '预估毛利率',
`gross_profit_status` VARCHAR(20) DEFAULT '' COMMENT '预估毛利情况',
`gross_profit_rank` 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_warranty_period_store_brand`
(`task_id`, `period_start`, `period_end`, `store_name`, `brand`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-延保表';
-- ---------- 表 2:权益盈利测算表 ----------
DROP TABLE IF EXISTS `report_equity_service`;
CREATE TABLE `report_equity_service` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '所属任务单据ID',
`period_start` DATE DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` DATE DEFAULT NULL COMMENT '统计周期结束日期',
-- 门店基础维度(9 列)
`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 '品牌',
-- 触客/成交(4 列)
`delivery_cnt` INT DEFAULT 0 COMMENT '交车',
`touch_cnt` INT DEFAULT 0 COMMENT '触客',
`deal_cnt` INT DEFAULT 0 COMMENT '成交数',
`penetration_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '渗透率',
-- 产值/成本/费用/毛利(18 列,与延保表一致)
`store_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '门店产值',
`upgrade_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '升级客单价',
`product_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '商品成本',
`store_share` DECIMAL(15,2) DEFAULT 0 COMMENT '门店分成',
`guarantee_amount` DECIMAL(15,2) DEFAULT 0 COMMENT '兜底金额',
`gl_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联分成',
`market_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '市场费',
`market_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '市场费占比',
`marketing_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '营销费用',
`marketing_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '营销费用占比',
`service_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '服务费用',
`service_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '服务费用占比',
`total_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '成本总计',
`cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '成本占比',
`gross_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '毛利测算',
`gross_profit_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '预估毛利率',
`gross_profit_status` VARCHAR(20) DEFAULT '' COMMENT '预估毛利情况',
`gross_profit_rank` 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_equity_period_store_brand`
(`task_id`, `period_start`, `period_end`, `store_name`, `brand`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-权益表';
-- ---------- 表 3:轻改-店中店汇总表 ----------
DROP TABLE IF EXISTS `report_light_reform_inshop`;
CREATE TABLE `report_light_reform_inshop` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '所属任务单据ID',
`period_start` DATE DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` DATE DEFAULT NULL COMMENT '统计周期结束日期',
-- 门店基础信息(13 列)
`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 '采买/兜底指标',
-- 销售端口(3 列)
`sales_order_cnt` INT DEFAULT 0 COMMENT '销售大定数',
`sales_touch_cnt` INT DEFAULT 0 COMMENT '销售触客数',
`sales_touch_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '销售触客率',
-- 交付端口(3 列)
`delivery_cnt` INT DEFAULT 0 COMMENT '交车数',
`delivery_touch_cnt` INT DEFAULT 0 COMMENT '交付触客数',
`delivery_touch_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '交付触客率',
-- 售后端口(6 列)
`aftersales_baohui_cnt` INT DEFAULT 0 COMMENT '售后首保回厂数',
`aftersales_shigu_cnt` INT DEFAULT 0 COMMENT '售后事故回厂数',
`aftersales_touch_cnt` INT DEFAULT 0 COMMENT '售后触客数',
`aftersales_touch_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '售后触客率',
`total_touch_cnt` INT DEFAULT 0 COMMENT '总触客数',
`total_deal_cnt` INT DEFAULT 0 COMMENT '总成交数',
-- 窗膜/车衣/精品 原厂+副厂(12 列 + 踏板 1 列)
`window_film_oe_cnt` INT DEFAULT 0 COMMENT '窗膜成交数-原厂',
`window_film_nonoe_cnt` INT DEFAULT 0 COMMENT '窗膜成交数-副厂',
`car_wrap_oe_cnt` INT DEFAULT 0 COMMENT '车衣成交数-原厂',
`car_wrap_nonoe_cnt` INT DEFAULT 0 COMMENT '车衣成交数-副厂',
`premium_oe_cnt` INT DEFAULT 0 COMMENT '精品成交数-原厂',
`premium_nonoe_cnt` INT DEFAULT 0 COMMENT '精品成交数-副厂',
`pedal_cnt` INT DEFAULT 0 COMMENT '踏板',
-- 产值(5 列)
`store_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '门店总产值',
`internal_settle_value` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算产值',
`total_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '合计总产值',
`oe_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '原厂总产值',
`nonoe_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '副厂总产值',
-- 客单/渗透(9 列)
`avg_unit_price_delivery` DECIMAL(15,2) DEFAULT 0 COMMENT '平均客单价(交车)',
`avg_price_target` DECIMAL(15,2) DEFAULT 0 COMMENT '平客目标值',
`avg_price_diff` DECIMAL(15,2) DEFAULT 0 COMMENT '平客差值',
`delivery_touch_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '交付触客客单价',
`upgrade_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '升级客单价',
`total_penetration_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '总订单渗透率',
`window_film_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '窗膜渗透率',
`car_wrap_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '车衣渗透率',
`premium_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '精品渗透率',
-- 成本-产品(8 列)
`product_cost_finance` DECIMAL(15,2) DEFAULT 0 COMMENT '产品成本(财务列表)',
`internal_settle_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算成本(财务列表)',
`oe_product_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '原厂产品成本(财务列表)',
`nonoe_product_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '副厂产品成本(财务列表)',
`window_film_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '窗膜成本',
`car_wrap_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '车衣成本',
`premium_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '精品成本',
`product_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '产品总成本占比',
-- 施工/激励/进销差/分成(11 列)
`construction_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '施工成本',
`construction_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '施工成本占比',
`frontline_incentive` DECIMAL(15,2) DEFAULT 0 COMMENT '一线激励',
`frontline_incentive_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '一线激励占比',
`gross_profit_pre_share` DECIMAL(15,2) DEFAULT 0 COMMENT '进销差(未分成)',
`gross_profit_pre_share_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '进销差占比',
`store_share` DECIMAL(15,2) DEFAULT 0 COMMENT '门店分成',
`store_share_per_car` DECIMAL(15,2) DEFAULT 0 COMMENT '门店单车利润',
`guarantee_amount` DECIMAL(15,2) DEFAULT 0 COMMENT '兜底金额',
`gl_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联分成',
`gl_share_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '广联分成占比',
-- 广联总分成/内部结算/施工收入(3 列)
`construction_income` DECIMAL(15,2) DEFAULT 0 COMMENT '施工收入',
`internal_settle_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算',
`gl_total_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联总分成',
-- 营销/市场/装修/房租/耗材/服务商(9 列)
`marketing_personnel_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '营销人员成本',
`marketing_personnel_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '营销人员成本占比',
`market_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '市场费',
`market_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '市场费占比',
`renovation_amortization` DECIMAL(15,2) DEFAULT 0 COMMENT '装修分摊',
`rent_utilities` DECIMAL(15,2) DEFAULT 0 COMMENT '房租、水电费用',
`store_consumables` DECIMAL(15,2) DEFAULT 0 COMMENT '门店耗材',
`service_provider_share` DECIMAL(15,2) DEFAULT 0 COMMENT '服务商分成',
`service_provider_share_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '服务商分成占比',
-- 成本总计/毛利(6 列)
`total_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '成本总计',
`cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '总计占比',
`gross_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '毛利测算',
`gross_profit_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '毛利率',
`gross_profit_status` VARCHAR(20) DEFAULT '' COMMENT '毛利情况',
`gross_profit_rank` 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_inshop_period_park_store`
(`task_id`, `period_start`, `period_end`, `park_name`, `store_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-轻改店中店汇总表';
-- ---------- 表 4:轻改-园区店汇总表 ----------
DROP TABLE IF EXISTS `report_light_reform_park`;
CREATE TABLE `report_light_reform_park` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '所属任务单据ID',
`period_start` DATE DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` DATE DEFAULT NULL COMMENT '统计周期结束日期',
-- 门店基础信息(12 列)
`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 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 '采买/兜底指标(流量费)',
-- 触客/交车/转化(7 列)
`delivery_cnt` INT DEFAULT 0 COMMENT '交车数',
`arrival_cnt` INT DEFAULT 0 COMMENT '到店数',
`arrival_invalid_cnt` INT DEFAULT 0 COMMENT '到店无效客户数',
`invalid_arrival_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '无效到店率',
`arrival_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '到店率',
`deal_cnt` INT DEFAULT 0 COMMENT '成交数',
`conversion_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '转化率',
-- 产值/客单(8 列)
`store_sales_output` DECIMAL(15,2) DEFAULT 0 COMMENT '门店销售产值',
`internal_settle_value` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算产值',
`total_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '合计总产值',
`output_progress` DECIMAL(10,6) DEFAULT 0 COMMENT '产值达成进度',
`avg_unit_price_arrival` DECIMAL(15,2) DEFAULT 0 COMMENT '平均客单价(到店)',
`avg_price_target` DECIMAL(15,2) DEFAULT 0 COMMENT '平客目标值',
`avg_price_diff` DECIMAL(15,2) DEFAULT 0 COMMENT '平客差值',
`upgrade_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '升级客单价',
-- 窗膜/车衣/精品(6 列)
`window_film_cnt` INT DEFAULT 0 COMMENT '窗膜成交数',
`window_film_convert` DECIMAL(10,6) DEFAULT 0 COMMENT '窗膜转化率',
`car_wrap_cnt` INT DEFAULT 0 COMMENT '车衣成交数',
`car_wrap_convert` DECIMAL(10,6) DEFAULT 0 COMMENT '车衣转化率',
`premium_cnt` INT DEFAULT 0 COMMENT '精品成交数',
`premium_convert` DECIMAL(10,6) DEFAULT 0 COMMENT '精品转化率',
-- 预算(3 列)
`est_traffic` INT DEFAULT 0 COMMENT '商务上架预估流量',
`est_delivery_cnt` INT DEFAULT 0 COMMENT '预估交车数',
`est_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '预估总产值(预算目标)',
-- 成本/分成/毛利(38 列)
`product_cost_finance` DECIMAL(15,2) DEFAULT 0 COMMENT '产品成本(财务列表)',
`product_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '产品成本占比',
`internal_settle_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算成本(财务列表)',
`traffic_fee_finance` DECIMAL(15,2) DEFAULT 0 COMMENT '流量费(财务列表)',
`traffic_fee_per_car` DECIMAL(15,2) DEFAULT 0 COMMENT '按单台计算流量/台',
`traffic_fee_order` DECIMAL(15,2) DEFAULT 0 COMMENT '按台次计算流量费',
`store_traffic_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '门店流量费',
`traffic_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '流量费率(列表测算)',
`gl_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联分成',
`gl_share_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '广联分成占比',
`internal_settle_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算',
`gl_total_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联总分成',
`personnel_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '人员成本',
`personnel_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '常规人员费率(加权参考)',
`construction_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '施工成本',
`construction_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '施工成本占比',
`market_fee_weighted` DECIMAL(15,2) DEFAULT 0 COMMENT '市场费(加权测算)',
`market_fee_weighted_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '市场费费率(加权参考)',
`service_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '服务费(商务报表)',
`service_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '服务费费率(加权参考)',
`renovation_amortization` DECIMAL(15,2) DEFAULT 0 COMMENT '装修分摊(商务报表)',
`renovation_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '装修占比',
`rent_utilities` DECIMAL(15,2) DEFAULT 0 COMMENT '房租、水电费用',
`rent_utilities_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '房租、水电占比',
`store_consumables` DECIMAL(15,2) DEFAULT 0 COMMENT '门店耗材',
`store_consumables_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '门店耗材占比',
`total_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '成本总计',
`cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '总计占比',
`gross_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '毛利测算',
`gross_profit_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '毛利率',
`gross_profit_status` VARCHAR(20) DEFAULT '' COMMENT '毛利情况',
`gross_profit_rank` 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_park_period_park_store`
(`task_id`, `period_start`, `period_end`, `park_name`, `store_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-轻改园区店汇总表';
-- ============================================================================
-- 增量 ALTER: 店中店新增 store_share_ratio (门店分成占比) 字段
-- 2026-09-10: col63 表头"门店分成(占比)"模板需要此列,但 ORM/DDL 均缺失
-- ============================================================================
ALTER TABLE report_light_reform_inshop
ADD COLUMN `store_share_ratio` DECIMAL(10, 6) DEFAULT 0
COMMENT '门店分成占比(门店分成/门店总产值)'
AFTER `store_share`;
-- ============================================================================
-- 增量 ALTER: 店中店新增后置施工成本 2 字段
-- DB 已有: construction_cost(总计), construction_cost_oe(前置原厂),
-- construction_cost_nonoe(前置副厂), construction_cost_ratio(总计占比)
-- 新增: construction_cost_post, construction_cost_post_ratio
-- construction_cost = oe + nonoe + post
-- ============================================================================
ALTER TABLE report_light_reform_inshop
ADD COLUMN `construction_cost_post` DECIMAL(15, 2) DEFAULT 0
COMMENT '后置施工成本(直营按商务政策, 服务商=0)'
AFTER `construction_cost_nonoe`,
ADD COLUMN `construction_cost_post_ratio` DECIMAL(10, 6) DEFAULT 0
COMMENT '后置施工成本占比(post/门店总产值)'
AFTER `construction_cost_post`;
-- 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
...@@ -42,3 +42,8 @@ WHERE base_scene_code = '100101' ...@@ -42,3 +42,8 @@ WHERE base_scene_code = '100101'
AND deleted_flag = 'N' AND deleted_flag = 'N'
ORDER BY created_date DESC; 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
...@@ -75,7 +75,7 @@ LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2 ...@@ -75,7 +75,7 @@ LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12) AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1 WHERE t1.status = 1 and t1.del_flag='N'
AND t2.scene_type = 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 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.dj_order_type !=6
......
...@@ -7,18 +7,25 @@ ...@@ -7,18 +7,25 @@
-- 关联表: -- 关联表:
-- gopa 利润分配主表 (子订单级, order_flag='N' 非汇总) -- gopa 利润分配主表 (子订单级, order_flag='N' 非汇总)
-- gopa2 利润分配汇总记录 (order_flag='Y', grain_size_type=1, 拿服务费/施工收入/产值) -- gopa2 利润分配汇总记录 (order_flag='Y', grain_size_type=1, 拿服务费/施工收入/产值)
-- gso 子订单表 (拿嘀加与第三方成本合计 = upgrade_dj_cost + upgrade_third_party_cost) -- gso 子订单表 (拿嘀加与第三方成本)
-- go 订单表 (scene_type / business_type / merchant_name) -- go 订单表 (scene_type / business_type / merchant_name)
-- po 支付单表 (success_date 周期过滤) -- po 支付单表 (success_date 周期过滤)
-- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901)) -- 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 + upgrade_third_party_cost) -- 商品成本 = upgrade_dj_cost + (shop_traffic_money_calculate_type=1 时才加 upgrade_third_party_cost)
-- 第三方成本仅在 GMV 口径算流量费时才计入
-- 门店分成/流量费 = shop_traffic_money (来自 gopa 主表) -- 门店分成/流量费 = shop_traffic_money (来自 gopa 主表)
-- 市场费 = 四项费用累计 (fee 子查询) -- 市场费 = 四项费用累计 (fee 子查询, 内层用 MAX 取单次值)
-- 服务费用 = 服务商金额 franchisee_profit_money (来自 gopa2 汇总记录) -- 服务费用 = 服务商金额 franchisee_profit_money (来自 gopa2, 内层用 MAX)
-- 门店产值 = total_price (来自 gopa2 汇总记录) -- 门店产值 = total_price (来自 gopa2, 内层用 MAX)
-- 其他费用 = custom_common_cost (来自 gopa2 汇总记录) -- 其他费用 = custom_common_cost (来自 gopa2, 内层用 MAX)
-- ============================================================================ -- ============================================================================
-- ========= 查询参数 ========= -- ========= 查询参数 =========
...@@ -28,40 +35,57 @@ SET @scene_type = 0; -- 固定: 0=延保/权益 ...@@ -28,40 +35,57 @@ SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 2; -- 2=延保 (1=权益, 另见 权益_财务成本分项.sql) SET @business_type = 2; -- 2=延保 (1=权益, 另见 权益_财务成本分项.sql)
SELECT SELECT
go.merchant_name AS `门店名称`, t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加与第三方成本合计 (子订单表) -- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(IFNULL(gso.upgrade_dj_cost, 0) + IFNULL(gso.upgrade_third_party_cost, 0)) SUM(t.product_cost) AS `商品成本`,
AS `商品成本`,
-- 门店分成/流量费 -- 门店分成/流量费
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS `门店分成`, SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
SUM(t.market_fee) AS `市场费`,
-- 市场费 = 四项费用累计 (expense_category_id IN (706,808,809,901)) -- 服务费用 = 服务商金额
SUM(IFNULL(fee.total, 0)) AS `市场费`, SUM(t.service_fee) AS `服务费用`,
-- 服务费用 = 服务商金额 (汇总记录) -- 门店产值
SUM(IFNULL(gopa2.franchisee_profit_money, 0)) AS `服务费用`, SUM(t.store_output_value) AS `门店产值`,
-- 门店产值 (汇总记录) -- 其他费用
SUM(IFNULL(gopa2.total_price, 0)) AS `门店产值`, SUM(t.other_cost) AS `其他费用`
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- 其他费用 (汇总记录) -- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(IFNULL(gopa2.custom_common_cost, 0)) AS `其他费用` 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,
FROM dj_car_life_goods_order_profit_allocation gopa SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
INNER JOIN dj_car_life_goods_order go
-- 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' ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N' ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N' ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2 LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y' AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1 AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N' AND gopa2.deleted_flag = 'N'
LEFT JOIN ( LEFT JOIN (
-- 四项费用累计子查询: 日期 + scene_type + business_type 必须与外层同步! -- 四项费用累计子查询: 日期 + scene_type + business_type 必须与外层同步!
SELECT SELECT
ecc.order_code, ecc.order_code,
...@@ -78,12 +102,15 @@ LEFT JOIN ( ...@@ -78,12 +102,15 @@ LEFT JOIN (
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
AND go.business_type = @business_type AND go.business_type = @business_type
GROUP BY ecc.order_code GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code ) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N' WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N' AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
AND go.business_type = @business_type AND go.business_type = @business_type
AND po.success_date >= @start_time AND po.success_date >= @start_time
AND po.success_date <= @end_time AND po.success_date <= @end_time
GROUP BY go.merchant_name;
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
...@@ -6,6 +6,12 @@ ...@@ -6,6 +6,12 @@
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步) -- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- 关联表: 同 延保_财务成本分项.sql -- 关联表: 同 延保_财务成本分项.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 不同) -- 字段口径: 同延保 (仅 business_type 不同)
-- ============================================================================ -- ============================================================================
...@@ -16,40 +22,57 @@ SET @scene_type = 0; -- 固定: 0=延保/权益 ...@@ -16,40 +22,57 @@ SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 1; -- 1=权益 (2=延保, 另见 延保_财务成本分项.sql) SET @business_type = 1; -- 1=权益 (2=延保, 另见 延保_财务成本分项.sql)
SELECT SELECT
go.merchant_name AS `门店名称`, t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加与第三方成本合计 -- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(IFNULL(gso.upgrade_dj_cost, 0) + IFNULL(gso.upgrade_third_party_cost, 0)) SUM(t.product_cost) AS `商品成本`,
AS `商品成本`,
-- 门店分成/流量费 -- 门店分成/流量费
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS `门店分成`, SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计 -- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
SUM(IFNULL(fee.total, 0)) AS `市场费`, SUM(t.market_fee) AS `市场费`,
-- 服务费用 = 服务商金额 -- 服务费用 = 服务商金额
SUM(IFNULL(gopa2.franchisee_profit_money, 0)) AS `服务费用`, SUM(t.service_fee) AS `服务费用`,
-- 门店产值 -- 门店产值
SUM(IFNULL(gopa2.total_price, 0)) AS `门店产值`, SUM(t.store_output_value) AS `门店产值`,
-- 其他费用 -- 其他费用
SUM(IFNULL(gopa2.custom_common_cost, 0)) 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,
FROM dj_car_life_goods_order_profit_allocation gopa SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
INNER JOIN dj_car_life_goods_order go
-- 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' ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N' ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N' ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2 LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y' AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1 AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N' AND gopa2.deleted_flag = 'N'
LEFT JOIN ( LEFT JOIN (
-- fee 子查询: 日期 + scene_type + business_type 与外层同步 -- fee 子查询: 日期 + scene_type + business_type 与外层同步
SELECT SELECT
ecc.order_code, ecc.order_code,
...@@ -66,12 +89,15 @@ LEFT JOIN ( ...@@ -66,12 +89,15 @@ LEFT JOIN (
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
AND go.business_type = @business_type AND go.business_type = @business_type
GROUP BY ecc.order_code GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code ) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N' WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N' AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
AND go.business_type = @business_type AND go.business_type = @business_type
AND po.success_date >= @start_time AND po.success_date >= @start_time
AND po.success_date <= @end_time AND po.success_date <= @end_time
GROUP BY go.merchant_name;
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
...@@ -5,13 +5,21 @@ ...@@ -5,13 +5,21 @@
-- 业务: business_type = 1 OR 2 (轻改不区分) -- 业务: business_type = 1 OR 2 (轻改不区分)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步) -- 日期: 支付成功时间 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 个字段 (不需要窗膜/车衣/精品/原厂/副厂/施工收入等): -- 园区店只消费 4 个字段 (不需要窗膜/车衣/精品/原厂/副厂/施工收入等):
-- 产品成本(财务列表) = dj_order_type != 6 -- 产品成本(财务列表) = dj_order_type != 6 → upgrade_shop_price - base_shop_price
-- 内部结算成本(财务列表) = dj_order_type = 6 -- 内部结算成本(财务列表) = dj_order_type = 6 → upgrade_shop_price - base_shop_price
-- 流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money -- 流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money
-- 市场费(加权测算) = 四项费用累计 -- 市场费(加权测算) = 四项费用累计 (fee 子查询, 内层用 MAX)
-- 字段口径/表关联/商品成本公式(upgrade_shop_price - base_shop_price)与店中店完全相同 -- 字段口径/表关联与店中店完全相同
-- ============================================================================ -- ============================================================================
-- ========= 查询参数 ========= -- ========= 查询参数 =========
...@@ -20,42 +28,55 @@ SET @end_time = '2026-08-31 23:59:59'; ...@@ -20,42 +28,55 @@ SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 1; -- 固定: 1=轻改 SET @scene_type = 1; -- 固定: 1=轻改
SELECT SELECT
go.merchant_name AS `门店名称`, t.merchant_name AS `门店名称`,
-- ===== 产品成本口径: upgrade_shop_price - base_shop_price ===== -- ===== 产品成本口径: 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 累加
-- 产品成本(财务列表) = 非内部结算 dj_order_type != 6
SUM(CASE WHEN gso.dj_order_type != 6 SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `产品成本(财务列表)`, ELSE 0 END) AS product_cost_finance,
-- 内部结算成本(财务列表) = 内部结算 dj_order_type = 6
SUM(CASE WHEN gso.dj_order_type = 6 SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `内部结算成本(财务列表)`, ELSE 0 END) AS internal_settle_cost,
-- 流量费(财务列表) = 非内部结算的 shop_traffic_money
SUM(CASE WHEN gso.dj_order_type != 6 SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0) THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS `流量费(财务列表)`, ELSE 0 END) AS store_share,
-- 市场费(加权测算) = 四项费用累计 (fee 子查询) -- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
SUM(IFNULL(fee.total, 0)) AS `市场费` MAX(IFNULL(fee.total, 0)) AS market_fee
FROM dj_car_life_goods_order_profit_allocation gopa FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N' ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N' ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N' ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2 LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y' AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1 AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N' AND gopa2.deleted_flag = 'N'
LEFT JOIN ( LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 -- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT SELECT
ecc.order_code, ecc.order_code,
SUM(ecc.expense_category_result) AS total SUM(ecc.expense_category_result) AS total
...@@ -70,11 +91,14 @@ LEFT JOIN ( ...@@ -70,11 +91,14 @@ LEFT JOIN (
AND po.success_date <= @end_time AND po.success_date <= @end_time
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
GROUP BY ecc.order_code GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code ) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N' WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N' AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
AND po.success_date >= @start_time AND po.success_date >= @start_time
AND po.success_date <= @end_time AND po.success_date <= @end_time
GROUP BY go.merchant_name;
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
...@@ -12,21 +12,25 @@ ...@@ -12,21 +12,25 @@
-- po 支付单表 (success_date 周期过滤) -- po 支付单表 (success_date 周期过滤)
-- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901)) -- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901))
-- --
-- 关键差异 (与延保/权益对比): -- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- 商品成本口径不同! 轻改用 upgrade_shop_price - base_shop_price -- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 延保/权益用 upgrade_dj_cost + upgrade_third_party_cost -- 直接 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 项): -- 字段口径 (店中店消费全部 10 项):
-- 产品成本(财务列表) = dj_order_type != 6 (非内部结算) 的商品成本 -- 产品成本(财务列表) = dj_order_type != 6 (非内部结算) 的 upgrade_shop_price - base_shop_price
-- 内部结算成本(财务列表) = dj_order_type = 6 (内部结算) 的商品成本 -- 内部结算成本(财务列表) = 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 LIKE '%AITO%' OR '%HIMA%'
-- 副厂产品成本(财务列表) = dj_order_type != 6 + goods_name NOT LIKE '%AITO%' AND NOT LIKE '%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 IN ('车衣','改色膜') -- 车衣成本 = upgrade_goods_type_name IN ('车衣','改色膜')
-- 精品成本 = upgrade_goods_type_name NOT IN (窗膜/车衣 所有类型) -- 精品成本 = upgrade_goods_type_name NOT IN (窗膜/车衣 所有类型)
-- 门店分成/流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money -- 门店分成/流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money
-- 施工收入 = custom_common_cost (汇总记录 gopa2) -- 施工收入 = custom_common_cost (汇总记录 gopa2, 内层用 MAX)
-- 市场费 = 四项费用累计 (fee 子查询) -- 市场费 = 四项费用累计 (fee 子查询, 内层用 MAX)
-- ============================================================================ -- ============================================================================
-- ========= 查询参数 ========= -- ========= 查询参数 =========
...@@ -35,73 +39,85 @@ SET @end_time = '2026-08-31 23:59:59'; ...@@ -35,73 +39,85 @@ SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 1; -- 固定: 1=轻改 SET @scene_type = 1; -- 固定: 1=轻改
SELECT SELECT
go.merchant_name AS `门店名称`, t.merchant_name AS `门店名称`,
-- ===== 产品成本口径: upgrade_shop_price - base_shop_price ===== -- ===== 产品成本口径: 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 累加
-- 产品成本(财务列表) = 非内部结算 dj_order_type != 6
SUM(CASE WHEN gso.dj_order_type != 6 SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `产品成本(财务列表)`, ELSE 0 END) AS product_cost_finance,
-- 内部结算成本(财务列表) = 内部结算 dj_order_type = 6
SUM(CASE WHEN gso.dj_order_type = 6 SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `内部结算成本(财务列表)`, ELSE 0 END) AS internal_settle_cost,
-- 原厂产品成本(财务列表) = 非内部结算 + goods_name 含 AITO/HIMA
SUM(CASE WHEN gso.dj_order_type != 6 SUM(CASE WHEN gso.dj_order_type != 6
AND (gso.upgrade_goods_name LIKE '%AITO%' AND (gso.upgrade_goods_name LIKE '%AITO%'
OR gso.upgrade_goods_name LIKE '%HIMA%') OR gso.upgrade_goods_name LIKE '%HIMA%')
THEN gso.upgrade_shop_price - gso.base_shop_price THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `原厂产品成本(财务列表)`, ELSE 0 END) AS oe_product_cost,
-- 副厂产品成本(财务列表) = 非内部结算 + goods_name 不含 AITO/HIMA
SUM(CASE WHEN gso.dj_order_type != 6 SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%' AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%' AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN gso.upgrade_shop_price - gso.base_shop_price THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `副厂产品成本(财务列表)`, ELSE 0 END) AS nonoe_product_cost,
-- 窗膜成本 (品类 = 太阳膜/天窗冰甲)
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜') SUM(CASE WHEN gso.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
THEN gso.upgrade_shop_price - gso.base_shop_price THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `窗膜成本`, ELSE 0 END) AS window_film_cost,
-- 车衣成本 (品类 = 车衣/改色膜)
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('车衣','改色膜') SUM(CASE WHEN gso.upgrade_goods_type_name IN ('车衣','改色膜')
THEN gso.upgrade_shop_price - gso.base_shop_price THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `车衣成本`, ELSE 0 END) AS car_wrap_cost,
-- 精品成本 (排除所有已归类品类)
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN ('自建商品-太阳膜','天窗冰甲','太阳膜','车衣','改色膜','踏板','充电桩','验收一级类目') SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN ('自建商品-太阳膜','天窗冰甲','太阳膜','车衣','改色膜','踏板','充电桩','验收一级类目')
THEN gso.upgrade_shop_price - gso.base_shop_price THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `精品成本`, ELSE 0 END) AS premium_cost,
-- 门店分成/流量费(财务列表) = 非内部结算的 shop_traffic_money
SUM(CASE WHEN gso.dj_order_type != 6 SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0) THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS `门店分成/流量费(财务列表)`, ELSE 0 END) AS store_share,
-- 施工收入 = custom_common_cost (汇总记录 gopa2)
SUM(IFNULL(gopa2.custom_common_cost, 0)) AS `施工收入`,
-- 市场费 = 四项费用累计 (fee 子查询) -- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
SUM(IFNULL(fee.total, 0)) AS `市场费` 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 FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N' ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N' ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N' ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2 LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y' AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1 AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N' AND gopa2.deleted_flag = 'N'
LEFT JOIN ( LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤) -- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT SELECT
ecc.order_code, ecc.order_code,
...@@ -117,11 +133,14 @@ LEFT JOIN ( ...@@ -117,11 +133,14 @@ LEFT JOIN (
AND po.success_date <= @end_time AND po.success_date <= @end_time
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
GROUP BY ecc.order_code GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code ) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N' WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N' AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
AND po.success_date >= @start_time AND po.success_date >= @start_time
AND po.success_date <= @end_time AND po.success_date <= @end_time
GROUP BY go.merchant_name;
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
No preview for this file type
# -*- coding: utf-8 -*-
"""广联日快照基础表处理:每日定时拉取通用品牌报表的「门店产值及个人成交排名」数据,
仅保存每个门店的 延保小计 / 权益小计 全量字段,落库到独立基础表 glsx_daily_deal_subtotal。
与本项目的 baic_special / avita_special 报表类型**无关联**:
- 数据源:dj.glsx.com.cn 报表导出接口(report_type=yanbaoMerAndPerRanking,filename=报表月,
取「通用品牌」一份),与 baic_special_processor.fetch_glsx_report / avita 的同名函数同源,
但本模块独立实现,避免耦合到具体品牌。
- 落库:独立基础表,按 stat_date(快照归属日期)做时间序列快照,与任何 DataProcessTask 无关。
- 触发:
· GlsxDailyScheduler 每日 Cron(07:00)→ scan_glsx_daily()(stat_date = 昨天);
· 手动补数 → 直接调用 snapshot_glsx(指定日期)(如补某周日的快照,供北汽 W1/W2/W3 分母取数)。
幂等:同 stat_date 先软删旧行再插新行。
"""
import io
import logging
from datetime import date, timedelta
import requests
import openpyxl
from decimal import Decimal, InvalidOperation
from models import db, GlsxDailyDealSubtotal
logger = logging.getLogger(__name__)
_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 _glsx_to_int(v):
"""单元格转 int:空/非数字/'-' → None(用于成交/交付/触客计数聚合)。"""
if v is None or v == '':
return None
s = str(v).strip().replace(',', '')
if s in ('-', 'None'):
return None
try:
return int(Decimal(s))
except (InvalidOperation, ValueError):
return None
def _to_dec(v):
"""单元格转 Decimal:空/'-' → None(用于目标产值 万元)。"""
if v is None or v == '':
return None
s = str(v).strip().replace(',', '')
if s in ('-', 'None'):
return None
try:
return Decimal(s)
except (InvalidOperation, ValueError):
return None
def _download_glsx_rows(stat_month):
"""通用:列出报表→定位「通用品牌」→下载 xlsx→返回 (rows, header_index)。失败返回 (None, None)。"""
if not stat_month:
logger.warning('[广联日快照] stat_month 为空,跳过')
return None, None
try:
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 None, None
key = target['key']
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 None, None
file_url = dlist[0]['url']
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 None, None
return rows, hidx
except Exception as e:
logger.warning(f'[广联日快照] 报表获取失败(stat_month={stat_month}): {e}')
return None, None
def fetch_daily_deal_subtotals(stat_month):
"""解析通用品牌报表,返回 {门店名称: {ext_warranty_deal_count, rights_deal_count,
gl_rights_deal_count, actual_output_wan, delivery_cnt, visit_cnt}}。
仅取 延保小计 / 权益小计 两个小计行(门店分段内的小计行,C 列为空、门店名从上一业务行向前携带);
按列名(归一后)定位,不依赖固定列号。任何失败返回空 dict(不致命)。
"""
rows, hidx = _download_glsx_rows(stat_month)
if rows is None or hidx is None:
return {}
try:
col = {_norm_header(n): j for j, n in enumerate(rows[hidx]) if n is not None}
ext_c = col.get('整车延保成交数')
rights_c = col.get('原厂权益成交数') # 延保小计 行
gl_rights_c = col.get('广联权益成交数') # 权益小计 行
actual_c = next((j for h, j in col.items() if '实际完成产值' in h), None) # 延保小计 行(目标产值列在门店小计行为空)
deliv_c = next((j for h, j in col.items() if '累计交付数' in h), None)
visit_c = next((j for h, j in col.items() if '实际售前触客数' in h), None)
store_c = col.get('门店')
if store_c is None:
logger.warning('[广联日快照] 报表缺少「门店」列,无法定位门店')
return {}
result = {}
cur = None # 向前携带的当前门店名(小计行 C 为空)
for row in rows[hidx + 1:]:
if not row:
continue
a = _norm_header(row[0]) if row[0] is not None else ''
c = str(row[store_c]).strip() if len(row) > store_c and row[store_c] else ''
if c:
cur = c
if not cur:
continue
rec = result.setdefault(cur, {})
if a == '延保小计':
if ext_c is not None and len(row) > ext_c and row[ext_c] not in (None, ''):
rec['ext_warranty_deal_count'] = _glsx_to_int(row[ext_c])
if rights_c is not None and len(row) > rights_c and row[rights_c] not in (None, ''):
rec['rights_deal_count'] = _glsx_to_int(row[rights_c])
if actual_c is not None and len(row) > actual_c and row[actual_c] not in (None, ''):
rec['actual_output_wan'] = _to_dec(row[actual_c])
if deliv_c is not None and len(row) > deliv_c and row[deliv_c] not in (None, ''):
rec['delivery_cnt'] = _glsx_to_int(row[deliv_c])
if visit_c is not None and len(row) > visit_c and row[visit_c] not in (None, ''):
rec['visit_cnt'] = _glsx_to_int(row[visit_c])
elif a == '权益小计':
if gl_rights_c is not None and len(row) > gl_rights_c and row[gl_rights_c] not in (None, ''):
rec['gl_rights_deal_count'] = _glsx_to_int(row[gl_rights_c])
logger.info(f'[广联日快照] 解析到 {len(result)} 个门店的延保小计/权益小计数据')
return result
except Exception as e:
logger.warning(f'[广联日快照] 解析失败(stat_month={stat_month}): {e}')
return {}
def snapshot_glsx(stat_date):
"""把一个指定日期(stat_date)的通用品牌报表快照落库基础表(幂等)。
- 报表月 filename = stat_date 所在月(月初跨月自动取上月)。
- 幂等:先对 (stat_date, is_deleted=0) 旧行做软删除,再批量插入新快照。
- 报表不可达 / 无数据 → 仅告警返回,不报错、不写空行。
供每日任务(stat_date=昨天)与手动补数共用。
"""
stat_month = stat_date.strftime('%Y-%m')
data = fetch_daily_deal_subtotals(stat_month)
if not data:
logger.warning(f'[广联快照] {stat_month}(stat_date={stat_date})无数据,跳过')
return {'success': 0, 'skipped': 'no_data', 'stat_date': str(stat_date)}
# 幂等:软删旧行
old_rows = GlsxDailyDealSubtotal.query.filter_by(
stat_date=stat_date, is_deleted=0).all()
for o in old_rows:
o.is_deleted = 1
db.session.flush()
# 插入新快照
objs = []
for store_name, rec in data.items():
objs.append(GlsxDailyDealSubtotal(
stat_date=stat_date,
store_name=store_name,
ext_warranty_deal_count=rec.get('ext_warranty_deal_count'),
rights_deal_count=rec.get('rights_deal_count'),
gl_rights_deal_count=rec.get('gl_rights_deal_count'),
actual_output_wan=rec.get('actual_output_wan'),
delivery_cnt=rec.get('delivery_cnt'),
visit_cnt=rec.get('visit_cnt'),
is_deleted=0,
))
db.session.add_all(objs)
db.session.commit()
logger.info(f'[广联快照] stat_date={stat_date} 落库 {len(objs)} 家门店'
f'(软删旧 {len(old_rows)} 行)')
return {'success': 1, 'stat_date': str(stat_date), 'stores': len(objs),
'deleted_old': len(old_rows)}
def scan_glsx_daily():
"""每日定时任务:拉取昨天所在月的通用品牌报表,按 stat_date=昨天 幂等落库基础表。
- 昨天 = today - 1 天;报表月 filename = 昨天所在月(月初跨月自动取上月)。
- 落库细节见 snapshot_glsx()。
"""
yesterday = date.today() - timedelta(days=1)
return snapshot_glsx(yesterday)
...@@ -63,7 +63,8 @@ class IndicatorClient: ...@@ -63,7 +63,8 @@ class IndicatorClient:
- end_date: str 'YYYY-MM-DD' - end_date: str 'YYYY-MM-DD'
- biz: int 单值(1=延保 2=轻改 3=权益) 或 list/tuple(如 [1,3] 多业务线); - biz: int 单值(1=延保 2=轻改 3=权益) 或 list/tuple(如 [1,3] 多业务线);
多值会序列化为逗号字符串 bizs="1,3"(与 itemCodes 风格一致); 多值会序列化为逗号字符串 bizs="1,3"(与 itemCodes 风格一致);
单值仍走原 "biz" 键,向后兼容现有调用方。 单值序列化为 bizs="N"(API 仅认 bizs 键,不再有 "biz" 单数形式);
None 表示不限定业务线 → 不传 bizs 键、查全量(A0018 全国经营总产值用此)。
- item_codes: list[str] 指标编码列表,如 ['A036', 'A075'] - item_codes: list[str] 指标编码列表,如 ['A036', 'A075']
- rate_codes: set[str] 率类指标编码,API 返回小数会 *100;None 则用 RATE_CODES 默认 - rate_codes: set[str] 率类指标编码,API 返回小数会 *100;None 则用 RATE_CODES 默认
...@@ -83,11 +84,13 @@ class IndicatorClient: ...@@ -83,11 +84,13 @@ class IndicatorClient:
"exts": "merchantIds", "exts": "merchantIds",
"itemCodes": ",".join(item_codes), "itemCodes": ",".join(item_codes),
} }
# biz 支持单值(int) / 多值(list):多业务线按约定序列化为逗号字符串 bizs="1,3" # biz=None 表示查全量:不要传 bizs 键,否则 API 把 "None" 当无效业务线过滤返回空
if isinstance(biz, (list, tuple, set)): if biz is None:
pass # 不传 bizs → 返回全业务线全量
elif isinstance(biz, (list, tuple, set)):
payload["bizs"] = ",".join(str(b) for b in biz) payload["bizs"] = ",".join(str(b) for b in biz)
else: else:
payload["biz"] = biz payload["bizs"] = str(biz)
last_err = None last_err = None
# 请求参数日志 # 请求参数日志
...@@ -168,3 +171,85 @@ class IndicatorClient: ...@@ -168,3 +171,85 @@ class IndicatorClient:
seen.add(c) seen.add(c)
unique.append(c) unique.append(c)
return self.fetch(start_date, end_date, biz, unique) 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()
...@@ -25,7 +25,7 @@ from report_utils import ( ...@@ -25,7 +25,7 @@ from report_utils import (
parse_inshop_delivery_touch, parse_commerce_policy_inshop, parse_inshop_delivery_touch, parse_commerce_policy_inshop,
parse_labor_cost, is_luxury_brand, parse_labor_cost, is_luxury_brand,
parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period, parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats, fuzzy_match_store, 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, get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
from models import ReportLightReformInshop, db from models import ReportLightReformInshop, db
...@@ -163,13 +163,13 @@ class LightReformInshopProcessor: ...@@ -163,13 +163,13 @@ class LightReformInshopProcessor:
goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end) goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end)
# 2d. 财务成本分项(店中店+园区店共用 SQL,按 dj_order_type + 品类 + 原厂/副厂切分) # 2d. 财务成本分项(店中店+园区店共用 SQL,按 dj_order_type + 品类 + 原厂/副厂切分)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1) finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 2b. 模糊匹配到门店 → 组装 sql_data dict(get_with_fallback 双优先用) # 2b. 精确匹配系统数据(系统 merchant_name 命名规范,精确避免误匹配)
biz_sql_data = {} biz_sql_data = {}
for rec in base_records: for rec in base_records:
sn = rec.get('store_name', '') sn = rec.get('store_name', '')
dr = fuzzy_match_store(sn, daily_report_map) or {} dr = exact_match_store(sn, daily_report_map) or {}
gs = fuzzy_match_store(sn, goods_stats_map) or {} gs = exact_match_store(sn, goods_stats_map) or {}
fs = fuzzy_match_store(sn, finance_map) or {} fs = exact_match_store(sn, finance_map) or {}
biz_sql_data[sn] = { biz_sql_data[sn] = {
# —— 日报类(来自 fetch_park_daily_report)—— # —— 日报类(来自 fetch_park_daily_report)——
'delivery_cnt': dr.get('delivery_cnt', 0), 'delivery_cnt': dr.get('delivery_cnt', 0),
...@@ -203,11 +203,26 @@ class LightReformInshopProcessor: ...@@ -203,11 +203,26 @@ class LightReformInshopProcessor:
'store_share': fs.get('store_share', Decimal('0')), 'store_share': fs.get('store_share', Decimal('0')),
'construction_income': fs.get('construction_income', Decimal('0')), 'construction_income': fs.get('construction_income', Decimal('0')),
'market_fee': fs.get('market_fee', 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 解析) ========== # ========== Step3: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map 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: 逐行计算 ========== # ========== Step5: 逐行计算 ==========
rows_to_insert = [] rows_to_insert = []
for rec in base_records: for rec in base_records:
...@@ -267,7 +282,8 @@ class LightReformInshopProcessor: ...@@ -267,7 +282,8 @@ class LightReformInshopProcessor:
store_share = sql_data.get('store_share', Decimal('0')) store_share = sql_data.get('store_share', Decimal('0'))
construction_income = sql_data.get('construction_income', Decimal('0')) construction_income = sql_data.get('construction_income', Decimal('0'))
market_fee_raw = sql_data.get('market_fee', 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 包含匹配 # 先精确匹配,失败则 fuzzy 包含匹配
...@@ -299,8 +315,9 @@ class LightReformInshopProcessor: ...@@ -299,8 +315,9 @@ class LightReformInshopProcessor:
store_consumables = prorate_by_period( store_consumables = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'store_consumables'), extract_budget_ratio(prev_budget_map, sn, 'store_consumables'),
period_start, period_end) period_start, period_end)
# 服务费占比:直接取(比例值不摊销) # 服务费占比:直营店强制 0,服务商直接取(与 park_processor 对齐)
sp_ratio = extract_budget_ratio(prev_budget_map, sn, 'service_provider_share_ratio') 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) headcount = labor_map.get(sn, 0)
...@@ -377,16 +394,21 @@ class LightReformInshopProcessor: ...@@ -377,16 +394,21 @@ class LightReformInshopProcessor:
product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_output_value) product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_output_value)
# 市场费:若一线激励存在(不为 0),则只算管理层市场费1+2 # 市场费:若一线激励存在(> 0),则只算管理层市场费1+2;否则管理层+阳光激励全算
# 这里 market_fee_raw 已经是 TODO 占位值,先原样取 if frontline_incentive and frontline_incentive > 0:
market_fee = market_fee_raw 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) market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
# 营销人员成本 # 营销人员成本
marketing_personnel_cost = Decimal('0') marketing_personnel_cost = Decimal('0')
if operate_type == '直营': 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 = ( marketing_personnel_cost = (
Decimal(str(headcount)) * Decimal('3500') + Decimal(str(headcount)) * base_salary_prorated +
store_output_value * Decimal('0.04') store_output_value * Decimal('0.04')
) )
marketing_personnel_ratio = safe_div_pct_decimal(marketing_personnel_cost, store_output_value) marketing_personnel_ratio = safe_div_pct_decimal(marketing_personnel_cost, store_output_value)
...@@ -417,9 +439,9 @@ class LightReformInshopProcessor: ...@@ -417,9 +439,9 @@ class LightReformInshopProcessor:
task_id=task_id, period_start=period_start, period_end=period_end, task_id=task_id, period_start=period_start, period_end=period_end,
# 基础维度 # 基础维度
region_area=region_area, province=province, city=rec.get('city', ''), region_area=region_area, province=province, city=rec.get('city', ''),
park_type=rec.get('park_type', ''), biz_line=rec.get('biz_line', '1.12'), 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', ''), operate_type=operate_type, region_manager=rec.get('region_manager', ''),
park_name=rec.get('park_name', ''), store_name=sn, brand=brand, park_name=store_to_park.get(sn, ''), store_name=sn, brand=brand,
brand_category=brand_category, purchase_indicator=purchase_indicator, brand_category=brand_category, purchase_indicator=purchase_indicator,
# 销售 # 销售
sales_order_cnt=sales_order_cnt, sales_touch_cnt=sales_touch_cnt, sales_order_cnt=sales_order_cnt, sales_touch_cnt=sales_touch_cnt,
......
...@@ -31,8 +31,8 @@ from report_utils import ( ...@@ -31,8 +31,8 @@ from report_utils import (
parse_park_delivery_touch, parse_commerce_policy_park, parse_park_delivery_touch, parse_commerce_policy_park,
parse_labor_cost, is_luxury_brand, parse_labor_cost, is_luxury_brand,
parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period, parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_indicator_data, fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_indicator_data, fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats,
fetch_light_reform_finance_stats, fetch_est_delivery_count, fuzzy_match_store, 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, get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
from models import ReportLightReformPark, db from models import ReportLightReformPark, db
...@@ -168,13 +168,15 @@ class LightReformParkProcessor: ...@@ -168,13 +168,15 @@ class LightReformParkProcessor:
est_delivery_map = fetch_est_delivery_count(base_scene_code='100101') est_delivery_map = fetch_est_delivery_count(base_scene_code='100101')
# 3d. 财务成本分项(店中店+园区店共用 SQL,park 侧仅消费 4 项) # 3d. 财务成本分项(店中店+园区店共用 SQL,park 侧仅消费 4 项)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1) finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 3e. 模糊匹配到门店 → 组装 sql_data dict # 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 = {} biz_sql_data = {}
for rec in base_records: for rec in base_records:
sn = rec.get('store_name', '') sn = rec.get('store_name', '')
dr = fuzzy_match_store(sn, daily_report_map) or {} dr = exact_match_store(sn, daily_report_map) or {}
gs = fuzzy_match_store(sn, goods_stats_map) or {} gs = exact_match_store(sn, goods_stats_map) or {}
fs = fuzzy_match_store(sn, finance_map) or {} fs = exact_match_store(sn, finance_map) or {}
eq = dr.get('equity_to_shop_count', 0) eq = dr.get('equity_to_shop_count', 0)
af = dr.get('after_sale_equity_to_shop_count', 0) af = dr.get('after_sale_equity_to_shop_count', 0)
biz_sql_data[sn] = { biz_sql_data[sn] = {
...@@ -191,7 +193,7 @@ class LightReformParkProcessor: ...@@ -191,7 +193,7 @@ class LightReformParkProcessor:
'store_sales_output': gs.get('store_output_value', Decimal('0')), 'store_sales_output': gs.get('store_output_value', Decimal('0')),
'internal_settle_value': gs.get('internal_settle_value', Decimal('0')), 'internal_settle_value': gs.get('internal_settle_value', Decimal('0')),
# —— 预估交车数(来自 fetch_est_delivery_count)—— # —— 预估交车数(来自 fetch_est_delivery_count)——
'est_delivery_cnt': fuzzy_match_store(sn, est_delivery_map) or 0, 'est_delivery_cnt': exact_match_store(sn, est_delivery_map) or 0,
# —— 财务分项(park 仅消费产品成本/内部结算成本/流量费/市场费)—— # —— 财务分项(park 仅消费产品成本/内部结算成本/流量费/市场费)——
'product_cost_finance': fs.get('product_cost_finance', Decimal('0')), 'product_cost_finance': fs.get('product_cost_finance', Decimal('0')),
'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')), 'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')),
...@@ -203,36 +205,82 @@ class LightReformParkProcessor: ...@@ -203,36 +205,82 @@ class LightReformParkProcessor:
# ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ========== # ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map prev_budget_map = budget_achieve_map
# ========== Step5: 合作门店数量(按 park_name 聚合) ========== # ========== Step4.5: store_name → park_name 映射(系统表优先,用于 Step6 输出) ==========
from collections import Counter store_to_park = {}
park_counter = Counter(r.get('park_name', '') for r in base_records if r.get('park_name')) 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.5: 预计算每个 park 的预估交车数合计(用于同 park 多门店分摊预估产值纠偏)========== # ========== Step5: 合作门店数量 + park 预估交车合计(保持原逻辑) ==========
# 分摊基数:Excel 第一优先,SQL/配置表回退(与循环内 est_delivery_cnt 取值逻辑一致) from collections import Counter
park_counter = Counter(p for p in store_to_park.values() if p)
park_est_delivery_total = {} park_est_delivery_total = {}
for rec in base_records: for rec in base_records:
pn = rec.get('park_name', '')
sn = rec.get('store_name', '') sn = rec.get('store_name', '')
pn = store_to_park.get(sn, '')
est = int(get_with_fallback( est = int(get_with_fallback(
rec.get('est_delivery_cnt', 0), rec.get('est_delivery_cnt', 0),
get_with_fallback( get_with_fallback(
fuzzy_match_store(sn, est_delivery_map) or 0, exact_match_store(sn, est_delivery_map) or 0,
fuzzy_match_store(sn, biz_sql_data).get('est_delivery_cnt', 0), biz_sql_data.get(sn, {}).get('est_delivery_cnt', 0),
), ),
) or 0) ) or 0)
park_est_delivery_total[pn] = park_est_delivery_total.get(pn, 0) + est 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: 逐行计算 ========== # ========== Step6: 逐行计算 ==========
rows_to_insert = [] rows_to_insert = []
for rec in base_records: for rec in base_records:
sn = rec.get('store_name', '') sn = rec.get('store_name', '')
province = rec.get('province', '') province = rec.get('province', '')
park_name = rec.get('park_name', '') park_name = store_to_park.get(sn, '')
operate_type = rec.get('operate_type', '') operate_type = rec.get('operate_type', '')
brand = rec.get('brand', '') brand = rec.get('brand', '')
region_area = region_map.get(('', province), '') region_area = region_map.get(('', province), '')
biz_type = is_luxury_brand(brand) # 类型=豪华/非豪华 biz_type = is_luxury_brand(brand)
partner_store_cnt = park_counter.get(park_name, 1) partner_store_cnt = park_counter.get(park_name, 1)
# —— Excel 第一优先 / SQL 回退 —— # —— Excel 第一优先 / SQL 回退 ——
...@@ -295,22 +343,18 @@ class LightReformParkProcessor: ...@@ -295,22 +343,18 @@ class LightReformParkProcessor:
total_output_value = store_sales_output + internal_settle_value total_output_value = store_sales_output + internal_settle_value
# 产值达成进度(预估总产值 = 预估产值纠偏按同 park 多门店的预估交车数占比分摊) # 产值达成进度:从合并组取头行预估产值,多门店合并组按预估交车数占比分摊
est_output_value_raw = rec.get('est_output_value', Decimal('0')) group = store_to_group.get(sn)
est_output_value = est_output_value_raw group_head_est = group['head_est'] if group else (rec.get('est_output_value', Decimal('0')) or Decimal('0'))
if est_output_value_raw and est_output_value_raw > 0: est_output_value = group_head_est
# 同 park 多门店共用一个纠偏值 → 按预估交车数占比分摊
park_total_est = park_est_delivery_total.get(park_name, 0) if group and len(group['stores']) > 1 and group_head_est > 0:
if partner_store_cnt > 1 and park_total_est > 0: # 多门店合并组 → 按预估交车数占比分摊
store_est_delivery = int(get_with_fallback( group_total_del = sum(group['deliveries'].values())
rec.get('est_delivery_cnt', 0), store_del = group['deliveries'].get(sn, 0)
get_with_fallback( if group_total_del > 0:
fuzzy_match_store(sn, est_delivery_map) or 0, est_output_value = (group_head_est
sql_data.get('est_delivery_cnt', 0), * Decimal(store_del) / Decimal(group_total_del)
),
) or 0)
est_output_value = (est_output_value_raw
* Decimal(store_est_delivery) / Decimal(park_total_est)
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) ).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
output_progress = safe_div_pct_decimal(total_output_value, est_output_value) output_progress = safe_div_pct_decimal(total_output_value, est_output_value)
...@@ -346,8 +390,11 @@ class LightReformParkProcessor: ...@@ -346,8 +390,11 @@ class LightReformParkProcessor:
# 人员成本(直营才算) # 人员成本(直营才算)
personnel_cost = Decimal('0') personnel_cost = Decimal('0')
if operate_type == '直营': 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 = ( personnel_cost = (
Decimal(str(headcount)) * Decimal('3500') + Decimal(str(headcount)) * base_salary_prorated +
store_sales_output * Decimal('0.04') store_sales_output * Decimal('0.04')
) )
personnel_cost_ratio = safe_div_pct_decimal(personnel_cost, store_sales_output) personnel_cost_ratio = safe_div_pct_decimal(personnel_cost, store_sales_output)
......
...@@ -734,6 +734,194 @@ class ReportLightReformPark(db.Model): ...@@ -734,6 +734,194 @@ class ReportLightReformPark(db.Model):
deleted_at = db.Column(db.DateTime, nullable=True) 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 BaicSpecialMonthData(db.Model):
"""北汽专项-月份明细数据表(data_table_type=baic_special 的主表,逐门店一行)
注意:列定义严格对齐已建好的真实 MySQL 表,多声明/错拼列都会导致 INSERT 报
Unknown column。region / store_type 来自 D+ 系统且 NOT NULL,本轮源文件不含,
先以空串占位,待 D+ 系统接入后回填。
"""
__tablename__ = 'baic_special_month_data'
store_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_code = db.Column(db.String(64), comment='门店编码')
region = db.Column(db.String(50), nullable=False, default='', comment='区域(D+系统,占位)')
store_type = db.Column(db.String(20), nullable=False, default='', comment='驻店类型:直营/服务商(D+系统,占位)')
store_name = db.Column(db.String(255), nullable=False, comment='门店名称')
brand = db.Column(db.String(50), comment='品牌,如:北汽极狐/北京越野')
operator_name = db.Column(db.String(100), comment='运营')
business_start_date = db.Column(db.Date, comment='业务开展时间(展业时间)')
resident_staff = db.Column(db.String(255), comment='驻店人员')
underwriting_rule = db.Column(db.String(500), comment='兜底门店规则(无兜底填「无」)')
output_target_wan = db.Column(db.DECIMAL(18, 4), comment='产值目标(万)')
output_current_wan = db.Column(db.DECIMAL(18, 4), comment='截止目前产值(万)')
achievement_rate = db.Column(db.DECIMAL(18, 8), comment='达成率')
new_delivery_cnt = db.Column(db.Integer, comment='新车交付数')
visit_cnt = db.Column(db.Integer, comment='触客数')
visit_rate = db.Column(db.DECIMAL(18, 8), comment='触客率')
comprehensive_penetration = db.Column(db.DECIMAL(18, 8), comment='综合渗透')
current_light = db.Column(db.String(2), comment='截止目前(灯):绿/黄/红')
w1_comprehensive_penetration = db.Column(db.DECIMAL(18, 8), comment='W1综合渗透')
w1_light_level = db.Column(db.String(2), comment='W1灯级')
w2_comprehensive_penetration = db.Column(db.DECIMAL(18, 8), comment='W2综合渗透')
w2_light_level = db.Column(db.String(2), comment='W2灯级')
w3_comprehensive_penetration = db.Column(db.DECIMAL(18, 8), comment='W3综合渗透')
w3_light_level = db.Column(db.String(2), comment='W3灯级')
w4_comprehensive_penetration = db.Column(db.DECIMAL(18, 8), comment='W4综合渗透')
w4_light_level = db.Column(db.String(2), comment='W4灯级')
# 周度原始数据快照(由结果表 generate_result_excel 渲染时按同口径回写,此处仅作持久化)
# 订单数 = 截止到当周累计(延保+权益);新车交付数 = 广联日快照表 glsx_daily_deal_subtotal 该周交付数
w1_order_cnt = db.Column(db.Integer, comment='W1累计(延保+权益)订单数(周快照)')
w1_new_delivery_cnt = db.Column(db.Integer, comment='W1累计新车交付数(广联报表,周快照)')
w2_order_cnt = db.Column(db.Integer, comment='W2累计(延保+权益)订单数(周快照)')
w2_new_delivery_cnt = db.Column(db.Integer, comment='W2累计新车交付数(广联报表,周快照)')
w3_order_cnt = db.Column(db.Integer, comment='W3累计(延保+权益)订单数(周快照)')
w3_new_delivery_cnt = db.Column(db.Integer, comment='W3累计新车交付数(广联报表,周快照)')
excellent_value = db.Column(db.DECIMAL(10, 6), comment='评灯标准-优秀值')
standard_value = db.Column(db.DECIMAL(10, 6), comment='评灯标准-标准值')
warning_value = db.Column(db.DECIMAL(10, 6), comment='评灯标准-预警值')
delivery_check_output_cnt = db.Column(db.Integer, comment='交车数核对-产值表交车数')
delivery_check_group_cnt = db.Column(db.Integer, comment='交车数核对-一店一群交车数(线上运营手工上传)')
delivery_check_diff = db.Column(db.Integer, comment='交车数核对-差异(产值表-一店一群)')
visit_check_output_cnt = db.Column(db.Integer, comment='触客数核对-产值表触客数')
visit_check_group_cnt = db.Column(db.Integer, comment='触客数核对-一店一群触客数(线上运营手工上传)')
visit_check_diff = db.Column(db.Integer, comment='触客数核对-差异(产值表-一店一群)')
is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除(软删除)')
created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
class GlsxDailyDealSubtotal(db.Model):
"""广联日快照基础表(独立基础表,不关联任何报表类型/任务)。
每日定时任务从广联报表(dj.glsx.com.cn,通用品牌,yanbaoMerAndPerRanking)拉取
「门店产值及个人成交排名」数据,仅保存每个门店的 延保小计 / 权益小计 全量字段:
- ext_warranty_deal_count : 延保小计-整车延保成交数
- rights_deal_count : 延保小计-原厂权益成交数
- gl_rights_deal_count : 权益小计-广联权益成交数
- actual_output_wan : 延保小计-实际完成产值(万元)
(报表「目标产值」列在门店小计行为空,故存实际完成产值)
- delivery_cnt : 延保小计-累计交付数(台)
- visit_cnt : 延保小计-实际售前触客数
stat_date 取拉取日的前一天;按 (stat_date, store_name) 幂等(先软删旧行再插新行)。
"""
__tablename__ = 'glsx_daily_deal_subtotal'
id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='自增主键')
stat_date = db.Column(db.Date, nullable=False, comment='快照日期(拉取的是前一天的数据)')
store_name = db.Column(db.String(200), nullable=False, comment='门店名称(报表门店列,精确匹配来源)')
ext_warranty_deal_count = db.Column(db.Integer, comment='延保小计-整车延保成交数')
rights_deal_count = db.Column(db.Integer, comment='延保小计-原厂权益成交数')
gl_rights_deal_count = db.Column(db.Integer, comment='权益小计-广联权益成交数')
actual_output_wan = db.Column(db.DECIMAL(18, 2), comment='延保小计-实际完成产值(万元)')
delivery_cnt = db.Column(db.Integer, comment='延保小计-累计交付数(台)')
visit_cnt = db.Column(db.Integer, comment='延保小计-实际售前触客数')
is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除(软删除)')
created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='最近更新时间')
class BaicSpecialMonthlyBusiness(db.Model):
"""北汽专项-月份业务数据表(逐门店×业务:延保/权益;D+系统订单数据,本轮暂不落)"""
__tablename__ = 'baic_special_monthly_business'
id = db.Column(db.BigInteger, primary_key=True, autoincrement=True, comment='自增主键')
store_id = db.Column(db.BigInteger, nullable=False, comment='关联 baic_special_month_data.store_id')
business_type = db.Column(db.Integer, nullable=False, comment='业务类型:延保/权益')
order_cnt = db.Column(db.Integer, nullable=False, default=0, comment='订单数')
delivery_penetration_rate = db.Column(db.DECIMAL(18, 8), comment='交车渗透率')
class BaicSpecialMonthSummaryMetrics(db.Model):
"""北汽专项-汇总指标表(data_table_type=baic_special 的汇总行,单任务一行)"""
__tablename__ = 'baic_special_month_summary_metrics'
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')
project_name = db.Column(db.String(50), nullable=False, default='北汽', comment='项目(硬值:北汽)')
brand = db.Column(db.String(50), nullable=False, default='北汽', comment='品牌')
store_cnt = db.Column(db.Integer, comment='门店数')
output_wan = db.Column(db.DECIMAL(18, 4), comment='产值(万)')
delivery_cnt = db.Column(db.Integer, comment='交付数')
pre_sale_visit_cnt = db.Column(db.Integer, comment='售前触客数')
pre_sale_visit_rate = db.Column(db.DECIMAL(18, 8), comment='售前触客率')
after_sale_store_cnt = db.Column(db.Integer, comment='售后门店数')
after_sale_scene_open_rate = db.Column(db.DECIMAL(18, 8), comment='售后场景开通率')
after_sale_order_cnt = db.Column(db.Integer, comment='售后订单数')
vehicle_ext_warranty_deal_cnt = db.Column(db.Integer, comment='整车延保成交数')
vehicle_ext_warranty_penetration_rate = db.Column(db.DECIMAL(18, 8), comment='整车延保渗透率')
original_rights_deal_cnt = db.Column(db.Integer, comment='原厂权益成交数')
original_rights_penetration_rate = db.Column(db.DECIMAL(18, 8), comment='原厂权益渗透率')
after_sale_scene_open_rate_mom_pp = db.Column(db.DECIMAL(18, 8), comment='售后场景开通率环比(百分点pp)')
pre_sale_visit_rate_mom_pp = db.Column(db.DECIMAL(18, 8), comment='售前触客率环比(百分点pp)')
vehicle_ext_warranty_penetration_rate_mom_pp = db.Column(db.DECIMAL(18, 8), comment='整车延保渗透率环比(百分点pp)')
original_rights_penetration_rate_mom_pp = db.Column(db.DECIMAL(18, 8), comment='原厂权益渗透率环比(百分点pp)')
is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除(软删除)')
created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
class ReportStoreEffectSummary(db.Model): class ReportStoreEffectSummary(db.Model):
"""门店店效人效汇总表(整体合计,单任务一行;合并结果表第5个sheet)""" """门店店效人效汇总表(整体合计,单任务一行;合并结果表第5个sheet)"""
__tablename__ = 'report_store_effect_summary' __tablename__ = 'report_store_effect_summary'
......
...@@ -456,6 +456,8 @@ class OutputValueProcessor: ...@@ -456,6 +456,8 @@ class OutputValueProcessor:
""" """
task_id = task.id task_id = task.id
stat_month = task.month or '' 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_start = getattr(task, 'period_start', None)
...@@ -627,10 +629,10 @@ class OutputValueProcessor: ...@@ -627,10 +629,10 @@ class OutputValueProcessor:
# ---------- 保存 + 上传 ---------- # ---------- 保存 + 上传 ----------
tmp_dir = tempfile.mkdtemp(prefix=f'output_value_result_{task_id}_') tmp_dir = tempfile.mkdtemp(prefix=f'output_value_result_{task_id}_')
try: try:
excel_path = os.path.join(tmp_dir, f'产值达成表_{stat_month}.xlsx') excel_path = os.path.join(tmp_dir, f'{type_name}_{today_str}.xlsx')
wb.save(excel_path) wb.save(excel_path)
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}" object_key = (f"data-process/{today_str}"
f"/output_value_{stat_month}_{task_id}.xlsx") f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key) file_url = upload_file(excel_path, object_key)
logger.info(f"[产值达成] 结果表已生成并上传: {file_url}({len(rows)} 行明细)") logger.info(f"[产值达成] 结果表已生成并上传: {file_url}({len(rows)} 行明细)")
return file_url return file_url
......
...@@ -86,13 +86,15 @@ SHEET_BIZ_MAP = [ ...@@ -86,13 +86,15 @@ SHEET_BIZ_MAP = [
# 1.1 业务:太阳膜、龙南系列 # 1.1 业务:太阳膜、龙南系列
{'pattern': '太阳膜-赛力斯', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'}, # 赛力斯用市场费总额 {'pattern': '太阳膜-赛力斯', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'}, # 赛力斯用市场费总额
{'pattern': '太阳膜', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'}, # 其他太阳膜用市场费 {'pattern': '太阳膜', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'}, # 其他太阳膜用市场费
{'pattern': '^龙南$', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'}, # 2.1 业务:权益、续保 —— 精确规则放前面,避免被模糊规则拦截
{'pattern': '龙南-', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'}, # 龙南-权益等 {'pattern': '龙南-权益', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'}, # 龙南下的权益=2.1+市场费
# 2.1 业务:权益、续保 {'pattern': '权益', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'}, # 权益默认取总额,Title行修正
{'pattern': '^权益$', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'},
{'pattern': '续保', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'}, {'pattern': '续保', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'},
# 2.3 业务:延保 # 2.3 业务:延保
{'pattern': '延保', 'biz_type': BIZ_TYPE_2_3, 'fee_col': 'market_fee'}, {'pattern': '延保', 'biz_type': BIZ_TYPE_2_3, 'fee_col': 'market_fee'},
# 1.1 业务:龙南系列(排除权益后)
{'pattern': '^龙南$', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'},
{'pattern': '龙南-', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'},
] ]
# 跳过的 Sheet 名称关键词 # 跳过的 Sheet 名称关键词
...@@ -1460,6 +1462,30 @@ class DataProcessor: ...@@ -1460,6 +1462,30 @@ class DataProcessor:
StoreEffectSummaryProcessor(app=self.app).process(task) StoreEffectSummaryProcessor(app=self.app).process(task)
return 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) == 'baic_special':
from baic_special_processor import BaicSpecialProcessor
logger.info(f"[处理任务] 路由 baic_special 任务 {task_id} 至 BaicSpecialProcessor")
BaicSpecialProcessor(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 # 类型白名单保护:当前引擎仅支持 SUPPORTED_PROCESS_TYPES
if getattr(task, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES: if getattr(task, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES:
raise Exception( raise Exception(
...@@ -1844,6 +1870,18 @@ class DataProcessor: ...@@ -1844,6 +1870,18 @@ class DataProcessor:
if not records: if not records:
return [] return []
# 预构建 2-tuple 索引:(flow_key, biz) → [(brand, gmv_ratio, GMV)]
# flow_key 同时存原始名和 to_standard 后的值,双向可查
flat_index = defaultdict(list)
for (sf, sb, sbr), data in settlement_map.items():
if not (sf and sb and sbr):
continue
entry = (sbr, data.get("gmv_ratio"), data["GMV"])
flat_index[(sf, sb)].append(entry)
std_f = to_standard(sf, '4s')
if std_f and std_f != sf:
flat_index[(std_f, sb)].append(entry)
# 按 (流量方, 业务类型) 分组 # 按 (流量方, 业务类型) 分组
groups = defaultdict(list) groups = defaultdict(list)
for r in records: for r in records:
...@@ -2019,6 +2057,74 @@ class DataProcessor: ...@@ -2019,6 +2057,74 @@ class DataProcessor:
return result return result
@staticmethod
def _append_split_result(result, flow, biz, fixed_brand, total_fee, entries):
"""
将 total_fee 按比例分摊到 entries 的各品牌,追加到 result。
比例优先级:gmv_ratio 归一化 → GMV 值归一化 → 平均分摊
Args:
result: 待追加的结果列表
flow: 流量方
biz: 业务类型
fixed_brand: 若不为 None,所有输出用这个品牌;若为 None 用 entries 里的品牌
total_fee: 待分摊的总费用
entries: [(brand, gmv_ratio_float_or_None, GMV_Decimal), ...]
"""
n = len(entries)
if n == 0:
return
# 判断是否有可用的 gmv_ratio(全部 None 就降级)
ratios = []
has_ratio = False
for (br, rt, gmv) in entries:
if rt is not None:
ratios.append(Decimal(str(rt)))
has_ratio = True
else:
ratios.append(Decimal("0"))
if has_ratio:
total_ratio = sum(ratios)
if total_ratio > 0:
for i, (br, rt, gmv) in enumerate(entries):
allocated = (total_fee * ratios[i] / total_ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
out_brand = fixed_brand if fixed_brand is not None else br
result.append({"流量方名称": flow, "业务类型": biz,
"品牌": out_brand, "市场费": allocated})
# 尾差归并到最后一条
allocated_sum = sum(item["市场费"] for item in result[-n:])
diff = total_fee - allocated_sum
if diff != 0:
result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
return
# 降级:用 GMV 值
gmv_total = sum(gmv for (_, _, gmv) in entries)
if gmv_total > 0:
for (br, rt, gmv) in entries:
allocated = (total_fee * gmv / gmv_total).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
out_brand = fixed_brand if fixed_brand is not None else br
result.append({"流量方名称": flow, "业务类型": biz,
"品牌": out_brand, "市场费": allocated})
allocated_sum = sum(item["市场费"] for item in result[-n:])
diff = total_fee - allocated_sum
if diff != 0:
result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
return
# 最终降级:平均分摊
avg = (total_fee / n).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
for (br, rt, gmv) in entries:
out_brand = fixed_brand if fixed_brand is not None else br
result.append({"流量方名称": flow, "业务类型": biz,
"品牌": out_brand, "市场费": avg})
allocated_sum = avg * n
diff = total_fee - allocated_sum
if diff != 0:
result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
# ======================================================== # ========================================================
# 解析市场费表 # 解析市场费表
# ======================================================== # ========================================================
......
# -*- coding: utf-8 -*-
"""临时脚本:用最新代码重跑北汽专项任务 900002,并把结果表落到本地预览文件名。
用法(在 data-process 目录):
PYTHONPATH="C:/Users/66/AppData/Roaming/Python/Python314/site-packages" C:/Python314/python.exe regen_baic900002.py
"""
import sys
import os
import shutil
HERE = os.path.dirname(os.path.abspath(__file__))
sys.path.insert(0, HERE)
TASK_ID = 900002
# 本地预览文件名(与用户在腾讯文档预览的文件名一致)
LOCAL_XLSX = os.path.join(HERE, 'outputs', f'baic_special_2026-08_task{TASK_ID}.xlsx')
from app import app, db
from models import DataProcessTask
import baic_special_processor as _bpmod
from baic_special_processor import BaicSpecialProcessor
# 让 generate_result_excel 实际调用的 upload_file 顺带把生成文件拷贝到本地预览路径
# (generate_result_excel 内部用 `from oss_utils import upload_file` 的局部名,需重绑模块属性)
_real_upload = _bpmod.upload_file
def _patched_upload(local_path, object_key=None):
try:
os.makedirs(os.path.dirname(LOCAL_XLSX), exist_ok=True)
shutil.copy(local_path, LOCAL_XLSX)
print(f"[regen] 已拷贝生成文件到本地预览: {LOCAL_XLSX}")
except Exception as e:
print(f"[regen] 本地拷贝失败: {e}")
return _real_upload(local_path, object_key)
_bpmod.upload_file = _patched_upload
with app.app_context():
task = DataProcessTask.query.filter_by(id=TASK_ID).first()
if not task:
print("ERROR: task 900002 not found")
sys.exit(1)
print(f"[regen] task {TASK_ID}: status={task.status}, month={task.month}")
task.status = 'PROCESSING'
db.session.commit()
print("[regen] 已置 PROCESSING,调用 scan_baic_special ...")
res = BaicSpecialProcessor().scan_baic_special()
print(f"[regen] scan_baic_special 返回: {res}")
task = DataProcessTask.query.filter_by(id=TASK_ID).first()
print(f"[regen] 处理完成: status={task.status}, result_file_url={task.result_file_url}")
print("[regen] done")
...@@ -267,7 +267,14 @@ def match_columns(columns, keywords_map): ...@@ -267,7 +267,14 @@ def match_columns(columns, keywords_map):
""" """
result = {} result = {}
# —— 先处理带 ordinal 的(返回 int 索引,因为列名相同无法区分)—— # —— 先处理直接传 int 索引的(比如 AF 列 = 31)——
for std, keywords in keywords_map.items():
for kw in keywords:
if isinstance(kw, int) and 0 <= kw < len(columns):
result[std] = kw
break
# —— 再处理带 ordinal 的(返回 int 索引,因为列名相同无法区分)——
for std, keywords in keywords_map.items(): for std, keywords in keywords_map.items():
for kw in keywords: for kw in keywords:
if isinstance(kw, tuple) and len(kw) == 2 and isinstance(kw[1], int): if isinstance(kw, tuple) and len(kw) == 2 and isinstance(kw[1], int):
...@@ -671,12 +678,16 @@ def parse_budget_achieve_excel(file_path, biz_type=None): ...@@ -671,12 +678,16 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
col_map = match_columns(df.columns, { col_map = match_columns(df.columns, {
'store_name': ['流量费名称', '流量方名称', '门店名', 'target_name'], 'store_name': ['流量费名称', '流量方名称', '门店名', 'target_name'],
'biz_type': ['业务类型', '业务线'], 'biz_type': ['业务类型', '业务线'],
# 人员工资占比 → 营销费用占比:Excel 有多个同名列 "本月占比",取第 4 个 # 人员工资占比 → 营销费用占比:Excel header=None row0 有 5 个同名"本月占比"
'labor_ratio': [("本月占比", 4), '人员工资占比', '人员工资', '人员成本占比', '营销费用占比'], # header=0 下 pandas 自动加后缀 .1~.4,ordinal 子串匹配能命中全部 5 个
# 第 1 个=成本占比(col11) / 第 2 个=流量费占比(col14) / 第 3 个=服务费占比(col17)
# 第 4 个=市场费占比(col23) / 第 5 个=营销团队工资占比(col31) ← 延保/权益要这个
'labor_ratio': [("本月占比", 5), '人员工资占比', '人员工资', '人员成本占比', '营销费用占比'],
'renovation_amortization': ['装修分摊', '装修费用', '装修摊销'], 'renovation_amortization': ['装修分摊', '装修费用', '装修摊销'],
'rent_utilities': ['房租水电', '房租、水电', '房租', '水电费'], 'rent_utilities': ['房租水电', '房租、水电', '房租', '水电费'],
'store_consumables': ['门店耗材', '耗材'], 'store_consumables': ['门店耗材', '耗材'],
'service_provider_share_ratio': ['服务费占比', '服务商分成占比', '服务费费率', ("本月占比", 5)], # 服务费占比 = 第 3 个本月占比(col17),与 labor_ratio(第5个) 不冲突
'service_provider_share_ratio': ['服务费占比', '服务商分成占比', '服务费费率', ("本月占比", 3)],
}) })
if 'store_name' not in col_map: if 'store_name' not in col_map:
...@@ -734,6 +745,7 @@ def parse_budget_achieve_excel(file_path, biz_type=None): ...@@ -734,6 +745,7 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
# 取平均 # 取平均
result = {} result = {}
multi_cnt_stores = [] # 收集多行平均的门店名
for (sn, _bt), fields in agg.items(): for (sn, _bt), fields in agg.items():
if sn not in result: if sn not in result:
result[sn] = { result[sn] = {
...@@ -743,11 +755,17 @@ def parse_budget_achieve_excel(file_path, biz_type=None): ...@@ -743,11 +755,17 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
'store_consumables': Decimal('0'), 'store_consumables': Decimal('0'),
'service_provider_share_ratio': Decimal('0'), 'service_provider_share_ratio': Decimal('0'),
} }
# 检查这个门店是否有任何字段 cnt > 1(多行被平均)
max_cnt = max((cnt for (_, cnt) in fields.values()), default=1)
if max_cnt > 1:
multi_cnt_stores.append((sn, {f: c for f, (_, c) in fields.items() if c > 1}))
for field, (total, cnt) in fields.items(): for field, (total, cnt) in fields.items():
if cnt > 0: if cnt > 0:
result[sn][field] = (total / Decimal(str(cnt))).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP) result[sn][field] = (total / Decimal(str(cnt))).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP)
logger.info(f"[预算达成Excel] {len(result)} 个门店匹配") logger.info(f"[预算达成Excel] biz_type={biz_type} {len(result)} 个门店匹配")
if multi_cnt_stores:
logger.info(f"[预算达成Excel] biz_type={biz_type} {len(multi_cnt_stores)} 个门店有多行→取平均: {multi_cnt_stores[:10]}")
return result return result
...@@ -755,18 +773,14 @@ def extract_budget_ratio(budget_map, store_name, field='labor_ratio'): ...@@ -755,18 +773,14 @@ def extract_budget_ratio(budget_map, store_name, field='labor_ratio'):
""" """
从 parse_budget_achieve_excel 返回值中安全取单个字段。 从 parse_budget_achieve_excel 返回值中安全取单个字段。
匹配逻辑:先精确匹配 store_name → budget_map key,失败则用 fuzzy_match_store 模糊包含匹配。 匹配逻辑:只做门店名**精确匹配**,取不到返回 Decimal('0')。
模糊匹配兼容"门店名"(SAAS表) vs "流量费名称"(预算表) 命名差异。 营销费用/服务费等占比必须精准对应门店,避免模糊匹配串店。
返回 Decimal,取不到返回 Decimal('0')。
""" """
if not budget_map or not store_name: if not budget_map or not store_name:
return Decimal('0') return Decimal('0')
# 1. 精确匹配
entry = budget_map.get(store_name) entry = budget_map.get(store_name)
if entry is None: if entry is None:
# 2. 模糊包含匹配 return Decimal('0')
entry = fuzzy_match_store(store_name, budget_map) or {}
val = entry.get(field, Decimal('0')) if isinstance(entry, dict) else Decimal('0') val = entry.get(field, Decimal('0')) if isinstance(entry, dict) else Decimal('0')
return val or Decimal('0') return val or Decimal('0')
...@@ -1046,10 +1060,10 @@ def _aggregate_by_biz_type(df, col_map, store_name_col, numeric_fields, text_fie ...@@ -1046,10 +1060,10 @@ def _aggregate_by_biz_type(df, col_map, store_name_col, numeric_fields, text_fie
result[sn] = {} result[sn] = {}
for f, v in fields.items(): for f, v in fields.items():
if isinstance(v, list): if isinstance(v, list):
# 数值 [sum, count] → 取平均 # 数值 [sum, count] → 取平均(高精度保留,避免 0.015 被 quantize(0.01) 提前四舍五入成 0.02)
total, cnt = v total, cnt = v
result[sn][f] = (total / Decimal(str(cnt))).quantize( result[sn][f] = (total / Decimal(str(cnt))).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP) if cnt > 0 else Decimal('0') Decimal('0.000001'), rounding=ROUND_HALF_UP) if cnt > 0 else Decimal('0')
else: else:
result[sn][f] = v result[sn][f] = v
return result return result
...@@ -1184,6 +1198,13 @@ def parse_commerce_policy_inshop(file_path, biz_type='1.1'): ...@@ -1184,6 +1198,13 @@ def parse_commerce_policy_inshop(file_path, biz_type='1.1'):
default = {f: Decimal('0') for f in numeric_fields} default = {f: Decimal('0') for f in numeric_fields}
# 百分比字段:Excel 里写 1.5% → pandas 读 0.015,需要 ×100 存 1-100 # 百分比字段:Excel 里写 1.5% → pandas 读 0.015,需要 ×100 存 1-100
pct_fields = {'frontline_incentive_ratio'} pct_fields = {'frontline_incentive_ratio'}
# === 诊断:打印 raw 原始值(×100 之前)===
if raw:
sample_sn = list(raw.keys())[:2]
logger.info(f"[商务政策-店中店] 诊断 raw 值: ")
for sn in sample_sn:
fr_val = raw.get(sn, {}).get('frontline_incentive_ratio', 'MISSING')
logger.info(f" {sn}: frontline_incentive_ratio raw={fr_val} type={type(fr_val).__name__}")
for sn, v in raw.items(): for sn, v in raw.items():
merged = dict(default) merged = dict(default)
merged.update({k: v[k] for k in numeric_fields if k in v}) merged.update({k: v[k] for k in numeric_fields if k in v})
...@@ -1249,7 +1270,7 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'): ...@@ -1249,7 +1270,7 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'):
df.columns = [str(c).strip() if c else '' for c in df.columns] df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, { col_map = match_columns(df.columns, {
'store_name': ['入驻门店', '门店名称', '门店名'], 'store_name': ['入驻门店', '门店名称', '门店名'],
'verify': ['检核业务线'], 'verify': [31], # AF 列,直接按索引取
'biz_type': ['人员业务归属', '业务类型', '业务线'], 'biz_type': ['人员业务归属', '业务类型', '业务线'],
'position': ['岗位', '职位'], 'position': ['岗位', '职位'],
}) })
...@@ -1266,16 +1287,18 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'): ...@@ -1266,16 +1287,18 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'):
result = {} result = {}
skip_verify = skip_biz = skip_pos = 0 skip_verify = skip_biz = skip_pos = 0
for _, row in df.iterrows(): for _, row in df.iterrows():
# 检核业务线 = True # 检核列:truthy = True / 1 / '1' / '是' / 'TRUE' / 'TUER'(兼容各种 Excel 值)
if verify_col: # verify_col 可能是 int(按索引取)或 str(按列名取)
v = row.get(verify_col) if verify_col is not None:
if v is not True: v = row.iloc[verify_col] if isinstance(verify_col, int) else row.get(verify_col)
v_norm = str(v).strip().upper() if v is not None else ''
if v is None or v_norm in ('', '0', '否', 'FALSE', 'NAN', 'NONE'):
skip_verify += 1 skip_verify += 1
continue continue
# 人员业务归属 = biz_type # 人员业务归属 = biz_type
if biz_col: if biz_col is not None:
bt_raw = row.get(biz_col) bt_raw = row.iloc[biz_col] if isinstance(biz_col, int) else row.get(biz_col)
bt = str(bt_raw).strip() if bt_raw is not None else '' bt = str(bt_raw).strip() if bt_raw is not None else ''
# pandas 可能把 '1.1' 读成 float 1.1 # pandas 可能把 '1.1' 读成 float 1.1
try: try:
...@@ -1288,13 +1311,15 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'): ...@@ -1288,13 +1311,15 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'):
continue continue
# 岗位筛选 # 岗位筛选
if pos_col: if pos_col is not None:
pos = str(row.get(pos_col, '')).strip() pos_raw = row.iloc[pos_col] if isinstance(pos_col, int) else row.get(pos_col)
pos = str(pos_raw).strip() if pos_raw is not None else ''
if pos and not any(t in pos for t in target_positions): if pos and not any(t in pos for t in target_positions):
skip_pos += 1 skip_pos += 1
continue continue
sn = str(row.get(col_map['store_name'], '')).strip() sn_raw = row.iloc[col_map['store_name']] if isinstance(col_map['store_name'], int) else row.get(col_map['store_name'], '')
sn = str(sn_raw).strip() if sn_raw is not None else ''
if not sn or sn in ('nan', 'None', ''): if not sn or sn in ('nan', 'None', ''):
continue continue
result[sn] = result.get(sn, 0) + 1 result[sn] = result.get(sn, 0) + 1
...@@ -1486,7 +1511,8 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1486,7 +1511,8 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
一条 SQL 批量查出商品成本 / 市场费 / 服务费 / 流量费 / 产值,避免 N+1 和多表 LEFT JOIN 笛卡尔乘积。 一条 SQL 批量查出商品成本 / 市场费 / 服务费 / 流量费 / 产值,避免 N+1 和多表 LEFT JOIN 笛卡尔乘积。
字段口径(与 Java 财务测算保持一致): 字段口径(与 Java 财务测算保持一致):
- product_cost = upgrade_dj_cost + upgrade_third_party_cost(嘀加与第三方成本合计,子订单表 gso) - product_cost = upgrade_dj_cost + (shop_traffic_money_calculate_type=1 时才加 upgrade_third_party_cost)
即第三方成本仅在按 GMV 口径算流量费时才计入商品成本
- market_fee = 四项费用累计(expense_category IN (706,808,809,901),子查询 GROUP BY order_code 避免重复行) - market_fee = 四项费用累计(expense_category IN (706,808,809,901),子查询 GROUP BY order_code 避免重复行)
- service_fee = franchisee_profit_money(服务商金额,主汇总记录 gopa2) - service_fee = franchisee_profit_money(服务商金额,主汇总记录 gopa2)
- shop_traffic_money = shop_traffic_money(流量费,来自主表 gopa 不是 gopa2) - shop_traffic_money = shop_traffic_money(流量费,来自主表 gopa 不是 gopa2)
...@@ -1526,8 +1552,6 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1526,8 +1552,6 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
end_str = end_date.strftime('%Y-%m-%d 23:59:59') if end_date else '' end_str = end_date.strftime('%Y-%m-%d 23:59:59') if end_date else ''
# —— SQL 构造 —— # —— SQL 构造 ——
# 子查询 fee:四项费用累计,INNER JOIN go+po 下推过滤避免笛卡尔乘积
# 外层:主表 gopa(子订单级) JOIN go+po+gso(子订单) + LEFT JOIN gopa2(主汇总 order_flag='Y') + LEFT JOIN fee
where_parts = [ where_parts = [
"gopa.deleted_flag = 'N'", "gopa.deleted_flag = 'N'",
"gopa.order_flag = 'N'", "gopa.order_flag = 'N'",
...@@ -1557,16 +1581,34 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1557,16 +1581,34 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
if business_type is not None: if business_type is not None:
fee_where.append(f"go.business_type = {business_type}") fee_where.append(f"go.business_type = {business_type}")
# 一条 SQL 搞定: 驱动表 gopa(order_flag='N' 子订单级) + LEFT JOIN gopa2(order_flag='Y' 主汇总级)
# product_cost → SUM(gso 子订单字段)
# shop_traffic_money/service_fee/store_output_value/other_cost → MAX(gopa2 主汇总字段)
# market_fee → MAX(fee 子查询)
sql = f""" sql = f"""
SELECT SELECT
go.merchant_name AS merchant_name, t.merchant_name AS merchant_name,
SUM(IFNULL(gso.upgrade_dj_cost, 0) + IFNULL(gso.upgrade_third_party_cost, 0)) SUM(t.product_cost) AS product_cost,
AS product_cost, SUM(t.market_fee) AS market_fee,
SUM(IFNULL(fee.total, 0)) AS market_fee, SUM(t.service_fee) AS service_fee,
SUM(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee, SUM(t.store_output_value) AS store_output_value,
SUM(IFNULL(gopa2.total_price, 0)) AS store_output_value, SUM(t.shop_traffic_money) AS shop_traffic_money,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money, SUM(t.other_cost) AS other_cost
SUM(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- 商品成本: 子订单级 gso 字段, 同订单多 sub_order → 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,
-- shop_traffic_money: 主汇总级字段, 从 gopa2(order_flag='Y') 取, MAX 防 LEFT JOIN 放大
MAX(IFNULL(gopa2.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 FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N' ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
...@@ -1584,19 +1626,21 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1584,19 +1626,21 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
ecc.order_code, ecc.order_code,
SUM(ecc.expense_category_result) AS total SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc 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_goods_order go ON ecc.order_code = go.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code AND po.deleted_flag = 'N'
WHERE {' AND '.join(fee_where)} WHERE {' AND '.join(fee_where)}
GROUP BY ecc.order_code GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code ) fee ON fee.order_code = gopa.order_code
WHERE {' AND '.join(where_parts)} WHERE {' AND '.join(where_parts)}
GROUP BY go.merchant_name GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name
""" """
try: try:
from sqlalchemy import text as sa_text from sqlalchemy import text as sa_text
_sql_preview = sql.strip().replace('\n', ' ')[:500] _sql_preview = sql.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_biz_sql_aggregated] biz_type={biz_type} dates={start_str}~{end_str} scene_type={scene_type} business_type={business_type} store_cnt={len(store_names) if store_names else 'all'} SQL={_sql_preview}...") logger.info(f"[BizSQL-fetch_biz_sql_aggregated] biz_type={biz_type} SQL={_sql_preview}...")
result = conn.execute(sa_text(sql)) result = conn.execute(sa_text(sql))
rows = result.mappings().all() rows = result.mappings().all()
out = {} out = {}
...@@ -1605,47 +1649,14 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1605,47 +1649,14 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
if not mn: if not mn:
continue continue
out[mn] = { out[mn] = {
'product_cost': Decimal(str(r['product_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'product_cost': Decimal(str(r['product_cost'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'market_fee': Decimal(str(r['market_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'market_fee': Decimal(str(r['market_fee'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'service_fee': Decimal(str(r['service_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'service_fee': Decimal(str(r['service_fee'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'store_output_value': Decimal(str(r['store_output_value'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'store_output_value': Decimal(str(r['store_output_value'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'shop_traffic_money': Decimal(str(r['shop_traffic_money'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'shop_traffic_money': Decimal(str(r['shop_traffic_money'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'other_cost': Decimal(str(r['other_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'other_cost': Decimal(str(r['other_cost'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
} }
logger.info(f"[BizSQL-延保权益财务] biz_type={biz_type} 聚合完成, {len(out)} 个门店") logger.info(f"[BizSQL-延保权益财务] biz_type={biz_type} 完成, {len(out)} 个门店")
# === 诊断:带 store_names 过滤返回 0 时,自动再跑一次不带过滤的全量 ===
if store_names and len(out) == 0:
logger.warning(f"[BizSQL-延保权益财务] store_cnt={len(store_names)} 过滤后返回 0,诊断全量...")
# 构造不带 store_names LIKE 条件的全量 SQL
diag_where_parts = [w for w in where_parts if 'LIKE' not in w]
diag_sql = sql.split("WHERE")[0] + "WHERE " + " AND ".join(diag_where_parts) + " GROUP BY go.merchant_name"
try:
_diag_preview = diag_sql.strip().replace('\n', ' ')[:400]
logger.info(f"[BizSQL-诊断] 全量 SQL={_diag_preview}...")
diag_rows = conn.execute(sa_text(diag_sql)).mappings().all()
logger.info(f"[BizSQL-诊断] 全量返回 {len(diag_rows)} 个门店")
if diag_rows:
diag_names = [r['merchant_name'] for r in diag_rows[:15]]
logger.info(f"[BizSQL-诊断] merchant_name 样本: {diag_names}")
# 比较 store_names 和 merchant_name 的交集
store_set = set(store_names)
name_set = {r['merchant_name'] for r in diag_rows}
exact_match = store_set & name_set
logger.info(f"[BizSQL-诊断] Excel store_names={len(store_set)}, DB merchant_name={len(name_set)}, 精确匹配={len(exact_match)}")
if exact_match:
logger.info(f"[BizSQL-诊断] 精确匹配样本: {list(exact_match)[:5]}")
# 模糊包含检查
fuzzy_hits = []
for sn in store_set:
for mn in name_set:
if sn and mn and (sn in mn or mn in sn):
fuzzy_hits.append((sn, mn))
break
logger.info(f"[BizSQL-诊断] 模糊包含匹配={len(fuzzy_hits)}")
if fuzzy_hits:
logger.info(f"[BizSQL-诊断] 模糊匹配样本: {fuzzy_hits[:5]}")
except Exception as de:
logger.error(f"[BizSQL-诊断] 全量查询也失败: {de}")
return out return out
except Exception as e: except Exception as e:
logger.error(f"[BizSQL-延保权益财务] 查询异常: {e}") logger.error(f"[BizSQL-延保权益财务] 查询异常: {e}")
...@@ -1659,6 +1670,17 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1659,6 +1670,17 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
pass pass
def exact_match_store(store_name, store_map):
"""
系统数据源精确匹配 — 门店名必须完全一致才返回。
用于 biz_sql_map / system_delivery_map / indicator_data 等系统数据源,
避免模糊匹配导致"广西河池中达"误匹配到其他含"中达"的门店。
"""
if not store_name or not store_map:
return None
return store_map.get(store_name)
def fuzzy_match_store(store_name, biz_sql_map, return_key=False): def fuzzy_match_store(store_name, biz_sql_map, return_key=False):
""" """
Excel 门店名 ↔ 业务表 merchant_name 模糊匹配。 Excel 门店名 ↔ 业务表 merchant_name 模糊匹配。
...@@ -1943,9 +1965,12 @@ def fetch_light_reform_goods_stats(start_date, end_date): ...@@ -1943,9 +1965,12 @@ def fetch_light_reform_goods_stats(start_date, end_date):
LEFT JOIN dj_car_life_goods_order t2 LEFT JOIN dj_car_life_goods_order t2
ON t2.order_code = t1.order_code ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12) AND t2.status IN (4,6,12)
AND t2.deleted_flag = 'N'
LEFT JOIN dj_car_life_pay_order t3 LEFT JOIN dj_car_life_pay_order t3
ON t3.order_code = t1.order_code ON t3.order_code = t1.order_code
AND t3.deleted_flag = 'N'
WHERE t1.status = 1 WHERE t1.status = 1
AND t1.deleted_flag = 'N'
AND t2.scene_type = 1 AND t2.scene_type = 1
AND t3.success_date BETWEEN '{start_str}' AND '{end_str}' AND t3.success_date BETWEEN '{start_str}' AND '{end_str}'
GROUP BY t2.merchant_name GROUP BY t2.merchant_name
...@@ -2011,14 +2036,17 @@ def fetch_est_delivery_count(base_scene_code='100101'): ...@@ -2011,14 +2036,17 @@ def fetch_est_delivery_count(base_scene_code='100101'):
return {} return {}
sql = f""" sql = f"""
SELECT traffic_party_name, SELECT t3.merchant_name AS traffic_party_name,
IF(estimated_delivery_count_per_month IS NULL, IF(t1.estimated_delivery_count_per_month IS NULL,
delivery_count, t1.delivery_count,
estimated_delivery_count_per_month) AS final_delivery_count t1.estimated_delivery_count_per_month) AS final_delivery_count
FROM dj_car_life_merchant_store_info FROM dj_car_life_merchant_store_info t1
WHERE base_scene_code = '{base_scene_code}' LEFT JOIN dj_car_life_service_merchant t3
AND deleted_flag = 'N' ON t1.traffic_party_id = t3.merchant_id
ORDER BY created_date DESC AND t3.deleted_flag = 'N'
WHERE t1.base_scene_code = '{base_scene_code}'
AND t1.deleted_flag = 'N'
ORDER BY t1.created_date DESC
""" """
out = {} out = {}
...@@ -2047,6 +2075,68 @@ def fetch_est_delivery_count(base_scene_code='100101'): ...@@ -2047,6 +2075,68 @@ def fetch_est_delivery_count(base_scene_code='100101'):
pass pass
def fetch_park_name_map(base_scene_code='100101'):
"""
园区店名称批量查询(静态配置表,无日期参数)。
数据源:dj_car_life_merchant_store_info(门店流量方配置表)
取值逻辑:traffic_party_name(流量方门店名)→ parking_store_name(园区店名称)
过滤条件:base_scene_code = '100101'(轻改), deleted_flag = 'N'
:param base_scene_code: 业务场景编码,默认 '100101' 轻改
:return: dict[traffic_party_name] = parking_store_name (str)
"""
from config import Config
if not Config.BIZ_SQL_ENABLED:
logger.warning("[BizSQL-园区名称] BIZ_SQL_ENABLED=false,跳过查询")
return {}
conn = _get_biz_sql_conn()
if conn is None:
return {}
sql = f"""
SELECT t3.merchant_name AS traffic_party_name,
t2.merchant_name AS parking_store_name
FROM dj_car_life_merchant_store_info t1
LEFT JOIN dj_car_life_service_merchant t2
ON t1.parking_store_id = t2.merchant_id
AND t2.deleted_flag = 'N'
LEFT JOIN dj_car_life_service_merchant t3
ON t1.traffic_party_id = t3.merchant_id
AND t3.deleted_flag = 'N'
WHERE t1.base_scene_code = '{base_scene_code}'
AND t1.deleted_flag = 'N'
AND t2.merchant_name IS NOT NULL
AND t3.merchant_name IS NOT NULL
ORDER BY t1.created_date DESC
"""
out = {}
try:
from sqlalchemy import text as sa_text
_sql_preview = sql.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_park_name_map] base_scene_code={base_scene_code} SQL={_sql_preview}...")
for r in conn.execute(sa_text(sql)).mappings().all():
tp = r['traffic_party_name']
ps = r['parking_store_name']
# ORDER BY created_date DESC → 同 traffic_party 多条时只取最新一条
if tp and tp not in out:
out[tp] = ps
logger.info(f"[BizSQL-园区名称] 完成, {len(out)} 个门店")
return out
except Exception as e:
logger.error(f"[BizSQL-园区名称] 查询异常: {e}")
import traceback
logger.error(traceback.format_exc())
return {}
finally:
try:
conn.close()
except Exception:
pass
def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1): def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
""" """
轻改 店中店 + 园区店 共用:财务成本分项批量查询(scene_type=1)。 轻改 店中店 + 园区店 共用:财务成本分项批量查询(scene_type=1)。
...@@ -2103,57 +2193,70 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1): ...@@ -2103,57 +2193,70 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
sql = f""" sql = f"""
SELECT SELECT
go.merchant_name AS merchant_name, t.merchant_name AS merchant_name,
-- 内层已按 merchant_name + order_code 聚合好, 外层全部 SUM 跨订单
SUM(t.product_cost_finance) AS product_cost_finance,
SUM(t.internal_settle_cost) AS internal_settle_cost,
SUM(t.oe_product_cost) AS oe_product_cost,
SUM(t.nonoe_product_cost) AS nonoe_product_cost,
SUM(t.window_film_cost) AS window_film_cost,
SUM(t.car_wrap_cost) AS car_wrap_cost,
SUM(t.premium_cost) AS premium_cost,
SUM(t.store_share) AS store_share,
SUM(t.construction_income) AS construction_income,
SUM(t.market_fee) AS market_fee,
SUM(t.mgmt_market_fee) AS mgmt_market_fee,
SUM(t.sunshine_incentive_fee) AS sunshine_incentive_fee
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- 产品成本(财务列表)= 非内部结算 dj_order_type != 6 -- gpa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(CASE WHEN gso.dj_order_type != 6 SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS product_cost_finance, ELSE 0 END) AS product_cost_finance,
-- 内部结算成本(财务列表)= 内部结算 dj_order_type = 6
SUM(CASE WHEN gso.dj_order_type = 6 SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS internal_settle_cost, ELSE 0 END) AS internal_settle_cost,
-- 原厂产品成本(非内部结算 + 名称含 AITO/HIMA)
SUM(CASE WHEN gso.dj_order_type != 6 SUM(CASE WHEN gso.dj_order_type != 6
AND (gso.upgrade_goods_name LIKE '%AITO%' AND (gso.upgrade_goods_name LIKE '%AITO%'
OR gso.upgrade_goods_name LIKE '%HIMA%') OR gso.upgrade_goods_name LIKE '%HIMA%')
THEN gso.upgrade_shop_price - gso.base_shop_price THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS oe_product_cost, ELSE 0 END) AS oe_product_cost,
-- 副厂产品成本(非内部结算 + 名称不含 AITO/HIMA)
SUM(CASE WHEN gso.dj_order_type != 6 SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%' AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%' AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN gso.upgrade_shop_price - gso.base_shop_price THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS nonoe_product_cost, ELSE 0 END) AS nonoe_product_cost,
-- 窗膜成本
SUM(CASE WHEN gso.upgrade_goods_type_name IN {FILM_TYPES} SUM(CASE WHEN gso.upgrade_goods_type_name IN {FILM_TYPES}
THEN gso.upgrade_shop_price - gso.base_shop_price THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS window_film_cost, ELSE 0 END) AS window_film_cost,
-- 车衣成本
SUM(CASE WHEN gso.upgrade_goods_type_name IN {CAR_WRAP_TYPES} SUM(CASE WHEN gso.upgrade_goods_type_name IN {CAR_WRAP_TYPES}
THEN gso.upgrade_shop_price - gso.base_shop_price THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS car_wrap_cost, ELSE 0 END) AS car_wrap_cost,
-- 精品成本(排除所有已归类品类)
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN {PREMIUM_EXCLUDE} SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN {PREMIUM_EXCLUDE}
THEN gso.upgrade_shop_price - gso.base_shop_price THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS premium_cost, ELSE 0 END) AS premium_cost,
-- 门店分成/流量费(财务列表)= 非内部结算 shop_traffic_money -- store_share: shop_traffic_money 来自主汇总级 gopa2(order_flag='Y'), MAX 防 LEFT JOIN 放大
SUM(CASE WHEN gso.dj_order_type != 6 MAX(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0) THEN IFNULL(gopa2.shop_traffic_money, 0)
ELSE 0 END) AS store_share, ELSE 0 END) AS store_share,
-- 施工收入 = custom_common_cost(来自主汇总记录 gopa2) -- construction_income / market_fee: MAX 取单次值
SUM(IFNULL(gopa2.custom_common_cost, 0)) AS construction_income, MAX(IFNULL(gopa2.custom_common_cost, 0)) AS construction_income,
MAX(IFNULL(fee.total, 0)) AS market_fee,
-- 市场费 = 四项费用累计(子查询 fee.total) MAX(IFNULL(fee.mgmt_fee, 0)) AS mgmt_market_fee,
SUM(IFNULL(fee.total, 0)) AS market_fee MAX(IFNULL(fee.sunshine_fee, 0)) AS sunshine_incentive_fee
FROM dj_car_life_goods_order_profit_allocation gopa FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go INNER JOIN dj_car_life_goods_order go
...@@ -2170,10 +2273,12 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1): ...@@ -2170,10 +2273,12 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
LEFT JOIN ( LEFT JOIN (
SELECT SELECT
ecc.order_code, ecc.order_code,
SUM(IF(ecc.expense_category_id IN (706, 808), ecc.expense_category_result, 0)) AS mgmt_fee,
SUM(IF(ecc.expense_category_id IN (809, 901), ecc.expense_category_result, 0)) AS sunshine_fee,
SUM(ecc.expense_category_result) AS total SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc 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_goods_order go ON ecc.order_code = go.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code AND po.deleted_flag = 'N'
WHERE {' AND '.join(fee_where)} WHERE {' AND '.join(fee_where)}
GROUP BY ecc.order_code GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code ) fee ON fee.order_code = gopa.order_code
...@@ -2182,7 +2287,9 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1): ...@@ -2182,7 +2287,9 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
AND go.scene_type = {scene_type} AND go.scene_type = {scene_type}
AND po.success_date >= '{start_str}' AND po.success_date >= '{start_str}'
AND po.success_date <= '{end_str}' AND po.success_date <= '{end_str}'
GROUP BY go.merchant_name GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name
""" """
try: try:
...@@ -2208,6 +2315,8 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1): ...@@ -2208,6 +2315,8 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
'store_share': Decimal(str(r['store_share'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'store_share': Decimal(str(r['store_share'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'construction_income': Decimal(str(r['construction_income'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'construction_income': Decimal(str(r['construction_income'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'market_fee': Decimal(str(r['market_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'market_fee': Decimal(str(r['market_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'mgmt_market_fee': Decimal(str(r.get('mgmt_market_fee', Decimal('0')))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'sunshine_incentive_fee': Decimal(str(r.get('sunshine_incentive_fee', Decimal('0')))).quantize(Decimal('0.01'), ROUND_HALF_UP),
} }
logger.info(f"[BizSQL-轻改财务] 完成, {len(out)} 个门店") logger.info(f"[BizSQL-轻改财务] 完成, {len(out)} 个门店")
return out return out
......
# -*- coding: utf-8 -*-
"""临时脚本:重跑北汽专项任务 900002(2026-08)并核对『截止目前产值(status=4) + 延保/权益订单数』落库与结果表。
说明:直接复用 app 上下文(config 会在导入时自动加载 .env,无需手动传 DB 密码),
调用 BaicSpecialProcessor().process(task) 与线上调度器等价。
"""
import os
import sys
from collections import defaultdict
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
from app import app, db
from baic_special_processor import BaicSpecialProcessor, BAIC_BIZ_EXT_WARRANTY, BAIC_BIZ_RIGHTS
from models import (
DataProcessTask, BaicSpecialMonthData, BaicSpecialMonthlyBusiness,
)
TASK_ID = 900002
def main():
with app.app_context():
task = DataProcessTask.query.filter_by(id=TASK_ID).first()
if not task:
print(f"[ERROR] 任务 {TASK_ID} 不存在")
return
# ---- 重跑前快照(用于对比 status=4 影响)----
before = BaicSpecialMonthData.query.filter_by(task_id=TASK_ID, is_deleted=0).all()
before_map = {d.store_name: (d.output_current_wan, d.achievement_rate) for d in before}
before_biz = BaicSpecialMonthlyBusiness.query.filter(
BaicSpecialMonthlyBusiness.store_id.in_([d.store_id for d in before])
).count() if before else 0
print(f"== 重跑前 ==")
print(f"任务状态: {task.status} | 明细活跃行: {len(before)} | 业务(延保/权益)行: {before_biz}")
# ---- 重跑 ----
print(f"\n== 开始重跑任务 {TASK_ID} ==")
BaicSpecialProcessor().process(task)
print(f"重跑完成 -> 任务状态: {task.status} | result_file_url 已刷新")
# ---- 重跑后核对 ----
detail = BaicSpecialMonthData.query.filter_by(task_id=TASK_ID, is_deleted=0).all()
store_ids = [d.store_id for d in detail]
biz = BaicSpecialMonthlyBusiness.query.filter(
BaicSpecialMonthlyBusiness.store_id.in_(store_ids)).all() if store_ids else []
biz_map = defaultdict(dict)
for b in biz:
biz_map[b.store_id][b.business_type] = b.order_cnt
print(f"\n== 重跑后核对 ==")
print(f"明细活跃行: {len(detail)} | 业务(延保/权益)行: {len(biz)}")
print(f"{'门店':<28}{'延保订单数':>10}{'权益订单数':>10}{'截止产值(万)':>14}{'达成率':>10}{'产值变化':>12}")
print("-" * 96)
diff_cnt = 0
for d in detail:
ext = biz_map.get(d.store_id, {}).get(BAIC_BIZ_EXT_WARRANTY)
rig = biz_map.get(d.store_id, {}).get(BAIC_BIZ_RIGHTS)
old_val, _ = before_map.get(d.store_name, (None, None))
if old_val is not None and d.output_current_wan is not None and old_val != d.output_current_wan:
diff_cnt += 1
chg = f"{d.output_current_wan - old_val:+.2f}"
else:
chg = "-"
name = (d.store_name or "")[:26]
print(f"{name:<28}{str(ext if ext is not None else '-'):>10}"
f"{str(rig if rig is not None else '-'):>10}"
f"{str(d.output_current_wan if d.output_current_wan is not None else '-'):>14}"
f"{str(d.achievement_rate if d.achievement_rate is not None else '-'):>10}"
f"{chg:>12}")
print("-" * 96)
print(f"延保订单数有值的门店: {sum(1 for d in detail if biz_map.get(d.store_id, {}).get(BAIC_BIZ_EXT_WARRANTY) is not None)}")
print(f"权益订单数有值的门店: {sum(1 for d in detail if biz_map.get(d.store_id, {}).get(BAIC_BIZ_RIGHTS) is not None)}")
print(f"截止目前产值因 status=4 发生变化的门店: {diff_cnt}")
# ---- 结果 Excel 本地副本核对(Q=17 订单数列)----
local_xlsx = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'outputs', f'baic_special_2026-08_task900002.xlsx')
if os.path.exists(local_xlsx):
import openpyxl
wb = openpyxl.load_workbook(local_xlsx, data_only=True)
ws = wb[wb.sheetnames[0]]
print(f"\n== 结果表本地副本: {local_xlsx} (sheet={ws.title}) ==")
# 简易校验:扫描业务=I/权益 行,Q(17) 应与 DB 一致
mismatch = 0
checked = 0
for r in range(1, ws.max_row + 1):
bizname = ws.cell(r, 9).value # I 列业务
if bizname in ('延保', '权益'):
q = ws.cell(r, 17).value
checked += 1
# 仅打印前若干行示例
if checked <= 8:
print(f" r{r} 业务={bizname} Q(订单数)={q}")
print(f" (已扫描 {checked} 行业务明细,示例见上)")
else:
print(f"\n[WARN] 未找到本地结果表: {local_xlsx}")
sys.stdout.flush()
os._exit(0)
if __name__ == '__main__':
main()
...@@ -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):
...@@ -364,6 +424,39 @@ class OutputValueScheduler(NewReportScheduler): ...@@ -364,6 +424,39 @@ class OutputValueScheduler(NewReportScheduler):
self._lock.release() 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): class StoreEffectSummaryScheduler(NewReportScheduler):
"""门店店效人效汇总表独立调度器(扫描 store_effect_earnings 类型任务,整体合计一行,第5个sheet)""" """门店店效人效汇总表独立调度器(扫描 store_effect_earnings 类型任务,整体合计一行,第5个sheet)"""
OUTPUT_CATEGORY = 'store_effect_summary' OUTPUT_CATEGORY = 'store_effect_summary'
...@@ -396,3 +489,208 @@ class StoreEffectSummaryScheduler(NewReportScheduler): ...@@ -396,3 +489,208 @@ class StoreEffectSummaryScheduler(NewReportScheduler):
finally: finally:
self._is_processing = False self._is_processing = False
self._lock.release() 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()
class BaicSpecialScheduler(NewReportScheduler):
"""北汽专项独立调度器(扫描 baic_special 类型任务,交给 BaicSpecialProcessor 处理)"""
OUTPUT_CATEGORY = 'baic_special'
JOB_NAME = 'baic_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}] 开始扫描 baic_special 待处理任务")
with self.app.app_context():
from baic_special_processor import BaicSpecialProcessor
processor = BaicSpecialProcessor(app=self.app)
result = processor.scan_baic_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 GlsxDailyScheduler(NewReportScheduler):
"""广联日快照调度器:每日定时(07:00)从通用品牌报表拉取昨天数据,落库基础表。
与具体报表类型无关(不扫描 DataProcessTask),仅每日调用 glsx_daily_processor.scan_glsx_daily()
把每个门店的 延保小计/权益小计 全量字段按 stat_date 幂等落库到 glsx_daily_deal_subtotal。
"""
OUTPUT_CATEGORY = 'glsx_daily'
JOB_NAME = 'glsx_daily_snapshot'
# 每日 07:00 触发(2026-09-28 由 02:00 调整)
# 拉取的是前一天数据;报表为月文件,按昨天所在月查询
CRON_HOUR = 7
CRON_MINUTE = 0
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
try:
from apscheduler.schedulers.background import BackgroundScheduler
from apscheduler.triggers.cron import CronTrigger
self._scheduler = BackgroundScheduler(daemon=True)
self._scheduler.add_job(
self._execute_scan,
trigger=CronTrigger(hour=self.CRON_HOUR, minute=self.CRON_MINUTE),
id=self.JOB_NAME, name=self.JOB_NAME, replace_existing=True,
)
self._scheduler.start()
self._running = True
logger.info(f"[{self.JOB_NAME}] APScheduler(Cron) 已启动:"
f"每日 {self.CRON_HOUR:02d}:{self.CRON_MINUTE:02d} 拉取昨天数据")
except ImportError:
logger.warning(f"[{self.JOB_NAME}] APScheduler 未安装,使用 threading 后备方案(每日检查)")
self._running = True
self._thread_timer_daily()
except Exception as e:
logger.error(f"[{self.JOB_NAME}] 启动失败: {str(e)}")
raise
def _thread_timer_daily(self):
"""后备方案:每日 07:00 执行一次快照。"""
if not self._running:
return
now = datetime.now()
if now.hour == self.CRON_HOUR and now.minute == self.CRON_MINUTE:
self._execute_scan()
timer = threading.Timer(60, self._thread_timer_daily)
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}] 开始执行广联日快照")
with self.app.app_context():
from glsx_daily_processor import scan_glsx_daily
result = scan_glsx_daily()
self._last_run_result = result
logger.info(f"[{self.JOB_NAME}] 日快照完成:{result}")
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()
...@@ -245,6 +245,7 @@ ...@@ -245,6 +245,7 @@
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); togglePeriodRow(cfg);
} }
...@@ -381,10 +382,18 @@ ...@@ -381,10 +382,18 @@
modalWeekNum = weekNum; modalWeekNum = weekNum;
} }
// 周期粒度行:始终显示(所有类型都支持按月/按周切换) // 周期粒度行:仅 support_week=true 的类型(通用+权益)才显示
function togglePeriodTypeRow() { // 其他类型(整月、月份+自定义日期)统一隐藏,用户不可切换按月/按周
function togglePeriodTypeRow(cfg) {
var row = document.getElementById('mPeriodTypeRow'); var row = document.getElementById('mPeriodTypeRow');
row.style.display = ''; 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号 // 周期提示:结束日期 ≤ 月份最后一天;开始默认1号
function updatePeriodHint() { function updatePeriodHint() {
...@@ -426,8 +435,13 @@ ...@@ -426,8 +435,13 @@
mMonth.disabled = locked; mMonth.disabled = locked;
// 周期框 disabled 由 togglePeriodRow 统一控制(按周时 disabled,按月时 need_period=True 可编辑) // 周期框 disabled 由 togglePeriodRow 统一控制(按周时 disabled,按月时 need_period=True 可编辑)
var cfg = typeConfigs.find(function (t) { return t.code === (task ? task.data_table_type : ''); }); 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(); // 显示粒度切换行 togglePeriodTypeRow(cfg); // 按 support_week 控制粒度切换行显示
togglePeriodRow(cfg); // 根据粒度 + need_period 控制周期行显示/disabled togglePeriodRow(cfg); // 根据粒度 + need_period 控制周期行显示/disabled
updatePeriodHint(); updatePeriodHint();
...@@ -656,6 +670,9 @@ ...@@ -656,6 +670,9 @@
// ---------- 弹窗:周期粒度切换 ---------- // ---------- 弹窗:周期粒度切换 ----------
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (btn) { document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (btn) {
btn.addEventListener('click', function () { 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; modalPeriodType = btn.dataset.type;
// 更新按钮组 active 状态 // 更新按钮组 active 状态
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (b) { document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (b) {
...@@ -664,7 +681,6 @@ ...@@ -664,7 +681,6 @@
}); });
// 切换粒度时重置 weekNum // 切换粒度时重置 weekNum
modalWeekNum = null; modalWeekNum = null;
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
if (modalPeriodType === 'week') { if (modalPeriodType === 'week') {
// 按周:渲染周下拉 + 自动计算日期 // 按周:渲染周下拉 + 自动计算日期
document.getElementById('mWeekSelect').style.display = ''; document.getElementById('mWeekSelect').style.display = '';
......
...@@ -39,13 +39,14 @@ from report_utils import ( ...@@ -39,13 +39,14 @@ from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_WARRANTY, BIZ_TYPE_EQUITY, INDICATOR_BIZ_MAP, STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_WARRANTY, BIZ_TYPE_EQUITY, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir, mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task, update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
get_subtask_status,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED, SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files, download_all_files,
parse_saas_base, parse_saas_base_sheet2, parse_saas_base_sheet2_exclude, parse_saas_base, parse_saas_base_sheet2, parse_saas_base_sheet2_exclude,
parse_region_map, parse_delivery_table, parse_region_map, parse_delivery_table,
parse_budget_achieve_excel, extract_budget_ratio, parse_labor_cost, parse_budget_achieve_excel, extract_budget_ratio, parse_labor_cost,
fetch_biz_sql_aggregated, fetch_park_daily_report, fetch_biz_sql_aggregated, fetch_park_daily_report,
fetch_indicator_data, fuzzy_match_store, safe_div_pct_decimal, prorate_by_period, fetch_indicator_data, fuzzy_match_store, exact_match_store, safe_div_pct_decimal, prorate_by_period,
) )
from models import ReportStoreEffectSummary, DataProcessTask, db from models import ReportStoreEffectSummary, DataProcessTask, db
...@@ -53,6 +54,10 @@ logger = logging.getLogger('StoreEffectSummaryProcessor') ...@@ -53,6 +54,10 @@ logger = logging.getLogger('StoreEffectSummaryProcessor')
SUMMARY_CATEGORY = 'store_effect_summary' SUMMARY_CATEGORY = 'store_effect_summary'
# 总看板(第5个 sheet)必须在以下前 4 张 sheet 全部 COMPLETED 后才能执行,
# 否则读到的源数据不全(前 4 张表尚未落库或仍是旧快照)。
PRECEDING_CATEGORIES = ['warranty', 'equity', 'inshop', 'park']
# 各业务类型 → (解析函数, 文件/sheet 参数, 指标 biz 键, 指标编码) # 各业务类型 → (解析函数, 文件/sheet 参数, 指标 biz 键, 指标编码)
BIZ_PLAN = [ BIZ_PLAN = [
('warranty', BIZ_TYPE_WARRANTY, INDICATOR_BIZ_MAP.get('warranty'), ('warranty', BIZ_TYPE_WARRANTY, INDICATOR_BIZ_MAP.get('warranty'),
...@@ -104,8 +109,39 @@ class StoreEffectSummaryProcessor: ...@@ -104,8 +109,39 @@ class StoreEffectSummaryProcessor:
logger.info(f"[店效人效汇总] 完成, 成功 {success_count}, 失败 {fail_count}") logger.info(f"[店效人效汇总] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': 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): def process(self, task):
task_id = task.id 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) update_subtask(task_id, SUMMARY_CATEGORY, SUBTASK_PROCESSING)
db.session.commit() db.session.commit()
...@@ -239,7 +275,8 @@ class StoreEffectSummaryProcessor: ...@@ -239,7 +275,8 @@ class StoreEffectSummaryProcessor:
if _m_start is None and period_start: if _m_start is None and period_start:
_m_start = period_start _m_start = period_start
_m_end = (period_end + timedelta(days=1)) if period_end else None _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) board_m = compute_metrics(tmp_dir, period_start, period_end, _m_start, _m_end,
task_id=task_id)
logger.info(f"[店效人效汇总] 双列看板指标计算完成,共 {len(board_m)} 项 " logger.info(f"[店效人效汇总] 双列看板指标计算完成,共 {len(board_m)} 项 "
f"(流失门店统计月={_m_start}~{_m_end})") f"(流失门店统计月={_m_start}~{_m_end})")
except Exception as e: except Exception as e:
...@@ -301,12 +338,12 @@ class StoreEffectSummaryProcessor: ...@@ -301,12 +338,12 @@ class StoreEffectSummaryProcessor:
if biz_tag in ('warranty', 'equity'): if biz_tag in ('warranty', 'equity'):
if biz_tag == 'warranty': if biz_tag == 'warranty':
ind = ind_warranty.get(store_name) or fuzzy_match_store(store_name, ind_warranty) or {} ind = ind_warranty.get(store_name) or exact_match_store(store_name, ind_warranty) or {}
biz = fuzzy_match_store(store_name, biz_sql_warranty) or {} biz = exact_match_store(store_name, biz_sql_warranty) or {}
budget_ratio_map = budget_warranty budget_ratio_map = budget_warranty
else: # equity else: # equity
ind = ind_equity.get(store_name) or fuzzy_match_store(store_name, ind_equity) or {} ind = ind_equity.get(store_name) or exact_match_store(store_name, ind_equity) or {}
biz = fuzzy_match_store(store_name, biz_sql_equity) or {} biz = exact_match_store(store_name, biz_sql_equity) or {}
budget_ratio_map = budget_equity budget_ratio_map = budget_equity
output_value = Decimal(str(ind.get('A036', 0))) output_value = Decimal(str(ind.get('A036', 0)))
...@@ -326,9 +363,9 @@ class StoreEffectSummaryProcessor: ...@@ -326,9 +363,9 @@ class StoreEffectSummaryProcessor:
labor_cost = Decimal('0') labor_cost = Decimal('0')
headcount = 0 headcount = 0
else: # 轻改 inshop / park else: # 轻改 inshop / park
ind = ind_light.get(store_name) or fuzzy_match_store(store_name, ind_light) or {} ind = ind_light.get(store_name) or exact_match_store(store_name, ind_light) or {}
biz1 = fuzzy_match_store(store_name, biz_sql_light) or {} biz1 = exact_match_store(store_name, biz_sql_light) or {}
park_dr = fuzzy_match_store(store_name, park_daily) or {} park_dr = exact_match_store(store_name, park_daily) or {}
output_value = Decimal(str(biz1.get('store_output_value', 0))) output_value = Decimal(str(biz1.get('store_output_value', 0)))
deal = int(Decimal(str(ind.get('A075', 0)))) deal = int(Decimal(str(ind.get('A075', 0))))
...@@ -428,6 +465,8 @@ class StoreEffectSummaryProcessor: ...@@ -428,6 +465,8 @@ class StoreEffectSummaryProcessor:
def generate_result_excel(self, task, row, board_metrics=None, local_only=False): def generate_result_excel(self, task, row, board_metrics=None, local_only=False):
stat_month = task.month or '' 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_end = getattr(task, 'period_end', None)
period_start = getattr(task, 'period_start', None) period_start = getattr(task, 'period_start', None)
end_date_str = period_end.strftime('%Y-%m-%d') if period_end else '' end_date_str = period_end.strftime('%Y-%m-%d') if period_end else ''
...@@ -447,14 +486,14 @@ class StoreEffectSummaryProcessor: ...@@ -447,14 +486,14 @@ class StoreEffectSummaryProcessor:
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'outputs', 'store_effect_summary') 'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True) os.makedirs(out_dir, exist_ok=True)
final_path = os.path.join(out_dir, f'红黄门店盈利测算_{stat_month}.xlsx') final_path = os.path.join(out_dir, f'{type_name}_{today_str}.xlsx')
import shutil import shutil
shutil.copy2(local_path, final_path) shutil.copy2(local_path, final_path)
logger.info(f"[店效人效汇总] 6 sheet 本地文件: {final_path}") logger.info(f"[店效人效汇总] 6 sheet 本地文件: {final_path}")
return final_path return final_path
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}" object_key = (f"data-process/{today_str}"
f"/red_yellow_report_{stat_month}_{task.id}.xlsx") f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(local_path, object_key) file_url = upload_file(local_path, object_key)
logger.info(f"[店效人效汇总] 6 sheet 已上传 OSS: {file_url}") logger.info(f"[店效人效汇总] 6 sheet 已上传 OSS: {file_url}")
return file_url return file_url
...@@ -529,10 +568,10 @@ class StoreEffectSummaryProcessor: ...@@ -529,10 +568,10 @@ class StoreEffectSummaryProcessor:
tmp_dir = tempfile.mkdtemp(prefix=f'store_effect_result_{task.id}_') tmp_dir = tempfile.mkdtemp(prefix=f'store_effect_result_{task.id}_')
try: try:
excel_path = os.path.join(tmp_dir, f'门店店效人效汇总表_{stat_month}.xlsx') excel_path = os.path.join(tmp_dir, f'{type_name}_{today_str}.xlsx')
wb.save(excel_path) wb.save(excel_path)
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}" object_key = (f"data-process/{today_str}"
f"/store_effect_summary_{stat_month}_{task.id}.xlsx") f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key) file_url = upload_file(excel_path, object_key)
logger.info(f"[店效人效汇总] 回退单行已上传: {file_url}") logger.info(f"[店效人效汇总] 回退单行已上传: {file_url}")
return file_url return file_url
......
# -*- 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!