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 1359 additions and 287 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 @@
- 处理引擎未接入:`process_task` 白名单(SUPPORTED_PROCESS_TYPES)会拦截并提示"引擎尚未接入"(与 future_expansion 一致),不会误跑预算流水线、不崩溃。
- 改动仅 config.py;前端按 DATA_TABLE_TYPES 动态渲染上传区,重启后端后上传页出现"阿维塔专项"选项。
- need_period 已按用户要求改为 False(阿维塔专项不需要所属周期项)。仍待确认:是否需重启后端(PID 13536)让前端生效。
- 澄清(用户纠正):阿维塔专项的「主机厂数据表」为独立数据表,格式不保证与现有「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,不可复用 report_utils.parse_delivery_table(鸿蒙/广联共用结构);后续接引擎时按用户实际提供的附件字段解析、写入阿维塔专属结果表。当前阶段仅配置类型+定义上传表名,解析逻辑未实现。已在 config.py 注释中标注此独立性。
## 阿维塔专项 引擎接入(task 37 实测落库)
- 用户已建两表:`avita_special_month_data`(明细,无 created_at/updated_at)/ `avita_special_month_summary_metrics`(汇总,仅 created_at)。
- 改动三处:`models.py` 加两 ORM 模型(对齐真实列,缺列会 INSERT 报 Unknown column);`avita_special_processor.py` 新建 `AvitaSpecialProcessor`(下载→解析双表头 Excel→按 task_id 先删后插→置 COMPLETED/result_file_url='');`processor.py` 的 `process_task` 在白名单**前**加 `avita_special` 路由分支。
- 源文件实测(task 37,7月样本「7月页签-字段取值说明」):2 行表头 + 8 家门店明细 + 末尾汇总段('阿维塔品牌汇总' + 售后门店数=3/售后场景开通率=0.38/售后订单数=0)。
- 解析坑:①store_name/store_short_name 是字符串列,不能走 `_to_dec` 数值转换(否则门店名全被置空);②明细表多声明的 created_at/updated_at 与实际表不符→已移除;③汇总表仅 created_at。已修正并落库成功。
- 结果:task 37 落库 COMPLETED,明细 8 行 + 汇总 1 行;汇总表 store_count/output_value/delivery_count 等源文件未提供→留空(待最终 Excel 生成或后续填充)。
- 当前无后端进程在跑(Get-Process 无 python),代码改动下次启动自动生效;前端页面"重新生成"需在后端运行新代码时才可用。
## 阿维塔专项 源文件新增门店模式/入驻时间两列(task 37 重跑)
- 用户更新源数据:月份明细新增「门店模式」(col2, 文本如服务商/直营) 与「入驻时间」(col3, Excel datetime) 两列,插入到原门店简称之后、主机厂指标之前 → 所有指标列整体右移 +2。
- `avita_special_processor.py` 改动:①`DETAIL_COL` 列索引整体右移(store_name=0/store_short_name=1/store_mode=2/entry_time=3/主机厂交付=4/延保=5/无忧=6/单车收入=7/总产值=8/广联交付=9/广联触客=10);②`_STR_COLS` 加 store_mode/entry_time,新增 `_to_date_str` 将入驻时间 datetime 格式化为 `YYYY-MM-DD` 写入 `varchar(10)`;③`_save` 由 `rec.get('store_mode'/'entry_time')` 写入(此前硬编码 None)。
- 重跑 task 37(run_avita37.py,app 上下文直接调用 AvitaSpecialProcessor):8 家门店门店模式/入驻时间全部填充成功,状态回 COMPLETED。临时脚本已清理。
- 重启后端:杀掉两个旧后端(24636/31508,监听 5000 的旧代码)后,以 `PYTHONPATH=用户site-packages` 重启(新 PID 30988,日志无报错,已加载新 avita 代码)。页面"重新生成"现在用新引擎,不会再清空这两列。
- 表列类型确认:`store_mode varchar(50)`、`entry_time varchar(10)`(均为文本,入驻时间存日期串)。
- 仍空缺:regional_operation/resident_name/广联延保成交数/广联无忧成交数 源文件未提供→留空。
## 阿维塔专项两表加 is_deleted 软删除(逻辑删除)
- 需求:avita_special_month_data 与 avita_special_month_summary_metrics 加 `is_deleted`(0正常/1已删除),后续不再物理删除,只逻辑删除(与项目偏好一致)。
- 改动三处:①`alter_avita_softdelete.py` 对两表 `ALTER TABLE ... ADD COLUMN is_deleted INT NOT NULL DEFAULT 0`(已跑,两表均加好);②`models.py` 两 ORM 模型加 `is_deleted = db.Column(db.Integer, nullable=False, default=0, comment='是否删除:0正常 / 1已删除(软删除)')`;③`avita_special_processor.py` 的 `_save` 由 `query.filter_by(task_id).delete()` 改为 `query.filter_by(task_id=..., is_deleted=0).update({is_deleted:1})` 逻辑删除旧行 + 新行 `is_deleted=0`(幂等),docstring 同步。
- 验证(重跑 task 37):明细 total=16(active=8 + 软删=8)、汇总 total=2(active=1 + 软删=1);门店模式/入驻时间写入无误,状态 COMPLETED。确认软删除生效、INSERT 未因新增列报错。
- 重启后端(杀 30988,新 PID 28164,日志无报错)加载新代码。临时脚本已清理。
- 注意:后续任何读这两张表的逻辑都需 `filter_by(is_deleted=0)`,否则会把历史软删行当活跃数据。
## 阿维塔专项 源文件新增驻店姓名一列(task 37 重跑)
- 用户更新源数据:月份明细再新增「驻店姓名」(col4, 文本如"创思/服务商"/"王永忠"),插入到入驻时间之后、主机厂指标之前 → 所有指标列整体右移 +1(累计右移 +3)。
- `avita_special_processor.py` 改动:①`DETAIL_COL` 列索引调整(resident_name=4,主机厂交付=5/延保=6/无忧=7/单车收入=8/总产值=9/广联交付=10/广联触客=11);②`_STR_COLS` 加 `resident_name`(字符串列勿走数值转换);③`_save` 由 `rec.get('resident_name')` 写入(此前硬编码 None);docstring 同步。
- 重跑 task 37(run_avita37.py,app 上下文):8 家门店驻店姓名全部填充成功(如 创思/服务商、王永忠、杨淑萍、林彩玲、刘秀锦),门店模式/入驻时间/数值无回退,软删除正确(active=8,历史 16 行 is_deleted=1),状态 COMPLETED。临时脚本已清理。
- 重启后端(杀 28164,新 PID 31244,日志无报错)加载新代码。页面"重新生成"现在用新引擎。
- 仍空缺:广联延保成交数/广联无忧成交数 源文件未提供→留空。
## 阿维塔专项 区域运营字段改由 dj_smartcarlife 查询(task 37 重跑)
- 需求:avita_special_month_data.regional_operation(区域运营)从 dj_smartcarlife 数据源读取,源文件无此列。
- 规则(两跳):①`select merchant_id from dj_car_life_service_merchant where merchant_name=门店名称 and deleted_flag='N'`;②用查到的 merchant_id `select director_name from dj_car_life_shop_merchant_director_config where deleted_flag='N' and merchant_id=:mid and director_type=9`,多条记录去重后 `/` 分隔。
- 改动(`avita_special_processor.py`):加 `from config import Config` + `create_engine(Config.BIZ_SQL_DATABASE_URL)` 引擎缓存 + `fetch_regional_operation(store_name)`(参数化 text 查询,模块级 `_BIZ_ENGINE` 缓存,异常不致命仅告警留空);`_save` 的 `regional_operation` 由 `None` 改为 `fetch_regional_operation(rec['store_name'])`;docstring 同步。
- 踩坑:`config` 模块无 `BIZ_SQL_DATABASE_URL` 属性(报 AttributeError),该连接串挂在 `Config` 类上 → 改用 `from config import Config` 取 `Config.BIZ_SQL_DATABASE_URL` 修复。
- 重跑 task 37(run_avita37.py):8 家门店区域运营全部填充成功(陈晓文/张爱豪/李明瑞/张浩锋/王孝樟/卓炯煜/刘淑君/李明瑞),状态从 FAILED 恢复 COMPLETED,软删除正确(active=8,历史 24 行 is_deleted=1)。临时脚本已清理。
- 重启后端(杀 31244 及幽灵 20340,新 PID 16536,日志 `Running on 5000` 无报错)加载新代码。注意 netstat 显示的 20340 是幽灵条目(PowerShell Get-Process 找不到),真实新进程为 16536。
- 仍空缺:广联延保成交数/广联无忧成交数 源文件未提供→留空。
# 2026-09-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-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 空闲)。
......@@ -5,10 +5,10 @@
# ============================================
# ---------- 数据库(MySQL) ----------
MYSQL_HOST=192.168.3.227
MYSQL_PORT=3306
MYSQL_USER=os_user
MYSQL_PASSWORD=os#123
MYSQL_HOST=192.168.1.228
MYSQL_PORT=3307
MYSQL_USER=wechat_user
MYSQL_PASSWORD=b4WRTkl
MYSQL_DB=data_report
# ---------- 阿里云 OSS ----------
......@@ -33,5 +33,5 @@ INIT_NICKNAME=系统管理员
# ---------- 服务 ----------
FLASK_HOST=0.0.0.0
FLASK_PORT=5001
FLASK_PORT=5000
FLASK_DEBUG=true
......@@ -4,3 +4,8 @@ __pycache__/
*.pyc
uploads/
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 (
LightReformParkScheduler,
OutputValueScheduler,
StoreEffectSummaryScheduler,
AvitaSpecialScheduler,
VoyahScheduler,
LeapmotorScheduler,
CommonEquityScheduler,
BaicSpecialScheduler,
GlsxDailyScheduler,
)
app = Flask(__name__, static_folder='static', static_url_path='')
......@@ -126,6 +132,11 @@ def parse_period(data, tcfg):
if period_type not in ('month', 'week'):
raise ValueError(f'period_type 仅支持 month / week,当前值:{period_type}')
# 校验:need_period=False 或 support_week=False 的类型不允许按周粒度
if period_type == 'week':
if not tcfg.get('need_period') or not tcfg.get('support_week'):
raise ValueError('该类型仅支持按月粒度,不可选择按周')
if period_type == 'week':
# 按周:强校验 week_num,后端计算权威日期区间
try:
......@@ -251,7 +262,8 @@ def meta_task_types():
"""数据表类型配置(含各类型所需表单类型清单、是否需要所属周期)"""
data = [
{'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()
]
return ok(data)
......@@ -652,6 +664,12 @@ light_reform_inshop_scheduler = LightReformInshopScheduler(app=app)
light_reform_park_scheduler = LightReformParkScheduler(app=app)
output_value_scheduler = OutputValueScheduler(app=app)
store_effect_summary_scheduler = StoreEffectSummaryScheduler(app=app)
voyah_scheduler = VoyahScheduler(app=app)
leapmotor_scheduler = LeapmotorScheduler(app=app)
common_equity_scheduler = CommonEquityScheduler(app=app)
avita_special_scheduler = AvitaSpecialScheduler(app=app)
baic_special_scheduler = BaicSpecialScheduler(app=app)
glsx_daily_scheduler = GlsxDailyScheduler(app=app)
ALL_SCHEDULERS = [
('budget_achievement', scheduler),
......@@ -661,6 +679,12 @@ ALL_SCHEDULERS = [
('light_reform_park', light_reform_park_scheduler),
('output_value', output_value_scheduler),
('store_effect_summary', store_effect_summary_scheduler),
('voyah_special', voyah_scheduler),
('leapmotor_special', leapmotor_scheduler),
('common_equity', common_equity_scheduler),
('avita_special', avita_special_scheduler),
('baic_special', baic_special_scheduler),
('glsx_daily', glsx_daily_scheduler),
]
......
......@@ -94,6 +94,10 @@ class Config:
INDICATOR_BIZ_LIGHT_REFORM = 2
INDICATOR_BIZ_EQUITY = 3
# ---------- 通用+权益:直营判定基准商户号 ----------
COMMON_EQUITY_PARTNER_MERCHANT_ID = int(os.getenv('COMMON_EQUITY_PARTNER_MERCHANT_ID', '44206988'))
COMMON_EQUITY_GROUP_ID = int(os.getenv('COMMON_EQUITY_GROUP_ID', '12'))
# ---------- 业务系统 SQL 数据源(嘀加 dj_smartcarlife 库)----------
BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'true').lower() == 'true'
BIZ_SQL_DATABASE_URL = os.getenv(
......@@ -129,6 +133,7 @@ class Config:
'budget_achievement': {
'name': '预算达成数据',
'need_period': False,
'support_week': False,
'forms': [
'结算数据汇总表',
'市场费总表',
......@@ -142,6 +147,7 @@ class Config:
'store_effect_earnings': {
'name': '店效人效及盈利测算',
'need_period': True,
'support_week': False,
'forms': [
'SAAS门店预算分解表',
'关系表',
......@@ -159,18 +165,17 @@ class Config:
'output_value': {
'name': '产值达成表',
'need_period': True,
'support_week': False,
'forms': [
'SAAS门店预算分解表',
'关系表',
],
},
'future_expansion': {
'name': '未来拓展',
'need_period': False,
'forms': [],
},
# 阿维塔专项:当前仅需上传主机厂数据表;
# forms[0] 的附件表名为暂定,后续若改名只需改此处。
# 阿维塔专项:当前仅需上传主机厂数据表(表名暂定,后续若改名只改下方 forms)。
# 注意:此「主机厂数据表」为阿维塔专项独立数据表,格式不保证与现有
# 「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,切勿复用
# report_utils.parse_delivery_table(鸿蒙/广联共用结构);
# 后续接入引擎时须按用户实际提供的附件字段解析并写入阿维塔专属结果表。
'avita_special': {
'name': '阿维塔专项',
'need_period': False,
......@@ -178,34 +183,40 @@ class Config:
'主机厂数据表',
],
},
# 阿维塔专项:当前仅需上传主机厂数据表;
# forms[0] 的附件表名为暂定,后续若改名只需改此处。
'avita_special': {
'name': '阿维塔专项',
# 北汽专项:当前仅需上传源数据表(表名暂定,后续若改名只改下方 forms)。
# 注意:源文件「北汽专项源数据表」仅含线上运营手工上传类字段
# (门店名称/品牌/兜底门店/一店一群交车数/一店一群触客数),
# 结果模板其余字段(区域/产值/订单/渗透/评灯/周趋势等)均来自 D+ 系统取数,
# 当前代码无 D+ 系统数据源,待后续接入后填充。
'baic_special': {
'name': '北汽专项',
'need_period': False,
'forms': [
'主机厂数据表',
'北汽专项源数据表',
],
},
# 零跑专项 / 岚图专项:无需上传 Excel,need_period=True 需要所属周期
'leapmotor_special': {
'name': '零跑专项',
'need_period': True,
'support_week': False,
'forms': [],
},
'voyah_special': {
'name': '岚图专项',
'need_period': True,
'support_week': False,
'forms': [],
},
# 通用+权益:支持按月/按周粒度,含 3 个附件
'common_equity': {
'name': '通用+权益',
'need_period': True,
'forms': [
'区域维度数据',
'汇总区数据',
'红黄门店数据',
],
},
# 'common_equity': {
# 'name': '通用+权益',
# 'need_period': True,
# 'support_week': True,
# 'forms': [
# '区域维度数据',
# '汇总区数据',
# '红黄门店数据',
# ],
# },
}
......@@ -25,7 +25,7 @@ from report_utils import (
download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps,
parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, exact_match_store,
fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
)
......@@ -175,9 +175,10 @@ class WarrantyProcessor:
indicator_data = {}
# ========== 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_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 解析) ==========
......@@ -190,13 +191,12 @@ class WarrantyProcessor:
resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {})
# Excel 门店名 → 业务表 merchant_name 模糊匹配
biz_data = fuzzy_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表"厅店名称"/"基础信息-门店名称"
# Excel 未匹配时,系统日报 scene_type=0 兜底
# 业务系统 SQL — 精确匹配,避免模糊误匹配(如"广西河池中达"误匹配到其他"中达"门店)
biz_data = exact_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表(两边都是 Excel,命名可能不同 → 模糊保留)
delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0
if delivery_cnt == 0 and system_delivery_map:
_sys_entry = 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
# 指标系统取值
......@@ -218,9 +218,22 @@ class WarrantyProcessor:
# —— 业务系统 SQL 取值(已在 L172 用 fuzzy_match_store 拿到 biz_data)——
product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', Decimal('0'))
service_fee = Decimal('0') if resident_type == '直营' else biz_data.get('service_fee', Decimal('0'))
# 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录)
store_share = biz_data.get('shop_traffic_money', Decimal('0'))
service_fee = Decimal('0') if resident_type != '服务商' else biz_data.get('service_fee', Decimal('0'))
# —— 门店分成:普通品牌取系统流量费 shop_traffic_money;岚图按渗透率区间算比例 * 门店产值 ——
# penetration_rate 范围 0-100(safe_div_pct 已 ×100)
is_lantu = (brand or '') == '岚图'
if is_lantu:
pr = float(penetration_rate)
if pr < 30:
lantu_ratio = Decimal('0.88')
elif pr < 50:
lantu_ratio = Decimal('0.85')
else:
lantu_ratio = Decimal('0.80')
store_share = (store_output_value * lantu_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
else:
store_share = biz_data.get('shop_traffic_money', Decimal('0'))
guarantee_amount = Decimal('0')
gl_share = store_output_value - product_cost - store_share - guarantee_amount
......
......@@ -25,7 +25,7 @@ from report_utils import (
download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps,
parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, exact_match_store,
fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
)
......@@ -177,9 +177,10 @@ class EquityProcessor:
indicator_data = {}
# ========== 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_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 解析) ==========
......@@ -192,14 +193,13 @@ class EquityProcessor:
resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {})
# Excel 门店名 → 业务表 merchant_name 模糊匹配
biz_data = fuzzy_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表"厅店名称"/"基础信息-门店名称"
# Excel 未匹配时,系统日报 scene_type=0 兜底
# 业务系统 SQL — 精确匹配
biz_data = exact_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表(Excel → Excel 保留模糊)
delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0
if delivery_cnt == 0 and system_delivery_map:
# system_delivery_map value 是 dict{delivery_cnt, equity_to_shop_count, ...}
_sys_entry = 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
# 指标系统取值
......@@ -214,7 +214,7 @@ class EquityProcessor:
# —— 业务系统 SQL 取值 ——
product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', Decimal('0'))
service_fee = Decimal('0') if resident_type == '直营' else biz_data.get('service_fee', Decimal('0'))
service_fee = Decimal('0') if resident_type != '服务商' else biz_data.get('service_fee', Decimal('0'))
# 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录)
store_share = biz_data.get('shop_traffic_money', Decimal('0'))
guarantee_amount = Decimal('0')
......
# -*- 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):
if not fmt or '%' not in fmt:
return fmt
if _is_ratio_field(attr_name):
# 真正的比例字段 → 转字面百分号(DB 已存 1-100,不应再自动乘 100)
return fmt.replace('%', '"%"')
# 真正的比例字段 → 统一保留 2 位小数 + 字面 "%"
# 防模板整数百分比格式(0%)四舍五入:DB 存 1.5 显示成 2%
return '0.00"%"'
else:
# 金额/数值字段被误配 % → 去掉百分号字符,保留数字精度
cleaned = fmt.replace('%', '').strip()
......
......@@ -42,3 +42,8 @@ WHERE base_scene_code = '100101'
AND deleted_flag = 'N'
ORDER BY created_date DESC;
-- =====================================================
-- 7. 查询园区店
-- 场景: base_scene_code='100101' 轻改
-- =====================================================
select traffic_party_name,parking_store_name from dj_car_life_merchant_store_info where base_scene_code ='100101' and deleted_flag ='N'
\ No newline at end of file
No preview for this file type
......@@ -75,7 +75,7 @@ LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1
WHERE t1.status = 1 and t1.del_flag='N'
AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6
......
......@@ -7,18 +7,25 @@
-- 关联表:
-- gopa 利润分配主表 (子订单级, order_flag='N' 非汇总)
-- gopa2 利润分配汇总记录 (order_flag='Y', grain_size_type=1, 拿服务费/施工收入/产值)
-- gso 子订单表 (拿嘀加与第三方成本合计 = upgrade_dj_cost + upgrade_third_party_cost)
-- gso 子订单表 (拿嘀加与第三方成本)
-- go 订单表 (scene_type / business_type / merchant_name)
-- po 支付单表 (success_date 周期过滤)
-- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901))
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY, order 级字段用 MAX 取单次值
-- 外层按 merchant_name GROUP BY, 全部 SUM 跨订单聚合
--
-- 字段口径:
-- 商品成本 = 嘀加与第三方成本合计 (upgrade_dj_cost + upgrade_third_party_cost)
-- 商品成本 = upgrade_dj_cost + (shop_traffic_money_calculate_type=1 时才加 upgrade_third_party_cost)
-- 第三方成本仅在 GMV 口径算流量费时才计入
-- 门店分成/流量费 = shop_traffic_money (来自 gopa 主表)
-- 市场费 = 四项费用累计 (fee 子查询)
-- 服务费用 = 服务商金额 franchisee_profit_money (来自 gopa2 汇总记录)
-- 门店产值 = total_price (来自 gopa2 汇总记录)
-- 其他费用 = custom_common_cost (来自 gopa2 汇总记录)
-- 市场费 = 四项费用累计 (fee 子查询, 内层用 MAX 取单次值)
-- 服务费用 = 服务商金额 franchisee_profit_money (来自 gopa2, 内层用 MAX)
-- 门店产值 = total_price (来自 gopa2, 内层用 MAX)
-- 其他费用 = custom_common_cost (来自 gopa2, 内层用 MAX)
-- ============================================================================
-- ========= 查询参数 =========
......@@ -28,62 +35,82 @@ SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 2; -- 2=延保 (1=权益, 另见 权益_财务成本分项.sql)
SELECT
go.merchant_name AS `门店名称`,
t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加与第三方成本合计 (子订单表)
SUM(IFNULL(gso.upgrade_dj_cost, 0) + IFNULL(gso.upgrade_third_party_cost, 0))
AS `商品成本`,
-- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(t.product_cost) AS `商品成本`,
-- 门店分成/流量费
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS `门店分成`,
SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计 (expense_category_id IN (706,808,809,901))
SUM(IFNULL(fee.total, 0)) AS `市场费`,
-- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
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 dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- 四项费用累计子查询: 日期 + scene_type + business_type 必须与外层同步!
FROM (
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
go.merchant_name,
gopa.order_code,
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(IFNULL(gso.upgrade_dj_cost, 0)
+ IF(gopa.shop_traffic_money_calculate_type = 1,
IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- 四项费用累计子查询: 日期 + scene_type + business_type 必须与外层同步!
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
AND po.success_date >= @start_time
AND po.success_date <= @end_time
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND go.business_type = @business_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name;
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
......@@ -6,6 +6,12 @@
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- 关联表: 同 延保_财务成本分项.sql
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY, order 级字段用 MAX 取单次值
-- 外层按 merchant_name GROUP BY, 全部 SUM 跨订单聚合
--
-- 字段口径: 同延保 (仅 business_type 不同)
-- ============================================================================
......@@ -16,62 +22,82 @@ SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 1; -- 1=权益 (2=延保, 另见 延保_财务成本分项.sql)
SELECT
go.merchant_name AS `门店名称`,
t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加与第三方成本合计
SUM(IFNULL(gso.upgrade_dj_cost, 0) + IFNULL(gso.upgrade_third_party_cost, 0))
AS `商品成本`,
-- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(t.product_cost) AS `商品成本`,
-- 门店分成/流量费
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS `门店分成`,
SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计
SUM(IFNULL(fee.total, 0)) AS `市场费`,
-- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
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 dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type + business_type 与外层同步
FROM (
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
go.merchant_name,
gopa.order_code,
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(IFNULL(gso.upgrade_dj_cost, 0)
+ IF(gopa.shop_traffic_money_calculate_type = 1,
IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type + business_type 与外层同步
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
AND po.success_date >= @start_time
AND po.success_date <= @end_time
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND go.business_type = @business_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name;
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name;
......@@ -5,13 +5,21 @@
-- 业务: business_type = 1 OR 2 (轻改不区分)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
--
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积 (同店中店)
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY
-- - gopa/gso 级字段 → SUM(同订单多 sub_order_code 要累加)
-- - order 级字段(fee.total) → MAX(避免 JOIN 膨胀)
-- 外层按 merchant_name GROUP BY → 全部 SUM 跨订单聚合
--
-- 与"轻改店中店"的区别:
-- 园区店只消费 4 个字段 (不需要窗膜/车衣/精品/原厂/副厂/施工收入等):
-- 产品成本(财务列表) = dj_order_type != 6
-- 内部结算成本(财务列表) = dj_order_type = 6
-- 产品成本(财务列表) = dj_order_type != 6 → upgrade_shop_price - base_shop_price
-- 内部结算成本(财务列表) = dj_order_type = 6 → upgrade_shop_price - base_shop_price
-- 流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money
-- 市场费(加权测算) = 四项费用累计
-- 字段口径/表关联/商品成本公式(upgrade_shop_price - base_shop_price)与店中店完全相同
-- 市场费(加权测算) = 四项费用累计 (fee 子查询, 内层用 MAX)
-- 字段口径/表关联与店中店完全相同
-- ============================================================================
-- ========= 查询参数 =========
......@@ -20,61 +28,77 @@ SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 1; -- 固定: 1=轻改
SELECT
go.merchant_name AS `门店名称`,
t.merchant_name AS `门店名称`,
-- ===== 产品成本口径: upgrade_shop_price - base_shop_price =====
-- 外层 SUM 跨订单聚合, 内层已按 merchant_name + order_code 聚合好
-- 产品成本(财务列表) = 非内部结算 dj_order_type != 6
SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `产品成本(财务列表)`,
SUM(t.product_cost_finance) AS `产品成本(财务列表)`,
SUM(t.internal_settle_cost) AS `内部结算成本(财务列表)`,
SUM(t.store_share) AS `流量费(财务列表)`,
-- 内部结算成本(财务列表) = 内部结算 dj_order_type = 6
SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `内部结算成本(财务列表)`,
-- order 级字段: 内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合
SUM(t.market_fee) AS `市场费`
-- 流量费(财务列表) = 非内部结算的 shop_traffic_money
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS `流量费(财务列表)`,
FROM (
SELECT
go.merchant_name,
gopa.order_code,
-- 市场费(加权测算) = 四项费用累计 (fee 子查询)
SUM(IFNULL(fee.total, 0)) AS `市场费`
-- ===== 内层: 按 merchant_name + order_code GROUP BY =====
-- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
SUM(CASE WHEN gso.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS product_cost_finance,
SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS internal_settle_cost,
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS store_share,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name;
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)
......@@ -61,9 +61,10 @@ class IndicatorClient:
参数:
- start_date: str 'YYYY-MM-DD'
- end_date: str 'YYYY-MM-DD'
- biz: int 单值(1=延保 2=轻改 3=权益) 或 list/tuple(如 [1,3] 多业务线);
多值会序列化为逗号字符串 bizs="1,3"(与 itemCodes 风格一致);
单值仍走原 "biz" 键,向后兼容现有调用方。
- biz: int 单值(1=延保 2=轻改 3=权益) 或 list/tuple(如 [1,3] 多业务线);
多值会序列化为逗号字符串 bizs="1,3"(与 itemCodes 风格一致);
单值序列化为 bizs="N"(API 仅认 bizs 键,不再有 "biz" 单数形式);
None 表示不限定业务线 → 不传 bizs 键、查全量(A0018 全国经营总产值用此)。
- item_codes: list[str] 指标编码列表,如 ['A036', 'A075']
- rate_codes: set[str] 率类指标编码,API 返回小数会 *100;None 则用 RATE_CODES 默认
......@@ -83,11 +84,13 @@ class IndicatorClient:
"exts": "merchantIds",
"itemCodes": ",".join(item_codes),
}
# biz 支持单值(int) / 多值(list):多业务线按约定序列化为逗号字符串 bizs="1,3"
if isinstance(biz, (list, tuple, set)):
# biz=None 表示查全量:不要传 bizs 键,否则 API 把 "None" 当无效业务线过滤返回空
if biz is None:
pass # 不传 bizs → 返回全业务线全量
elif isinstance(biz, (list, tuple, set)):
payload["bizs"] = ",".join(str(b) for b in biz)
else:
payload["biz"] = biz
payload["bizs"] = str(biz)
last_err = None
# 请求参数日志
......@@ -168,3 +171,85 @@ class IndicatorClient:
seen.add(c)
unique.append(c)
return self.fetch(start_date, end_date, biz, unique)
# ---------- 按商户 ID 列表查询(岚图/零跑专项等按 merchant_id 匹配的场景)----------
def fetch_by_merchant_ids(self, start_date, end_date, item_codes, merchant_ids, biz=1):
"""
查询指定商户列表在指定周期的指标数据。
与 fetch() 的区别:
- payload 显式携带 merchantIds(多个英文逗号分隔)+ exts=merchantIds + bizs;
- 返回按 merchant_id(而非 merchantName)聚合,便于用商户号直接取值,
避免门店名匹配的歧义。
参数:
- start_date / end_date: str 'YYYY-MM-DD'
- item_codes: list[str],如 ['A075', 'A084']
- merchant_ids: list[str|int],商户 ID 列表(会序列化为英文逗号分隔)
- biz: int,业务线(1=延保),payload 键为 bizs
返回:
dict[merchant_id(str)][item_code] = Decimal
注意粒度为「商户 × 指标」:同一请求传多个 itemCodes 时,每个商户
每个指标各一条数据,本方法已按 (merchant_id, item_code) 建好双层索引。
空 dict 表示查询失败或无数据。
"""
if not item_codes or not merchant_ids:
return {}
payload = {
"dateType": 4,
"startDate": start_date,
"endDate": end_date,
"exts": "merchantIds",
"itemCodes": ",".join(item_codes),
"merchantIds": ",".join(str(m) for m in merchant_ids),
"bizs": biz,
}
last_err = None
logger.info(f"[IndicatorAPI] POST {self.url} payload={payload}")
for attempt in range(1, self.retry + 2): # 首次 + retry 次
ok, content = self._post(payload)
if ok:
if attempt > 1:
logger.info(f"[IndicatorAPI] 第 {attempt} 次重试成功")
return self._aggregate_by_merchant_id(content)
last_err = content
logger.warning(f"[IndicatorAPI] 第 {attempt} 次失败 err={last_err}")
if attempt <= self.retry:
time.sleep(1 * attempt)
logger.error(f"[指标系统] 按商户查询最终失败: {last_err}")
return {}
@staticmethod
def _aggregate_by_merchant_id(content):
"""
将 API 返回的扁平列表按 merchant_id + itemCode 聚合成双层字典。
输入(商户 × 指标 粒度,每商户每 itemCode 各一条):
content = [{"itemCode":"A075","merchantId":"1001","itemValue":216,...},
{"itemCode":"A084","merchantId":"1001","itemValue":480,...}, ...]
输出:
{"1001": {"A075": Decimal("216"), "A084": Decimal("480")}, ...}
"""
result = {}
for row in content or []:
code = row.get('itemCode')
mid = row.get('merchantId') or row.get('merchant_id')
val = row.get('itemValue')
if not code or not mid or val is None:
continue
try:
val_dec = Decimal(str(val))
except Exception:
val_dec = float(val)
merchant_dict = result.setdefault(str(mid), {})
# 同一 merchant_id + itemCode 出现多条(异常情况)取第一条
merchant_dict.setdefault(code, val_dec)
logger.info(f"[指标系统] 按商户聚合完成:{len(result)} 个商户, "
f"{len(content or [])} 条原始数据")
return result
......@@ -25,7 +25,7 @@ from report_utils import (
parse_inshop_delivery_touch, parse_commerce_policy_inshop,
parse_labor_cost, is_luxury_brand,
parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats, 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,
)
from models import ReportLightReformInshop, db
......@@ -163,13 +163,13 @@ class LightReformInshopProcessor:
goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end)
# 2d. 财务成本分项(店中店+园区店共用 SQL,按 dj_order_type + 品类 + 原厂/副厂切分)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 2b. 模糊匹配到门店 → 组装 sql_data dict(get_with_fallback 双优先用)
# 2b. 精确匹配系统数据(系统 merchant_name 命名规范,精确避免误匹配)
biz_sql_data = {}
for rec in base_records:
sn = rec.get('store_name', '')
dr = fuzzy_match_store(sn, daily_report_map) or {}
gs = fuzzy_match_store(sn, goods_stats_map) or {}
fs = fuzzy_match_store(sn, finance_map) or {}
dr = exact_match_store(sn, daily_report_map) or {}
gs = exact_match_store(sn, goods_stats_map) or {}
fs = exact_match_store(sn, finance_map) or {}
biz_sql_data[sn] = {
# —— 日报类(来自 fetch_park_daily_report)——
'delivery_cnt': dr.get('delivery_cnt', 0),
......@@ -203,11 +203,26 @@ class LightReformInshopProcessor:
'store_share': fs.get('store_share', Decimal('0')),
'construction_income': fs.get('construction_income', Decimal('0')),
'market_fee': fs.get('market_fee', Decimal('0')),
'mgmt_market_fee': fs.get('mgmt_market_fee', Decimal('0')),
'sunshine_incentive_fee': fs.get('sunshine_incentive_fee', Decimal('0')),
}
# ========== Step3: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map
# ========== Step4.5: store_name → park_name 映射(系统表优先,与园区店同逻辑) ==========
park_name_sys_map = fetch_park_name_map(base_scene_code='100101')
store_to_park = {}
for rec in base_records:
sn = rec.get('store_name', '')
store_to_park[sn] = (
park_name_sys_map.get(sn) # 精确匹配
or rec.get('park_name', '') # Excel 原值兜底
)
_hit = sum(1 for v in store_to_park.values() if v)
logger.info(f"[park_name-inshop] store_to_park 映射 {_hit}/{len(store_to_park)} 有值, "
f"sample={list(store_to_park.items())[:5]}")
# ========== Step5: 逐行计算 ==========
rows_to_insert = []
for rec in base_records:
......@@ -267,7 +282,8 @@ class LightReformInshopProcessor:
store_share = sql_data.get('store_share', 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 包含匹配
......@@ -299,8 +315,9 @@ class LightReformInshopProcessor:
store_consumables = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'store_consumables'),
period_start, period_end)
# 服务费占比:直接取(比例值不摊销)
sp_ratio = extract_budget_ratio(prev_budget_map, sn, 'service_provider_share_ratio')
# 服务费占比:直营店强制 0,服务商直接取(与 park_processor 对齐)
sp_ratio = Decimal('0') if operate_type == '直营' else extract_budget_ratio(
prev_budget_map, sn, 'service_provider_share_ratio')
# —— 人力成本 ——
headcount = labor_map.get(sn, 0)
......@@ -377,16 +394,21 @@ class LightReformInshopProcessor:
product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_output_value)
# 市场费:若一线激励存在(不为 0),则只算管理层市场费1+2
# 这里 market_fee_raw 已经是 TODO 占位值,先原样取
market_fee = market_fee_raw
# 市场费:若一线激励存在(> 0),则只算管理层市场费1+2;否则管理层+阳光激励全算
if frontline_incentive and frontline_incentive > 0:
market_fee = mgmt_market_fee
else:
market_fee = mgmt_market_fee + sunshine_incentive_fee
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
# 营销人员成本
marketing_personnel_cost = Decimal('0')
if operate_type == '直营':
# 底薪 3500 元/人/月,按统计周期天数折算:3500 * 周期天数 / 月份总天数
# (周期天数 = period_end - period_start + 1,含首尾;月份总天数 = period_start 所在月天数)
base_salary_prorated = prorate_by_period(Decimal('3500'), period_start, period_end)
marketing_personnel_cost = (
Decimal(str(headcount)) * Decimal('3500') +
Decimal(str(headcount)) * base_salary_prorated +
store_output_value * Decimal('0.04')
)
marketing_personnel_ratio = safe_div_pct_decimal(marketing_personnel_cost, store_output_value)
......@@ -417,9 +439,9 @@ class LightReformInshopProcessor:
task_id=task_id, period_start=period_start, period_end=period_end,
# 基础维度
region_area=region_area, province=province, city=rec.get('city', ''),
park_type=rec.get('park_type', ''), 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', ''),
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,
# 销售
sales_order_cnt=sales_order_cnt, sales_touch_cnt=sales_touch_cnt,
......
......@@ -31,8 +31,8 @@ from report_utils import (
parse_park_delivery_touch, parse_commerce_policy_park,
parse_labor_cost, is_luxury_brand,
parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_indicator_data, fetch_park_daily_report, fetch_light_reform_goods_stats,
fetch_light_reform_finance_stats, fetch_est_delivery_count, fuzzy_match_store,
fetch_indicator_data, fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats,
fetch_est_delivery_count, fetch_park_name_map, fuzzy_match_store, exact_match_store,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
)
from models import ReportLightReformPark, db
......@@ -168,13 +168,15 @@ class LightReformParkProcessor:
est_delivery_map = fetch_est_delivery_count(base_scene_code='100101')
# 3d. 财务成本分项(店中店+园区店共用 SQL,park 侧仅消费 4 项)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 3e. 模糊匹配到门店 → 组装 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 = {}
for rec in base_records:
sn = rec.get('store_name', '')
dr = fuzzy_match_store(sn, daily_report_map) or {}
gs = fuzzy_match_store(sn, goods_stats_map) or {}
fs = fuzzy_match_store(sn, finance_map) or {}
dr = exact_match_store(sn, daily_report_map) or {}
gs = exact_match_store(sn, goods_stats_map) or {}
fs = exact_match_store(sn, finance_map) or {}
eq = dr.get('equity_to_shop_count', 0)
af = dr.get('after_sale_equity_to_shop_count', 0)
biz_sql_data[sn] = {
......@@ -191,7 +193,7 @@ class LightReformParkProcessor:
'store_sales_output': gs.get('store_output_value', Decimal('0')),
'internal_settle_value': gs.get('internal_settle_value', Decimal('0')),
# —— 预估交车数(来自 fetch_est_delivery_count)——
'est_delivery_cnt': fuzzy_match_store(sn, est_delivery_map) or 0,
'est_delivery_cnt': exact_match_store(sn, est_delivery_map) or 0,
# —— 财务分项(park 仅消费产品成本/内部结算成本/流量费/市场费)——
'product_cost_finance': fs.get('product_cost_finance', Decimal('0')),
'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')),
......@@ -203,36 +205,82 @@ class LightReformParkProcessor:
# ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map
# ========== Step5: 合作门店数量(按 park_name 聚合) ==========
from collections import Counter
park_counter = Counter(r.get('park_name', '') for r in base_records if r.get('park_name'))
# ========== Step4.5: store_name → park_name 映射(系统表优先,用于 Step6 输出) ==========
store_to_park = {}
for rec in base_records:
sn = rec.get('store_name', '')
store_to_park[sn] = (
park_name_sys_map.get(sn) # 精确匹配
or rec.get('park_name', '') # Excel 原值兜底
)
_hit = sum(1 for v in store_to_park.values() if v)
logger.info(f"[park_name] store_to_park 映射 {_hit}/{len(store_to_park)} 有值, "
f"sample={list(store_to_park.items())[:5]}")
# ========== Step5.5: 预计算每个 park 的预估交车数合计(用于同 park 多门店分摊预估产值纠偏)==========
# 分摊基数:Excel 第一优先,SQL/配置表回退(与循环内 est_delivery_cnt 取值逻辑一致)
# ========== Step5: 合作门店数量 + park 预估交车合计(保持原逻辑) ==========
from collections import Counter
park_counter = Counter(p for p in store_to_park.values() if p)
park_est_delivery_total = {}
for rec in base_records:
pn = rec.get('park_name', '')
sn = rec.get('store_name', '')
pn = store_to_park.get(sn, '')
est = int(get_with_fallback(
rec.get('est_delivery_cnt', 0),
get_with_fallback(
fuzzy_match_store(sn, est_delivery_map) or 0,
fuzzy_match_store(sn, biz_sql_data).get('est_delivery_cnt', 0),
exact_match_store(sn, est_delivery_map) or 0,
biz_sql_data.get(sn, {}).get('est_delivery_cnt', 0),
),
) or 0)
park_est_delivery_total[pn] = park_est_delivery_total.get(pn, 0) + est
# ========== Step5.5: 识别合并组(Excel 合并单元格) ==========
# 按物理行顺序:est_output_value > 0 的行是"头行",后面连续 est=0 的行属于同一合并组
from decimal import Decimal as _D
merge_groups = []
cur_group = None
for rec in base_records:
sn = rec.get('store_name', '')
est_val = rec.get('est_output_value', _D('0')) or _D('0')
est_del = int(rec.get('est_delivery_cnt', 0) or 0)
if est_val > 0:
if cur_group is not None:
merge_groups.append(cur_group)
cur_group = {
'head_est': est_val,
'stores': [sn],
'deliveries': {sn: est_del},
}
else:
if cur_group is None:
cur_group = {'head_est': _D('0'), 'stores': [sn], 'deliveries': {sn: est_del}}
else:
cur_group['stores'].append(sn)
cur_group['deliveries'][sn] = est_del
if cur_group is not None:
merge_groups.append(cur_group)
store_to_group = {}
for g in merge_groups:
for sn in g['stores']:
store_to_group[sn] = g
multi_groups = [g for g in merge_groups if len(g['stores']) > 1]
logger.info(f"[合并行] 共 {len(merge_groups)} 个合并组, 其中 {len(multi_groups)} 个是多门店组:")
for g in multi_groups:
logger.info(f" head_est={g['head_est']}, stores={g['stores']}")
# ========== Step6: 逐行计算 ==========
rows_to_insert = []
for rec in base_records:
sn = rec.get('store_name', '')
province = rec.get('province', '')
park_name = rec.get('park_name', '')
park_name = store_to_park.get(sn, '')
operate_type = rec.get('operate_type', '')
brand = rec.get('brand', '')
region_area = region_map.get(('', province), '')
biz_type = is_luxury_brand(brand) # 类型=豪华/非豪华
biz_type = is_luxury_brand(brand)
partner_store_cnt = park_counter.get(park_name, 1)
# —— Excel 第一优先 / SQL 回退 ——
......@@ -295,22 +343,18 @@ class LightReformParkProcessor:
total_output_value = store_sales_output + internal_settle_value
# 产值达成进度(预估总产值 = 预估产值纠偏按同 park 多门店的预估交车数占比分摊)
est_output_value_raw = rec.get('est_output_value', Decimal('0'))
est_output_value = est_output_value_raw
if est_output_value_raw and est_output_value_raw > 0:
# 同 park 多门店共用一个纠偏值 → 按预估交车数占比分摊
park_total_est = park_est_delivery_total.get(park_name, 0)
if partner_store_cnt > 1 and park_total_est > 0:
store_est_delivery = int(get_with_fallback(
rec.get('est_delivery_cnt', 0),
get_with_fallback(
fuzzy_match_store(sn, est_delivery_map) or 0,
sql_data.get('est_delivery_cnt', 0),
),
) or 0)
est_output_value = (est_output_value_raw
* Decimal(store_est_delivery) / Decimal(park_total_est)
# 产值达成进度:从合并组取头行预估产值,多门店合并组按预估交车数占比分摊
group = store_to_group.get(sn)
group_head_est = group['head_est'] if group else (rec.get('est_output_value', Decimal('0')) or Decimal('0'))
est_output_value = group_head_est
if group and len(group['stores']) > 1 and group_head_est > 0:
# 多门店合并组 → 按预估交车数占比分摊
group_total_del = sum(group['deliveries'].values())
store_del = group['deliveries'].get(sn, 0)
if group_total_del > 0:
est_output_value = (group_head_est
* Decimal(store_del) / Decimal(group_total_del)
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
output_progress = safe_div_pct_decimal(total_output_value, est_output_value)
......@@ -346,8 +390,11 @@ class LightReformParkProcessor:
# 人员成本(直营才算)
personnel_cost = Decimal('0')
if operate_type == '直营':
# 底薪 3500 元/人/月,按统计周期天数折算:3500 * 周期天数 / 月份总天数
# (周期天数 = period_end - period_start + 1,含首尾;月份总天数 = period_start 所在月天数)
base_salary_prorated = prorate_by_period(Decimal('3500'), period_start, period_end)
personnel_cost = (
Decimal(str(headcount)) * Decimal('3500') +
Decimal(str(headcount)) * base_salary_prorated +
store_sales_output * Decimal('0.04')
)
personnel_cost_ratio = safe_div_pct_decimal(personnel_cost, store_sales_output)
......
......@@ -456,6 +456,8 @@ class OutputValueProcessor:
"""
task_id = task.id
stat_month = task.month or ''
today_str = datetime.now().strftime('%Y%m%d')
type_name = task.data_table_type_name or task.data_table_type or 'result'
# 统计周期起止(页面参数「所属周期」的起止时间)
period_start = getattr(task, 'period_start', None)
......@@ -627,10 +629,10 @@ class OutputValueProcessor:
# ---------- 保存 + 上传 ----------
tmp_dir = tempfile.mkdtemp(prefix=f'output_value_result_{task_id}_')
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)
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
f"/output_value_{stat_month}_{task_id}.xlsx")
object_key = (f"data-process/{today_str}"
f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key)
logger.info(f"[产值达成] 结果表已生成并上传: {file_url}({len(rows)} 行明细)")
return file_url
......
......@@ -84,15 +84,17 @@ TITLE_TO_BIZ = {
# fee_col: 'market_fee' 表示取"市场费"列,'market_fee_total' 表示取"市场费总额"列
SHEET_BIZ_MAP = [
# 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'}, # 其他太阳膜用市场费
{'pattern': '^龙南$', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'},
{'pattern': '龙南-', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'}, # 龙南-权益等
# 2.1 业务:权益、续保
{'pattern': '^权益$', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'},
{'pattern': '续保', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'},
# 2.3 业务:延保
{'pattern': '延保', 'biz_type': BIZ_TYPE_2_3, 'fee_col': 'market_fee'},
{'pattern': '太阳膜-赛力斯', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'}, # 赛力斯用市场费总额
{'pattern': '太阳膜', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'}, # 其他太阳膜用市场费
# 2.1 业务:权益、续保 —— 精确规则放前面,避免被模糊规则拦截
{'pattern': '龙南-权益', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'}, # 龙南下的权益=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'},
# 2.3 业务:延保
{'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 名称关键词
......@@ -1460,6 +1462,30 @@ class DataProcessor:
StoreEffectSummaryProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == 'avita_special':
from avita_special_processor import AvitaSpecialProcessor
logger.info(f"[处理任务] 路由 avita_special 任务 {task_id} 至 AvitaSpecialProcessor")
AvitaSpecialProcessor(app=self.app).process(task)
return
if getattr(task, 'data_table_type', None) == '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
if getattr(task, 'data_table_type', None) not in SUPPORTED_PROCESS_TYPES:
raise Exception(
......@@ -1844,6 +1870,18 @@ class DataProcessor:
if not records:
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)
for r in records:
......@@ -2019,6 +2057,74 @@ class DataProcessor:
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")
# -*- 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()
......@@ -245,6 +245,7 @@
function onTypeChange() {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
renderFileInputs(cfg ? cfg.forms : []);
togglePeriodTypeRow(cfg); // 按 support_week 控制粒度切换行显示
togglePeriodRow(cfg);
}
......@@ -381,10 +382,18 @@
modalWeekNum = weekNum;
}
// 周期粒度行:始终显示(所有类型都支持按月/按周切换)
function togglePeriodTypeRow() {
// 周期粒度行:仅 support_week=true 的类型(通用+权益)才显示
// 其他类型(整月、月份+自定义日期)统一隐藏,用户不可切换按月/按周
function togglePeriodTypeRow(cfg) {
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号
function updatePeriodHint() {
......@@ -426,9 +435,14 @@
mMonth.disabled = locked;
// 周期框 disabled 由 togglePeriodRow 统一控制(按周时 disabled,按月时 need_period=True 可编辑)
var cfg = typeConfigs.find(function (t) { return t.code === (task ? task.data_table_type : ''); });
// 防御:若原 task 的 period_type 为 week 但当前类型不支持,强制重置
if (cfg && !cfg.support_week && modalPeriodType === 'week') {
modalPeriodType = 'month';
modalWeekNum = null;
}
renderFileInputs(cfg ? cfg.forms : []);
togglePeriodTypeRow(); // 显示粒度切换行
togglePeriodRow(cfg); // 根据粒度 + need_period 控制周期行显示/disabled
togglePeriodTypeRow(cfg); // 按 support_week 控制粒度切换行显示
togglePeriodRow(cfg); // 根据粒度 + need_period 控制周期行显示/disabled
updatePeriodHint();
// 初始化粒度按钮组 active 状态
......@@ -656,6 +670,9 @@
// ---------- 弹窗:周期粒度切换 ----------
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (btn) {
btn.addEventListener('click', function () {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
// 防御:当前类型不支持按周时忽略点击(理论上行已隐藏,用户不可达)
if (!cfg || !cfg.support_week) return;
modalPeriodType = btn.dataset.type;
// 更新按钮组 active 状态
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (b) {
......@@ -664,7 +681,6 @@
});
// 切换粒度时重置 weekNum
modalWeekNum = null;
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
if (modalPeriodType === 'week') {
// 按周:渲染周下拉 + 自动计算日期
document.getElementById('mWeekSelect').style.display = '';
......
......@@ -39,13 +39,14 @@ from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_WARRANTY, BIZ_TYPE_EQUITY, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
get_subtask_status,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files,
parse_saas_base, parse_saas_base_sheet2, parse_saas_base_sheet2_exclude,
parse_region_map, parse_delivery_table,
parse_budget_achieve_excel, extract_budget_ratio, parse_labor_cost,
fetch_biz_sql_aggregated, fetch_park_daily_report,
fetch_indicator_data, fuzzy_match_store, 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
......@@ -53,6 +54,10 @@ logger = logging.getLogger('StoreEffectSummaryProcessor')
SUMMARY_CATEGORY = 'store_effect_summary'
# 总看板(第5个 sheet)必须在以下前 4 张 sheet 全部 COMPLETED 后才能执行,
# 否则读到的源数据不全(前 4 张表尚未落库或仍是旧快照)。
PRECEDING_CATEGORIES = ['warranty', 'equity', 'inshop', 'park']
# 各业务类型 → (解析函数, 文件/sheet 参数, 指标 biz 键, 指标编码)
BIZ_PLAN = [
('warranty', BIZ_TYPE_WARRANTY, INDICATOR_BIZ_MAP.get('warranty'),
......@@ -104,8 +109,39 @@ class StoreEffectSummaryProcessor:
logger.info(f"[店效人效汇总] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count}
def _preceding_sheets_all_completed(self, task_id):
"""总看板闸门:前 4 张 sheet(warranty/equity/inshop/park)是否全部 COMPLETED。
返回 (all_completed, pending_list):
- all_completed=True → 总看板可以执行;
- all_completed=False → pending_list 列出尚未就绪的 category=status,
供日志提示。任一未 COMPLETED(PENDING/PROCESSING/None/FAILED)都视为未就绪,
总看板返回等待,自身子任务保持 PENDING,由下一轮调度重试。
"""
pending = []
for cat in PRECEDING_CATEGORIES:
st = get_subtask_status(task_id, cat)
if st != SUBTASK_COMPLETED:
pending.append(f"{cat}={st}")
return (len(pending) == 0, pending)
def process(self, task):
task_id = task.id
# 幂等:自身子任务已 COMPLETED 则跳过(防止调度器重复扫描重算)
if is_subtask_completed(task_id, SUMMARY_CATEGORY):
logger.info(f"[店效人效汇总] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
# 闸门:总看板必须在前 4 张 sheet(延保/权益/店中店/园区店)全部 COMPLETED 后执行,
# 否则读到的是未落库/旧的前置数据(如 2.3交车数会偏旧)。
# 前置未就绪时直接返回(自身子任务保持 PENDING,等下一轮调度重试),不置 FAILED。
all_done, pending = self._preceding_sheets_all_completed(task_id)
if not all_done:
logger.info(f"[店效人效汇总] 任务 {task_id} 前 4 张 sheet 尚未全部完成,"
f"总看板暂缓执行,等待下一轮:未完成任务={pending}")
return
update_subtask(task_id, SUMMARY_CATEGORY, SUBTASK_PROCESSING)
db.session.commit()
......@@ -239,7 +275,8 @@ class StoreEffectSummaryProcessor:
if _m_start is None and period_start:
_m_start = period_start
_m_end = (period_end + timedelta(days=1)) if period_end else None
board_m = compute_metrics(tmp_dir, period_start, period_end, _m_start, _m_end)
board_m = compute_metrics(tmp_dir, period_start, period_end, _m_start, _m_end,
task_id=task_id)
logger.info(f"[店效人效汇总] 双列看板指标计算完成,共 {len(board_m)} 项 "
f"(流失门店统计月={_m_start}~{_m_end})")
except Exception as e:
......@@ -301,12 +338,12 @@ class StoreEffectSummaryProcessor:
if biz_tag in ('warranty', 'equity'):
if biz_tag == 'warranty':
ind = ind_warranty.get(store_name) or fuzzy_match_store(store_name, ind_warranty) or {}
biz = fuzzy_match_store(store_name, biz_sql_warranty) or {}
ind = ind_warranty.get(store_name) or exact_match_store(store_name, ind_warranty) or {}
biz = exact_match_store(store_name, biz_sql_warranty) or {}
budget_ratio_map = budget_warranty
else: # equity
ind = ind_equity.get(store_name) or fuzzy_match_store(store_name, ind_equity) or {}
biz = fuzzy_match_store(store_name, biz_sql_equity) or {}
ind = ind_equity.get(store_name) or exact_match_store(store_name, ind_equity) or {}
biz = exact_match_store(store_name, biz_sql_equity) or {}
budget_ratio_map = budget_equity
output_value = Decimal(str(ind.get('A036', 0)))
......@@ -326,9 +363,9 @@ class StoreEffectSummaryProcessor:
labor_cost = Decimal('0')
headcount = 0
else: # 轻改 inshop / park
ind = ind_light.get(store_name) or fuzzy_match_store(store_name, ind_light) or {}
biz1 = fuzzy_match_store(store_name, biz_sql_light) or {}
park_dr = fuzzy_match_store(store_name, park_daily) or {}
ind = ind_light.get(store_name) or exact_match_store(store_name, ind_light) or {}
biz1 = exact_match_store(store_name, biz_sql_light) or {}
park_dr = exact_match_store(store_name, park_daily) or {}
output_value = Decimal(str(biz1.get('store_output_value', 0)))
deal = int(Decimal(str(ind.get('A075', 0))))
......@@ -428,6 +465,8 @@ class StoreEffectSummaryProcessor:
def generate_result_excel(self, task, row, board_metrics=None, local_only=False):
stat_month = task.month or ''
today_str = datetime.now().strftime('%Y%m%d')
type_name = task.data_table_type_name or task.data_table_type or 'result'
period_end = getattr(task, 'period_end', None)
period_start = getattr(task, 'period_start', None)
end_date_str = period_end.strftime('%Y-%m-%d') if period_end else ''
......@@ -447,14 +486,14 @@ class StoreEffectSummaryProcessor:
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True)
final_path = os.path.join(out_dir, f'红黄门店盈利测算_{stat_month}.xlsx')
final_path = os.path.join(out_dir, f'{type_name}_{today_str}.xlsx')
import shutil
shutil.copy2(local_path, final_path)
logger.info(f"[店效人效汇总] 6 sheet 本地文件: {final_path}")
return final_path
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
f"/red_yellow_report_{stat_month}_{task.id}.xlsx")
object_key = (f"data-process/{today_str}"
f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(local_path, object_key)
logger.info(f"[店效人效汇总] 6 sheet 已上传 OSS: {file_url}")
return file_url
......@@ -529,10 +568,10 @@ class StoreEffectSummaryProcessor:
tmp_dir = tempfile.mkdtemp(prefix=f'store_effect_result_{task.id}_')
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)
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}"
f"/store_effect_summary_{stat_month}_{task.id}.xlsx")
object_key = (f"data-process/{today_str}"
f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key)
logger.info(f"[店效人效汇总] 回退单行已上传: {file_url}")
return file_url
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!