Commit e864dae8 by 周立明

门店耗材录入及修复装修摊牌计算问题

1 parent f16ebf0f
# 2026-08-11 工作记录
## 预算达成数据 · 写入 renovation_amortization(装修摊销)
数据源:`data_process_file` 中 `form_type='装修费用表'`(task #16 附件 id=122,OSS 同「门店装修费用明细汇总.xlsx」)。
目标表:`biz_budget_achieve.renovation_amortization`(decimal(15,2),注释"仅1.1业务")。
字段规则(用户 2026-08-11 确认):
- 仅 `business_type='1.1'` 参与。
- 基数 = 明细表「合同金额」(L 列) ÷ 36 个月。
- 仅取明细中「实际验收日期」(T 列) 存在的记录,且 stat_month ∈ [验收次月, 验收+36个月] 才计提。
- 匹配优先级:结果行 `traffic_name` ↔ 明细 `门店名称`(F);匹配不到再用 `park_store` ↔ 明细 `系统园区店名称`(G)。D+ 前缀归一。
- 按「门店(门店名称+系统园区店名称)」归集,门店费用只计一次,再按该门店各结果行 GMV 占比分摊。
实现要点(与原字面规则的关键修正):
- 初版按 F 池 / G 池独立聚合,导致同一门店被 F、G 双命中时费用计两次(浙江旺泽锦华 47,121.84)。
改为**按门店(门店名称+系统园区店名称)键归集、GMV 分摊**,消除重复计提;去重后总额 66,884.27(双计数版本为 90,934.11)。
- 新增 `parsers/renovation_parser.py`;`clean_budget_achievement.py` 增加 `compute_renovation_amounts`/`update_renovation`/`process_renovation`,
settlement 写库后追加第二步装修摊销 UPDATE(INSERT 不含该列,DELETE+INSERT 重置后由 UPDATE 回填,幂等)。
执行结果(task #16 / 2026-06):
- 2026-06 最终 654 行(1.1=124)。写前发现 `task_id=16 & stat_month=2026-06` 竟有 1336 行历史脏数据,DELETE+INSERT 已清掉重写。
- 装修摊销:非空 23 行 / 合计 66,884.27 / 空 631 行。浙江旺泽锦华门店合计 = 23,560.92(无重复)。
- task #16 当前状态为 FAILED(非 PROCESSING),脚本原按规则会跳过;新增 `--force` 参数忽略状态过滤用于手动回填(不改库内任务状态),本次用 `--force` 执行。
注意项:
- 精确名称匹配:个别行 traffic_name/park_store 与明细 F/G 存在细微差异(如多空格/全角),未匹配→NULL;最高 gmv 的浙江旺泽锦华行因此为 NULL。如需模糊匹配可再加。
- 任务状态 FAILED 是异常(脚本本身不更新任务状态),正常流水线应由编排器置 PROCESSING 后运行。
## 预算达成数据 · 新增 mgv_ratio + 重构装修摊销匹配(2026-08-11 续)
新增字段 `biz_budget_achieve.mgv_ratio` decimal(9,6),注释"MGV占比(按业务类型)=本行GMV/同业务类型GMV合计"。
- 在 `save_budget_rows` 保存 gmv 数据时按业务类型聚合计算(DELETE+INSERT 全量重写,幂等)。
- 校验:654 行全非空,与 `gmv/业务类型GMV合计` 零偏差;按业务类型合计≈1.0。
装修摊销匹配规则按用户补充口径重构为**「逐条明细定 F/G 模式」**(替代上版"门店合池"):
- 每条装修明细:先以「门店名称」(F) 匹配结果行 `traffic_name`,命中→进 F 池按 GMV 分摊;
若「门店名称」匹配不到任何 traffic_name,才以「系统园区店名称」(G) 匹配 `park_store`(限 1.1)→进 G 池按 GMV 分摊。
- 每条明细只计一次(F/G 二选一),彻底避免重复计提;同池多行按 GMV 占比摊分。
- 与原"门店合池"版差异:同店被 F、G 同时引用的行本版只走一条路径。结果由 23 行/66,884.27 变为 **15 行/67,092.75**(总额相近,更集中于 F 命中行)。
- 实现:`compute_renovation_amounts` 重写(f_pool/g_pool + `_allocate` 辅助);`mgv_ratio` 加入 INSERT 列与参数。
- 重跑 2026-06(--force)后:654 行、mgv_ratio 全非空、装修摊销 15 行/67,092.75、浙江旺泽锦华=23,560.92(无重复)。
注:当前 task #16 仍为 FAILED,重跑一律用 `--force`。若用户其实想保留"门店合池"23 行口径,可回退 `compute_renovation_amounts` 到门店键归集版。
## mgv_ratio 统计口径修正(2026-08-11 再续)
`mgv_ratio` 分母由「同业务类型 GMV 合计」改为「**同业务类型 + 同流量方名称 GMV 合计**」。
- 改动仅在 `save_budget_rows`:`bt_gmv` 聚合键由 `business_type` 改为 `(business_type, traffic_name)`。
- 文件头注释同步更新(MGV占比=本行GMV/同业务类型且同流量方名称GMV合计)。
- 重跑 2026-06(--force)后校验:按「业务类型+流量方名称」分组,每组 mgv_ratio 合计≈1.0(偏差>0.001 的组数=0);654 行中仅 3 行为 NULL(gmv=0.00 行,分母为零属正常)。
## 新增 mgv_ratio_park 字段(2026-08-11 续)
在 `biz_budget_achieve` 新增列 `mgv_ratio_park` decimal(9,6),注释"MGV占比(按业务类型和园区店)=本行GMV/同业务类型+同园区店GMV合计"(用 AFTER mgv_ratio)。
- `save_budget_rows` 同时计算两个占比:mgv_ratio 按 `(business_type, traffic_name)`、mgv_ratio_park 按 `(business_type, park_store)`;INSERT 列与参数各加 `mgv_ratio_park`。
- 用途:装修摊销按园区店(G)匹配时用 mgv_ratio_park 做 GMV 占比摊分。`query_task_biz_rows` 增加读取 mgv_ratio_park;`compute_renovation_amounts._allocate` 的 G 池 `field='mgv_ratio_park'`,F 池保持按 gmv。
- G 池 mgv_ratio_park 为空(dry-run 未写库/0-gmv 组)时回退按 gmv 占比,避免整池漏配;真实运行 mgv_ratio_park 已落库,优先使用。
- 重跑 2026-06(--force)校验:按「业务类型+园区店」分组每组合计≈1.0(偏离>0.001 组数=0);654 行仅 1 行 NULL(拉萨康达昌隆,2.3 业务,gmv=0.00 整组为零)。装修摊销结果不变:15 行 / 67,092.75。
- 说明:mgv_ratio_park=1.0 的单行(如 浙江旺泽锦华 某非 1.1 行)属正常——其 (业务类型,园区店) 组合唯一。
## 字段改名 mgv→gmv + 占比末行余额补差(2026-08-11 续)
用户要求:字段名写错,由 `mgv_ratio`/`mgv_ratio_park` 改为 `gmv_ratio`/`gmv_ratio_park`;且保证每组占比合计精确等于 1.0(末行用 1 - 其余占比之和回填)。
- DB:`ALTER TABLE ... CHANGE mgv_ratio gmv_ratio ...`、`CHANGE mgv_ratio_park gmv_ratio_park ...`(decimal(9,6) 及注释同步更新)。
- 代码:`save_budget_rows` 新增 `_fill_ratio(field, key_of, denom_of)`,先算各非末行 `round(gmv/denom,6)`,末行 `round(1 - 其余之和,6)`(极个别四舍五入致负数时回退自身正常占比,避免负值);gmv_ratio 按 (业务类型,流量方名称)、gmv_ratio_park 按 (业务类型,园区店)。INSERT 列/参数、query_task_biz_rows、compute_renovation_amounts(`gmv_ratio_park`) 引用同步改名。
- 重跑 2026-06(--force)校验:两组「合计≠1.0」的组数均为 0(精确=1.000000);NULL 行 gmv_ratio=3、gmv_ratio_park=1(均 GMV=0 整组为零)。装修摊销结果不变(15 行/67,092.75)。
## 广西恒为数据核查(2026-08-11 续,误报澄清)
用户怀疑 1.1 下「广西恒为汽车销售服务有限公司 / 自然到店(广西恒为)」两条(park_store=D+广西南宁恒为园区店)装修摊销应按 gmv_ratio_park 分摊(预期 430.82/58.76)。核查结论:误报,无需改动。
- 装修明细第 41 行 `门店名称(F)`=「广西恒为汽车销售服务有限公司」,与 id 6934 `traffic_name` 精确匹配 → 走 F 池(按门店名称),整笔 `17601.4/36=488.93` 计入 id 6934(正确)。注意:17601.4/36=488.93(非 489.48,此前的算术误算)。
- id 6935(自然到店(广西恒为))= NULL:自身 traffic_name 不匹配明细门店名称,且该明细已被 F 池 6934 占用(F 优先、每条明细只计一次),故不回落 G 池。为规则下的必然结果。
- 用户原预期值基于「明细未命中门店名称」错误前提,前提不成立,不适用。当前数据正确。
## 深圳布吉万国城 4 家无装修摊销诊断(2026-08-11)
4 家 1.1 流量方(深圳市新融通/深圳市电通智行/(自然到店)万国城园区店/深圳新融耀)park_store 均为 D+深圳布吉万国城园区店,gmv_ratio_park 合计=1.0(有效 G 池组)。2026-06 全为 NULL,两因叠加:
- 装修明细 Row1(合同88100,验收2026-01-26 在窗口内):系统园区店名称(G)='深圳万国城园区店'(缺'布吉')≠ 业务侧'D+深圳布吉万国城园区店' → G 不匹配;门店名称(F)=3 店名用 、/换行 拼接 → 精确 F 匹配失败 → 整行未匹配。
- 装修明细 Row2(合同11000,G='D+深圳布吉万国城园区店' 精确命中):验收2026-06-21,摊销次月起(2026-07),2026-06 不在窗口 → 正确排除。
结论:2026-06 这 4 家 NULL 符合规则与源数据;若要 6 月分摊 Row1 的 88100,须修正源 Excel(G 列补'布吉'或拆分并名),属源数据名称不一致。Row2 自 2026-07 起自动命中。
## 装修摊销时间窗口「36个月上界」澄清(2026-08-11 续,误报澄清)
用户担心 `compute_renovation_amounts` 的 `in_window` 只判了「次月」下界、漏了「验收+36月」上界。核查结论:误报,代码两界都在。
- 实际代码(clean_budget_achievement.py:357-359):`start_idx=accept_idx+1; end_idx=accept_idx+n_months(n_months=36); return start_idx<=cur_idx<=end_idx`。窗口即 [验收次月, 验收+36月](共36期),上界生效。
- 等价表述(用户最终确认):「36个月之内」= 从当前月往前推36个月,验收日期须 ∈ [当前月-36, 当前月-1](不早于当前月往前36个月、不晚于当前月前一月)。与代码 `当前月∈[验收次月,验收+36月]` 完全等价,无需改代码。验收当月不计入(次月起算)。
- 边界验证(cur=2026-06):验收2023-06-15 → 命中(末月, accept+36=2026-06);验收2023-05-31 → 排除(accept+36=2026-05);验收2020-01-10 → 排除。证明 +36 上界确实在跑。
- 之所以「看着像只判次月」:当前装修明细全部验收日期在 2025-07~2026-12(最新约12个月),无一超出 +36 上界,故对现有数据行为退化为「次月及以后」,但上界并未缺失。
- 深圳布吉万国城 Row2(验收2026-06-21)窗口=[2026-07, 2029-06],2026-06 正确排除;2026-07 起至 2029-06 自动命中(G 精确匹配 D+深圳布吉万国城园区店)。
- 结论:无需改代码。
## 装修摊销窗口一度误改并还原(2026-08-11 续)
用户在确认窗口口径时一度口述「当前月份须 ∈ [验收-36月, 验收+1月]」,我据此改了 `in_window`(下限=accept-36、上限=accept+1,dry-run 显示 2026-06 仅 8 行/8013.56)。随后用户确认自己口述有误,正确窗口应为「[验收+1月, 验收+36月]」即**原始实现**。
- 已还原 `in_window`:`start_idx=accept_idx+1; end_idx=accept_idx+n_months(36)`(clean_budget_achievement.py:354-363 及函数头注释、compute_renovation_amounts 第 2 点注释同步还原)。
- 注意:误改那次只做了 --dry-run,从未 --force 写库,故库内数据始终为原始正确值(2026-06 = 15 行 / 67,092.75)。还原后 dry-run 复现 15 行/67092.75,与库内一致,无需重跑。
- 用户表示「后续再确认区间边界」,待其最终拍板窗口定义前,维持 [验收次月, 验收+36月]。
## 新增 store_consumables(门店资产耗材)字段(2026-08-11)
用户要求:在 biz_budget_achieve 新增 `store_consumables`(门店资产耗材),数据源为「门店资产耗材明细表」(已上传 OSS,task #16 附件 id=123,form_type 直接读 `门店资产耗材明细表`),写入逻辑与装修摊销高度相似。
- DB:`biz_budget_achieve.store_consumables` decimal(15,2) NULL(注释「门店耗材」)——**此前已存在,无需新建**。
- 新增文件 `parsers/consumables_parser.py`:`ConsumablesDetailParser`(用 pandas,按文件魔数自动选 xlrd/openpyxl 引擎;列:门店名称/系统园区店名称/月份/业务类型/金额)。`normalize_bt()` 去 精品/权益/延保/尊享/智行 后缀;`strip_dplus()` 去 D+。
- 脚本改动(clean_budget_achievement.py):
- 常量 `FORM_TYPE_CONSUMABLES='门店资产耗材明细表'`;import 增加 `ConsumablesDetailParser, normalize_bt`。
- `query_consumables_file(conn,task_id)`、`query_all_biz_rows(conn,task_id,stat_month)`(取全部业务类型结果行,含 business_type 列)。
- `compute_consumables_amounts(detail_rows, biz_rows, stat_month)`:镜像装修摊销,差异——金额不除摊销月数、按明细自身业务类型分别匹配预算行、只取当月明细(月份标签如 '6月')。
- **候选名匹配(关键)**:耗材明细「门店名称」列混含公司名与园区店名,故将「门店名称」+「系统园区店名称」均作候选(去重、去 D+),先试 F(traffic_name) 再试 G(park_store),每条明细只计一次、不双重命中;F 池按 GMV 占比、G 池按 `gmv_ratio_park` 分摊。
- `update_consumables(conn, amounts)`、`process_consumables()`、`_preview_consumables()`;`process_task` 在装修摊销后调用 `process_consumables`(dry-run 也预览)。
- 2026-06 重跑(--force)结果:store_consumables 命中 22 行、合计 **22637.58**(632 行 NULL);装修摊销不变(15 行/67092.75)。
- 校验:候选匹配金额经独立核算 = 22637.57(与代码分摊总额 22637.58 仅 1 分四舍五入差),逻辑自洽。未匹配 11163.30 为预算表 2026-06 中确实不存在的门店名(留 NULL,与装修摊销规则一致)。
- 注:若用严格「门店名称→traffic_name / 系统园区店名称→park_store」列映射会漏掉东莞寮步、佛山金辉、保定定州等(其园区店名填在门店名称列),故采用候选名匹配。
## store_consumables 候选名匹配「不去 D+」修正(2026-08-11 续)
用户明确要求:store_consumables 候选名匹配(compute_consumables_amounts)**不能 strip_if_dplus(去 D+)**,保留原值。
- 改动:候选名生成(`d['store_name']`+`d['park_store_name']` 去重)去掉 `strip_if_dplus`;预算行 map 侧(build `bt_f`/`bt_g`)也一并去掉 `strip_if_dplus`,使两侧口径一致——带 D+ 的园区店名精确命中 `park_store`、不带 D+ 的公司名命中 `traffic_name`。(装修摊销 compute_renovation_amounts 仍保留去 D+,不受影响。)
- dry-run 对比(task #16 / 2026-06):旧(去D+) = 22 行/22637.58 → 新(不去D+) = 20 行/12607.96。其余 20 行金额完全不变、无新增,改动干净且局部。
- 副作用(源数据不一致导致):id 8056(7437.59) / id 8058(2592.03) 两个预算行落空(合计 10029.62)。其命中明细 `门店名称`=「东莞寮步国际汽车城园区店」(**源表缺 D+ 前缀**,30 条/10029.62),而预算 `park_store`=「D+东莞寮步国际汽车城园区店」(带 D+)。不去 D+ 后源表缺 D+ 无法匹配带 D+ 的预算园区店。其余带 D+ 的明细(如 D+万国城比亚迪园区店)仍正常命中。
- 处置:已改代码,未写库。待用户拍板——(a) 接受该 2 行落空,或 (b) 修正源 Excel 给东莞寮步补 D+ 后重跑恢复。
## 金额分摊末行余额补差 + 全局对账(2026-08-11 续)
用户要求:用 gmv 占比算出的各预算行 store_consumables / renovation_amortization 合计,必须精确等于匹配到的明细金额总和。做法:最后一个计算占比的行 = 总金额 − 前面已算金额(装修摊销同处理)。
- 新增模块级辅助 `distribute_by_weight(total, items)`:池总额先 round 到分;逐行 `round(total*w/wsum,2)`,末行(最后一个 weight>0)用 `total - 前面已算` 回填吸收残差。确保**每个池内部分摊合计精确等于该池金额**。
- 新增 `reconcile_total(result, target_total)`:各池分别补差后,跨池四舍五入仍可能残留最多几分;把残差加到金额最大的一行,使**全局合计精确等于「匹配明细金额总和(分取整)」**。
- 装修摊销 `compute_renovation_amounts._allocate` 与门店耗材 `compute_consumables_amounts._alloc` 的 F/G 两种分摊均改用 `distribute_by_weight`;两函数末尾各调一次 `reconcile_total`(target = round(Σf_pool + Σg_pool, 2))。
- 验证(task #16 / 2026-06,独立重算匹配明细总额对比):装修摊销 sum(result)=67092.74 == 匹配明细 67092.74(差 0.0000,15 行);门店耗材 sum(result)=12607.95 == 匹配明细 12607.95(差 0.0000,20 行)。此前不补差时装修摊销差 0.0064、改池总分取整后仍差 0.01,加全局对账后归零。
- 已 --force 重跑落库:renovation_amortization 15 行/67092.74(较旧值 67092.75 调减 1 分,全局对账所致);store_consumables 20 行/12607.95(不变)。DB 已核对一致。
## 装修摊销 G 池(园区店)匹配新增限制:门店名称须为空(2026-08-11)
用户要求:装修摊销按「系统园区店名称」(G 池) 兜底匹配时,必须额外限制明细的「门店名称」列为空;门店名称非空但未命中 F 的明细,不允许再落到 G 池。
- 改动:`compute_renovation_amounts` 入池判定由 `elif gn and gn in g_rows` 改为 `elif gn and gn in g_rows and not fn`(fn=归一化门店名称);同步更新第 3 条规则注释与 MEMORY.md 长期约定。
- 影响评估(task #16 / 2026-06):当前数据中**所有走 G 池的装修明细其门店名称本来就为空**,故 0 行被排除,G 池仍 932.40、F 池 66160.34、合计 67092.74 不变;模块实跑 15 行/67092.74 与独立重算明细总额精确相等(差 0.0000)。该限制对未来「门店名称非空却想走 G 池」的源数据生效。无需重写 DB(落库值未变)。
# 项目长期约定(data-report / 预算达成数据处理)
## 装修摊销匹配规则(clean_budget_achievement.py)
- 数据源:装修费用明细汇总(form_type='装修费用表'),仅 business_type='1.1' 参与。
- 基数 = 合同金额(L) / 36,仅取有实际验收日期(T) 且 stat_month 落在 [验收次月, 验收+36月] 的记录。
- 每条明细独立判定、只计一次(F/G 二选一):
- 先用明细「门店名称」(F) 匹配结果表 `traffic_name` → F 池(按命中行 GMV 占比分摊);
- 若 F 未命中**且明细「门店名称」列为空**,再用明细「系统园区店名称」(G) 匹配结果表 `park_store` → G 池(按 `gmv_ratio_park` 分摊)。**门店名称非空但未命中 F 的明细,不允许落到 G 池(2026-08-11 新增限制)。**
- **硬约束(用户拍板 2026-08-11):不允许同一条明细双重命中。F 命中后即占用该明细,不得再落到 G 池与同园区店其它流量方共享。**
- **金额分摊余额补差(2026-08-11):** 装修摊销与门店耗材的分摊都需保证「各方金额合计 == 匹配到的明细金额总和」。做法:新增 `distribute_by_weight(total, items)` 辅助——池总额先对齐到分,逐行 round(total*weight/wsum,2),**最后一个 weight>0 的行用 total-前面已算金额 回填**吸收四舍五入残差(每个池内部精确);再经 `reconcile_total` 做**全局对账**:把所有池的分摊合计对齐到「匹配明细总额(分取整)」,残差(最多几分)加到金额最大的一行,保证跨池也精确相等。renovation 与 consumables 的 F/G 分摊均复用这两个辅助。
- 匹配归一化:装修摊销(compute_renovation_amounts)名称仍统一 `strip_if_dplus`(去 'D+' 前缀)后比较;**门店资产耗材候选匹配不去 D+**(见上)。
## 门店资产耗材 store_consumables(mirror 装修摊销,2026-08-11 新增)
- 数据源:门店资产耗材明细表(form_type='门店资产耗材明细表',OSS 附件;task #16 附件 id=123)。
- 解析器 `parsers/consumables_parser.py`,按文件魔数自动选 xlrd(.xls)/openpyxl(.xlsx);业务类型去 精品/权益/延保/尊享/智行 后缀对齐预算表。
- 金额不除摊销月数、不限制业务类型;**按明细自身业务类型分别匹配**预算行;只取与 stat_month 同月的明细(月份标签如 '6月')。
- **候选名匹配(关键差异,2026-08-11 再次修正)**:耗材明细「门店名称」+「系统园区店名称」都作候选(去重),**保留原值不去 'D+' 前缀**(用户明确:候选名侧不能 strip_if_dplus)。先试 F(`traffic_name`) 再试 G(`park_store`),每条明细只计一次、不双重命中;F 池按 GMV 占比、G 池按 `gmv_ratio_park` 分摊。预算行 map 侧同样不去 D+,使带 D+ 的园区店名精确命中 `park_store`、不带 D+ 的公司名命中 `traffic_name`。
- 副作用:源表「东莞寮步国际汽车城园区店」30 条明细缺 D+ 前缀(预算 park_store 为 `D+东莞寮步国际汽车城园区店`),不去 D+ 后这 2 个预算行(8056/8058, 合计 10029.62) 落空。需改源 Excel 补 D+ 后重跑才能恢复。
- 不要用严格的「门店名称→traffic_name / 系统园区店名称→park_store」列映射(会漏掉佛山金辉、保定定州等把园区店名填在门店名称列的行)。
## gmv 占比字段
- `gmv_ratio` = 本行GMV / 同业务类型+同流量方名称 GMV 合计;
- `gmv_ratio_park` = 本行GMV / 同业务类型+同园区店 GMV 合计(供 G 池摊分用)。
- 保存 gmv 数据时计算;每组末行用 `1 - 其余占比之和` 回填,保证组内合计精确=1.000000;GMV=0 的整组为零 → 该组全部 NULL(正常)。
## 运行约定
- 任务 #16 对应 2026-06,当前 status=FAILED;手动回填一律加 `--force`(正常流水线应由编排器置 PROCESSING 再跑)。
- 命令:`python clean_budget_achievement.py -t budget_achievement -m 2026-06 [--force] [--dry-run]`
- 上月占比字段(cost_gmv_ratio_previous 等)在跑过 2026-05 后重跑 2026-06 会自动回填。
......@@ -18,6 +18,7 @@
service_fee、service_fee_ratio_current、service_fee_ratio_previous、
cost_revenue、traffic_fee_revenue、dijia_profit_sharing、
renovation_amortization(装修摊销,仅 1.1 业务)、
store_consumables(门店资产耗材,按明细业务类型分别匹配预算行并分摊)、
gmv_ratio(MGV占比=本行GMV/同业务类型且同流量方名称GMV合计,保存 gmv 时计算)、
gmv_ratio_park(MGV占比=本行GMV/同业务类型且同园区店GMV合计,保存 gmv 时计算;
用于装修摊销按园区店匹配时的 GMV 占比摊分;每组末行用 1-其余占比之和保证合计=1.0)
......@@ -49,11 +50,17 @@ import pymysql
import requests
from config import Config
from parsers import SettlementSummaryParser, RenovationDetailParser
# 数据源表单类型:结算数据汇总表 / 装修费用表
from parsers import (
SettlementSummaryParser,
RenovationDetailParser,
ConsumablesDetailParser,
normalize_bt,
)
# 数据源表单类型:结算数据汇总表 / 装修费用表 / 门店资产耗材明细表
FORM_TYPE_SETTLEMENT = '结算数据汇总表'
FORM_TYPE_RENOVATION = '装修费用表'
FORM_TYPE_CONSUMABLES = '门店资产耗材明细表'
# 装修摊销:摊销总月数(合同金额 / 摊销总月数)
RENOVATION_AMORT_MONTHS = 36
# 仅业务类型 1.1 需要装修摊销
......@@ -330,9 +337,10 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV
- 先用明细「门店名称」(F) 匹配结果行的 traffic_name:
命中 → 该明细费用计入 F 池(key=归一化门店名称),
按命中结果行的 GMV 占比分摊;
- 若「门店名称」匹配不到任何结果行的 traffic_name,
- 若「门店名称」匹配不到任何结果行的 traffic_name,且「门店名称」列为空,
再用明细「系统园区店名称」(G) 匹配结果行的 park_store(限 1.1):
命中 → 计入 G 池(key=归一化系统园区店名称),按命中结果行 GMV 占比分摊。
注:门店名称非空但未命中 F 的明细,不允许再落到 G 池。
4. 每条明细只计一次(F / G 二选一),因此不会重复计提;
同一匹配池(同一 traffic_name / 同一 park_store)下有多条结果行的,
按各行 GMV 占比摊分该池的装修摊销总额。
......@@ -386,8 +394,10 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV
gn = strip_if_dplus(d['park_store_name'])
if fn and fn in f_rows:
f_pool[fn] += amt # F 模式:按门店名称匹配
elif gn and gn in g_rows:
g_pool[gn] += amt # G 模式(兜底):按系统园区店名称匹配
elif gn and gn in g_rows and not fn:
# G 模式(兜底):仅当「门店名称」列为空时才允许按系统园区店名称匹配;
# 门店名称非空但未命中 F 的明细,不允许再落到 G 池。
g_pool[gn] += amt
# 按 GMV 占比分摊各池
# - F 池(按门店名称/traffic_name 匹配):用本行 GMV 在池内占比摊分;
......@@ -407,34 +417,35 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV
ratios = [float(r['gmv_ratio_park']) if r.get('gmv_ratio_park') is not None else None
for r in rows]
if all(x is not None for x in ratios):
for r, rp in zip(rows, ratios):
if rp > 0:
result[r['id']] = result.get(r['id'], 0) + round(total * rp, 2)
dist = distribute_by_weight(
total, [(r['id'], rp) for r, rp in zip(rows, ratios)])
for rid, amt in dist.items():
result[rid] = result.get(rid, 0) + amt
continue
# 回退:按 GMV 占比
gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
if gmv_sum <= 0:
share = round(total / len(rows), 2)
for r in rows:
result[r['id']] = result.get(r['id'], 0) + share
dist = distribute_by_weight(total, [(r['id'], 1) for r in rows])
else:
for r in rows:
result[r['id']] = result.get(r['id'], 0) + round(
total * float(r['gmv'] or 0) / gmv_sum, 2)
dist = distribute_by_weight(
total, [(r['id'], float(r['gmv'] or 0)) for r in rows])
for rid, amt in dist.items():
result[rid] = result.get(rid, 0) + amt
continue
# 默认:按本行 GMV 占比摊分
gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
if gmv_sum <= 0:
share = round(total / len(rows), 2)
for r in rows:
result[r['id']] = result.get(r['id'], 0) + share
dist = distribute_by_weight(total, [(r['id'], 1) for r in rows])
else:
for r in rows:
result[r['id']] = result.get(r['id'], 0) + round(
total * float(r['gmv'] or 0) / gmv_sum, 2)
dist = distribute_by_weight(
total, [(r['id'], float(r['gmv'] or 0)) for r in rows])
for rid, amt in dist.items():
result[rid] = result.get(rid, 0) + amt
_allocate(f_pool, f_rows, field='gmv')
_allocate(g_pool, g_rows, field='mgv_ratio_park')
# 全局对账:各池分摊合计对齐到「匹配明细金额总和(分取整)」,消除跨池四舍五入残差
reconcile_total(result, round(sum(f_pool.values()) + sum(g_pool.values()), 2))
return result
......@@ -445,6 +456,61 @@ def strip_if_dplus(name):
return name or ''
def distribute_by_weight(total, items):
"""将 total 按权重分摊到各 (row_id, weight),每行四舍五入到 2 位小数;
为保证各池分摊金额合计精确等于该池匹配到的明细金额总和,最后一行
(items 中最后一个 weight>0 的行)用 ``total - 前面各行已算金额`` 回填,
吸收四舍五入残差,使本池合计精确 = total。
Args:
total: 该池应摊总额(float)。
items: list of (row_id, weight),weight<=0 的行被忽略(不参与分摊)。
Returns:
dict: {row_id: 金额(float, 已四舍五入 2 位)},仅含 weight>0 的行。
"""
pos = [(rid, w) for rid, w in items if w and w > 0]
if not pos:
return {}
wsum = sum(w for _, w in pos)
if wsum <= 0:
return {}
# 池总额先对齐到「分」,使末行余额补差后各池分摊合计精确等于该池金额(无舍入残差)
total = round(total, 2)
out = {}
n = len(pos)
acc = 0.0
for i, (rid, w) in enumerate(pos):
if i == n - 1:
amt = round(total - acc, 2) # 末行余额补差,吸收残差
else:
amt = round(total * w / wsum, 2)
acc += amt
out[rid] = amt
return out
def reconcile_total(result, target_total):
"""把 result 中各行金额合计对齐到 target_total(2 位小数)。
各池已分别做末行余额补差,但跨池四舍五入可能残留最多几分钱的差异;
这里把残差加到金额最大的一行,保证「各方金额合计 == 匹配明细金额总和」
精确成立(残差通常仅几分钱,加到最大行对相对占比扰动最小)。
Args:
result: dict {biz_row_id: 金额},会被原地修改。
target_total: 该口径下匹配到的明细金额总和(2 位小数)。
"""
if not result:
return
cur = round(sum(result.values()), 2)
diff = round(target_total - cur, 2)
if abs(diff) < 0.005:
return
rid = max(result, key=lambda k: result[k]) # 加到金额最大的行,最小化扰动
result[rid] = round(result[rid] + diff, 2)
def update_renovation(conn, amounts):
"""把计算好的装修摊销写回 biz_budget_achieve(按主键 id 更新)。
......@@ -467,6 +533,176 @@ def update_renovation(conn, amounts):
raise
# ---------------- 门店资产耗材 ----------------
def query_consumables_file(conn, task_id):
"""查询任务下未删除的「门店资产耗材明细表」附件(按 id 倒序,最新在前)。"""
sql = (
'SELECT id, task_id, form_type, file_name, file_url, clean_status '
'FROM data_process_file '
'WHERE task_id = %s AND form_type = %s AND is_deleted = 0 '
'ORDER BY id DESC'
)
with conn.cursor() as cur:
cur.execute(sql, (task_id, FORM_TYPE_CONSUMABLES))
return cur.fetchall()
def query_all_biz_rows(conn, task_id, stat_month):
"""查询本任务下指定统计月的全部预算达成结果行(门店资产耗材按业务类型分别匹配用)。
Returns:
list[dict]: {id, traffic_name, park_store, gmv, gmv_ratio_park, business_type}
"""
sql = (
'SELECT id, traffic_name, park_store, gmv, gmv_ratio_park, business_type '
'FROM biz_budget_achieve '
'WHERE task_id = %s AND stat_month = %s'
)
with conn.cursor() as cur:
cur.execute(sql, (task_id, stat_month))
return cur.fetchall()
def compute_consumables_amounts(detail_rows, biz_rows, stat_month):
"""按规则计算每行预算达成数据的「门店资产耗材」金额。
逻辑与装修摊销高度相似,差异:
- 金额直接作为分摊基数,不做除法(无摊销总月数);
- 不限制业务类型:按明细自身的业务类型(归一化后)分别匹配对应业务的预算行;
- 仅取与 stat_month 同月的明细(月份标签如 '6月')。
匹配规则(每条明细只计一次,F 优先):
耗材明细的「门店名称」列实际混含公司名与园区店名,故采用候选名匹配:
将明细的「门店名称」与「系统园区店名称」均作为候选名(去重,保留原值、不去 'D+' 前缀):
1. 先任一轮候选名命中【同业务类型】结果行的 traffic_name(F) → 计入 F 池,
按命中结果行 GMV 占比分摊;
2. 否则任一轮候选名命中【同业务类型】结果行的 park_store(G) → 计入 G 池,
按命中结果行 gmv_ratio_park(同业务类型+同园区店)分摊;
3. 每条明细只计一次(F / G 二选一),与装修摊销一致不允许双重命中。
Args:
detail_rows: ConsumablesDetailParser.parse() 的结果列表。
biz_rows: query_all_biz_rows() 的结果列表(全部业务类型)。
stat_month: 'YYYY-MM'。
Returns:
dict: {biz_row_id: 金额(float, 已四舍五入 2 位)}
未匹配到明细的结果行不出现在返回 dict 中(保持 NULL)。
"""
from collections import defaultdict
cur_m = int(stat_month.split('-')[1])
month_label = f'{cur_m}月'
# 按业务类型分桶预算行,并预建 F/G 映射
bt_f = defaultdict(dict) # bt -> {归一化门店名称: [biz rows]}
bt_g = defaultdict(dict) # bt -> {归一化园区店名称: [biz rows]}
for r in biz_rows:
bt = r['business_type']
tn = (r['traffic_name'] or '').strip()
ps = (r['park_store'] or '').strip()
if tn:
bt_f[bt].setdefault(tn, []).append(r)
if ps:
bt_g[bt].setdefault(ps, []).append(r)
# 每条明细独立判定 F / G,累加进对应池(按 (bt, 名称) 聚合,每条明细只计一次)
f_pool = defaultdict(float) # (bt, 门店名称) -> 应摊总额
g_pool = defaultdict(float) # (bt, 园区店名称) -> 应摊总额
for d in detail_rows:
if d.get('month') != month_label:
continue
amt = float(d['amount'] or 0)
if amt <= 0:
continue
bt = normalize_bt(d['business_type'])
fmap = bt_f.get(bt, {})
gmap = bt_g.get(bt, {})
# 候选名:门店名称 + 系统园区店名称,去重(保留原值,不去 'D+' 前缀)
cands = []
for raw in (d['store_name'], d['park_store_name']):
n = str(raw or '').strip()
if n and n not in cands:
cands.append(n)
# F 优先:任一候选名命中 traffic_name
fkey = next((c for c in cands if c in fmap), None)
if fkey:
f_pool[(bt, fkey)] += amt # F 模式:按门店名称匹配
else:
gkey = next((c for c in cands if c in gmap), None)
if gkey:
g_pool[(bt, gkey)] += amt # G 模式(兜底):按系统园区店名称匹配
# 按 GMV 占比分摊各池
# - F 池(按门店名称/traffic_name 匹配):用本行 GMV 在池内占比摊分;
# - G 池(按系统园区店名称/park_store 匹配):用 gmv_ratio_park(同业务类型+同园区店)
# 作为该行的摊分系数,更直接体现「同业务类型+同园区店」的 GMV 占比。
result = {}
def _alloc(pool, row_map, field='gmv'):
for key, total in pool.items():
if total <= 0:
continue
rows = row_map[key]
if field == 'mgv_ratio_park':
ratios = [float(r['gmv_ratio_park']) if r.get('gmv_ratio_park') is not None else None
for r in rows]
if all(x is not None for x in ratios):
dist = distribute_by_weight(
total, [(r['id'], rp) for r, rp in zip(rows, ratios)])
for rid, amt in dist.items():
result[rid] = result.get(rid, 0) + amt
continue
# 回退:按 GMV 占比(如 dry-run 尚未写库、或 0-GMV 组)
gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
if gmv_sum <= 0:
dist = distribute_by_weight(total, [(r['id'], 1) for r in rows])
else:
dist = distribute_by_weight(
total, [(r['id'], float(r['gmv'] or 0)) for r in rows])
for rid, amt in dist.items():
result[rid] = result.get(rid, 0) + amt
continue
# 默认:按本行 GMV 占比摊分
gmv_sum = sum(float(r['gmv'] or 0) for r in rows)
if gmv_sum <= 0:
dist = distribute_by_weight(total, [(r['id'], 1) for r in rows])
else:
dist = distribute_by_weight(
total, [(r['id'], float(r['gmv'] or 0)) for r in rows])
for rid, amt in dist.items():
result[rid] = result.get(rid, 0) + amt
_alloc(f_pool, {(bt, n): bt_f[bt][n] for (bt, n) in f_pool}, field='gmv')
_alloc(g_pool, {(bt, n): bt_g[bt][n] for (bt, n) in g_pool}, field='mgv_ratio_park')
# 全局对账:各池分摊合计对齐到「匹配明细金额总和(分取整)」,消除跨池四舍五入残差
reconcile_total(result, round(sum(f_pool.values()) + sum(g_pool.values()), 2))
return result
def update_consumables(conn, amounts):
"""把计算好的门店资产耗材写回 biz_budget_achieve(按主键 id 更新)。
Args:
amounts: dict {biz_row_id: 金额}。空 dict 则不更新。
Returns:
int: 更新行数。
"""
if not amounts:
return 0
sql = f'UPDATE {TARGET_TABLE} SET store_consumables = %s WHERE id = %s'
params = [(amt, rid) for rid, amt in amounts.items()]
try:
with conn.cursor() as cur:
cur.executemany(sql, params)
conn.commit()
return len(params)
except Exception:
conn.rollback()
raise
# ---------------- 文件下载 ----------------
......@@ -525,8 +761,9 @@ def process_task(conn, task, dry_run=False):
log(' dry-run:不写库,样例前 3 行:')
for r in rows[:3]:
log(f' {r}')
# dry-run 也演示装修摊销预览(依赖库内已有的 1.1 行)
# dry-run 也演示装修摊销 / 门店资产耗材预览(依赖库内已有的结果行)
_preview_renovation(conn, task_id, stat_month, dry_run=True)
_preview_consumables(conn, task_id, stat_month)
return len(rows)
deleted, inserted = save_budget_rows(conn, task_id, stat_month, rows)
......@@ -538,7 +775,9 @@ def process_task(conn, task, dry_run=False):
# 第二步:装修摊销(来自「装修费用表」附件,仅 1.1 业务)
ren_updated = process_renovation(conn, task_id, stat_month, dry_run=False)
return inserted + ren_updated
# 第三步:门店资产耗材(来自「门店资产耗材明细表」附件,按业务类型分别匹配)
cons_updated = process_consumables(conn, task_id, stat_month, dry_run=False)
return inserted + ren_updated + cons_updated
except Exception:
if not dry_run:
update_clean_status(conn, file_row['id'], CLEAN_PENDING) # 失败回退为待清洗
......@@ -593,6 +832,60 @@ def process_renovation(conn, task_id, stat_month, dry_run=False):
return updated
def _preview_consumables(conn, task_id, stat_month):
"""演示门店资产耗材计算(dry-run 用),不写库。"""
cons_files = query_consumables_file(conn, task_id)
if not cons_files:
log(' [门店资产耗材预览] 未找到「门店资产耗材明细表」附件,跳过')
return 0
with tempfile.TemporaryDirectory(prefix='cons_') as tmp:
local = download_file(cons_files[0]['file_url'], tmp)
details = ConsumablesDetailParser(local).parse()
biz_rows = query_all_biz_rows(conn, task_id, stat_month)
amounts = compute_consumables_amounts(details, biz_rows, stat_month)
cur_m = int(stat_month.split('-')[1])
m_label = f'{cur_m}月'
m_cnt = sum(1 for d in details if d.get('month') == m_label)
log(f' [门店资产耗材预览] 明细总 {len(details)} 行(本月 {m_label} {m_cnt} 行)'
f' / 结果 {len(biz_rows)} 行 / 匹配命中 {len(amounts)} 行 / 金额总额 {sum(amounts.values()):.2f}')
for rid, amt in list(amounts.items())[:5]:
br = next((b for b in biz_rows if b['id'] == rid), None)
log(f' 行#{rid} {br["park_store"]}({br["traffic_name"]}) → {amt:.2f}')
def process_consumables(conn, task_id, stat_month, dry_run=False):
"""处理门店资产耗材:下载明细表 → 按业务类型匹配预算行 → GMV 占比分摊 → 写回。"""
cons_files = query_consumables_file(conn, task_id)
if not cons_files:
log(f' 跳过门店资产耗材:未找到未删除的「{FORM_TYPE_CONSUMABLES}」附件')
return 0
if len(cons_files) > 1:
log(f' 注意:存在 {len(cons_files)} 个未删除的「{FORM_TYPE_CONSUMABLES}」附件,取最新一个(id={cons_files[0]["id"]})')
cons_file = cons_files[0]
log(f' 门店资产耗材附件 #{cons_file["id"]}:{cons_file["file_name"]}')
with tempfile.TemporaryDirectory(prefix='cons_') as tmp:
local = download_file(cons_file['file_url'], tmp)
details = ConsumablesDetailParser(local).parse()
biz_rows = query_all_biz_rows(conn, task_id, stat_month)
if not biz_rows:
log(' 无预算达成结果行,门店资产耗材跳过')
return 0
amounts = compute_consumables_amounts(details, biz_rows, stat_month)
cur_m = int(stat_month.split('-')[1])
m_label = f'{cur_m}月'
m_cnt = sum(1 for d in details if d.get('month') == m_label)
log(f' 门店资产耗材:明细总 {len(details)} 行(本月 {m_label} {m_cnt} 行)'
f' / 结果 {len(biz_rows)} 行 / 匹配命中 {len(amounts)} 行 / 金额总额 {sum(amounts.values()):.2f}')
if dry_run:
return len(amounts)
updated = update_consumables(conn, amounts)
log(f' 写入 store_consumables:更新 {updated} 行(未匹配行保持 NULL)')
return updated
def main():
ap = argparse.ArgumentParser(description='预算达成数据清洗:结算数据汇总表 → biz_budget_achieve')
ap.add_argument('-t', '--data-table-type', required=True,
......
......@@ -6,5 +6,7 @@
"""
from .settlement_parser import SettlementSummaryParser, normalize_brand
from .renovation_parser import RenovationDetailParser
from .consumables_parser import ConsumablesDetailParser, normalize_bt
__all__ = ['SettlementSummaryParser', 'normalize_brand', 'RenovationDetailParser']
__all__ = ['SettlementSummaryParser', 'normalize_brand', 'RenovationDetailParser',
'ConsumablesDetailParser', 'normalize_bt']
# -*- coding: utf-8 -*-
"""门店资产耗材明细表解析器。
职责:解析「D+门店资产耗材每月采购明细表」(.xls / .xlsx),提取计算门店资产耗材
(store_consumables) 分摊所需的字段:
- 门店名称(对应结果表 traffic_name 的 F 匹配键)
- 系统园区店名称(对应结果表 park_store 的 G 兜底匹配键)
- 业务类型(用于按业务类型分别匹配预算行)
- 月份(用于筛选与 stat_month 对应的当月明细)
- 金额(采购金额,直接作为分摊基数,不做除法)
解析器只负责「读 Excel → 结构化数据」,不关心数据库读写。
支持 .xls(xlrd)与 .xlsx(openpyxl)两种格式,按文件魔数自动识别引擎。
"""
import os
import re
import pandas as pd
# 业务类型后缀(需归一化去掉,使其与预算达成表的 business_type 对齐)
BT_SUFFIXES = ('精品', '权益', '延保', '尊享', '智行')
def _cell(row, col):
"""取单元格并清洗:None / NaN → ''。"""
if col not in row:
return ''
v = row[col]
if v is None or (isinstance(v, float) and pd.isna(v)):
return ''
return v
def _to_num(value):
"""单元格数值归一:None/空/布尔 → 0.0;数字原样;字符串去千分位与货币符号后转 float。"""
if value is None or isinstance(value, bool):
return 0.0
if isinstance(value, (int, float)):
return float(value)
s = str(value).strip().replace(',', '')
if not s:
return 0.0
s = re.sub(r'[^\d.\-]', '', s) # 去掉 ¥、空格等非数字字符
if s in ('', '.', '-'):
return 0.0
try:
return float(s)
except ValueError:
return 0.0
def normalize_bt(s):
"""业务类型归一化:去掉 精品/权益/延保/尊享/智行 等后缀,与预算表 business_type 对齐。"""
s = str(s or '').strip()
for suf in BT_SUFFIXES:
if s.endswith(suf):
s = s[:-len(suf)]
return s
def strip_dplus(name):
"""去掉名称前缀 'D+'(匹配时归一化用)。"""
if name and name.startswith('D+'):
return name[2:]
return name
def _detect_engine(path):
"""按文件魔数识别 Excel 引擎:.xlsx = PK(zip) → openpyxl;.xls = OLE → xlrd。"""
with open(path, 'rb') as f:
head = f.read(8)
if head[:2] == b'PK':
return 'openpyxl'
if head[:4] == b'\xd0\xcf\x11\xe0':
return 'xlrd'
return None
class ConsumablesDetailParser:
"""门店资产耗材明细表解析器。"""
def __init__(self, file_path):
if not os.path.exists(file_path):
raise FileNotFoundError(f'门店资产耗材明细表不存在:{file_path}')
self.file_path = file_path
self.details = []
def parse(self):
"""解析第一个 sheet,返回明细列表。
每行返回 dict:
store_name 门店名称
park_store_name 系统园区店名称
month 月份(如 '6月')
business_type 业务类型(未归一化,如 '1.1精品')
amount 金额(float)
Returns:
list[dict]
"""
engine = _detect_engine(self.file_path)
df = pd.read_excel(self.file_path, engine=engine, header=0, dtype=str)
details = []
for _, row in df.iterrows():
store_name = str(_cell(row, '门店名称')).strip()
park_store = str(_cell(row, '系统园区店名称')).strip()
# 门店名称与系统园区店名称均为空的行视为空行/合计行,跳过
if not store_name and not park_store:
continue
details.append({
'store_name': store_name,
'park_store_name': park_store,
'month': str(_cell(row, '月份')).strip(),
'business_type': str(_cell(row, '业务类型')).strip(),
'amount': _to_num(_cell(row, '金额')),
})
self.details = details
return details
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!