feat(xq0085): 团购核对支持对比表与门店归属(v1.1.0)
This commit is contained in:
@@ -0,0 +1,467 @@
|
|||||||
|
# XQ0085 团购数据核对 — 交接文档
|
||||||
|
|
||||||
|
> 最近更新:2026-11-27(通联分支拆到 XQ0082,本插件只保留美团 / 抖音;新增 UI 与打包校验)
|
||||||
|
> 2026-11-27(对比表核对补全:今日遗留按团购统计回填 + 退款/撤销核销冲减 + 按门店/项目分组验证 + 双人餐/三人餐补平台结错)
|
||||||
|
> 2026-11-26 更新:完整链路已实跑;修复「贴入日期退化为文本」;新增核对前置预检;抖音基础信息维护改为与美团同一套;日滚动口径改为「昨日遗留 = 今日遗留 - 漏核销」
|
||||||
|
> 状态:**插件代码已落地**(`xq0085` v1.1.0,本轮修 bug 未升版本),**单测 43 项全绿**;9.29 → 9.30 完整链路已跑通。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 1. 需求与当前进度
|
||||||
|
|
||||||
|
| 项 | 内容 |
|
||||||
|
|---|---|
|
||||||
|
| 需求单 | XQ0085 团购数据核对 |
|
||||||
|
| 插件目录 | `plugins/XQ0001-0100/XQ0085 团购数据核对/` |
|
||||||
|
| 插件 id / 版本 | `xq0085` / `1.1.0`(`plugin.json` 与 `__init__.py` 一致) |
|
||||||
|
| 两条分支 | `check_meituan` 美团、`check_douyin` 抖音(通联 `check_tonglian` 已于 2026-11-27 拆到 **XQ0082 通联数据核对**) |
|
||||||
|
| 本轮新增 | 对比 sheet 日滚动:清 I/J/K,`昨日遗留 = 今日遗留 - 漏核销`(缺哪边按 0),再清空今日遗留与漏核销,按 X 列备注过滤,COM 重算后校验 W 列 |
|
||||||
|
| 当前代码状态 | ✅ 已接入美团 / 抖音分支;✅ 4 个单测通过;⚠️ 完整链路待验证;⚠️ W 非 0 是否硬失败待业务确认 |
|
||||||
|
| 共享盘策略 | `\\caiwu01\共享文件夹\1111\TG` **全程只读**;所有写操作只落本地 `<根>\过程表` 副本 |
|
||||||
|
|
||||||
|
### 1.1 两条分支索引
|
||||||
|
|
||||||
|
- 美团 `check_meituan`:共享表只读复制 → 订单收入明细合并 + 合计 → 基础信息补维护 → 门店归属(CRM 券号) → 报表按值贴入马敏总表副本(平台-新美大 + 团购统计) → **对比 sheet 日滚动**。
|
||||||
|
- 抖音 `check_douyin`:共享表只读复制 → 核销明细 A~BR 重贴 → 四口径预计收入合计校验 → 基础信息补维护 → 报表 N~Z 贴入平台-抖音 → **对比 sheet 日滚动**。
|
||||||
|
- 通联 `check_tonglian` 已于 2026-11-27 拆成独立插件 **XQ0082 通联数据核对**
|
||||||
|
(`plugins/XQ0001-0100/XQ0082 通联数据核对/`),本插件不再包含 `check_tonglian`、
|
||||||
|
`run_tonglian`、`tonglian_overwrite` 与 `<根>\通联` 子目录。
|
||||||
|
|
||||||
|
> 注意:代码里的实际调用顺序是「粘贴马敏总表之后、进度 85% 时执行对比表日滚动」(见 `Xq0085Plugin._run_meituan()` / `_run_douyin()`),不是业务口径描述的“第一步”。排查问题按代码顺序看。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 2. 目录与文件职责
|
||||||
|
|
||||||
|
| 文件 | 本轮改动 / 职责 |
|
||||||
|
|---|---|
|
||||||
|
| `config/__init__.py` | 新增 `COMPARE_*` 常量:sheet 名、数据起始行、表头扫描行、清空列、标题关键词、X 备注规则、W 验证列与容差 |
|
||||||
|
| `logic/compare_sheets.py` | **本轮核心新增文件**:定位列、生成编辑计划、zip+XML 写盘、COM 重算、W 列验证、幂等跳过 |
|
||||||
|
| `logic/preflight.py` | **本轮新增**:核对前置预检(导出明细 / 核对表 / 总表 / CRM 支付数据、日期覆盖、同类多份拦截),不通过则分支不动任何表 |
|
||||||
|
| `logic/daily_detail.py` | 本轮调整顺序:先确认「团购收益明细」存在再清空【订单收入明细表】,缺文件直接返回 |
|
||||||
|
| `__init__.py` | import `compare_sheets`;新增 `run_compare` / `compare_force` 参数;新增 `_run_compare()`;美团、抖音分支调用;`detail['compare']` 与汇总日志 |
|
||||||
|
| `plugin.json` | 暴露 `run_compare`(默认 true)、`compare_force`(默认 false)两个参数 |
|
||||||
|
| `tests/unit/test_xq0085_compare.py` | 6 个单测:R-S 滚动清空、X 备注过滤、幂等跳过、sheet 名归一化、W 验证失败、R/S 组合与两边皆空 |
|
||||||
|
| `tests/unit/test_xq0085_paste_date.py` | 3 个单测:日期写序列号、新增行沿用日期格式、空日期保持为空 |
|
||||||
|
| `tests/unit/test_xq0085_preflight.py` | 8 个单测:齐备通过、缺团购明细拦截、预订选填、日期不覆盖拦截、同类多份拦截、缺总表拦截、抖音分支、文件名日期解析 |
|
||||||
|
| `tests/unit/test_xq0085_base_info.py` | 4 个单测:读 A/B 不读 O/P、写 A/B/E/F、公式文本忽略、美团/抖音布局差异 |
|
||||||
|
| `logic/base_info_sync.py` | **本轮重构**:拆出 `layout()` / `scan()` / `apply()`,美团与抖音共用同一套;新增 B 列内部名候选池、平台名去重、公式文本跳过 |
|
||||||
|
| `logic/douyin_daily.py` | **本轮修复**:基础信息原读【报表】O/P(VLOOKUP 结果列)并与 A 列比对,且写入阶段读到公式文本 → 改为复用 `base_info_sync`,与美团完全一致 |
|
||||||
|
| `logic/paste_to_master.py` | 本轮修 `_make_cell()`:日期写 Excel 序列号(原来写 `inlineStr` 退化文本);新增行向上回看 20 行沿用同列样式。复用 `_CELL_RE` / `_ROW_RE` / `_col_num` / `_make_cell` / `_sheet_xml_path` |
|
||||||
|
| `logic/com_refresh.py` | 未改;复用 `refresh()` 做 WPS/Excel COM 重算 |
|
||||||
|
| `logic/zipio.py` | 未改;复用 `open_zip()` 修复 WPS 写坏的 ZIP64 条目大小 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 2.1 前置预检(2026-11-26 新增)
|
||||||
|
|
||||||
|
`logic/preflight.py`:进入美团 / 抖音分支前先跑预检,**不通过就中止,一张表都不动**。
|
||||||
|
|
||||||
|
| 分支 | 检查项 | 必填 | 不通过时 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 美团 | `过程表\美团M.D.xlsx` | 是 | error,中止 |
|
||||||
|
| 美团 | `过程表\马敏团购总表M.D.xlsx` | 是 | error,中止 |
|
||||||
|
| 美团 | `团购收益明细_*.xlsx` | 是 | error,中止 |
|
||||||
|
| 美团 | `预订收益明细_*.xlsx` | 否(账号无预订业务时本就为空) | WARN,继续 |
|
||||||
|
| 美团 | `团购支付数据-YYYYMMDD.xlsx`(`config.CRM_EXPORT_DIR`,或传 `crm_dir`) | 是 | error,中止 |
|
||||||
|
| 抖音 | `过程表\抖音M.D.xlsx` | 是 | error,中止 |
|
||||||
|
| 抖音 | `过程表\马敏团购总表M.D.xlsx` | 是 | error,中止 |
|
||||||
|
| 抖音 | `核销明细*.xlsx` | 是 | error,中止 |
|
||||||
|
|
||||||
|
规则:
|
||||||
|
|
||||||
|
- 明细搜索顺序 = `<根>\美团`(或 `<根>\抖音`)→ `<根>\过程表`,与 `config.search_dirs()` 一致;
|
||||||
|
- 文件名必须能解析出日期,且**营业日落在区间内**(单日文件即等于营业日);解析不出日期只 WARN、不拦截;
|
||||||
|
- **同类明细 ≥ 2 份直接 error**:`daily_detail.run()` 会把匹配到的文件全部合并,多留一份历史明细就串天 → 要求目录里只放营业日当天那份;
|
||||||
|
- 返回 `{'ok','day','action','checks','errors','warns','message'}`;插件存进 `detail['preflight']`,汇总日志追加「前置预检通过 / 前置预检未通过(已中止)」,预检失败时插件 `run()['ok'] = False`。
|
||||||
|
|
||||||
|
配套修复:`daily_detail.run()` 原来是「先清空【订单收入明细表】A~AI,再去 glob 找明细」,缺文件时会把整张明细表清空;现改成**先收集明细、找不到就直接返回且不动表**,清空动作挪到明细就绪之后。`douyin_daily.run()` 原本就在贴入前校验导出文件,无需调整。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 3. 对比 sheet 日滚动业务规则(已确认)
|
||||||
|
|
||||||
|
### 3.1 处理对象
|
||||||
|
|
||||||
|
| 分支 | sheet 配置值 | 真实表名样例 | 匹配方式 |
|
||||||
|
|---|---|---|---|
|
||||||
|
| 美团 | `新美大对比 (2)` | `新美大对比 (2)` | 归一化后精确匹配 → 包含匹配 |
|
||||||
|
| 抖音 | `抖音对比(2)` | `抖音对比(2)` / `抖音对比 (2)` | 全半角括号、空格、`*` 都归一 |
|
||||||
|
|
||||||
|
归一化由 `compare_sheets._norm()` 完成:去空白、全角括号转半角、全角星号转半角。
|
||||||
|
|
||||||
|
### 3.2 行范围与列定位
|
||||||
|
|
||||||
|
- **数据区**:第 5 行起至该 sheet 末行;前 4 行是标题 / 表头,不写。
|
||||||
|
- **表头扫描**:前 `COMPARE_HEADER_SCAN_ROWS = 4` 行里找标题。
|
||||||
|
- **按标题定位的列**:
|
||||||
|
- `漏核销`(`COMPARE_MISS_TITLE`):找不到只 WARN,跳过该列,不写死列字母。
|
||||||
|
- `昨日遗留`(`COMPARE_YESTERDAY_TITLE`):必须找到。
|
||||||
|
- `今日遗留`(`COMPARE_TODAY_TITLE`):必须找到。
|
||||||
|
- `验证`(`COMPARE_VERIFY_TITLE`):找不到时回退到固定列 `W`(`COMPARE_VERIFY_COL`)。
|
||||||
|
- **固定列**:`I` / `J` / `K` 清空;`X` 是备注列,**无表头**,固定按列号处理。
|
||||||
|
|
||||||
|
真实表实测列位:**按标题定位,不同月份表会漂移**。9.30 表:表头第 4 行,昨日遗留 `Q`、今日遗留 `R`、漏核销 `S`、验证 `W`、备注 `X`;9.18 表漏核销在 `N`。所以代码不允许写死列字母(`漏核销` 找不到只 WARN 跳过)。
|
||||||
|
|
||||||
|
### 3.3 每行处理动作
|
||||||
|
|
||||||
|
| 顺序 | 动作 | 说明 |
|
||||||
|
|---|---|---|
|
||||||
|
| 1 | 清空 `I` / `J` / `K` | 上日核对结果 |
|
||||||
|
| 2 | 计算 `昨日遗留 = 今日遗留 - 漏核销` | **2026-11-26 修正口径**:不是直接搬 R;哪边为空按 0 算(没有今日遗留就是 `0 - 漏核销`,可能为负数);两边都空则不写(清空),避免整表铺 0 |
|
||||||
|
| 3 | 清空「漏核销」列 | 按标题定位;找不到只 WARN 跳过 |
|
||||||
|
| 4 | 清空「今日遗留」 | 今天的「今日遗留」是待更新列 |
|
||||||
|
| 5 | 按 `X` 备注过滤「昨日遗留」 | 见下表;**不能按日期阈值算** |
|
||||||
|
| 6 | 写盘 → COM 重算 → 校验 `W` | 有值单元格全部 ≈ 0 才算通过 |
|
||||||
|
|
||||||
|
> 幂等提示:R 和 S 都会被清空,所以「已滚动过」的判定是「今日遗留与漏核销都空 + 昨日遗留有值」。
|
||||||
|
> 今日遗留/漏核销里出现非数字(错误值、文本)时按 0 参与计算,并计数 WARN 提示人工复核。
|
||||||
|
|
||||||
|
### 3.4 X 列备注过滤规则
|
||||||
|
|
||||||
|
| X 列文本 | 处理 | 正则 / 判断 |
|
||||||
|
|---|---|---|
|
||||||
|
| 空 / `None` / 纯空白 | 保留「昨日遗留」 | `not text` |
|
||||||
|
| 含「前消费」格式,如 `2026年10月31日前消费` | 保留「昨日遗留」 | `COMPARE_KEEP_REMARK_RE = r'前\s*消费'` |
|
||||||
|
| 其它任何备注内容,如 `其他项目待处理` | 清空「昨日遗留」 | 上述两条都不满足 |
|
||||||
|
|
||||||
|
用户明确口径:**只找文本格式,不关联日期**。
|
||||||
|
|
||||||
|
### 3.5 W 列验证
|
||||||
|
|
||||||
|
- 真实表公式口径:`W = M - T`;`M = G+H+I-L+K+J`;`T = O+Q-R+S`。
|
||||||
|
- 代码不重写公式,只在 COM 重算后读缓存值判断:
|
||||||
|
- 空单元格跳过;
|
||||||
|
- 数值且 `abs(value) <= COMPARE_VERIFY_TOL`(`1e-6`)视为 0;
|
||||||
|
- 非数值 / 错误值(如 `#DIV/0!`)/ 超出容差 → 记入 `bad`,取前 10 行写日志。
|
||||||
|
- 当前行为:**验证失败只 WARN,`run()['ok']` 仍为 True**,另置 `verified=False`。是否改成硬失败见 §7 待确认项。
|
||||||
|
|
||||||
|
### 3.6 幂等与特殊情况
|
||||||
|
|
||||||
|
| 场景 | 行为 |
|
||||||
|
|---|---|
|
||||||
|
| 「今日遗留」与「漏核销」数据区都全空,且「昨日遗留」有值 | 判定今天已滚动过,跳过写盘;避免重复运行抹掉计算结果 |
|
||||||
|
| 需要强制重跑 | `compare_force=True`(界面「核对-强制重跑日滚动」) |
|
||||||
|
| 「今日遗留」是公式列且缓存全空 | 前置 COM 重算一次,再重新生成计划;常规路径只在写盘后重算一次,避免 14MB 大表算两遍 |
|
||||||
|
| 「今日遗留」是公式列但已有值 | 按规则清空,公式一并清除;日志 WARN 提示需确认当天是否由上游重填 |
|
||||||
|
| sheet 名找不到 | `run()` 返回 `ok=False`,插件层记 WARN,不中断整条分支 |
|
||||||
|
| `dry_run=True` | 只生成计划,不写文件;W 验证读旧缓存并注明「未重算」 |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 4. 技术实现要点
|
||||||
|
|
||||||
|
### 4.1 为什么不用 openpyxl 保存
|
||||||
|
|
||||||
|
马敏总表含透视、外部链接、共享公式和大体积样式。`openpyxl.save()` 会破坏这些结构,因此写盘采用 zip + XML 直接改单元格:
|
||||||
|
|
||||||
|
1. `openpyxl.load_workbook(..., read_only=True, data_only=True)` 只读取值;
|
||||||
|
2. `_plan_sheet()` 生成 `{行号: {列号: 值或 None}}` 编辑计划;
|
||||||
|
3. `_patch_sheet()` 单次扫描 `sheet*.xml`,逐行替换或追加,清空时保留原 `s=` 样式;
|
||||||
|
4. `_write_sheet()` 逐条目复制 zip,仅替换目标 sheet XML,`os.replace(tmp, path)` 落盘。
|
||||||
|
|
||||||
|
`_patch_sheet()` 已从“逐行整段 `replace`”改成单次 `finditer` + `pieces` 拼接,避免 O(n²)。14MB 真实表完整脚本耗时从约 53 秒降到约 10 秒。
|
||||||
|
|
||||||
|
### 4.2 COM 重算
|
||||||
|
|
||||||
|
`logic/com_refresh.refresh()` 优先 `Ket.Application`(WPS 表格),失败退 `Excel.Application`:
|
||||||
|
- `PivotCaches().RefreshAll()`;
|
||||||
|
- 指定 sheet 的 `PivotTables().RefreshTable()` 兜底;
|
||||||
|
- `CalculateFullRebuild()`,失败退 `CalculateFull()`;
|
||||||
|
- `wb.Save()` 后关闭。
|
||||||
|
|
||||||
|
本机实测 COM 可用,引擎为 **WPS**。COM 失败时只 WARN,W 列读旧缓存值。
|
||||||
|
|
||||||
|
### 4.3 总表文件路径与分支切换
|
||||||
|
|
||||||
|
- 总表副本路径:`config.WORK_DIR\马敏团购总表{month}.{day}.xlsx`,由 `compare_sheets.master_path(day)` 生成。
|
||||||
|
- 工作根目录由界面 `save_dir` 注入;留空默认 `D:\资料\财务\团购数据核对`。
|
||||||
|
- 美团产物落 `<根>\美团`,抖音落 `<根>\抖音`,总表副本共用 `<根>\过程表`。
|
||||||
|
|
||||||
|
### 4.4 日期列写法(2026-11-26 修复)
|
||||||
|
|
||||||
|
`_make_cell()` 原来把 `datetime` 一律写成 `t="inlineStr"` 文本,导致 CRM【团购统计】的「消费日期」落成 `'2026-09-30 00:00:00'` 字符串(人工表是日期类型):
|
||||||
|
透视按日期分组失效、日期匹配公式失配,实跑日志里的「刷新透视 0 次」与之相关。
|
||||||
|
|
||||||
|
修改:
|
||||||
|
|
||||||
|
1. `datetime` / `date` 一律写 Excel 序列号(`openpyxl.utils.datetime.to_excel`),不带 `t`;
|
||||||
|
2. 新增行(超出原表尾的追加行)没有原单元格可继承样式,向上回看最多 20 行取同列 `s=`,否则日期会按「常规」显示成 `4xxxx` 裸数字;
|
||||||
|
3. 空日期仍不落单元格,保持空。
|
||||||
|
|
||||||
|
实测:修复后 `团购统计` B2~B1353 全部为 `datetime` 且格式 `yyyy\-mm\-dd`,与 `马敏团购总表9.30_bak.xlsx` 一致;平台两张 sheet 无此问题(本来就没有日期列)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
### 4.5 基础信息维护(美团 / 抖音同一套,2026-11-26 修抖音)
|
||||||
|
|
||||||
|
两套表结构一致:`A`=平台门店名、`B`=内部(标准)门店名、`C`=品牌、`E`=平台套餐/商品名、`F`=内部项目名。报表靠 VLOOKUP 取 B/C/F:
|
||||||
|
|
||||||
|
- 美团:`订单收入明细表` AC/AD → `基础信息!$A$3:$B$1973`、`$E$2:$F$12924`
|
||||||
|
- 抖音:`报表` N/O → `基础信息!$A$5:$C$1992`,P → `$E$5:$F$4998`
|
||||||
|
|
||||||
|
统一实现 `logic/base_info_sync.py`:
|
||||||
|
|
||||||
|
1. `layout(name)` 只描述差异(sheet 名、数据起始行、VLOOKUP 上界),`LAYOUT_MEITUAN` / `LAYOUT_DOUYIN` 两套;
|
||||||
|
2. `scan(workbook, layout)`:读【报表】`A`/`B`(平台原文)与【基础信息】`A`/`E`,按**平台名**判重,返回 `new_shops` / `new_items` / `range_warnings`;内部名候选池优先取 `B` 列;
|
||||||
|
3. `apply(workbook, scanned, layout)`:门店写 `A`+`B`(猜不到则同名,能猜则写 `C` 品牌)、套餐写 `E`+`F`,按平台名去重、幂等;
|
||||||
|
4. `run()` 供美团用:先 `data_only` 扫描、再开可保存的 workbook 写。
|
||||||
|
|
||||||
|
抖音原实现的两个 bug(已修):
|
||||||
|
|
||||||
|
- 读【报表】`O`/`P`(VLOOKUP 的**结果**列:标准门店名 / 标准项目名)去比对 `A`(平台名)→ 永远不匹配,每天误报几百个「新门店」;
|
||||||
|
- 写入阶段用 `load_workbook()`(无 `data_only`)重读报表 → 读到 `=+VLOOKUP(...)` 公式文本,会往 `基础信息!A5` 起写 **943 行公式**。现改为直接复用扫描结果,且 `_read_report_pairs()` 遇到 `=` 开头的值一律跳过并 WARN。
|
||||||
|
|
||||||
|
实测 9.30:抖音报表唯一门店 65 / 商品 34,全部已在 `A`/`E` 中(缺口 0),`A` 有 `B` 空 0 行、`E` 有 `F` 空 0 行 → 正确行为是「无新增」,不再误报、也不再写垃圾。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 5. 参数与运行方式
|
||||||
|
|
||||||
|
### 5.1 界面参数
|
||||||
|
|
||||||
|
| 参数 | 默认 | 作用 |
|
||||||
|
|---|---|---|
|
||||||
|
| `action` | `check_meituan` | 分支;决定处理哪张对比 sheet |
|
||||||
|
| `daily_day` | 今天 | 营业日;决定总表副本文件名 |
|
||||||
|
| `save_dir` | 默认根 | 本地工作根目录;留空用 `D:\资料\财务\团购数据核对` |
|
||||||
|
| `run_compare` | `true` | 是否执行对比 sheet 日滚动 |
|
||||||
|
| `compare_force` | `false` | 忽略幂等,强制重跑 |
|
||||||
|
| `use_com_refresh` | `true` | 是否用 WPS/Excel COM 刷新透视并重算 |
|
||||||
|
| `dry_run` | `false` | 只核对不写入 |
|
||||||
|
| `debug_mode` | `false` | 调试日志(完整 JSON 只在 DEBUG 输出) |
|
||||||
|
|
||||||
|
### 5.2 单测
|
||||||
|
|
||||||
|
按项目规范使用本地 `.venv`:
|
||||||
|
|
||||||
|
```powershell
|
||||||
|
& 'e:\code\37duAutomation\.venv\Scripts\python.exe' -m unittest tests.unit.test_xq0085_base_info tests.unit.test_xq0085_preflight tests.unit.test_xq0085_paste_date tests.unit.test_xq0085_compare -v
|
||||||
|
```
|
||||||
|
|
||||||
|
2026-11-26 实测:**Ran 22 tests / OK**。覆盖:
|
||||||
|
- `test_yesterday_equals_today_minus_miss` / `test_both_empty_clears_yesterday`:`昨日遗留 = 今日遗留 - 漏核销`、无今日遗留取负漏核销、两边皆空则清空、R/S 随后被清空。
|
||||||
|
- `test_scan_uses_report_ab_not_op` / `test_apply_writes_abef` / `test_formula_text_is_ignored` / `test_meituan_layout_rows`:基础信息扫描与写入、公式文本跳过、两套布局。
|
||||||
|
- `test_all_ready` / `test_booking_detail_optional` / `test_missing_group_detail_blocks` / `test_wrong_day_blocks` / `test_multiple_files_blocks` / `test_missing_master_blocks` / `test_douyin_branch_needs_detail_only` / `test_dates_in_name`:预检各项拦截与放行。
|
||||||
|
- `test_roll_and_clear`:I/J/K、漏核销、R 清空;X 空 / 前消费保留,其它备注清空;W 全 0 通过。
|
||||||
|
- `test_idempotent_skip`:第二次运行跳过,且不清掉已保留的昨日遗留。
|
||||||
|
- `test_sheet_name_normalized`:全半角括号 / 空格表名都能匹配。
|
||||||
|
- `test_verify_column_failure`:W 有非 0 时 `verify.ok=False`、`bad_count=1`。
|
||||||
|
- `test_datetime_written_as_serial`:日期不落 `inlineStr`,文本仍落 `inlineStr`。
|
||||||
|
- `test_patch_keeps_date_type_and_format`:贴入后既有行与新增行都是 `datetime` 且保留 `yyyy\-mm\-dd`。
|
||||||
|
- `test_empty_date_stays_empty`:空日期不写单元格。
|
||||||
|
|
||||||
|
### 5.3 结果回传
|
||||||
|
|
||||||
|
`detail['compare']` 是 `compare_sheets.run()` 的完整返回,含:
|
||||||
|
`ok / message / path / sheet / rows / kept / cleared / skipped / com / com_after / verify / verified`。
|
||||||
|
`_run_compare()` 只按 `ok` 记日志;W 验证失败不会把插件整体置为失败(见 §7)。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 6. 已做的验证与踩坑结论
|
||||||
|
|
||||||
|
| 时间 / 数据 | 结论 |
|
||||||
|
|---|---|
|
||||||
|
| 真实 9.18 总表 | 确认表头结构、sheet 名、数据起始行、Q/R/N/W/X 列位;X 样例含「2026年10月31日前消费」等 |
|
||||||
|
| 9.18 历史表滚动 + 重算 | W 仍有 211 行非 0;原因是当天的平台明细 / 团购统计与对比表不是同一完整链路状态,**不是实现问题** |
|
||||||
|
| 9.30 人工处理态表 | 人工已处理完,Q/R/J/K 是完成态;再跑滚动等于进入下一天,W 自然不平。用户明确:给的是人工完成表,所以不需要处理昨日遗留;**实际流程仍必须 Q←R** |
|
||||||
|
| COM 探测 | 本机 `(True, 'WPS')`,可刷新透视并重算 |
|
||||||
|
| 性能 | 写盘从 O(n²) 改为单次扫描后,14MB 表脚本约 10 秒 |
|
||||||
|
| 9.29 → 9.30 完整链路(2026-11-26 实跑) | 粘贴 904 / 943 / 1352 行;美团滚动 50 个值、清 X 备注 1 行,抖音滚动 15 个值、清 2 行;COM(WPS) 两次重算成功。W 非 0:美团 **246**(人工 170,其中 170 行完全重合)、抖音 **32**(人工 0) |
|
||||||
|
| W 差异归因(2026-11-26) | 多出的 76(美团)/ 32(抖音)行**全部**由「当日 R/J 未回填」造成,例 `row113` 人工 R=4 → 我们 W=−4、`row125` 人工 J=−2 → 我们 W=+2;逐行可解释,不是滚动实现错误 |
|
||||||
|
| 人工表自身也不平 | `马敏团购总表9.30_bak.xlsx` 美团对比 W 非 0 有 **170 行**、抖音 0 行 → 「W 全 0」不是现实验收口径,见 §7-2 |
|
||||||
|
| 清空安全性核查 | 9.29 原表对比 sheet 的 `I/J/K/N/Q/R/S` **全是常量无公式**,仅 `W` 是 `=M5-T5`,清空不会毁公式 |
|
||||||
|
| 日期类型修复(2026-11-26) | 修复前后跑同一链路,W 非 0 与 Q/R 数值完全一致;`团购统计` 消费日期由文本变回 `datetime` + `yyyy\-mm\-dd`,含超出原表尾的新增行 |
|
||||||
|
| 日滚动口径修正(2026-11-26) | 业务澄清:`昨日遗留 = 今日遗留 - 漏核销`,原先直接 `Q ← R` 是错的。9.29/9.30 两张表的漏核销列全空,所以历史实跑结果(Q=49 / W 非 0 246)与修正后一致;有漏核销数据时才会不同 |
|
||||||
|
|
||||||
|
### 6.1 不要拿人工完成态表验证滚动
|
||||||
|
|
||||||
|
人工完成的 9.30 表里「昨日遗留」已经准确,再跑 `Q ← R` 会把下一天的遗留提前覆盖,W 验证必然失败。验证滚动正确性必须用:
|
||||||
|
|
||||||
|
> 前一天完成表(提供昨日「今日遗留」) + 当天导出数据(提供当天「今日遗留」) → 跑完整链路 → 与当天人工完成表比对。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 7. 待确认 / 待办
|
||||||
|
|
||||||
|
1. ~~**跑 9.29 → 9.30 完整链路**~~ **已完成(2026-11-26)**
|
||||||
|
- 临时环境:`E:\tmp\xq85_chain\`(不入库),脚本 `run_chain.py`,调用链 `paste.run()` → `compare_sheets.run(check_meituan)` → `compare_sheets.run(check_douyin)`;日志 `chain_run1.log` / `chain_run2.log`,原表备份 `马敏团购总表9.30_orig.xlsx`。
|
||||||
|
- 结论:链路跑通,无异常中断;W 非 0(美团 246 / 抖音 32)**全部可归因于当天 R/J 未回填**,详见 §6。
|
||||||
|
- 待补:把中间态产物与人工完成态一起给业务确认(Q 49 vs 20、R 0 vs 67 属完成态差异,不可直接等值比对)。
|
||||||
|
2. **W 非 0 是否硬失败**(仍未定,且口径本身被数据质疑)
|
||||||
|
- 当前:`compare_sheets.run()` 末尾只 WARN 并置 `verified=False`,`ok=True`;`Xq0085Plugin._run_compare()` 因此不报错。
|
||||||
|
- 新证据:人工完成表美团对比自身就有 170 行 W 非 0 → 「有值全 0」不可能达成。需业务改成「允许的差异行白名单 / 容差 / 仅校验当天已回填行」。
|
||||||
|
- 若要硬失败:改 `compare_sheets.run()` 的 W 校验分支(返回 `ok=False` 或抛 `CompareError`),并同步决定是否中断后续分支。口径未定前不要擅自改。
|
||||||
|
3. **透视刷新仍是 0 次**
|
||||||
|
- 日期文本问题已修,但 COM 日志依旧「刷新透视 0 次」,需确认该表透视是否本就手动刷新 / 数据源是否指向 `团购统计` 的固定区域,避免以为透视已更新。
|
||||||
|
4. **发布**
|
||||||
|
- 本次只修 bug、**未升版本**(`xq0085` 仍为 1.1.0),未打包;确认口径后再定版本号走测试通道 → 人工验证 → **人**执行转正;agent 不得自行转正 / 不得默认 `publish --prod`。
|
||||||
|
5. **临时脚本归档**
|
||||||
|
- `E:\tmp\xq85_chain\*`(`run_chain.py` / `diag.py` / `diag_formula.py` / `preflight_check.py` / 日志)都是验证脚本,不入库;如需长期复现,再决定是否整理进 `tools/`。
|
||||||
|
6. **前置预检已落地(2026-11-26)**
|
||||||
|
- 插件入口 `_preflight()` 在美团 / 抖音分支开头拦截:缺明细、日期不覆盖营业日、同类多份 → 中止且不动表;`daily_detail.run()` 的「先清空后找文件」顺序已修。
|
||||||
|
- **日常运行前必须先把当天的导出放到位**(预检只看这三个目录):
|
||||||
|
- 美团:`团购收益明细_YYYYMMDD_YYYYMMDD.xlsx`(+ 有预订业务时 `预订收益明细_*.xlsx`)→ `<根>\美团`
|
||||||
|
- 抖音:`核销明细_*.xlsx` → `<根>\抖音`
|
||||||
|
- CRM:`团购支付数据-YYYYMMDD.xlsx` → `config.CRM_EXPORT_DIR`(默认 `D:\资料\财务\CRM数据导出`)
|
||||||
|
- 目录里**不要留历史明细**,否则 `glob` 全合并串天(预检会直接 error)。
|
||||||
|
7. **抖音基础信息已与美团统一(2026-11-26)**
|
||||||
|
- 修掉两处 bug:读 `O`/`P` → 改读 `A`/`B`;写入阶段读到公式文本 → 改为复用扫描结果;另加「`=` 开头的值一律跳过」兜底。
|
||||||
|
- 单测 4 项通过;**真实表复扫(抖音 / 美团 9.30)还没跑完整**(命令被执行到后台),下次跑链路时确认日志出现「基础信息无新增,未改动」。
|
||||||
|
- `B`/`C`/`F` 仍是「能猜则写、猜不到留空给人工补」:`F` 用 `ITEM_KEYWORD_RULES` 关键词规则 + 双人/三人后缀,`B` 用 `门店映射表.json` + 相似度(阈值 0.45,猜不到则同名),`C` 仅在能取到品牌时写。
|
||||||
|
8. **今日遗留 R / J 仍需人工维护**(用户已确认是后续繁琐步骤)
|
||||||
|
- 代码只清空 R/J、不生成;W 因此不会自动归零,属业务动作,不是实现缺陷。若将来要做,需先定义「按当天核销/漏核销推算遗留」的口径。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 8. 注意事项(交接必读)
|
||||||
|
|
||||||
|
- 共享盘只读;本地过程表副本可以写,但不要写共享盘。
|
||||||
|
- `漏核销` 必须按标题找,找不到只告警跳过,不要改成写死列字母。
|
||||||
|
- `X` 列无表头,判断的是备注文本格式 `前\s*消费`,**不是日期阈值**。
|
||||||
|
- 人工完成态表不能用来验证滚动;会误判。
|
||||||
|
- 幂等保护是防重复滚动的关键;除非明确要重跑,不要开 `compare_force`。
|
||||||
|
- 大表写盘不要回退到 openpyxl 保存,也不要把 `_patch_sheet()` 改回逐行 `replace`。
|
||||||
|
- W 列验证读的是 COM 重算后的缓存值;COM 失败时读旧缓存,日志会提示。
|
||||||
|
- 日期列必须写 Excel 序列号(`_make_cell()` 已处理),不要回退成 `inlineStr`,否则透视按日期分组、日期匹配全部失效。
|
||||||
|
- 运行前先让预检通过:缺导出明细 / 日期不覆盖营业日 / 同类多份都会直接中止,别为了「先跑跑看」绕过预检去点单步。
|
||||||
|
- 基础信息只认「报表 `A`/`B` → 基础信息 `A`/`B`/`E`/`F`」这条线;不要再去读 `O`/`P`/`N` 这些 VLOOKUP 结果列,扫描必须 `data_only`。
|
||||||
|
- 所有运行 / 测试 / 依赖操作使用项目根 `.venv`,不污染全局环境。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 9. 相关位置速查
|
||||||
|
|
||||||
|
| 内容 | 位置 |
|
||||||
|
|---|---|
|
||||||
|
| 新增常量 | `plugins/XQ0001-0100/XQ0085 团购数据核对/config/__init__.py` 第 208 行附近 |
|
||||||
|
| 核心实现 | `plugins/XQ0001-0100/XQ0085 团购数据核对/logic/compare_sheets.py` |
|
||||||
|
| 插件接入 | `plugins/XQ0001-0100/XQ0085 团购数据核对/__init__.py` 第 87、219、224、264 行附近 |
|
||||||
|
| 参数定义 | `plugins/XQ0001-0100/XQ0085 团购数据核对/plugin.json` 第 85 行附近 |
|
||||||
|
| 单测 | `tests/unit/test_xq0085_compare.py` |
|
||||||
|
| COM 重算 | `plugins/XQ0001-0100/XQ0085 团购数据核对/logic/com_refresh.py` |
|
||||||
|
| 参考交接文档风格 | `docs/需求单/XQ0001-0100/XQ0012 EHR预支及支付报酬自动发起ERP付款申请/交接文档.md` |
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 10. 对比表核对:回填 + 退款冲减 + 分组验证(2026-11-27)
|
||||||
|
|
||||||
|
> 本节取代 §3.3~§3.5 的「逐行 W 必须为 0」口径;§3.3 的滚动顺序(Q = R - S)仍然保留。
|
||||||
|
|
||||||
|
### 10.1 新口径
|
||||||
|
|
||||||
|
1. **今日遗留(R)不再人工填**:按对比表 A 列门店 + B 列核销项目名称,从【团购统计】G 列
|
||||||
|
「未消费项目个数」汇总回填;取数类型与对比表 C/D 的 SUMIFS 一致:
|
||||||
|
美团 = `{美团, 点评}`,抖音 = `{抖音}`(`config.COMPARE_STATS_TYPES`)。
|
||||||
|
2. **验证改为分组**:按 E 列门店 + F 列项目分组,**组内 W 求和为 0 才算平**;
|
||||||
|
W 为 `-`/空 的行不参与(`config.COMPARE_VERIFY_SKIP`),整组都是 `-` 的不计入。
|
||||||
|
3. **归并名单**(`config.COMPARE_GROUP_MEMBERS`):
|
||||||
|
- 二选一 = {二选一, 艾养耳道, 头舒耳道}
|
||||||
|
- 四选一 = {四选一, 专项头疗, 专项采耳, 经络刮痧, 五行火罐}
|
||||||
|
- `艾灸耳道` **不并入**(团购统计里没有该核销项目名,回填值为空);
|
||||||
|
- 对比表 F 列公式本身已把含「五行」→四选一、含「头舒耳道」→二选一,代码只补剩余成员。
|
||||||
|
4. **退款/撤销核销冲减**:从本地美团表【订单收入明细表】C 列「业务类型」、抖音表【核销明细】
|
||||||
|
I 列「核销状态」取 `已消费退 / 撤销核销 / 核销后退款 / 已撤销核销` 的行,**按行数**计,
|
||||||
|
同门店同项目从今日遗留里扣掉(不按日期筛)。
|
||||||
|
- 门店与项目先按该表【基础信息】映射:`A 平台门店→B 内部门店`、`E 平台商品名→F 内部项目`
|
||||||
|
(实测美团 23/23、抖音 8/8 全部命中);
|
||||||
|
- 门店精确查不到时,用平台名括号里的店名(`…(成渝立交店)` → `成渝立交`)匹配总表门店;
|
||||||
|
- 项目在对比表里没有同名行时,按归并组扣在组内第一行(如基础信息把「专项采耳」映射成「四选一」);
|
||||||
|
- 都对不上的列入日志,不冲减。
|
||||||
|
5. **不平只出明细**:`ok` 仍为 True,结果里带 `groups_total / groups_ok / unbalanced[(门店, 项目, 差额)]`。
|
||||||
|
6. **双人餐/三人餐补平台结错**:前面步骤跑完仍不平、且餐行自身不为 0 时,在【平台结错】列按**差额倍数**补:
|
||||||
|
`N = 餐行差额`(如餐行 -3 则 N=3),餐行 J = `N`、同门店基础项目行 J = `-2N`(双人餐)/ `-3N`(三人餐)。
|
||||||
|
例:`印象贵足 +6`、`印象贵足双人餐 -3` → 两行各写 -6 / 3 后都归零。
|
||||||
|
- 基础行不为正(如 -7)时不写,避免把差额越改越大,列入 `meal_skipped` 告警;
|
||||||
|
- 同一基础行遇到双人+三人餐同时不平,按各自 N 累加;
|
||||||
|
- 改完仍不平的保留差额,最终分组验证里报出来。
|
||||||
|
|
||||||
|
### 10.2 执行顺序(`compare_sheets.run()`)
|
||||||
|
|
||||||
|
1. 定位列:表头第 4 行的 Q/R/S(按标题)、A/B(第 1 个「门店」「核销项目名称」,回填用原始名)、
|
||||||
|
E/F(第 2 个,分组用)、W(「验证」)、J(「平台结错」);
|
||||||
|
2. 读【团购统计】→ 生成今日遗留回填计划;
|
||||||
|
3. 读本地美团 / 抖音表的【基础信息】与退款 sheet → 生成同门店同项目的冲减笔数;
|
||||||
|
4. 判重:当前 R 已等于「未消费 − 退款笔数」→ 跳过写入(`compare_force=true` 强制);
|
||||||
|
5. 生成 edits:清 I/J/K、清漏核销、Q = 昨天的 R − S(X 备注过滤)、R = 团购统计未消费 − 退款笔数;
|
||||||
|
6. zip+XML 写盘 → COM 重算 → 按 E/F 分组核 W;
|
||||||
|
7. 仍不平的双人餐/三人餐配对 → 写【平台结错】→ 再重算 → 再核一次;
|
||||||
|
8. 【团购统计】没有该平台数据时**整个 sheet 中止、不动表**(既不能回填也无法判重)。
|
||||||
|
|
||||||
|
### 10.3 代码位置
|
||||||
|
|
||||||
|
| 内容 | 位置 |
|
||||||
|
|---|---|
|
||||||
|
| 归并 / 取数 / 回填 / 退款冲减 / 分组验证 / 平台结错 | `logic/compare_groups.py`(新增,纯函数:`norm_item` / `load_unused` / `load_refunds` / `_match_store` / `build_fill_edits` / `verify` / `build_meal_edits`) |
|
||||||
|
| 编排、写盘、日志 | `logic/compare_sheets.py`(`_plan_sheet` / `run` / `_locate_group_cols` / `_locate_title_col` / `_log_refund`) |
|
||||||
|
| 常量 | `config/__init__.py` 的 `COMPARE_GROUP_*` / `COMPARE_STATS_*` / `COMPARE_VERIFY_SKIP` / `COMPARE_MEAL_*` / `COMPARE_PLATFORM_ERROR_*` / `COMPARE_REFUND_GROUPS` / `COMPARE_BASE_INFO_*` |
|
||||||
|
| 抖音补贴团购统计 | `__init__.py` `_run_douyin()`:`paste_to_master.run(jobs_filter=['douyin', 'group'])` |
|
||||||
|
| 单测 | `tests/unit/test_xq0085_compare_groups.py`(20 项)+ 更新后的 `test_xq0085_compare.py` |
|
||||||
|
|
||||||
|
### 10.4 实测(9.30 完成态副本,等价于处理 10.1)
|
||||||
|
|
||||||
|
| 项 | 美团 | 抖音 |
|
||||||
|
|---|---|---|
|
||||||
|
| 分组数 | 6564 | 6564 |
|
||||||
|
| 平 / 不平 | 6499 / 65 | 6548 / 16 |
|
||||||
|
| 今日遗留回填 | 40 行非零(含负数) | 25 行非零 |
|
||||||
|
| 退款/撤销核销 | 23 行 → 18 个门店项目 | 8 行 → 7 个门店项目 |
|
||||||
|
| 平台结错修正 | 6 对 | 5 对 |
|
||||||
|
| COM 重算 | WPS 成功(刷新透视 0 次,两次) | WPS 成功 |
|
||||||
|
|
||||||
|
- 退款冲减示例:`加州CEO会馆/印象贵足` 未消费 1、退款 2 笔 → 今日遗留 -1;
|
||||||
|
`北城天街CEO会馆/龙手足道` 未消费 5、退款 1 笔 → 4;
|
||||||
|
- 对比不含退款时(上一版):美团 6480/84、抖音 6531/33,说明退款冲减把差异消掉了一大半;
|
||||||
|
- 不平台阶示例:`印象贵足 +2 / 印象贵足双人餐 -1` → J 写 `-2 / 1` 后两行都归零;
|
||||||
|
`+3/-1` 只补 `-2`,基础行留 `+1`,按「保留剩余差额」报在最终明细里;
|
||||||
|
- 美团仍有 65 组不平,其中约 30 组是 `测试7` 测试数据;
|
||||||
|
- 重复运行不传 `force` 会判定「已回填」并跳过,文件字节级不变(已实测);
|
||||||
|
- 注意:完成态表再跑一次等于进入下一天,数值不能直接当 9.30 的业务结论。
|
||||||
|
|
||||||
|
### 10.5 使用注意
|
||||||
|
|
||||||
|
- **R 现在是脚本写入列**:手工改 R 会在下次运行时被覆盖(除非 `dry_run`)。
|
||||||
|
- **J(平台结错)也由脚本重写**:每天先清空,再按双人餐/三人餐规则写回;人工在 J 上的其它调整会被清掉。
|
||||||
|
- 退款/撤销核销**不按日期筛**:表里有几条就扣几笔(美团表本身已按营业日筛选过,
|
||||||
|
抖音核销明细是整份导出,跨天行也会计入)。
|
||||||
|
- 回填按 **A/B 原始项目名**查团购统计(不是 E/F);E/F 的 F 会把「五行火罐→四选一」「头舒耳道→二选一」,
|
||||||
|
用 F 查会漏掉这两类项目的未消费。
|
||||||
|
- 面值券别名(如「1240代1500随心兑」)在团购统计里没有对应核销项目名,回填留空,日志会列前 10 个。
|
||||||
|
- 团购统计的消费日期与营业日不一致时会 WARN,提示可能没贴当天数据。
|
||||||
|
|
||||||
|
---
|
||||||
|
|
||||||
|
## 11. 新版 31 列模板适配(2026-11-27,11-24 实跑)
|
||||||
|
|
||||||
|
### 11.1 模板变化与对应处理
|
||||||
|
|
||||||
|
| 变化 | 处理 |
|
||||||
|
|---|---|
|
||||||
|
| 美团导出/订单收入明细表改成 31 列(`账户名称…账单周期` + AC~AI 辅助列) | `config.DAILY_EXPORT_TO_TARGET` 按 11-24 真实数据反推的列映射;`daily_detail` 重写 |
|
||||||
|
| 平台把「收益类型 / 业务类型」两个名字对调 | 目标 B(收益类型)← 导出 4(业务类型:团购/其他);目标 C(业务类型)← 导出 3(收益类型:已核销…) |
|
||||||
|
| 导出 31「账单周期」是合并单元格,读出来只有「至」 | 目标 AB 取导出 30(与现有表一致) |
|
||||||
|
| 明细表有 8 个透视 + 6 个外部链接 | 写盘改成 zip+XML(`logic/sheet_xml.py`),不再用 openpyxl 保存 |
|
||||||
|
| `daily_detail` 原来没有 `wb.save()`,改了不落盘 | 已随重写修掉 |
|
||||||
|
| dimension 被写成 1×1 / 100 万行 | 各处读取加 `reset_dimensions()`;否则抖音导出读 0 行、美团表非只读打开会卡死 |
|
||||||
|
| WPS 保存后 zip 条目重叠(透视缓存报 BadZipFile) | zip 写入从流式 + Zip64 改为整条 `writestr` |
|
||||||
|
| 报表 I~P 是固定 904 行公式块,刷新后尾部 462 行 `#N/A` | 贴总表时过滤错误行(`paste_to_master._read_values`) |
|
||||||
|
| 营业日口径 | 统一按 **10 点切日**(当日 10:00 ~ 次日 09:59),明细、退款、透视一致 |
|
||||||
|
| 平台结错倍数 | `N = 餐行差额`,餐行 J = N、基础行 J = -2N/-3N |
|
||||||
|
|
||||||
|
### 11.2 11-24 实跑结果(输入用根目录 `团购收益明细_20261124_20261125.xlsx`)
|
||||||
|
|
||||||
|
| 项 | 结果 |
|
||||||
|
|---|---|
|
||||||
|
| 明细合并 | 3060 行(10 点切日),与现有表 3171/3182 行逐单元格一致 |
|
||||||
|
| 贴总表 | 平台-新美大 515 行、团购统计 964 行 |
|
||||||
|
| 对比表 | 7197 组,平 7196,不平 1 |
|
||||||
|
| 与 `马敏团购总表11.24.bak.xlsx` | 昨日遗留 Q 0 行差异;今日遗留 R 1 行;验证 W 1 行 |
|
||||||
|
|
||||||
|
唯一差异:`成渝立交行政会馆/印象贵足`,`.bak` 手工填了今日遗留 2(团购统计未消费为 0),按规则回填 0,W 差 -2。
|
||||||
|
|
||||||
|
### 11.3 待修
|
||||||
|
|
||||||
|
- **抖音四口径的「明细 / 转换」为 0**:核销明细的 BS(营业日,`=IF(HOUR(L)<10,…)`)与转换表 BQ 是辅助公式列,
|
||||||
|
粘贴后没有按新数据重算,导致明细口径筛不到行;这是抖音对比表 78 组不平的主因。
|
||||||
|
- 抖音单次运行约 12 分钟(核销明细 9615 行 + 两次 COM 重算),性能后续可优化。
|
||||||
@@ -2,12 +2,14 @@
|
|||||||
"""XQ0085 团购数据核对 —— 美团核对 + 抖音核对,两条独立分支。
|
"""XQ0085 团购数据核对 —— 美团核对 + 抖音核对,两条独立分支。
|
||||||
|
|
||||||
从 XQ0041 抽出核对部分,插件自包含、不开浏览器、不做下载。共享盘全程只读:
|
从 XQ0041 抽出核对部分,插件自包含、不开浏览器、不做下载。共享盘全程只读:
|
||||||
先把当天的核对表从共享盘复制到本地 ``WORK_DIR/_work/``,后续所有处理只改本地副本。
|
先把当天的核对表从共享盘复制到本地 ``<根>\过程表``(各分支共用,马敏总表只此一份),
|
||||||
|
后续所有处理都只改这份本地副本;导出明细与产物各落 ``<根>\美团`` / ``<根>\抖音``。
|
||||||
|
通联扫码统计表已拆到独立插件 XQ0082。
|
||||||
|
|
||||||
* ``check_meituan``:复制共享表 → 订单收入明细合并+合计 → 基础信息补维护
|
* ``check_meituan``:复制共享表 → 订单收入明细合并+合计 → 基础信息补维护
|
||||||
→ 报表按值贴入本地马敏总表副本(平台-新美大 + CRM 团购统计);
|
→ 门店归属 → 报表按值贴入本地马敏总表副本(平台-新美大 + CRM 团购统计)→ 对比表核对;
|
||||||
* ``check_douyin``:复制共享表 → 核销明细 A~BR 重贴 → 四口径预计收入合计校验
|
* ``check_douyin``:复制共享表 → 核销明细 A~BR 重贴 → 四口径预计收入合计校验
|
||||||
→ 基础信息补维护 → 抖音报表 N~Z 按值贴入本地总表副本(平台-抖音)。
|
→ 基础信息补维护 → 抖音报表 N~Z 按值贴入本地总表副本(平台-抖音)→ 对比表核对。
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
from datetime import date, datetime, timedelta
|
from datetime import date, datetime, timedelta
|
||||||
@@ -15,7 +17,8 @@ from datetime import date, datetime, timedelta
|
|||||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||||
|
|
||||||
from . import config
|
from . import config
|
||||||
from .logic import base_info_sync, daily_detail, douyin_daily, paste_to_master, share_copy
|
from .logic import (base_info_sync, compare_sheets, daily_detail, douyin_daily,
|
||||||
|
paste_to_master, preflight, share_copy, store_map)
|
||||||
|
|
||||||
ACTION_CHECK_MEITUAN = 'check_meituan'
|
ACTION_CHECK_MEITUAN = 'check_meituan'
|
||||||
ACTION_CHECK_DOUYIN = 'check_douyin'
|
ACTION_CHECK_DOUYIN = 'check_douyin'
|
||||||
@@ -47,13 +50,16 @@ def _check_day(fields):
|
|||||||
class Xq0085Plugin(ScenePlugin):
|
class Xq0085Plugin(ScenePlugin):
|
||||||
id = 'xq0085'
|
id = 'xq0085'
|
||||||
name = '团购数据核对'
|
name = '团购数据核对'
|
||||||
version = '1.0.0'
|
version = '1.1.0'
|
||||||
description = ('团购数据核对(美团 + 抖音两条独立分支,共享盘只读):'
|
description = ('团购数据核对(美团 + 抖音两条独立分支;通联扫码统计表已拆到 XQ0082)。'
|
||||||
'先把当天的核对表从共享盘复制到本地 _work,再全部在本地副本上处理。'
|
'两条分支都先把当天的核对表从共享盘复制到本地「过程表」,再全部在本地副本上处理:'
|
||||||
'美团核对:团购+预订收益明细合并贴入【订单收入明细表】、明细/透视/报表三口径合计校验、'
|
'美团核对:团购+预订收益明细合并贴入【订单收入明细表】、明细/透视/报表三口径合计校验、'
|
||||||
'报表 #N/A 基础信息补维护、报表按值贴入马敏总表【平台-新美大】与 CRM【团购统计】。'
|
'报表 #N/A 基础信息补维护、门店归属(CRM 券号 join,输出门店核对表)、'
|
||||||
|
'报表按值贴入马敏总表【平台-新美大】与 CRM【团购统计】。'
|
||||||
'抖音核对:导出核销明细 A~BR 重贴【核销明细】、明细/透视/报表/转换四口径预计收入合计校验、'
|
'抖音核对:导出核销明细 A~BR 重贴【核销明细】、明细/透视/报表/转换四口径预计收入合计校验、'
|
||||||
'报表 O/P 基础信息补维护、报表按值贴入【平台-抖音】。')
|
'报表 O/P 基础信息补维护、报表按值贴入【平台-抖音】。'
|
||||||
|
'两条分支最后都做对比表核对:滚动昨日遗留、按团购统计未消费回填今日遗留、'
|
||||||
|
'退款/撤销核销冲减、按门店+项目分组校验验证列、双人餐/三人餐补平台结错。')
|
||||||
platform = ''
|
platform = ''
|
||||||
uses_month = False
|
uses_month = False
|
||||||
capabilities = ['xq0085']
|
capabilities = ['xq0085']
|
||||||
@@ -72,8 +78,15 @@ class Xq0085Plugin(ScenePlugin):
|
|||||||
'default': True},
|
'default': True},
|
||||||
'run_base_info': {'type': 'boolean', 'title': '美团-基础信息补维护(报表 #N/A)',
|
'run_base_info': {'type': 'boolean', 'title': '美团-基础信息补维护(报表 #N/A)',
|
||||||
'default': True},
|
'default': True},
|
||||||
|
'run_store_map': {'type': 'boolean', 'title': '美团-门店归属(CRM 券号)',
|
||||||
|
'default': True},
|
||||||
'run_paste_master': {'type': 'boolean', 'title': '按值贴入马敏总表(只写本地副本)',
|
'run_paste_master': {'type': 'boolean', 'title': '按值贴入马敏总表(只写本地副本)',
|
||||||
'default': True},
|
'default': True},
|
||||||
|
'run_compare': {'type': 'boolean',
|
||||||
|
'title': '核对-对比表滚动+今日遗留回填',
|
||||||
|
'default': True},
|
||||||
|
'compare_force': {'type': 'boolean', 'title': '核对-强制重跑',
|
||||||
|
'default': False},
|
||||||
'run_douyin_daily': {'type': 'boolean', 'title': '抖音-核销明细重贴+四口径合计',
|
'run_douyin_daily': {'type': 'boolean', 'title': '抖音-核销明细重贴+四口径合计',
|
||||||
'default': True},
|
'default': True},
|
||||||
'run_douyin_base': {'type': 'boolean', 'title': '抖音-基础信息补维护(报表 O/P)',
|
'run_douyin_base': {'type': 'boolean', 'title': '抖音-基础信息补维护(报表 O/P)',
|
||||||
@@ -90,20 +103,23 @@ class Xq0085Plugin(ScenePlugin):
|
|||||||
config.set_log(ctx.log)
|
config.set_log(ctx.log)
|
||||||
config.set_progress(ctx.progress)
|
config.set_progress(ctx.progress)
|
||||||
config.set_debug(fields.get('debug_mode'))
|
config.set_debug(fields.get('debug_mode'))
|
||||||
config.set_work_dir(fields.get('save_dir'))
|
|
||||||
|
|
||||||
action = _resolve_action(fields)
|
action = _resolve_action(fields)
|
||||||
|
# 工作目录按分支取默认:美团 → 新美大平台核对,抖音 → 抖音平台核对
|
||||||
|
work_dir = config.set_work_dir(fields.get('save_dir'), action=action)
|
||||||
day = _check_day(fields)
|
day = _check_day(fields)
|
||||||
dry = bool(fields.get('dry_run'))
|
dry = bool(fields.get('dry_run'))
|
||||||
use_com = bool(fields.get('use_com_refresh', True))
|
use_com = bool(fields.get('use_com_refresh', True))
|
||||||
share_root = str(fields.get('share_root') or '').strip()
|
share_root = str(fields.get('share_root') or '').strip()
|
||||||
copy_share = bool(fields.get('copy_share_table', True))
|
copy_share = bool(fields.get('copy_share_table', True))
|
||||||
detail = {'action': action, 'day': day.isoformat(), 'share': None,
|
detail = {'action': action, 'day': day.isoformat(), 'work_dir': work_dir,
|
||||||
'daily': None, 'base_info': None, 'paste': None,
|
'out_dir': config.OUT_DIR, 'share': None, 'preflight': None,
|
||||||
'douyin': None, 'results': {}}
|
'daily': None, 'base_info': None, 'store': None, 'paste': None,
|
||||||
|
'compare': None, 'douyin': None, 'results': {}}
|
||||||
|
|
||||||
config.log(f'== {self.name} {action} 营业日 {day.isoformat()} '
|
config.log(f'== {self.name} {action} 营业日 {day.isoformat()} '
|
||||||
+ ('(只核对不写入)' if dry else '') + ' ==')
|
+ ('(只核对不写入)' if dry else '') + ' ==')
|
||||||
|
config.log(f'过程表目录:{work_dir};分支产物目录:{config.OUT_DIR}')
|
||||||
ctx.progress(3)
|
ctx.progress(3)
|
||||||
|
|
||||||
# ---------- 第 1 步:共享盘只读复制当天表到本地 ----------
|
# ---------- 第 1 步:共享盘只读复制当天表到本地 ----------
|
||||||
@@ -112,7 +128,7 @@ class Xq0085Plugin(ScenePlugin):
|
|||||||
if action == ACTION_CHECK_MEITUAN
|
if action == ACTION_CHECK_MEITUAN
|
||||||
else [config.DOUYIN_SHARE_KEYWORD, config.LINK_BOOK])
|
else [config.DOUYIN_SHARE_KEYWORD, config.LINK_BOOK])
|
||||||
sc = share_copy.copy_prev_tables(share_root=share_root, day=day,
|
sc = share_copy.copy_prev_tables(share_root=share_root, day=day,
|
||||||
keywords=keywords, dry_run=dry)
|
keywords=keywords, dry_run=dry)
|
||||||
config.log(sc.get('message') or '')
|
config.log(sc.get('message') or '')
|
||||||
detail['share'] = sc
|
detail['share'] = sc
|
||||||
if not sc.get('ok'):
|
if not sc.get('ok'):
|
||||||
@@ -126,7 +142,11 @@ class Xq0085Plugin(ScenePlugin):
|
|||||||
self._run_douyin(fields, day, dry, use_com, detail, ctx)
|
self._run_douyin(fields, day, dry, use_com, detail, ctx)
|
||||||
|
|
||||||
ctx.progress(100)
|
ctx.progress(100)
|
||||||
parts = [f'美团核对' if action == ACTION_CHECK_MEITUAN else '抖音核对']
|
parts = [{ACTION_CHECK_MEITUAN: '美团核对',
|
||||||
|
ACTION_CHECK_DOUYIN: '抖音核对'}[action]]
|
||||||
|
pf = detail.get('preflight')
|
||||||
|
if pf is not None:
|
||||||
|
parts.append('前置预检通过' if pf.get('ok') else '前置预检未通过(已中止)')
|
||||||
if detail['daily'] and detail['daily'].get('ok'):
|
if detail['daily'] and detail['daily'].get('ok'):
|
||||||
d = detail['daily']
|
d = detail['daily']
|
||||||
parts.append(f'明细{d["detail_rows"]}行 合计{d["total"]:.2f}')
|
parts.append(f'明细{d["detail_rows"]}行 合计{d["total"]:.2f}')
|
||||||
@@ -135,14 +155,42 @@ class Xq0085Plugin(ScenePlugin):
|
|||||||
parts.append(f'核销明细{d["detail_rows"]}行 四口径'
|
parts.append(f'核销明细{d["detail_rows"]}行 四口径'
|
||||||
f'{d["detail_total"]:.2f}/{d["pivot_total"]:.2f}/'
|
f'{d["detail_total"]:.2f}/{d["pivot_total"]:.2f}/'
|
||||||
f'{d["report_total"]:.2f}/{d["convert_total"]:.2f}')
|
f'{d["report_total"]:.2f}/{d["convert_total"]:.2f}')
|
||||||
|
if detail['store'] and detail['store'].get('ok'):
|
||||||
|
s = detail['store']
|
||||||
|
parts.append(f'门店归属 {s["mapped"]} 行 / {s["stores"]} 家店')
|
||||||
if detail['paste'] and detail['paste'].get('ok'):
|
if detail['paste'] and detail['paste'].get('ok'):
|
||||||
p = detail['paste']
|
p = detail['paste']
|
||||||
parts.append(f'总表粘贴 新美大{p["meituan_rows"]}/团购{p["group_rows"]}/'
|
parts.append(f'总表粘贴 新美大{p["meituan_rows"]}/团购{p["group_rows"]}/'
|
||||||
f'抖音{p["douyin_rows"]}行')
|
f'抖音{p["douyin_rows"]}行')
|
||||||
|
if detail['compare']:
|
||||||
|
c = detail['compare']
|
||||||
|
if c.get('skipped'):
|
||||||
|
parts.append(f'对比表跳过({c["skipped"]})')
|
||||||
|
elif c.get('ok'):
|
||||||
|
parts.append(f'对比表滚动{c["rows"]}行、今日遗留回填{c.get("fill_rows", 0)}行'
|
||||||
|
+ (f'(退款冲减{c["refund_rows"]}行)' if c.get('refund_rows') else '')
|
||||||
|
+ f',分组{c.get("groups_total", 0)}组平{c.get("groups_ok", 0)}/'
|
||||||
|
f'不平{c.get("unbalanced_count", 0)}'
|
||||||
|
+ (f',平台结错修正{len(c.get("meal_adjust") or [])}对'
|
||||||
|
if c.get('meal_adjust') else ''))
|
||||||
|
ok = bool((detail.get('preflight') or {}).get('ok', True))
|
||||||
config.log('完成:' + ';'.join(parts))
|
config.log('完成:' + ';'.join(parts))
|
||||||
return {'ok': True, 'message': ';'.join(parts), 'detail': detail}
|
return {'ok': ok, 'message': ';'.join(parts), 'detail': detail}
|
||||||
|
|
||||||
|
def _preflight(self, fields, day, action, detail):
|
||||||
|
"""核对前置预检:缺文件 / 日期不符 / 同类多份时直接中止,不写任何表。"""
|
||||||
|
pf = preflight.run(day=day, action=action, crm_dir=fields.get('crm_dir'))
|
||||||
|
for c in pf.get('warns') or []:
|
||||||
|
config.log(f'预检 {c["name"]}:{c["message"]}', 'WARN')
|
||||||
|
config.log(pf.get('message') or '')
|
||||||
|
detail['preflight'] = pf
|
||||||
|
if not pf.get('ok'):
|
||||||
|
config.log('前置预检未通过,已中止本次核对(未改动任何表)', 'WARN')
|
||||||
|
return bool(pf.get('ok'))
|
||||||
|
|
||||||
def _run_meituan(self, fields, day, dry, use_com, detail, ctx):
|
def _run_meituan(self, fields, day, dry, use_com, detail, ctx):
|
||||||
|
if not self._preflight(fields, day, ACTION_CHECK_MEITUAN, detail):
|
||||||
|
return
|
||||||
if bool(fields.get('run_daily_detail', True)):
|
if bool(fields.get('run_daily_detail', True)):
|
||||||
ctx.progress(35)
|
ctx.progress(35)
|
||||||
d = daily_detail.run(day=day, dry_run=dry, use_com=use_com)
|
d = daily_detail.run(day=day, dry_run=dry, use_com=use_com)
|
||||||
@@ -159,6 +207,15 @@ class Xq0085Plugin(ScenePlugin):
|
|||||||
if bi.get('ok') and (bi.get('new_shops') or bi.get('new_items')):
|
if bi.get('ok') and (bi.get('new_shops') or bi.get('new_items')):
|
||||||
config.log(f'基础信息需补维护:新增门店 {len(bi["new_shops"])} / '
|
config.log(f'基础信息需补维护:新增门店 {len(bi["new_shops"])} / '
|
||||||
f'套餐 {len(bi["new_items"])}', 'WARN')
|
f'套餐 {len(bi["new_items"])}', 'WARN')
|
||||||
|
if bool(fields.get('run_store_map', True)):
|
||||||
|
# 门店归属:券号 join CRM,输出「门店核对_起_止.xlsx」与累积映射表(不动任何表)
|
||||||
|
ctx.progress(65)
|
||||||
|
sm = store_map.run(dry_run=dry, progress_from=62, progress_to=74)
|
||||||
|
config.log(sm.get('message') or '')
|
||||||
|
detail['store'] = sm
|
||||||
|
if not sm.get('ok'):
|
||||||
|
# crm_sdk 未挂载 / CRM 未登录只告警:不影响明细、基础信息与总表粘贴
|
||||||
|
config.log(f'门店归属未完成:{sm.get("message")}', 'WARN')
|
||||||
if bool(fields.get('run_paste_master', True)):
|
if bool(fields.get('run_paste_master', True)):
|
||||||
ctx.progress(75)
|
ctx.progress(75)
|
||||||
pm = paste_to_master.run(day=day, dry_run=dry, jobs_filter=['meituan', 'group'])
|
pm = paste_to_master.run(day=day, dry_run=dry, jobs_filter=['meituan', 'group'])
|
||||||
@@ -166,8 +223,23 @@ class Xq0085Plugin(ScenePlugin):
|
|||||||
detail['paste'] = pm
|
detail['paste'] = pm
|
||||||
if not pm.get('ok'):
|
if not pm.get('ok'):
|
||||||
config.log(f'马敏总表粘贴未完成:{pm.get("message")}', 'WARN')
|
config.log(f'马敏总表粘贴未完成:{pm.get("message")}', 'WARN')
|
||||||
|
if bool(fields.get('run_compare', True)):
|
||||||
|
# 核对第一步:总表副本是昨天的表,今日遗留先滚到昨日遗留,再清今日遗留/IJK/漏核销
|
||||||
|
ctx.progress(85)
|
||||||
|
self._run_compare(fields, day, ACTION_CHECK_MEITUAN, dry, detail)
|
||||||
|
|
||||||
|
def _run_compare(self, fields, day, action, dry, detail):
|
||||||
|
cs = compare_sheets.run(day=day, action=action, dry_run=dry,
|
||||||
|
use_com=bool(fields.get('use_com_refresh', True)),
|
||||||
|
force=bool(fields.get('compare_force')))
|
||||||
|
config.log(cs.get('message') or '')
|
||||||
|
detail['compare'] = cs
|
||||||
|
if not cs.get('ok'):
|
||||||
|
config.log(f'对比表日滚动未完成:{cs.get("message")}', 'WARN')
|
||||||
|
|
||||||
def _run_douyin(self, fields, day, dry, use_com, detail, ctx):
|
def _run_douyin(self, fields, day, dry, use_com, detail, ctx):
|
||||||
|
if not self._preflight(fields, day, ACTION_CHECK_DOUYIN, detail):
|
||||||
|
return
|
||||||
if bool(fields.get('run_douyin_daily', True)):
|
if bool(fields.get('run_douyin_daily', True)):
|
||||||
ctx.progress(35)
|
ctx.progress(35)
|
||||||
dy = douyin_daily.run(day=day, dry_run=dry, use_com=use_com)
|
dy = douyin_daily.run(day=day, dry_run=dry, use_com=use_com)
|
||||||
@@ -180,11 +252,15 @@ class Xq0085Plugin(ScenePlugin):
|
|||||||
detail['base_info'] = (detail['douyin'] or {}).get('base_info')
|
detail['base_info'] = (detail['douyin'] or {}).get('base_info')
|
||||||
if bool(fields.get('run_paste_master', True)):
|
if bool(fields.get('run_paste_master', True)):
|
||||||
ctx.progress(75)
|
ctx.progress(75)
|
||||||
pm = paste_to_master.run(day=day, dry_run=dry, jobs_filter=['douyin'])
|
# 抖音对比(2)的 C/D 与今日遗留回填都依赖【团购统计】,必须一起贴当天数据
|
||||||
|
pm = paste_to_master.run(day=day, dry_run=dry, jobs_filter=['douyin', 'group'])
|
||||||
config.log(pm.get('message') or '')
|
config.log(pm.get('message') or '')
|
||||||
detail['paste'] = pm
|
detail['paste'] = pm
|
||||||
if not pm.get('ok'):
|
if not pm.get('ok'):
|
||||||
config.log(f'平台-抖音粘贴未完成:{pm.get("message")}', 'WARN')
|
config.log(f'平台-抖音粘贴未完成:{pm.get("message")}', 'WARN')
|
||||||
|
if bool(fields.get('run_compare', True)):
|
||||||
|
ctx.progress(85)
|
||||||
|
self._run_compare(fields, day, ACTION_CHECK_DOUYIN, dry, detail)
|
||||||
|
|
||||||
|
|
||||||
PLUGINS.append(Xq0085Plugin)
|
PLUGINS.append(Xq0085Plugin)
|
||||||
|
|||||||
@@ -1,27 +1,48 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""xq0085 团购数据核对 打包脚本:生成 dist-plugin/xq0085_v<版本>.zip。
|
"""xq0085 团购数据核对 打包脚本:生成 dist-plugin/xq0085_v<版本>.zip。
|
||||||
|
|
||||||
|
排除:ui-src(前端源码,发布包只要构建产物 ui/)、node_modules、__pycache__、
|
||||||
|
debug、.sessions、本脚本、*.pyc/*.pyo。
|
||||||
|
声明了 ``"ui": true`` 时必须先构建出 ``ui/index.html``,否则直接报错。
|
||||||
|
|
||||||
用法:.venv\\Scripts\\python.exe plugins\\XQ0001-0100\\XQ0085 团购数据核对\\_pack.py
|
用法:.venv\\Scripts\\python.exe plugins\\XQ0001-0100\\XQ0085 团购数据核对\\_pack.py
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import sys
|
||||||
import zipfile
|
import zipfile
|
||||||
|
|
||||||
HERE = os.path.dirname(os.path.abspath(__file__))
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
||||||
ROOT = os.path.abspath(os.path.join(HERE, '..', '..', '..'))
|
ROOT = os.path.abspath(os.path.join(HERE, '..', '..', '..'))
|
||||||
OUT = os.path.join(ROOT, 'dist-plugin')
|
OUT = os.path.join(ROOT, 'dist-plugin')
|
||||||
|
EXCLUDE_DIRS = {'ui-src', 'node_modules', '__pycache__', 'debug', '.sessions'}
|
||||||
|
EXCLUDE_FILES = {'_pack.py'}
|
||||||
|
|
||||||
with open(os.path.join(HERE, 'plugin.json'), encoding='utf-8') as fp:
|
|
||||||
manifest = json.load(fp)
|
|
||||||
name = 'xq%s_v%s.zip' % (manifest['id'].replace('xq', ''), manifest['version'])
|
|
||||||
os.makedirs(OUT, exist_ok=True)
|
|
||||||
target = os.path.join(OUT, name)
|
|
||||||
|
|
||||||
with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as zf:
|
def main():
|
||||||
for dirpath, _, files in os.walk(HERE):
|
with open(os.path.join(HERE, 'plugin.json'), encoding='utf-8') as fp:
|
||||||
for f in files:
|
manifest = json.load(fp)
|
||||||
if f == '_pack.py' or f.endswith('.pyc'):
|
|
||||||
continue
|
if manifest.get('ui') and not os.path.isfile(os.path.join(HERE, 'ui', 'index.html')):
|
||||||
full = os.path.join(dirpath, f)
|
sys.exit('插件声明了 ui: true,但缺少 ui/index.html;请先在 ui-src 下执行 npm run build')
|
||||||
zf.write(full, os.path.relpath(full, HERE))
|
|
||||||
print(target)
|
name = 'xq%s_v%s.zip' % (manifest['id'].replace('xq', ''), manifest['version'])
|
||||||
|
os.makedirs(OUT, exist_ok=True)
|
||||||
|
target = os.path.join(OUT, name)
|
||||||
|
|
||||||
|
with zipfile.ZipFile(target, 'w', zipfile.ZIP_DEFLATED) as zf:
|
||||||
|
for dirpath, dirnames, files in os.walk(HERE):
|
||||||
|
dirnames[:] = [d for d in dirnames if d not in EXCLUDE_DIRS]
|
||||||
|
for f in files:
|
||||||
|
if f in EXCLUDE_FILES or f.endswith(('.pyc', '.pyo')):
|
||||||
|
continue
|
||||||
|
full = os.path.join(dirpath, f)
|
||||||
|
rel = os.path.relpath(full, HERE)
|
||||||
|
zf.write(full, rel)
|
||||||
|
|
||||||
|
size = os.path.getsize(target) / 1024
|
||||||
|
print(f'{target}({size:.0f} KB)')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
main()
|
||||||
|
|||||||
@@ -3,8 +3,9 @@
|
|||||||
|
|
||||||
从 XQ0041 抽出「美团核对」「抖音核对」两条线,插件自包含:
|
从 XQ0041 抽出「美团核对」「抖音核对」两条线,插件自包含:
|
||||||
只依赖标准库 / 第三方库 / 底座注入的 RunContext。
|
只依赖标准库 / 第三方库 / 底座注入的 RunContext。
|
||||||
共享盘全程只读,所有表先复制到本地 ``WORK_DIR/_work/`` 再处理。
|
共享盘全程只读,所有表先复制到本地过程表目录(``<根>\过程表``)再处理。
|
||||||
"""
|
"""
|
||||||
|
import glob
|
||||||
import os
|
import os
|
||||||
import time
|
import time
|
||||||
|
|
||||||
@@ -52,18 +53,68 @@ def progress(pct):
|
|||||||
|
|
||||||
|
|
||||||
# ==================== 工作目录 ====================
|
# ==================== 工作目录 ====================
|
||||||
DEFAULT_WORK_DIR = r'D:\资料\财务\新美大平台核对'
|
# 默认根目录 ``D:\\资料\\财务\\团购数据核对``,下面固定三个子目录:
|
||||||
WORK_DIR = DEFAULT_WORK_DIR
|
# 美团\\ 美团核对:团购/预订收益明细导出、门店核对_*.xlsx、门店映射表.json
|
||||||
|
# 抖音\\ 抖音核对:核销明细导出、抖音侧产物
|
||||||
|
# 过程表\\ 共享盘只读复制来的核对表与马敏团购总表(美团/抖音共用一份,只改本地副本)
|
||||||
|
# 通联扫码统计表已拆到独立插件 XQ0082,本插件不再使用 通联\\ 目录。
|
||||||
|
# 界面「本地工作目录」填的是根目录,留空回默认根。
|
||||||
|
DEFAULT_ROOT_DIR = r'D:\资料\财务\团购数据核对'
|
||||||
|
SUBDIR_MEITUAN = '美团'
|
||||||
|
SUBDIR_DOUYIN = '抖音'
|
||||||
|
SUBDIR_PROCESS = '过程表'
|
||||||
|
|
||||||
|
ROOT_DIR = DEFAULT_ROOT_DIR
|
||||||
|
WORK_DIR = os.path.join(ROOT_DIR, SUBDIR_PROCESS) # 表池:共享盘副本 + 马敏总表副本
|
||||||
|
OUT_DIR = os.path.join(ROOT_DIR, SUBDIR_MEITUAN) # 当前分支的导出与产物目录
|
||||||
|
|
||||||
|
ACTION_DOUYIN = 'check_douyin'
|
||||||
|
_BRANCH_SUBDIR = {ACTION_DOUYIN: SUBDIR_DOUYIN}
|
||||||
|
|
||||||
|
|
||||||
def set_work_dir(path=None):
|
def set_work_dir(path=None, action=None):
|
||||||
"""界面「保存目录」覆盖默认目录;留空回默认。返回实际生效目录。"""
|
"""界面「本地工作目录」= 根目录;留空回默认根。返回过程表目录。
|
||||||
global WORK_DIR
|
|
||||||
p = str(path or '').strip().strip('"').strip()
|
美团核对产物落 ``<根>\\美团``,抖音核对 ``<根>\\抖音``;通联已拆到 XQ0082,本插件不再用 ``<根>\\通联``。
|
||||||
WORK_DIR = p or DEFAULT_WORK_DIR
|
美团/抖音的核对表与马敏总表副本共用 ``<根>\\过程表`` 一份,避免总表按分支分叉。
|
||||||
|
"""
|
||||||
|
global ROOT_DIR, WORK_DIR, OUT_DIR
|
||||||
|
root = str(path or '').strip().strip('"').strip() or DEFAULT_ROOT_DIR
|
||||||
|
ROOT_DIR = root
|
||||||
|
WORK_DIR = os.path.join(root, SUBDIR_PROCESS)
|
||||||
|
OUT_DIR = os.path.join(root, _BRANCH_SUBDIR.get(str(action or '').strip(), SUBDIR_MEITUAN))
|
||||||
return WORK_DIR
|
return WORK_DIR
|
||||||
|
|
||||||
|
|
||||||
|
def ensure_dirs():
|
||||||
|
"""确保过程表与当前分支目录存在(写盘前调用)。"""
|
||||||
|
for d in (WORK_DIR, OUT_DIR):
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
return [WORK_DIR, OUT_DIR]
|
||||||
|
|
||||||
|
|
||||||
|
def search_dirs():
|
||||||
|
"""找输入明细时的搜索顺序:当前分支目录 → 过程表。"""
|
||||||
|
return [OUT_DIR, WORK_DIR]
|
||||||
|
|
||||||
|
|
||||||
|
def glob_files(pattern):
|
||||||
|
"""按 search_dirs 顺序返回所有匹配文件(排除备份/临时文件)。"""
|
||||||
|
paths = []
|
||||||
|
for d in search_dirs():
|
||||||
|
paths.extend(sorted(glob.glob(os.path.join(d, pattern))))
|
||||||
|
return [p for p in paths if '_备份' not in p
|
||||||
|
and not os.path.basename(p).startswith('~$')]
|
||||||
|
|
||||||
|
|
||||||
|
def latest_file(pattern):
|
||||||
|
"""分支目录与过程表里取修改时间最新的匹配文件;找不到返回空串。"""
|
||||||
|
paths = glob_files(pattern)
|
||||||
|
if not paths:
|
||||||
|
return ''
|
||||||
|
return max(paths, key=os.path.getmtime)
|
||||||
|
|
||||||
|
|
||||||
# ==================== 共享盘(只读) ====================
|
# ==================== 共享盘(只读) ====================
|
||||||
SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG'
|
SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG'
|
||||||
SHARE_CHECK_ROOT = SHARE_ROOT
|
SHARE_CHECK_ROOT = SHARE_ROOT
|
||||||
@@ -71,7 +122,6 @@ SHARE_TABLE_KEYWORD = '美团'
|
|||||||
DOUYIN_SHARE_KEYWORD = '抖音'
|
DOUYIN_SHARE_KEYWORD = '抖音'
|
||||||
SHARE_TABLE_EXT = '.xlsx'
|
SHARE_TABLE_EXT = '.xlsx'
|
||||||
LINK_BOOK = '马敏团购总表'
|
LINK_BOOK = '马敏团购总表'
|
||||||
DAILY_WORK_DIR = '_work' # 共享表拉下来的本地副本目录
|
|
||||||
|
|
||||||
# ==================== 美团:订单收入明细表 ====================
|
# ==================== 美团:订单收入明细表 ====================
|
||||||
PROFIT_HEADER_ROW = 2
|
PROFIT_HEADER_ROW = 2
|
||||||
@@ -81,6 +131,49 @@ DAILY_HEADER_ROW = 3
|
|||||||
DAILY_DATA_START = 4
|
DAILY_DATA_START = 4
|
||||||
DAILY_EXCLUDE_BUSINESS = ('其他',)
|
DAILY_EXCLUDE_BUSINESS = ('其他',)
|
||||||
|
|
||||||
|
# 2026-11 新版导出(31 列)→ 订单收入明细表 A..AB(按 11.24 真实数据反推):
|
||||||
|
# 新版导出把「收益类型 / 业务类型」两个名字对调了——
|
||||||
|
# 导出 3 收益类型 = 已核销 / 已消费退 / 撤销核销(旧版叫业务类型)
|
||||||
|
# 导出 4 业务类型 = 团购 / 其他(旧版叫团购类型)
|
||||||
|
# 所以目标 B(收益类型)取导出 4,目标 C(业务类型)取导出 3。
|
||||||
|
# 导出 2 线上场景、6 订单号、30 关联买单订单号/券号 在目标表里没有对应列,丢弃。
|
||||||
|
DAILY_EXPORT_TO_TARGET = (
|
||||||
|
(1, 1), # 账户名称
|
||||||
|
(4, 2), # 业务类型(团购/其他) → 收益类型
|
||||||
|
(3, 3), # 收益类型(已核销…) → 业务类型
|
||||||
|
(5, 4), # 订单类型
|
||||||
|
(7, 5), # 券号
|
||||||
|
(8, 6), # 下单时间
|
||||||
|
(9, 7), # 验券/退款/调整时间
|
||||||
|
(10, 8), # 团购ID/通兑券ID
|
||||||
|
(11, 9), # 套餐名
|
||||||
|
(12, 10), # 消费门店Id
|
||||||
|
(13, 11), # 消费门店
|
||||||
|
(14, 12), # 特殊账期业务
|
||||||
|
(15, 13), # 入账日期
|
||||||
|
(16, 14), # 打款状态
|
||||||
|
(17, 15), # 打款单号
|
||||||
|
(18, 16), # 结算价
|
||||||
|
(19, 17), # 总收入
|
||||||
|
(20, 18), # 技术服务费费率
|
||||||
|
(21, 19), # 平台技术服务费
|
||||||
|
(22, 20), # 商家营销费用
|
||||||
|
(23, 21), # 其他调整
|
||||||
|
(24, 22), # 自配打包费
|
||||||
|
(25, 23), # 自配送费
|
||||||
|
(26, 24), # 渠道佣金
|
||||||
|
(27, 25), # 渠道标签
|
||||||
|
(28, 26), # 备注
|
||||||
|
(29, 27), # 关联纠纷单号
|
||||||
|
# 导出 31「账单周期」是合并单元格,读出来只有「至」;现有表该列取的是导出 30
|
||||||
|
(30, 28), # 关联买单订单号/券号 → 账单周期
|
||||||
|
)
|
||||||
|
DAILY_TIME_COL = 9 # 导出:验券/退款/调整时间(按日期 == 营业日筛选)
|
||||||
|
DAILY_SETTLE_COL = 18 # 导出:结算价
|
||||||
|
DAILY_INCOME_COL = 19 # 导出:总收入
|
||||||
|
DAILY_HELPER_FIRST = 29 # 目标 AC 起为辅助列(公式,沿用模板行下拉)
|
||||||
|
DAILY_HELPER_LAST = 35 # 目标 AI
|
||||||
|
|
||||||
# ==================== 美团:基础信息补维护 ====================
|
# ==================== 美团:基础信息补维护 ====================
|
||||||
BASE_SHEET = '基础信息'
|
BASE_SHEET = '基础信息'
|
||||||
REPORT_SHEET = '报表'
|
REPORT_SHEET = '报表'
|
||||||
@@ -92,17 +185,161 @@ BASE_ITEM_VLOOKUP_MAX = 12924
|
|||||||
BASE_RANGE_WARN_RATIO = 0.9
|
BASE_RANGE_WARN_RATIO = 0.9
|
||||||
STORE_MAP_FILE = '门店映射表.json'
|
STORE_MAP_FILE = '门店映射表.json'
|
||||||
|
|
||||||
|
# ==================== 美团:门店归属(CRM 券号,v1.1.0 从 XQ0041 迁入) ====================
|
||||||
|
# 口径差异:美团收益明细的日期是「验券/退款/调整时间」,CRM 团购核销报表按「核销日」归档,
|
||||||
|
# 同一笔单在两边可能差一天;实测按 ±1 天取窗口,券号命中率从 78.6% → 100%。
|
||||||
|
DETAIL_HEADER_ROW = 2 # 团购收益明细表头行(数据从下一行起)
|
||||||
|
DETAIL_DATA_START = 3
|
||||||
|
TIME_COL = '验券/退款/调整时间'
|
||||||
|
CRM_DATE_WINDOW = 1
|
||||||
|
CRM_GROUP_REPORT = 'groupData' # crm_sdk.reports.REPORTS 里的 key
|
||||||
|
CRM_PAGE_SIZE = 500
|
||||||
|
STORE_OUT_PREFIX = '门店核对' # 产物:门店核对_起_止.xlsx
|
||||||
|
|
||||||
|
# ==================== 套餐名 → 项目 关键词规则 ====================
|
||||||
|
# (关键词, 标准项目名),匹配时长关键词优先;关键词与套餐名都做归一化
|
||||||
|
# (全半角括号、·、空格、"分钟"都忽略),所以「音遇SPA(80)」能对上「音遇·SPA80分钟」。
|
||||||
|
ITEM_KEYWORD_RULES = (
|
||||||
|
# 套票归并
|
||||||
|
('头舒耳道', '二选一'),
|
||||||
|
('艾养耳道', '二选一'),
|
||||||
|
('专项头疗', '四选一'),
|
||||||
|
('专项采耳', '四选一'),
|
||||||
|
('经络刮痧', '四选一'),
|
||||||
|
('五行火罐', '四选一'),
|
||||||
|
# 筋养推拿 6 选 N
|
||||||
|
('筋养推拿6选一', '筋养推拿1'),
|
||||||
|
('筋养推拿6选二', '筋养推拿2'),
|
||||||
|
('筋养推拿6选三', '筋养推拿3'),
|
||||||
|
('筋养推拿6选四', '筋养推拿4'),
|
||||||
|
('筋养推拿6选五', '筋养推拿5'),
|
||||||
|
('筋养推拿6选六', '筋养推拿6'),
|
||||||
|
('筋养推拿6选七', '筋养推拿7'),
|
||||||
|
# 单人/双人套餐(长词优先)
|
||||||
|
('龙手足道双人餐', '龙手足道双人餐'),
|
||||||
|
('龙手足道', '龙手足道'),
|
||||||
|
('印象贵足双人餐', '印象贵足双人餐'),
|
||||||
|
('印象贵足', '印象贵足'),
|
||||||
|
('太极指压', '太极指压'),
|
||||||
|
('筋络归真', '筋络归真'),
|
||||||
|
('玄门归真', '玄门归真'),
|
||||||
|
('培元归真', '培元归真'),
|
||||||
|
# 带时长区分的项目
|
||||||
|
('个性化推拿100', '个性化推拿(100)'),
|
||||||
|
('个性化推拿80', '个性化推拿(80)'),
|
||||||
|
('音遇spa100', '音遇SPA(100)'),
|
||||||
|
('音遇spa80', '音遇SPA(80)'),
|
||||||
|
('音愈spa110', '【音愈SPA】110分钟'),
|
||||||
|
('音愈spa90', '【音愈SPA】90分钟'),
|
||||||
|
('音愈spa70', '【音愈SPA】70分钟'),
|
||||||
|
('耳脑spa', '耳脑SPA'),
|
||||||
|
('大师修脚', '大师修脚'),
|
||||||
|
# 肩颈温络 / 温灸:表内两种写法并存,各自保留原样
|
||||||
|
('肩颈温络', '肩颈温络'),
|
||||||
|
('肩颈温灸', '肩颈温灸'),
|
||||||
|
)
|
||||||
|
|
||||||
# ==================== 马敏团购总表:按值粘贴 ====================
|
# ==================== 马敏团购总表:按值粘贴 ====================
|
||||||
MASTER_SHEET_MEITUAN = '平台-新美大'
|
MASTER_SHEET_MEITUAN = '平台-新美大'
|
||||||
MASTER_SHEET_DOUYIN = '平台-抖音'
|
MASTER_SHEET_DOUYIN = '平台-抖音'
|
||||||
MASTER_SHEET_GROUP_STATS = '团购统计'
|
MASTER_SHEET_GROUP_STATS = '团购统计'
|
||||||
MEITUAN_REPORT_COLS = ('I', 'P')
|
MEITUAN_REPORT_COLS = ('I', 'P')
|
||||||
DOUYIN_REPORT_COLS = ('N', 'Z')
|
DOUYIN_REPORT_COLS = ('N', 'Z')
|
||||||
|
|
||||||
|
# ==================== 马敏团购总表:对比 sheet 日滚动(核对第一步) ====================
|
||||||
|
# 总表副本是「昨天的表」复制来的:副本里的「今日遗留」其实是昨天的,先滚到「昨日遗留」,
|
||||||
|
# 再把「今日遗留」清空等当天重算;同时清掉 I/J/K 与「漏核销」列的上日结果。
|
||||||
|
COMPARE_SHEET_MEITUAN = '新美大对比 (2)' # 实际表名带全半角括号差异,按名字归一化匹配
|
||||||
|
COMPARE_SHEET_DOUYIN = '抖音对比(2)'
|
||||||
|
COMPARE_DATA_START = 5 # 数据起始行(前 4 行是表头/标题)
|
||||||
|
COMPARE_HEADER_SCAN_ROWS = 4 # 表头可能在前 1~4 行,标题按行扫描定位
|
||||||
|
COMPARE_CLEAR_COLS = ('I', 'J', 'K') # 每天先清空的三列
|
||||||
|
COMPARE_MISS_TITLE = '漏核销' # 漏核销列(按标题定位)
|
||||||
|
COMPARE_YESTERDAY_TITLE = '昨日遗留'
|
||||||
|
COMPARE_TODAY_TITLE = '今日遗留'
|
||||||
|
# 备注列无表头,固定 X 列;判断的是文本格式不是日期:
|
||||||
|
# 空 或 含「前消费」(如「2026年10月31日前消费」)→ 昨日遗留保留;
|
||||||
|
# 其它备注内容 → 昨日遗留清空。
|
||||||
|
COMPARE_REMARK_COL = 'X'
|
||||||
|
COMPARE_KEEP_REMARK_RE = r'前\s*消费'
|
||||||
|
# 滚动写完后重算一次,再核 W 列「验证」:按 E 门店 + F 项目分组,组内求和为 0 才算平。
|
||||||
|
COMPARE_VERIFY_TITLE = '验证'
|
||||||
|
COMPARE_VERIFY_COL = 'W' # 找不到「验证」表头时的兜底列
|
||||||
|
COMPARE_VERIFY_TOL = 1e-6
|
||||||
|
# W 列这些值不参与分组求和(「-」表示该行不适用);空单元格同样跳过。
|
||||||
|
COMPARE_VERIFY_SKIP = ('', '-', '-', '—', '--')
|
||||||
|
COMPARE_UNBALANCED_LIMIT = 50 # 返回/日志里最多列出的不平组数
|
||||||
|
|
||||||
|
# ==================== 马敏团购总表:分组验证(2026-11-27) ====================
|
||||||
|
# 对比表 A/B 是透视原始名,E/F 是「门店 / 核销项目名称」映射(E==A,F 带归并公式);
|
||||||
|
# 验证按 E + F 分组,组内 W 求和为 0 即平。二选一/四选一 自身也是项目名,与成员同组。
|
||||||
|
COMPARE_GROUP_MEMBERS = {
|
||||||
|
'二选一': ('二选一', '艾养耳道', '头舒耳道'),
|
||||||
|
'四选一': ('四选一', '专项头疗', '专项采耳', '经络刮痧', '五行火罐'),
|
||||||
|
}
|
||||||
|
# 定位 E/F:表头行里第 2 次出现的「门店」「核销项目名称」(第 1 次是 A/B)。
|
||||||
|
COMPARE_GROUP_HEADERS = ('门店', '核销项目名称')
|
||||||
|
COMPARE_GROUP_FALLBACK_COLS = ('E', 'F')
|
||||||
|
|
||||||
|
# ==================== 马敏团购总表:今日遗留回填(2026-11-27) ====================
|
||||||
|
# 今日遗留(R)不再人工填:取【团购统计】「未消费项目个数」按 门店+项目 汇总回填。
|
||||||
|
COMPARE_STATS_SHEET = '团购统计'
|
||||||
|
COMPARE_STATS_DATA_START = 2
|
||||||
|
COMPARE_STATS_TYPE_COL = 'A' # 团购类型
|
||||||
|
COMPARE_STATS_DATE_COL = 'B' # 消费日期
|
||||||
|
COMPARE_STATS_STORE_COL = 'C' # 门店
|
||||||
|
COMPARE_STATS_ITEM_COL = 'D' # 核销项目名称
|
||||||
|
COMPARE_STATS_UNUSED_COL = 'G' # 未消费项目个数
|
||||||
|
# 取数类型与对比表 C/D 的 SUMIFS 保持一致(美团 = 点评 + 美团,抖音 = 抖音)。
|
||||||
|
COMPARE_STATS_TYPES = {
|
||||||
|
'check_meituan': ('美团', '点评'),
|
||||||
|
'check_douyin': ('抖音',),
|
||||||
|
}
|
||||||
|
|
||||||
|
# ==================== 马敏团购总表:双人餐/三人餐平台结错(2026-11-27) ====================
|
||||||
|
# 前面回填 + 分组验证跑完仍不平、且是「双人餐 / 三人餐」行时,在【平台结错】列补调整:
|
||||||
|
# 餐行(双人餐/三人餐)写 1,同门店的基础项目行写 -2(双人)/ -3(三人)。
|
||||||
|
# 例:印象贵足 +2、印象贵足双人餐 -1 → 餐行 J=1、基础行 J=-2,两行各自归零。
|
||||||
|
COMPARE_PLATFORM_ERROR_TITLE = '平台结错'
|
||||||
|
COMPARE_PLATFORM_ERROR_COL = 'J'
|
||||||
|
COMPARE_MEAL_SUFFIXES = {'双人餐': 2, '三人餐': 3} # 后缀 → 人数(基础行写 -人数)
|
||||||
|
COMPARE_MEAL_ADJUST = 1 # 餐行写入值
|
||||||
|
|
||||||
|
# ==================== 马敏团购总表:退款/撤销核销冲减今日遗留(2026-11-27) ====================
|
||||||
|
# 从本地美团表的【订单收入明细表】、抖音表的【核销明细】找非「已核销」的业务类型,
|
||||||
|
# 按「门店 + 核销项目名称」计行数,从今日遗留里扣掉(不按日期筛)。
|
||||||
|
# 门店/项目一律先按该表【基础信息】映射:A 平台门店→B 内部门店,E 平台商品名→F 内部项目。
|
||||||
|
COMPARE_REFUND_GROUPS = {
|
||||||
|
'check_meituan': {
|
||||||
|
'book': '美团', # 本地表文件名关键词:美团M.D.xlsx
|
||||||
|
'sheet': '订单收入明细表',
|
||||||
|
'data_start': 4,
|
||||||
|
'status_col': 'C', # 业务类型
|
||||||
|
'store_col': 'K', # 消费门店
|
||||||
|
'item_col': 'I', # 套餐名(按基础信息 E→F 映射)
|
||||||
|
'item_fallback_col': 'AF', # 映射不到时用「品项名称」(已是内部项目名)
|
||||||
|
'date_col': 'G', # 验券/退款/调整时间,按营业日筛
|
||||||
|
'statuses': ('已消费退', '撤销核销', '核销后退款', '已撤销核销'),
|
||||||
|
},
|
||||||
|
'check_douyin': {
|
||||||
|
'book': '抖音',
|
||||||
|
'sheet': '核销明细',
|
||||||
|
'data_start': 2,
|
||||||
|
'status_col': 'I', # 核销状态
|
||||||
|
'store_col': 'H', # 核销门店
|
||||||
|
'item_col': 'O', # 商品名称(按基础信息 E→F 映射)
|
||||||
|
'item_fallback_col': '',
|
||||||
|
'date_col': 'L', # 核销时间,按营业日筛
|
||||||
|
'statuses': ('已消费退', '撤销核销', '核销后退款', '已撤销核销'),
|
||||||
|
},
|
||||||
|
}
|
||||||
|
COMPARE_BASE_INFO_SHEET = '基础信息'
|
||||||
|
COMPARE_BASE_INFO_COLS = ('A', 'B', 'E', 'F') # 平台门店/内部门店/平台商品/内部项目
|
||||||
|
COMPARE_REFUND_STORE_MIN_RATIO = 0.6 # 门店名相似度兜底阈值
|
||||||
MASTER_DATA_START = 5
|
MASTER_DATA_START = 5
|
||||||
GROUP_STATS_DATA_START = 2
|
GROUP_STATS_DATA_START = 2
|
||||||
CRM_EXPORT_DIR = r'D:\资料\财务\CRM数据导出'
|
CRM_EXPORT_DIR = r'D:\资料\财务\CRM数据导出'
|
||||||
CRM_GROUP_PAY_PREFIX = '团购支付数据'
|
CRM_GROUP_PAY_PREFIX = '团购支付数据'
|
||||||
DOUYIN_WORK_DIR = r'D:\资料\财务\抖音平台核对'
|
|
||||||
DOUYIN_TABLE_PREFIX = '抖音'
|
DOUYIN_TABLE_PREFIX = '抖音'
|
||||||
DOUYIN_TABLE_EXT = '.xlsx'
|
DOUYIN_TABLE_EXT = '.xlsx'
|
||||||
|
|
||||||
@@ -122,10 +359,12 @@ DY_CONVERT_SHEET = '转换'
|
|||||||
DY_CONVERT_TIME_COL = 'BQ'
|
DY_CONVERT_TIME_COL = 'BQ'
|
||||||
DY_CONVERT_INCOME_COL = 'AE'
|
DY_CONVERT_INCOME_COL = 'AE'
|
||||||
DY_BASE_SHEET = '基础信息'
|
DY_BASE_SHEET = '基础信息'
|
||||||
DY_REPORT_SHOP_COL = 'O' # 报表 O/P 乱码 → 新增门店/项目
|
DY_REPORT_SHOP_COL = 'O' # 报表 O/P 是 VLOOKUP 结果列,只用于判断是否 #N/A
|
||||||
DY_REPORT_ITEM_COL = 'P'
|
DY_REPORT_ITEM_COL = 'P'
|
||||||
DY_BASE_INFO_ROW = 5 # 基础信息门店映射起始行
|
DY_BASE_INFO_ROW = 5 # 基础信息门店映射起始行(表头第 4 行)
|
||||||
DY_BASE_ITEM_ROW = 5 # 基础信息品项映射起始行
|
DY_BASE_ITEM_ROW = 5 # 基础信息品项映射起始行
|
||||||
|
DY_BASE_INFO_VLOOKUP_MAX = 1992 # 报表 N/O 的 VLOOKUP 上界:基础信息!$A$5:$C$1992
|
||||||
|
DY_BASE_ITEM_VLOOKUP_MAX = 4998 # 报表 P 的 VLOOKUP 上界:基础信息!$E$5:$F$4998
|
||||||
|
|
||||||
# ==================== 运行参数 ====================
|
# ==================== 运行参数 ====================
|
||||||
RETRY_MAX = 3
|
RETRY_MAX = 3
|
||||||
|
|||||||
@@ -1,49 +1,106 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""基础信息补维护:检查【报表】里 VLOOKUP 补不到(#N/A)的新增门店/新增套餐。
|
"""基础信息补维护:检查【报表】里 VLOOKUP 补不到(#N/A)的新增门店/新增套餐。
|
||||||
|
|
||||||
比对【报表】A/B 列与【基础信息】A/E 列,新增项写入本地副本。
|
比对【报表】A/B 列(平台门店名 / 平台套餐名)与【基础信息】A/E 列,新增项写入本地副本:
|
||||||
同时检查固定 VLOOKUP 范围上界:到 90% 提示扩范围,超界提示人工改公式(不改表)。
|
门店写 A(平台名)+ B(内部名,猜不到则同名)+ C(品牌);套餐写 E(平台名)+ F(项目名)。
|
||||||
|
|
||||||
|
美团与抖音两套表结构一致(A/B 门店、E/F 品项),只有 sheet 名、起始行和 VLOOKUP 上界不同,
|
||||||
|
差异集中在 :func:`layout`;扫描一律读 ``data_only`` 的值,写入再用可保存的工作簿,避免读到公式。
|
||||||
|
同时检查固定 VLOOKUP 范围上界:到 90% 提示扩范围,超界提示人工改公式(不改公式)。
|
||||||
"""
|
"""
|
||||||
import glob
|
import glob
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
|
import re
|
||||||
from difflib import SequenceMatcher
|
from difflib import SequenceMatcher
|
||||||
|
|
||||||
import openpyxl
|
import openpyxl
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
|
from . import sheet_xml
|
||||||
|
|
||||||
COL_BI_A = 1
|
COL_BI_A = 1
|
||||||
COL_BI_B = 2
|
COL_BI_B = 2
|
||||||
|
COL_BI_C = 3
|
||||||
COL_BI_E = 5
|
COL_BI_E = 5
|
||||||
COL_BI_F = 6
|
COL_BI_F = 6
|
||||||
|
|
||||||
|
LAYOUT_MEITUAN = 'meituan'
|
||||||
|
LAYOUT_DOUYIN = 'douyin'
|
||||||
|
|
||||||
def _read_report_pairs(ws):
|
|
||||||
|
def layout(name=LAYOUT_MEITUAN):
|
||||||
|
"""返回一套基础信息布局:sheet 名、数据起始行、VLOOKUP 上界。"""
|
||||||
|
if name == LAYOUT_DOUYIN:
|
||||||
|
return {'label': '抖音',
|
||||||
|
'base_sheet': config.DY_BASE_SHEET,
|
||||||
|
'report_sheet': config.REPORT_SHEET,
|
||||||
|
'report_start': config.REPORT_DATA_START,
|
||||||
|
'shop_row': config.DY_BASE_INFO_ROW,
|
||||||
|
'item_row': config.DY_BASE_ITEM_ROW,
|
||||||
|
'shop_limit': config.DY_BASE_INFO_VLOOKUP_MAX,
|
||||||
|
'item_limit': config.DY_BASE_ITEM_VLOOKUP_MAX}
|
||||||
|
return {'label': '美团',
|
||||||
|
'base_sheet': config.BASE_SHEET,
|
||||||
|
'report_sheet': config.REPORT_SHEET,
|
||||||
|
'report_start': config.REPORT_DATA_START,
|
||||||
|
'shop_row': config.BASE_INFO_ROW,
|
||||||
|
'item_row': config.BASE_ITEM_ROW,
|
||||||
|
'shop_limit': config.BASE_INFO_VLOOKUP_MAX,
|
||||||
|
'item_limit': config.BASE_ITEM_VLOOKUP_MAX}
|
||||||
|
|
||||||
|
|
||||||
|
def _reset_if_needed(ws):
|
||||||
|
"""模板/导出的 dimension 常写成 1×1 或百万行。"""
|
||||||
|
rows, cols = ws.max_row or 1, ws.max_column or 1
|
||||||
|
if rows <= 1 or cols <= 1 or rows > 100000 or cols > 1000:
|
||||||
|
ws.reset_dimensions()
|
||||||
|
|
||||||
|
|
||||||
|
def _read_report_pairs(ws, start_row=None):
|
||||||
pairs = []
|
pairs = []
|
||||||
seen = set()
|
seen = set()
|
||||||
for r in range(config.REPORT_DATA_START, int(ws.max_row or 0) + 1):
|
start = config.REPORT_DATA_START if start_row is None else start_row
|
||||||
shop = str(ws.cell(r, 1).value or '').strip()
|
skipped = 0
|
||||||
item = str(ws.cell(r, 2).value or '').strip()
|
for row in ws.iter_rows(min_row=start, max_col=2, values_only=True):
|
||||||
|
shop = str(row[0] or '').strip() if len(row) > 0 else ''
|
||||||
|
item = str(row[1] or '').strip() if len(row) > 1 else ''
|
||||||
|
if shop.startswith('=') or item.startswith('='):
|
||||||
|
# 用非 data_only 打开时会读到公式文本,绝不能当门店/套餐名写进基础信息
|
||||||
|
skipped += 1
|
||||||
|
continue
|
||||||
if shop and shop != '0' and (shop, item) not in seen:
|
if shop and shop != '0' and (shop, item) not in seen:
|
||||||
seen.add((shop, item))
|
seen.add((shop, item))
|
||||||
pairs.append((shop, item))
|
pairs.append((shop, item))
|
||||||
|
if skipped:
|
||||||
|
config.log(f'报表 A/B 读到 {skipped} 行公式文本(应 data_only 打开),已跳过', 'WARN')
|
||||||
return pairs
|
return pairs
|
||||||
|
|
||||||
|
|
||||||
|
def _key(text):
|
||||||
|
"""判重键:VLOOKUP 大小写不敏感,判重也必须归一,否则 HiFi/HIFI 会被当成新门店。"""
|
||||||
|
return str(text or '').strip().casefold()
|
||||||
|
|
||||||
|
|
||||||
def _column_values(ws, col, start_row):
|
def _column_values(ws, col, start_row):
|
||||||
values = set()
|
"""返回 (归一化判重键集合, 末行号, 原始值列表去重保序)。"""
|
||||||
|
keys = set()
|
||||||
|
raw = []
|
||||||
last = start_row - 1
|
last = start_row - 1
|
||||||
for r in range(start_row, int(ws.max_row or 0) + 1):
|
for offset, row in enumerate(ws.iter_rows(min_row=start_row, max_col=col,
|
||||||
v = str(ws.cell(r, col).value or '').strip()
|
values_only=True)):
|
||||||
|
v = str(row[col - 1] or '').strip() if len(row) >= col else ''
|
||||||
if v and v != '0':
|
if v and v != '0':
|
||||||
values.add(v)
|
k = _key(v)
|
||||||
last = r
|
if k not in keys:
|
||||||
return values, last
|
keys.add(k)
|
||||||
|
raw.append(v)
|
||||||
|
last = start_row + offset
|
||||||
|
return keys, last, raw
|
||||||
|
|
||||||
|
|
||||||
def _load_shop_map():
|
def _load_shop_map():
|
||||||
path = os.path.join(config.WORK_DIR, config.STORE_MAP_FILE)
|
path = os.path.join(config.OUT_DIR, config.STORE_MAP_FILE)
|
||||||
try:
|
try:
|
||||||
with open(path, encoding='utf-8-sig') as fp:
|
with open(path, encoding='utf-8-sig') as fp:
|
||||||
data = json.load(fp)
|
data = json.load(fp)
|
||||||
@@ -53,109 +110,235 @@ def _load_shop_map():
|
|||||||
|
|
||||||
|
|
||||||
def _guess_shop(name, existing, shop_map):
|
def _guess_shop(name, existing, shop_map):
|
||||||
|
"""猜内部门店名:先查门店映射表(CRM 名 ↔ 内部名),再按相似度兜底。"""
|
||||||
|
name_key = _key(name)
|
||||||
|
pool = [(e, _key(e)) for e in existing]
|
||||||
|
known = {k for _, k in pool}
|
||||||
for crm, info in shop_map.items():
|
for crm, info in shop_map.items():
|
||||||
if not isinstance(info, dict):
|
if not isinstance(info, dict):
|
||||||
continue
|
continue
|
||||||
if str(info.get('shop') or info.get('门店') or '').strip() in existing:
|
internal = str(info.get('shop') or info.get('门店') or '').strip()
|
||||||
if crm and (crm in name or name in crm):
|
if internal and _key(internal) in known:
|
||||||
return str(info.get('shop') or info.get('门店')).strip(), \
|
crm_key = _key(crm)
|
||||||
str(info.get('brand') or info.get('品牌') or '').strip()
|
if crm_key and (crm_key in name_key or name_key in crm_key):
|
||||||
|
return internal, str(info.get('brand') or info.get('品牌') or '').strip()
|
||||||
best, score = '', 0.0
|
best, score = '', 0.0
|
||||||
for e in existing:
|
for orig, key in pool:
|
||||||
s = SequenceMatcher(None, name, e).ratio()
|
s = SequenceMatcher(None, name_key, key).ratio()
|
||||||
if s > score:
|
if s > score:
|
||||||
best, score = e, s
|
best, score = orig, s
|
||||||
return (best if score >= 0.45 else ''), ''
|
return (best if score >= 0.45 else ''), ''
|
||||||
|
|
||||||
|
|
||||||
def _guess_item(name):
|
_NORM_MAP = {ord('('): '(', ord(')'): ')', ord('['): '[', ord(']'): ']',
|
||||||
if '【' in name and '】' in name:
|
ord('【'): '[', ord('】'): ']', ord(' '): ' ', ord('·'): '', ord('•'): '',
|
||||||
return name.split('【', 1)[1].split('】', 1)[0].strip()
|
ord('×'): 'x', ord('*'): '*'}
|
||||||
|
|
||||||
|
|
||||||
|
def _norm_item(text):
|
||||||
|
"""归一化:全半角括号统一、去 ·/空白/「分钟」/括号,便于关键词包含匹配。"""
|
||||||
|
t = str(text or '').translate(_NORM_MAP)
|
||||||
|
t = re.sub(r'\s+', '', t).lower().replace('分钟', '')
|
||||||
|
return re.sub(r'[()\[\]]', '', t)
|
||||||
|
|
||||||
|
|
||||||
|
def _item_rules():
|
||||||
|
rules = [(_norm_item(k), v) for k, v in config.ITEM_KEYWORD_RULES]
|
||||||
|
rules.sort(key=lambda kv: len(kv[0]), reverse=True) # 长关键词优先
|
||||||
|
return rules
|
||||||
|
|
||||||
|
|
||||||
|
# 能加人数后缀的基础项目(双人/三人餐)
|
||||||
|
_HEADCOUNT_BASE = ('龙手足道', '印象贵足', '太极指压', '筋络归真', '玄门归真', '培元归真')
|
||||||
|
|
||||||
|
|
||||||
|
def _headcount_suffix(normed):
|
||||||
|
"""识别双人/三人:x2 / ×2 / 双人 → 双人餐;x3 / 三人 → 三人餐。"""
|
||||||
|
if '三人' in normed or 'x3' in normed:
|
||||||
|
return '三人餐'
|
||||||
|
if '双人' in normed or 'x2' in normed:
|
||||||
|
return '双人餐'
|
||||||
return ''
|
return ''
|
||||||
|
|
||||||
|
|
||||||
def run(table_path='', dry_run=False):
|
def _guess_item(name):
|
||||||
|
"""套餐名 → 项目:按关键词规则(长词优先)匹配,双人/三人餐自动加后缀。
|
||||||
|
|
||||||
|
匹配不到返回空——**不做【】提取**,因为【】里是套餐分类(健康足体/人气轻养等),
|
||||||
|
当成项目会写错;空值交给人工补,不会污染基础信息。
|
||||||
|
"""
|
||||||
|
normed = _norm_item(name)
|
||||||
|
suffix = _headcount_suffix(normed)
|
||||||
|
for keyword, value in _item_rules():
|
||||||
|
if not keyword or keyword not in normed:
|
||||||
|
continue
|
||||||
|
if suffix and value in _HEADCOUNT_BASE:
|
||||||
|
return value + suffix
|
||||||
|
return value
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def scan(workbook, lay=None):
|
||||||
|
"""读【报表】A/B 与【基础信息】A/E,返回待补条目(只读,不写表)。
|
||||||
|
|
||||||
|
``workbook`` 必须是 ``data_only=True`` 打开的,否则报表读到的是公式文本。
|
||||||
|
"""
|
||||||
|
lay = lay or layout()
|
||||||
|
out = {'ok': False, 'new_shops': [], 'new_items': [], 'range_warnings': [],
|
||||||
|
'message': '', 'written': 0}
|
||||||
|
if lay['base_sheet'] not in workbook.sheetnames or \
|
||||||
|
lay['report_sheet'] not in workbook.sheetnames:
|
||||||
|
out['message'] = f'缺少【{lay["base_sheet"]}】或【{lay["report_sheet"]}】'
|
||||||
|
return out
|
||||||
|
base = workbook[lay['base_sheet']]
|
||||||
|
report = workbook[lay['report_sheet']]
|
||||||
|
for ws in (base, report):
|
||||||
|
_reset_if_needed(ws)
|
||||||
|
pairs = _read_report_pairs(report, lay['report_start'])
|
||||||
|
shops, last_a, shop_values = _column_values(base, COL_BI_A, lay['shop_row'])
|
||||||
|
items, last_e, _ = _column_values(base, COL_BI_E, lay['item_row'])
|
||||||
|
internal_shops, _, internal_values = _column_values(base, COL_BI_B, lay['shop_row'])
|
||||||
|
shop_map = _load_shop_map()
|
||||||
|
|
||||||
|
new_shops, new_items = [], []
|
||||||
|
seen_shops, seen_items = set(), set()
|
||||||
|
for shop, item in pairs:
|
||||||
|
shop_key = _key(shop)
|
||||||
|
if shop_key and shop_key not in shops and shop_key not in seen_shops:
|
||||||
|
# 内部名候选池优先用 B 列(已是内部名),没有再退回 A 列
|
||||||
|
internal, brand = _guess_shop(shop, internal_values or shop_values, shop_map)
|
||||||
|
new_shops.append({'crm': shop, 'internal': internal, 'brand': brand})
|
||||||
|
seen_shops.add(shop_key)
|
||||||
|
item_key = _key(item)
|
||||||
|
if item_key and item_key not in items and item_key not in seen_items:
|
||||||
|
internal_item = _guess_item(item)
|
||||||
|
if internal_item:
|
||||||
|
new_items.append({'crm': item, 'internal': internal_item})
|
||||||
|
seen_items.add(item_key)
|
||||||
|
|
||||||
|
warnings = []
|
||||||
|
for name, last, limit in (
|
||||||
|
('门店映射(A~B)', last_a, lay['shop_limit']),
|
||||||
|
('品项映射(E~F)', last_e, lay['item_limit']),
|
||||||
|
):
|
||||||
|
ratio = last / float(limit) if limit else 0.0
|
||||||
|
if last > limit:
|
||||||
|
warnings.append(f'{name}已到第 {last} 行,超出报表公式上界 {limit};'
|
||||||
|
f'超出部分查不到,需要人工把 VLOOKUP 范围改大')
|
||||||
|
elif ratio >= config.BASE_RANGE_WARN_RATIO:
|
||||||
|
warnings.append(f'{name}已到第 {last} 行(上界 {limit},'
|
||||||
|
f'已用 {ratio:.0%}),建议尽快扩范围')
|
||||||
|
for warning in warnings:
|
||||||
|
config.log(warning, 'WARN')
|
||||||
|
|
||||||
|
out.update(ok=True, new_shops=new_shops, new_items=new_items,
|
||||||
|
range_warnings=warnings, last_shop=last_a, last_item=last_e)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def apply(workbook, scanned, lay=None):
|
||||||
|
"""把 :func:`scan` 的结果写进【基础信息】,返回写入行数;不做任何猜测。"""
|
||||||
|
lay = lay or layout()
|
||||||
|
base = workbook[lay['base_sheet']]
|
||||||
|
shops, last_a, _ = _column_values(base, COL_BI_A, lay['shop_row'])
|
||||||
|
items, last_e, _ = _column_values(base, COL_BI_E, lay['item_row'])
|
||||||
|
changed = 0
|
||||||
|
r = last_a + 1
|
||||||
|
for entry in scanned.get('new_shops') or []:
|
||||||
|
crm = entry.get('crm') or ''
|
||||||
|
crm_key = _key(crm)
|
||||||
|
if not crm_key or crm_key in shops:
|
||||||
|
continue
|
||||||
|
base.cell(r, COL_BI_A, crm)
|
||||||
|
base.cell(r, COL_BI_B, entry.get('internal') or crm)
|
||||||
|
if entry.get('brand'):
|
||||||
|
base.cell(r, COL_BI_C, entry['brand'])
|
||||||
|
shops.add(crm_key)
|
||||||
|
r += 1
|
||||||
|
changed += 1
|
||||||
|
r = last_e + 1
|
||||||
|
for entry in scanned.get('new_items') or []:
|
||||||
|
crm = entry.get('crm') or ''
|
||||||
|
crm_key = _key(crm)
|
||||||
|
if not crm_key or not entry.get('internal') or crm_key in items:
|
||||||
|
continue
|
||||||
|
base.cell(r, COL_BI_E, crm)
|
||||||
|
base.cell(r, COL_BI_F, entry['internal'])
|
||||||
|
items.add(crm_key)
|
||||||
|
r += 1
|
||||||
|
changed += 1
|
||||||
|
return changed
|
||||||
|
|
||||||
|
|
||||||
|
def write_changes(path, scanned, lay=None):
|
||||||
|
"""把 scan 结果追加到【基础信息】(zip+XML,不破坏透视/外部链接)。
|
||||||
|
|
||||||
|
返回写入的单元格数;门店按 A/B(+C)、套餐按 E/F 追加在各自末行之后。
|
||||||
|
"""
|
||||||
|
lay = lay or layout()
|
||||||
|
cells = []
|
||||||
|
row_no = int(scanned.get('last_shop') or (lay['shop_row'] - 1)) + 1
|
||||||
|
for entry in scanned.get('new_shops') or []:
|
||||||
|
crm = entry.get('crm') or ''
|
||||||
|
if not crm:
|
||||||
|
continue
|
||||||
|
cells.append((row_no, COL_BI_A, crm))
|
||||||
|
cells.append((row_no, COL_BI_B, entry.get('internal') or crm))
|
||||||
|
if entry.get('brand'):
|
||||||
|
cells.append((row_no, COL_BI_C, entry['brand']))
|
||||||
|
row_no += 1
|
||||||
|
row_no = int(scanned.get('last_item') or (lay['item_row'] - 1)) + 1
|
||||||
|
for entry in scanned.get('new_items') or []:
|
||||||
|
crm = entry.get('crm') or ''
|
||||||
|
if not crm or not entry.get('internal'):
|
||||||
|
continue
|
||||||
|
cells.append((row_no, COL_BI_E, crm))
|
||||||
|
cells.append((row_no, COL_BI_F, entry['internal']))
|
||||||
|
row_no += 1
|
||||||
|
if not cells:
|
||||||
|
return 0
|
||||||
|
values = {}
|
||||||
|
for row, col, value in cells:
|
||||||
|
values.setdefault(row, [None] * COL_BI_F)[col - 1] = value
|
||||||
|
sheet_xml.write_rows(path, lay['base_sheet'], values,
|
||||||
|
start_row=min(values), last_row=max(values))
|
||||||
|
return len(cells)
|
||||||
|
|
||||||
|
|
||||||
|
def run(table_path='', dry_run=False, layout_name=LAYOUT_MEITUAN):
|
||||||
src = str(table_path or '').strip()
|
src = str(table_path or '').strip()
|
||||||
if not src:
|
if not src:
|
||||||
cands = glob.glob(os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR, '美团*.xlsx'))
|
cands = glob.glob(os.path.join(config.WORK_DIR, '美团*.xlsx'))
|
||||||
src = cands[0] if cands else ''
|
src = cands[0] if cands else ''
|
||||||
result = {'ok': False, 'message': '', 'path': src,
|
result = {'ok': False, 'message': '', 'path': src,
|
||||||
'new_shops': [], 'new_items': [], 'range_warnings': []}
|
'new_shops': [], 'new_items': [], 'range_warnings': [], 'written': 0}
|
||||||
if not src or not os.path.isfile(src):
|
if not src or not os.path.isfile(src):
|
||||||
result['message'] = '未找到本地美团核对表副本'
|
result['message'] = '未找到本地美团核对表副本'
|
||||||
return result
|
return result
|
||||||
|
|
||||||
wb = openpyxl.load_workbook(src, data_only=False)
|
lay = layout(layout_name)
|
||||||
|
wb = openpyxl.load_workbook(src, read_only=True, data_only=True)
|
||||||
try:
|
try:
|
||||||
if config.BASE_SHEET not in wb.sheetnames or config.REPORT_SHEET not in wb.sheetnames:
|
scanned = scan(wb, lay)
|
||||||
result['message'] = f'{os.path.basename(src)} 缺少【{config.BASE_SHEET}】或【{config.REPORT_SHEET}】'
|
|
||||||
return result
|
|
||||||
base = wb[config.BASE_SHEET]
|
|
||||||
report = wb[config.REPORT_SHEET]
|
|
||||||
pairs = _read_report_pairs(report)
|
|
||||||
shops, last_a = _column_values(base, COL_BI_A, config.BASE_INFO_ROW)
|
|
||||||
items, last_e = _column_values(base, COL_BI_E, config.BASE_ITEM_ROW)
|
|
||||||
shop_map = _load_shop_map()
|
|
||||||
|
|
||||||
new_shops, new_items = [], []
|
|
||||||
for shop, item in pairs:
|
|
||||||
if shop not in shops:
|
|
||||||
internal, brand = _guess_shop(shop, shops, shop_map)
|
|
||||||
new_shops.append({'crm': shop, 'internal': internal, 'brand': brand})
|
|
||||||
if item:
|
|
||||||
internal_item = _guess_item(item)
|
|
||||||
if internal_item and internal_item not in items:
|
|
||||||
new_items.append({'crm': item, 'internal': internal_item})
|
|
||||||
|
|
||||||
warnings = []
|
|
||||||
for name, last, limit in (
|
|
||||||
('门店映射(A~B)', last_a, config.BASE_INFO_VLOOKUP_MAX),
|
|
||||||
('品项映射(E~F)', last_e, config.BASE_ITEM_VLOOKUP_MAX),
|
|
||||||
):
|
|
||||||
ratio = last / float(limit) if limit else 0.0
|
|
||||||
if last > limit:
|
|
||||||
warnings.append(f'{name}已到第 {last} 行,超出报表公式上界 {limit};'
|
|
||||||
f'超出部分查不到,需要人工把 VLOOKUP 范围改大')
|
|
||||||
elif ratio >= config.BASE_RANGE_WARN_RATIO:
|
|
||||||
warnings.append(f'{name}已到第 {last} 行(上界 {limit},'
|
|
||||||
f'已用 {ratio:.0%}),建议尽快扩范围')
|
|
||||||
result['range_warnings'] = warnings
|
|
||||||
for warning in warnings:
|
|
||||||
config.log(warning, 'WARN')
|
|
||||||
|
|
||||||
result.update(new_shops=new_shops, new_items=new_items)
|
|
||||||
if dry_run:
|
|
||||||
result.update(ok=True, message=f'[演练] 新增门店 {len(new_shops)} / '
|
|
||||||
f'套餐 {len(new_items)}')
|
|
||||||
return result
|
|
||||||
|
|
||||||
changed = 0
|
|
||||||
r = last_a + 1
|
|
||||||
for entry in new_shops:
|
|
||||||
internal = entry['internal'] or entry['crm']
|
|
||||||
if internal in shops or not entry['crm']:
|
|
||||||
continue
|
|
||||||
base.cell(r, COL_BI_A, entry['crm'])
|
|
||||||
base.cell(r, COL_BI_B, internal)
|
|
||||||
if entry['brand']:
|
|
||||||
base.cell(r, 3, entry['brand'])
|
|
||||||
shops.add(entry['crm'])
|
|
||||||
r += 1
|
|
||||||
changed += 1
|
|
||||||
r = last_e + 1
|
|
||||||
for entry in new_items:
|
|
||||||
if entry['internal'] in items:
|
|
||||||
continue
|
|
||||||
base.cell(r, COL_BI_E, entry['crm'])
|
|
||||||
base.cell(r, COL_BI_F, entry['internal'])
|
|
||||||
items.add(entry['internal'])
|
|
||||||
r += 1
|
|
||||||
changed += 1
|
|
||||||
if changed:
|
|
||||||
wb.save(src)
|
|
||||||
result.update(ok=True, path=src,
|
|
||||||
message=f'基础信息补维护:新增门店 {len(new_shops)} / '
|
|
||||||
f'套餐 {len(new_items)},写入 {changed} 行到本地副本')
|
|
||||||
return result
|
|
||||||
finally:
|
finally:
|
||||||
wb.close()
|
wb.close()
|
||||||
|
result.update(new_shops=scanned['new_shops'], new_items=scanned['new_items'],
|
||||||
|
range_warnings=scanned['range_warnings'])
|
||||||
|
if not scanned['ok']:
|
||||||
|
result['message'] = f'{os.path.basename(src)} {scanned["message"]}'
|
||||||
|
return result
|
||||||
|
|
||||||
|
new_shops, new_items = scanned['new_shops'], scanned['new_items']
|
||||||
|
if dry_run:
|
||||||
|
result.update(ok=True, message=f'[演练] 新增门店 {len(new_shops)} / '
|
||||||
|
f'套餐 {len(new_items)}')
|
||||||
|
return result
|
||||||
|
if not new_shops and not new_items:
|
||||||
|
result.update(ok=True, path=src, message='基础信息无新增,未改动')
|
||||||
|
return result
|
||||||
|
|
||||||
|
changed = write_changes(src, scanned, lay)
|
||||||
|
result.update(ok=True, path=src, written=changed,
|
||||||
|
message=f'基础信息补维护:新增门店 {len(new_shops)} / '
|
||||||
|
f'套餐 {len(new_items)},写入 {changed} 行到本地副本')
|
||||||
|
return result
|
||||||
|
|||||||
@@ -2,7 +2,7 @@
|
|||||||
"""用 WPS/Excel COM 真正刷新透视表 + 重算公式缓存(本地副本)。
|
"""用 WPS/Excel COM 真正刷新透视表 + 重算公式缓存(本地副本)。
|
||||||
|
|
||||||
项目里已有成熟模式(XQ0037 / XQ0052):优先 ``Ket.Application``(WPS 表格),
|
项目里已有成熟模式(XQ0037 / XQ0052):优先 ``Ket.Application``(WPS 表格),
|
||||||
失败退 ``Excel.Application``。只刷新本地 ``_work/`` 副本,不碰共享盘。
|
失败退 ``Excel.Application``。只刷新本地过程表副本,不碰共享盘。
|
||||||
|
|
||||||
对外:
|
对外:
|
||||||
refresh(path, sheets=None) -> {"ok", "engine", "message"}
|
refresh(path, sheets=None) -> {"ok", "engine", "message"}
|
||||||
|
|||||||
@@ -0,0 +1,485 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""对比 sheet:今日遗留回填 + 按门店/项目分组验证(美团 / 抖音共用)。
|
||||||
|
|
||||||
|
2026-11-27 业务口径:
|
||||||
|
|
||||||
|
* **今日遗留(R)不再人工填**:取总表【团购统计】「未消费项目个数」(G),
|
||||||
|
按「门店 + 核销项目名称」汇总后逐行回填(美团取 类型 ∈ {美团, 点评},抖音取 抖音);
|
||||||
|
* **验证改为分组**:按 E 列门店 + F 列项目分组,组内 W 求和为 0 才算平;
|
||||||
|
W 为 ``-`` / 空的行不参与(见 :data:`config.COMPARE_VERIFY_SKIP`);
|
||||||
|
* ``二选一`` / ``四选一`` 自身也是项目名,与其成员同组统计
|
||||||
|
(见 :data:`config.COMPARE_GROUP_MEMBERS`)。
|
||||||
|
|
||||||
|
本模块只读表、只算数;写盘仍由 :mod:`compare_sheets` 用 zip+XML 完成,避免循环依赖。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from collections import defaultdict
|
||||||
|
from datetime import date, datetime, timedelta
|
||||||
|
from difflib import SequenceMatcher
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
from openpyxl.utils import column_index_from_string
|
||||||
|
|
||||||
|
from .. import config
|
||||||
|
|
||||||
|
|
||||||
|
def _cell(row, cnum):
|
||||||
|
"""取一行里第 cnum 列(1 起)的值,越界返回 None。"""
|
||||||
|
idx = int(cnum) - 1
|
||||||
|
if idx < 0 or idx >= len(row):
|
||||||
|
return None
|
||||||
|
return row[idx]
|
||||||
|
|
||||||
|
|
||||||
|
def _text(row, cnum):
|
||||||
|
value = _cell(row, cnum)
|
||||||
|
return '' if value is None else str(value).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def to_number(value):
|
||||||
|
"""转 float;None/空/非数值返回 None(0 是有效值,不能和「空」混)。"""
|
||||||
|
if value is None or isinstance(value, bool):
|
||||||
|
return None
|
||||||
|
if isinstance(value, (int, float)):
|
||||||
|
return float(value)
|
||||||
|
text = str(value).strip().replace(',', '')
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return float(text)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _clean(value):
|
||||||
|
"""回填用:0 / 空 → None(表里留空),其它保留整数形态。"""
|
||||||
|
num = to_number(value)
|
||||||
|
if num is None or abs(num) < 1e-9:
|
||||||
|
return None
|
||||||
|
return int(num) if float(num).is_integer() else round(num, 2)
|
||||||
|
|
||||||
|
|
||||||
|
def _as_date(value):
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.date()
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
text = str(value or '').strip()[:10]
|
||||||
|
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(text, fmt).date()
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def norm_item(text):
|
||||||
|
"""项目名归并:命中组成员的返回组名(二选一 / 四选一),否则原样返回。"""
|
||||||
|
key = str(text or '').strip()
|
||||||
|
if not key:
|
||||||
|
return ''
|
||||||
|
for group, members in config.COMPARE_GROUP_MEMBERS.items():
|
||||||
|
if key in members:
|
||||||
|
return group
|
||||||
|
return key
|
||||||
|
|
||||||
|
|
||||||
|
def load_unused(path, types):
|
||||||
|
"""读【团购统计】里指定团购类型的「未消费项目个数」,按 (门店, 项目) 汇总。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: 本地马敏团购总表副本
|
||||||
|
types: 参与汇总的团购类型,如 ``('美团', '点评')``
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``{'ok','stats','date','rows','message'}``;
|
||||||
|
``stats`` = ``{(门店, 项目): 未消费个数}``,``date`` 为数据里的最大消费日期。
|
||||||
|
"""
|
||||||
|
wanted = {str(t).strip() for t in (types or ()) if str(t).strip()}
|
||||||
|
out = {'ok': False, 'stats': {}, 'date': '', 'rows': 0, 'message': ''}
|
||||||
|
if not path or not os.path.isfile(path):
|
||||||
|
out['message'] = f'未找到总表副本:{path}'
|
||||||
|
return out
|
||||||
|
|
||||||
|
sheet = config.COMPARE_STATS_SHEET
|
||||||
|
i_type = column_index_from_string(config.COMPARE_STATS_TYPE_COL)
|
||||||
|
i_date = column_index_from_string(config.COMPARE_STATS_DATE_COL)
|
||||||
|
i_store = column_index_from_string(config.COMPARE_STATS_STORE_COL)
|
||||||
|
i_item = column_index_from_string(config.COMPARE_STATS_ITEM_COL)
|
||||||
|
i_unused = column_index_from_string(config.COMPARE_STATS_UNUSED_COL)
|
||||||
|
width = max(i_type, i_date, i_store, i_item, i_unused)
|
||||||
|
|
||||||
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
|
try:
|
||||||
|
if sheet not in wb.sheetnames:
|
||||||
|
out['message'] = f'总表缺少 sheet「{sheet}」'
|
||||||
|
return out
|
||||||
|
stats = defaultdict(float)
|
||||||
|
latest = None
|
||||||
|
used = 0
|
||||||
|
for row in wb[sheet].iter_rows(min_row=config.COMPARE_STATS_DATA_START,
|
||||||
|
max_col=width, values_only=True):
|
||||||
|
cells = list(row) + [None] * (width - len(row))
|
||||||
|
kind = str(cells[i_type - 1] or '').strip()
|
||||||
|
if wanted and kind not in wanted:
|
||||||
|
continue
|
||||||
|
store = str(cells[i_store - 1] or '').strip()
|
||||||
|
item = str(cells[i_item - 1] or '').strip()
|
||||||
|
if not store or not item:
|
||||||
|
continue
|
||||||
|
stats[(store, item)] += to_number(cells[i_unused - 1]) or 0.0
|
||||||
|
used += 1
|
||||||
|
day = _as_date(cells[i_date - 1])
|
||||||
|
if day and (latest is None or day > latest):
|
||||||
|
latest = day
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
out.update(ok=True, stats=dict(stats), rows=used,
|
||||||
|
date=latest.isoformat() if latest else '')
|
||||||
|
if not stats:
|
||||||
|
out['message'] = f'【{sheet}】没有 {"、".join(sorted(wanted)) or "任何"} 类型的核销记录'
|
||||||
|
else:
|
||||||
|
out['message'] = (f'【{sheet}】{len(stats)} 个门店/项目组合,'
|
||||||
|
f'消费日期 {out["date"] or "空"}')
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def build_fill_edits(rows, stats, store_col, item_col, refunds=None, start_row=None):
|
||||||
|
"""按 A 列门店 + B 列原始项目名,从团购统计取「未消费项目个数」回填今日遗留。
|
||||||
|
|
||||||
|
若给了 ``refunds``({(门店, 项目): 笔数}),再同门店同项目从今日遗留里扣掉;
|
||||||
|
精确项目名找得到就扣在那一行,否则按归并组(二选一/四选一)扣在组内第一行。
|
||||||
|
``stats`` 为空(未贴当天团购统计)时不产计划,保持原值。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``{'edits': {行号: 值或 None}, 'filled': n, 'unmatched': [...],
|
||||||
|
'refund_applied': [...], 'refund_unmatched': [...], 'skipped': ''}``
|
||||||
|
"""
|
||||||
|
start = config.COMPARE_DATA_START if start_row is None else int(start_row)
|
||||||
|
out = {'edits': {}, 'filled': 0, 'unmatched': [], 'skipped': '',
|
||||||
|
'refund_applied': [], 'refund_unmatched': []}
|
||||||
|
if not stats:
|
||||||
|
out['skipped'] = '团购统计无该平台数据,今日遗留保持原样'
|
||||||
|
return out
|
||||||
|
|
||||||
|
values = {}
|
||||||
|
unmatched = set()
|
||||||
|
for offset, row in enumerate(rows):
|
||||||
|
row_no = start + offset
|
||||||
|
store = _text(row, store_col)
|
||||||
|
item = _text(row, item_col)
|
||||||
|
key = (store, item)
|
||||||
|
values[row_no] = _clean(stats.get(key)) if store else None
|
||||||
|
if item and key not in stats:
|
||||||
|
unmatched.add(item)
|
||||||
|
|
||||||
|
if refunds:
|
||||||
|
row_index, group_index = {}, {}
|
||||||
|
for offset, row in enumerate(rows):
|
||||||
|
row_no = start + offset
|
||||||
|
store = _text(row, store_col)
|
||||||
|
item = _text(row, item_col)
|
||||||
|
row_index.setdefault((store, item), row_no)
|
||||||
|
group_index.setdefault((store, norm_item(item)), row_no)
|
||||||
|
for (store, item), count in sorted(refunds.items()):
|
||||||
|
row_no = row_index.get((store, item))
|
||||||
|
if row_no is None:
|
||||||
|
row_no = group_index.get((store, norm_item(item)))
|
||||||
|
if row_no is None:
|
||||||
|
out['refund_unmatched'].append({'store': store, 'item': item, 'count': count})
|
||||||
|
continue
|
||||||
|
values[row_no] = (values.get(row_no) or 0.0) - float(count)
|
||||||
|
out['refund_applied'].append({'store': store, 'item': item, 'row': row_no,
|
||||||
|
'count': count, 'value': _clean(values[row_no])})
|
||||||
|
|
||||||
|
out['edits'] = {row_no: _clean(value) for row_no, value in values.items()}
|
||||||
|
out['filled'] = sum(1 for value in out['edits'].values() if value is not None)
|
||||||
|
out['unmatched'] = sorted(unmatched)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _alias(name):
|
||||||
|
"""取平台门店名最后一个括号里的店名并去掉末尾「店」。"""
|
||||||
|
hits = re.findall(r'[((]([^(())]+)[))]', str(name or ''))
|
||||||
|
if not hits:
|
||||||
|
return ''
|
||||||
|
return re.sub(r'店$', '', hits[-1].strip())
|
||||||
|
|
||||||
|
|
||||||
|
def _match_store(name, base_stores, pool):
|
||||||
|
"""平台门店名 → 内部门店名:先查基础信息 A→B,再按括号店名匹配总表门店。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``(内部门店, 匹配方式)``;匹配不到返回 ``('', 原因)``。
|
||||||
|
"""
|
||||||
|
key = str(name or '').strip()
|
||||||
|
if not key:
|
||||||
|
return '', '门店为空'
|
||||||
|
hit = base_stores.get(key)
|
||||||
|
if hit:
|
||||||
|
return hit, '基础信息'
|
||||||
|
alias = _alias(key) or key
|
||||||
|
exact = [s for s in pool if s == alias]
|
||||||
|
if len(exact) == 1:
|
||||||
|
return exact[0], '同名'
|
||||||
|
pref = [s for s in pool if s.startswith(alias)]
|
||||||
|
if len(pref) == 1:
|
||||||
|
return pref[0], '前缀'
|
||||||
|
if len(pref) > 1:
|
||||||
|
return '', '多候选:' + '/'.join(pref[:3])
|
||||||
|
rev = [s for s in pool if alias.startswith(s)]
|
||||||
|
if len(rev) == 1:
|
||||||
|
return rev[0], '反向'
|
||||||
|
if not pool:
|
||||||
|
return '', '总表门店为空'
|
||||||
|
best = max(pool, key=lambda s: SequenceMatcher(None, alias, s).ratio())
|
||||||
|
if SequenceMatcher(None, alias, best).ratio() >= config.COMPARE_REFUND_STORE_MIN_RATIO:
|
||||||
|
return best, '相似'
|
||||||
|
return '', '无匹配:' + alias
|
||||||
|
|
||||||
|
|
||||||
|
def _biz_day(value):
|
||||||
|
"""营业日:hour < 10 算前一天(与明细表 AD 列同一口径)。"""
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
day, hour = value.date(), value.hour
|
||||||
|
elif isinstance(value, date):
|
||||||
|
day, hour = value, 0
|
||||||
|
else:
|
||||||
|
text = str(value or '').strip()
|
||||||
|
m = re.match(r'(\d{4})[-/](\d{1,2})[-/](\d{1,2})[ T](\d{1,2}):', text)
|
||||||
|
if m:
|
||||||
|
batch = [int(x) for x in m.groups()]
|
||||||
|
day, hour = date(*batch[:3]), batch[3]
|
||||||
|
else:
|
||||||
|
day, hour = _as_date(text), 0
|
||||||
|
if day is None:
|
||||||
|
return None
|
||||||
|
return day - timedelta(days=1) if hour < 10 else day
|
||||||
|
|
||||||
|
|
||||||
|
def _reset_if_needed(ws):
|
||||||
|
"""平台导出/模板的 dimension 经常不准:1×1 会读不到,写成百万行又会白扫。"""
|
||||||
|
rows = ws.max_row or 1
|
||||||
|
cols = ws.max_column or 1
|
||||||
|
if rows <= 1 or cols <= 1 or rows > 100000 or cols > 1000:
|
||||||
|
ws.reset_dimensions()
|
||||||
|
|
||||||
|
|
||||||
|
def _read_base_info(wb):
|
||||||
|
"""读【基础信息】:返回 ({平台商品名: 内部项目}, {平台门店: 内部门店})。"""
|
||||||
|
sheet = config.COMPARE_BASE_INFO_SHEET
|
||||||
|
if sheet not in wb.sheetnames:
|
||||||
|
return {}, {}
|
||||||
|
a, b, e, f = (column_index_from_string(c) for c in config.COMPARE_BASE_INFO_COLS)
|
||||||
|
width = max(a, b, e, f)
|
||||||
|
items, stores = {}, {}
|
||||||
|
ws = wb[sheet]
|
||||||
|
_reset_if_needed(ws)
|
||||||
|
for row in ws.iter_rows(min_row=1, max_col=width, values_only=True):
|
||||||
|
cells = list(row) + [None] * (width - len(row))
|
||||||
|
product = str(cells[e - 1] or '').strip()
|
||||||
|
item = str(cells[f - 1] or '').strip()
|
||||||
|
if product and item:
|
||||||
|
items.setdefault(product, item)
|
||||||
|
platform_store = str(cells[a - 1] or '').strip()
|
||||||
|
store = str(cells[b - 1] or '').strip()
|
||||||
|
if platform_store and store:
|
||||||
|
stores.setdefault(platform_store, store)
|
||||||
|
return items, stores
|
||||||
|
|
||||||
|
|
||||||
|
def load_refunds(path, plan, store_pool, day=None):
|
||||||
|
"""统计本地表里退款/撤销核销的笔数(按 门店+项目,默认只算营业日当天)。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
path: 本地美团 / 抖音表(同一本工作簿里有【基础信息】和明细 sheet)
|
||||||
|
plan: :data:`config.COMPARE_REFUND_GROUPS` 里的一项
|
||||||
|
store_pool: 总表里出现的门店名(用于括号店名匹配)
|
||||||
|
day: 营业日;给了就按 plan['date_col'] 过滤(导出常跨好几天)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``{'ok','counts','rows','items','unmatched','message'}``;
|
||||||
|
``counts`` = ``{(内部门店, 内部项目): 笔数}``。
|
||||||
|
"""
|
||||||
|
out = {'ok': False, 'counts': {}, 'rows': 0, 'items': {}, 'unmatched': [], 'message': ''}
|
||||||
|
if not path or not os.path.isfile(path):
|
||||||
|
out['message'] = f'未找到本地表:{path}'
|
||||||
|
return out
|
||||||
|
sheet = plan.get('sheet') or ''
|
||||||
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
|
try:
|
||||||
|
if sheet not in wb.sheetnames:
|
||||||
|
out['message'] = f'缺少 sheet「{sheet}」:{os.path.basename(path)}'
|
||||||
|
return out
|
||||||
|
base_items, base_stores = _read_base_info(wb)
|
||||||
|
statuses = {str(s).strip() for s in (plan.get('statuses') or ())}
|
||||||
|
i_status = column_index_from_string(plan['status_col'])
|
||||||
|
i_store = column_index_from_string(plan['store_col'])
|
||||||
|
i_item = column_index_from_string(plan['item_col'])
|
||||||
|
fallback = plan.get('item_fallback_col') or ''
|
||||||
|
i_fallback = column_index_from_string(fallback) if fallback else 0
|
||||||
|
date_col = plan.get('date_col') or ''
|
||||||
|
i_date = column_index_from_string(date_col) if date_col else 0
|
||||||
|
width = max(i_status, i_store, i_item, i_fallback, i_date)
|
||||||
|
|
||||||
|
ws = wb[sheet]
|
||||||
|
_reset_if_needed(ws)
|
||||||
|
counts = defaultdict(int)
|
||||||
|
unmatched = []
|
||||||
|
rows = 0
|
||||||
|
skipped_day = 0
|
||||||
|
for row in ws.iter_rows(min_row=int(plan.get('data_start') or 1),
|
||||||
|
max_col=width, values_only=True):
|
||||||
|
cells = list(row) + [None] * (width - len(row))
|
||||||
|
status = str(cells[i_status - 1] or '').strip()
|
||||||
|
if status not in statuses:
|
||||||
|
continue
|
||||||
|
if day is not None and i_date:
|
||||||
|
if _biz_day(cells[i_date - 1]) != day:
|
||||||
|
skipped_day += 1
|
||||||
|
continue
|
||||||
|
rows += 1
|
||||||
|
raw_store = str(cells[i_store - 1] or '').strip()
|
||||||
|
raw_item = str(cells[i_item - 1] or '').strip()
|
||||||
|
store, how = _match_store(raw_store, base_stores, store_pool)
|
||||||
|
item = base_items.get(raw_item, '')
|
||||||
|
if not item and i_fallback:
|
||||||
|
item = str(cells[i_fallback - 1] or '').strip()
|
||||||
|
if not store or not item:
|
||||||
|
unmatched.append({'status': status, 'store': raw_store, 'item': raw_item,
|
||||||
|
'reason': how if not store else '项目未映射'})
|
||||||
|
continue
|
||||||
|
counts[(store, item)] += 1
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
out.update(ok=True, counts=dict(counts), rows=rows, items=base_items,
|
||||||
|
unmatched=unmatched, skipped_day=skipped_day)
|
||||||
|
if not rows:
|
||||||
|
out['message'] = (f'【{sheet}】营业日没有退款/撤销核销行'
|
||||||
|
+ (f'(另有 {skipped_day} 行是其它日期,已跳过)' if skipped_day else ''))
|
||||||
|
elif unmatched:
|
||||||
|
out['message'] = (f'【{sheet}】{rows} 行退款/撤销,'
|
||||||
|
f'{sum(counts.values())} 行已归位,{len(unmatched)} 行未匹配')
|
||||||
|
else:
|
||||||
|
out['message'] = (f'【{sheet}】{rows} 行退款/撤销,全部已归到 '
|
||||||
|
f'{len(counts)} 个门店项目')
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def verify(rows, cols, start_row=None, limit=None):
|
||||||
|
"""按 (E 门店, F 项目归并后) 分组,组内 W 求和为 0 判平。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
rows: ``compare_sheets._read_cells()`` 读出的数据行(第 5 行起)
|
||||||
|
cols: 列号字典,需含 ``store`` / ``item`` / ``verify``
|
||||||
|
start_row: 数据起始行,默认 :data:`config.COMPARE_DATA_START`
|
||||||
|
limit: 返回的不平组上限,默认 :data:`config.COMPARE_UNBALANCED_LIMIT`
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``ok / total_groups / ok_groups / unbalanced / unbalanced_count /
|
||||||
|
skipped_rows / checked_rows / bad_rows``;``unbalanced`` 每项含
|
||||||
|
``store / item / diff / rows / bad``。
|
||||||
|
"""
|
||||||
|
start = config.COMPARE_DATA_START if start_row is None else int(start_row)
|
||||||
|
limit = config.COMPARE_UNBALANCED_LIMIT if limit is None else int(limit)
|
||||||
|
groups = {}
|
||||||
|
skipped_rows = checked_rows = bad_rows = 0
|
||||||
|
|
||||||
|
for offset, row in enumerate(rows):
|
||||||
|
row_no = start + offset
|
||||||
|
store = _text(row, cols['store'])
|
||||||
|
item = norm_item(_text(row, cols['item']))
|
||||||
|
group = groups.setdefault((store, item),
|
||||||
|
{'sum': 0.0, 'count': 0, 'skipped': 0,
|
||||||
|
'bad': [], 'row_ids': []})
|
||||||
|
raw = _cell(row, cols['verify'])
|
||||||
|
text = '' if raw is None else str(raw).strip()
|
||||||
|
if raw is None or text in config.COMPARE_VERIFY_SKIP:
|
||||||
|
group['skipped'] += 1
|
||||||
|
skipped_rows += 1
|
||||||
|
continue
|
||||||
|
num = to_number(raw)
|
||||||
|
if num is None:
|
||||||
|
group['bad'].append([row_no, text])
|
||||||
|
bad_rows += 1
|
||||||
|
continue
|
||||||
|
group['sum'] += num
|
||||||
|
group['count'] += 1
|
||||||
|
group['row_ids'].append(row_no)
|
||||||
|
checked_rows += 1
|
||||||
|
|
||||||
|
total = ok = 0
|
||||||
|
unbalanced = []
|
||||||
|
for (store, item), group in groups.items():
|
||||||
|
if not group['count'] and not group['bad']:
|
||||||
|
continue # 整组都是「-」/空,不参与
|
||||||
|
total += 1
|
||||||
|
diff = round(group['sum'], 2)
|
||||||
|
if not group['bad'] and abs(diff) <= config.COMPARE_VERIFY_TOL:
|
||||||
|
ok += 1
|
||||||
|
continue
|
||||||
|
unbalanced.append({'store': store, 'item': item, 'diff': diff,
|
||||||
|
'rows': group['count'], 'bad': group['bad'][:5]})
|
||||||
|
unbalanced.sort(key=lambda x: (-abs(x['diff']), x['store'], x['item']))
|
||||||
|
|
||||||
|
return {'ok': not unbalanced, 'total_groups': total, 'ok_groups': ok,
|
||||||
|
'unbalanced': unbalanced[:limit], 'unbalanced_count': len(unbalanced),
|
||||||
|
'skipped_rows': skipped_rows, 'checked_rows': checked_rows,
|
||||||
|
'bad_rows': bad_rows, 'groups': groups}
|
||||||
|
|
||||||
|
|
||||||
|
def build_meal_edits(groups):
|
||||||
|
"""对仍不平的「双人餐 / 三人餐」配对生成【平台结错】列调整。
|
||||||
|
|
||||||
|
触发:餐行(双人餐/三人餐)自身不平,同门店存在基础项目行,且基础行为正数
|
||||||
|
(基础行为负时再减只会扩大差额,跳过并列入 skipped 由人工看)。
|
||||||
|
倍数:``N`` = 餐行的差额(正数),餐行 J = N,基础行 J = -人数 × N
|
||||||
|
(双人餐 -2N、三人餐 -3N);同一基础行遇到多餐时累加。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
groups: :func:`verify` 返回的 ``groups``(键 ``(门店, 项目)``)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``(edits, detail, skipped)``;``edits`` = ``{行号: J 值}``,``detail`` 每项含
|
||||||
|
``store / item / base / meal_row / base_row / times / meal_j / base_j``,
|
||||||
|
``skipped`` 每项含 ``store / item / base / sum / reason``。
|
||||||
|
"""
|
||||||
|
suffixes = config.COMPARE_MEAL_SUFFIXES
|
||||||
|
edits, detail, skipped = {}, [], []
|
||||||
|
for (store, item), info in sorted(groups.items()):
|
||||||
|
suffix = next((s for s in suffixes
|
||||||
|
if item.endswith(s) and item != s), '')
|
||||||
|
if not suffix:
|
||||||
|
continue
|
||||||
|
if abs(info['sum']) <= config.COMPARE_VERIFY_TOL and not info['bad']:
|
||||||
|
continue # 餐行自己平,不需要修正
|
||||||
|
base = item[:-len(suffix)]
|
||||||
|
base_info = groups.get((store, base))
|
||||||
|
if not base_info:
|
||||||
|
continue # 没有基础项目行,无法配对
|
||||||
|
if base_info['sum'] <= config.COMPARE_VERIFY_TOL:
|
||||||
|
skipped.append({'store': store, 'item': item, 'base': base,
|
||||||
|
'sum': round(base_info['sum'], 2),
|
||||||
|
'reason': '基础行不为正,写负数会扩大差额'})
|
||||||
|
continue
|
||||||
|
meal_rows = info['row_ids'] or [row for row, _ in info['bad']]
|
||||||
|
base_rows = base_info['row_ids'] or [row for row, _ in base_info['bad']]
|
||||||
|
if not meal_rows or not base_rows:
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 倍数 = 餐行差额(如餐行 -3 → 写 3 和 -2×3)
|
||||||
|
times = int(round(-info['sum'])) if info['sum'] < 0 else config.COMPARE_MEAL_ADJUST
|
||||||
|
times = max(1, times)
|
||||||
|
meal_row, base_row = meal_rows[0], base_rows[0]
|
||||||
|
headcount = suffixes[suffix]
|
||||||
|
meal_j = times
|
||||||
|
base_j = -headcount * times
|
||||||
|
edits[meal_row] = edits.get(meal_row, 0) + meal_j
|
||||||
|
edits[base_row] = edits.get(base_row, 0) + base_j
|
||||||
|
detail.append({'store': store, 'item': item, 'base': base,
|
||||||
|
'meal_row': meal_row, 'base_row': base_row,
|
||||||
|
'times': times, 'meal_j': meal_j, 'base_j': base_j})
|
||||||
|
return edits, detail, skipped
|
||||||
@@ -0,0 +1,610 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""马敏团购总表「对比」sheet 日滚动 + 清空(核对流程第一步)。
|
||||||
|
|
||||||
|
每天的总表副本是从**昨天的表**复制来的,所以副本里的「今日遗留」其实是昨天的数据:
|
||||||
|
先滚到「昨日遗留」,再把「今日遗留」清空等当天重算。两张 sheet 各处理一次:
|
||||||
|
|
||||||
|
* 美团分支 → 「新美大对比 (2)」
|
||||||
|
* 抖音分支 → 「抖音对比(2)」
|
||||||
|
|
||||||
|
数据行 :data:`config.COMPARE_DATA_START`(第 5 行)到该 sheet 末行:
|
||||||
|
|
||||||
|
1. I/J/K 三列清空(上日核对结果);
|
||||||
|
2. Q「昨日遗留」= R「今日遗留」当前值 - S「漏核销」(R 是昨天填的),按值写入;
|
||||||
|
3. R「今日遗留」按【团购统计】「未消费项目个数」逐行回填(见 :mod:`compare_groups`);
|
||||||
|
4. 按 X 列(无表头的备注列)过滤昨日遗留:X 为空、或备注是「某某前消费」这类说明
|
||||||
|
→ 昨日遗留保留;其它备注内容 → 昨日遗留清空;
|
||||||
|
5. 「漏核销」列清空(按标题定位,找不到只告警跳过);
|
||||||
|
6. 写盘后用 WPS/Excel COM 重算一次,再按 **E 门店 + F 项目分组**核 W 列「验证」:
|
||||||
|
组内求和为 0 才算平(``-`` / 空不参与),不平只出明细、不判失败。
|
||||||
|
|
||||||
|
幂等保护:若当前 R 列已等于按【团购统计】算出的回填值,说明今天已经填过/滚过,直接跳过——
|
||||||
|
避免重复运行把「昨日遗留」也抹掉(``force=True`` 可强制重跑)。
|
||||||
|
|
||||||
|
写盘用 zip+XML 直接改单元格(保留透视、共享公式、外部链接),不走 openpyxl save。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import shutil
|
||||||
|
import zipfile
|
||||||
|
from datetime import date, datetime
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
from openpyxl.utils import column_index_from_string as col
|
||||||
|
from openpyxl.utils import get_column_letter as letter
|
||||||
|
|
||||||
|
from .. import config
|
||||||
|
from . import compare_groups, com_refresh, share_copy
|
||||||
|
from .paste_to_master import (_CELL_RE, _ROW_RE, _col_num, _make_cell,
|
||||||
|
_sheet_xml_path)
|
||||||
|
from .zipio import open_zip
|
||||||
|
|
||||||
|
|
||||||
|
class CompareError(RuntimeError):
|
||||||
|
"""对比表处理失败(sheet 缺失 / 列标题找不到 / 写盘失败)。"""
|
||||||
|
|
||||||
|
|
||||||
|
def _norm(text):
|
||||||
|
"""表名/标题归一化:去空白,全角括号与星号转半角(表名两种写法都能对上)。"""
|
||||||
|
s = str(text or '').strip()
|
||||||
|
return re.sub(r'\s+', '', s).replace('(', '(').replace(')', ')').replace('*', '*')
|
||||||
|
|
||||||
|
|
||||||
|
def _find_sheet(sheetnames, wanted):
|
||||||
|
"""按归一化名精确匹配,再退化为包含匹配;找不到返回空串。"""
|
||||||
|
key = _norm(wanted)
|
||||||
|
for name in sheetnames:
|
||||||
|
if _norm(name) == key:
|
||||||
|
return name
|
||||||
|
for name in sheetnames:
|
||||||
|
if key and key in _norm(name):
|
||||||
|
return name
|
||||||
|
return ''
|
||||||
|
|
||||||
|
|
||||||
|
def _parse_day(value):
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.date()
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
text = str(value or '').strip()[:10]
|
||||||
|
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(text, fmt).date()
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def master_path(day):
|
||||||
|
return os.path.join(config.WORK_DIR,
|
||||||
|
f'{config.LINK_BOOK}{day.month}.{day.day}.xlsx')
|
||||||
|
|
||||||
|
|
||||||
|
def _locate_columns(ws, max_col):
|
||||||
|
"""在前几行表头里定位「漏核销 / 昨日遗留 / 今日遗留」列号(1 起)。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``(header_row, {'miss': 列号, 'yesterday': 列号, 'today': 列号})``,缺失的键不出现。
|
||||||
|
"""
|
||||||
|
titles = {'miss': config.COMPARE_MISS_TITLE,
|
||||||
|
'yesterday': config.COMPARE_YESTERDAY_TITLE,
|
||||||
|
'today': config.COMPARE_TODAY_TITLE}
|
||||||
|
best = (0, {})
|
||||||
|
for r in range(1, min(config.COMPARE_HEADER_SCAN_ROWS, int(ws.max_row or 0)) + 1):
|
||||||
|
row = [ws.cell(r, c).value for c in range(1, max_col + 1)]
|
||||||
|
found = {}
|
||||||
|
for c, v in enumerate(row, 1):
|
||||||
|
t = _norm(v)
|
||||||
|
if not t:
|
||||||
|
continue
|
||||||
|
for key, title in titles.items():
|
||||||
|
if key not in found and _norm(title) in t:
|
||||||
|
found[key] = c
|
||||||
|
if len(found) > len(best[1]):
|
||||||
|
best = (r, found)
|
||||||
|
return best
|
||||||
|
|
||||||
|
|
||||||
|
def _read_cells(path, sheet, max_col):
|
||||||
|
"""读数据区(第 5 行起)每行在需要的列上的值,返回 (值行列表, 末行号)。
|
||||||
|
|
||||||
|
只读一次、区间取列,避免 read_only 模式下逐格访问巨慢。
|
||||||
|
"""
|
||||||
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
|
try:
|
||||||
|
ws = wb[sheet]
|
||||||
|
rows = []
|
||||||
|
for row in ws.iter_rows(min_row=config.COMPARE_DATA_START, max_col=max_col,
|
||||||
|
values_only=True):
|
||||||
|
rows.append(list(row))
|
||||||
|
while rows and all(v is None for v in rows[-1]):
|
||||||
|
rows.pop()
|
||||||
|
last = config.COMPARE_DATA_START + len(rows) - 1
|
||||||
|
return rows, last
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _to_number(value):
|
||||||
|
"""数值/数字文本 → float;#DIV/0!、空、异常返回 None。"""
|
||||||
|
if value is None or isinstance(value, bool):
|
||||||
|
return None
|
||||||
|
if isinstance(value, (int, float)):
|
||||||
|
return float(value)
|
||||||
|
text = str(value).strip().replace(',', '')
|
||||||
|
if not text:
|
||||||
|
return None
|
||||||
|
try:
|
||||||
|
return float(text)
|
||||||
|
except ValueError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _cell_value(row, cnum):
|
||||||
|
"""取数据行第 cnum 列(1 起)的值,越界返回 None。"""
|
||||||
|
idx = int(cnum) - 1
|
||||||
|
return row[idx] if 0 <= idx < len(row) else None
|
||||||
|
|
||||||
|
|
||||||
|
def _same_number(left, right):
|
||||||
|
"""判重用的相等判断:None 与 None 相同,数值按容差比较。"""
|
||||||
|
a, b = compare_groups.to_number(left), compare_groups.to_number(right)
|
||||||
|
if a is None or b is None:
|
||||||
|
return a is None and b is None
|
||||||
|
return abs(a - b) <= config.COMPARE_VERIFY_TOL
|
||||||
|
|
||||||
|
|
||||||
|
def _locate_group_cols(ws, header_row, max_col):
|
||||||
|
"""找表头行里的门店/核销项目名称列:返回 (A/B 原始列, E/F 分组列)。
|
||||||
|
|
||||||
|
A/B 是透视原始名(回填今日遗留用它查团购统计),E/F 是分组用列
|
||||||
|
(F 带归并公式)。任一处找不到第 2 次出现时,E/F 回退配置的兜底列。
|
||||||
|
"""
|
||||||
|
titles = config.COMPARE_GROUP_HEADERS
|
||||||
|
found = {t: [] for t in titles}
|
||||||
|
for c in range(1, max_col + 1):
|
||||||
|
text = _norm(ws.cell(header_row, c).value)
|
||||||
|
if not text:
|
||||||
|
continue
|
||||||
|
for title in titles:
|
||||||
|
if text == _norm(title):
|
||||||
|
found[title].append(c)
|
||||||
|
|
||||||
|
raw, grp = [], []
|
||||||
|
for title, fallback in zip(titles, config.COMPARE_GROUP_FALLBACK_COLS):
|
||||||
|
hits = found[title]
|
||||||
|
raw.append(hits[0] if hits else col(fallback))
|
||||||
|
grp.append(hits[1] if len(hits) > 1 else col(fallback))
|
||||||
|
missing = [t for t in titles if len(found[t]) < 2]
|
||||||
|
if missing:
|
||||||
|
config.log(f'表头第 {header_row} 行没找到第 2 个「{"、".join(missing)}」,'
|
||||||
|
f'分组列回退 {"、".join(config.COMPARE_GROUP_FALLBACK_COLS)}', 'WARN')
|
||||||
|
return raw[0], raw[1], grp[0], grp[1]
|
||||||
|
|
||||||
|
|
||||||
|
def _locate_title_col(ws, max_col, title, fallback_letter):
|
||||||
|
"""在前几行表头里找标题包含 title 的列;找不到回退 fallback_letter。"""
|
||||||
|
for r in range(1, min(config.COMPARE_HEADER_SCAN_ROWS, int(ws.max_row or 0)) + 1):
|
||||||
|
row = [ws.cell(r, c).value for c in range(1, max_col + 1)]
|
||||||
|
for c, value in enumerate(row, 1):
|
||||||
|
if value is not None and title in _norm(value):
|
||||||
|
return c
|
||||||
|
config.log(f'没找到「{title}」表头,回退 {fallback_letter} 列', 'WARN')
|
||||||
|
return col(fallback_letter)
|
||||||
|
|
||||||
|
|
||||||
|
def _rebuild_row(row_xml, row_no, edits):
|
||||||
|
"""按 ``{列号: 值或 None}`` 重建一行:指定列替换/清空(清空保留原样式),其余原样。"""
|
||||||
|
cells, styles = {}, {}
|
||||||
|
if row_xml:
|
||||||
|
for m in _CELL_RE.finditer(row_xml):
|
||||||
|
cnum = _col_num(m.group(1))
|
||||||
|
sm = re.search(r'\bs="(\d+)"', m.group(3) or '')
|
||||||
|
if sm:
|
||||||
|
styles[cnum] = sm.group(1)
|
||||||
|
if cnum not in edits:
|
||||||
|
cells[cnum] = m.group(0)
|
||||||
|
for cnum, value in edits.items():
|
||||||
|
if value is None:
|
||||||
|
s = f' s="{styles[cnum]}"' if cnum in styles else ''
|
||||||
|
cells[cnum] = f'<c r="{letter(cnum)}{row_no}"{s}/>'
|
||||||
|
else:
|
||||||
|
cells[cnum] = _make_cell(row_no, cnum, value, styles.get(cnum, ''))
|
||||||
|
return '<row r="{}">{}</row>'.format(
|
||||||
|
row_no, ''.join(cell for _, cell in sorted(cells.items())))
|
||||||
|
|
||||||
|
|
||||||
|
def _patch_sheet(xml_text, edits_by_row):
|
||||||
|
"""把 ``{行号: {列号: 值}}`` 应用到 sheet XML(单次扫描 + 一次拼接,避免 O(n²))。"""
|
||||||
|
pieces, handled, pos = [], set(), 0
|
||||||
|
for m in _ROW_RE.finditer(xml_text):
|
||||||
|
mm = re.search(r'\br="(\d+)"', '<row' + (m.group(1) or '') + '>')
|
||||||
|
if not mm:
|
||||||
|
continue
|
||||||
|
row_no = int(mm.group(1))
|
||||||
|
if row_no not in edits_by_row:
|
||||||
|
continue
|
||||||
|
pieces.append(xml_text[pos:m.start()])
|
||||||
|
pieces.append(_rebuild_row(m.group(0), row_no, edits_by_row[row_no]))
|
||||||
|
pos = m.end()
|
||||||
|
handled.add(row_no)
|
||||||
|
pieces.append(xml_text[pos:])
|
||||||
|
out = ''.join(pieces)
|
||||||
|
|
||||||
|
missing = [r for r in sorted(edits_by_row) if r not in handled]
|
||||||
|
if missing:
|
||||||
|
extra = ''.join(_rebuild_row(None, r, edits_by_row[r]) for r in missing)
|
||||||
|
out = out.replace('</sheetData>', extra + '</sheetData>', 1)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _write_sheet(path, sheet, edits_by_row):
|
||||||
|
"""zip+XML 写一个 sheet(其余部件原样搬运,保留透视/外部链接)。"""
|
||||||
|
zf = open_zip(path)
|
||||||
|
tmp = path + '.cmp.tmp'
|
||||||
|
try:
|
||||||
|
xml_path = _sheet_xml_path(zf, sheet)
|
||||||
|
if not xml_path:
|
||||||
|
raise CompareError(f'工作簿里找不到 sheet「{sheet}」的 XML')
|
||||||
|
text = zf.read(xml_path).decode('utf-8', 'replace')
|
||||||
|
patched = _patch_sheet(text, edits_by_row)
|
||||||
|
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||||
|
for info in zf.infolist():
|
||||||
|
if info.is_dir():
|
||||||
|
continue
|
||||||
|
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||||
|
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||||
|
zi.external_attr = info.external_attr
|
||||||
|
data = patched.encode('utf-8') if info.filename == xml_path else zf.read(info)
|
||||||
|
dst.writestr(zi, data)
|
||||||
|
finally:
|
||||||
|
zf.close()
|
||||||
|
os.replace(tmp, path)
|
||||||
|
|
||||||
|
|
||||||
|
def _plan_sheet(path, sheet, action, force, day):
|
||||||
|
"""为一张对比 sheet 生成 edits 计划(含今日遗留回填、退款冲减与判重)。"""
|
||||||
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
|
try:
|
||||||
|
if sheet not in wb.sheetnames:
|
||||||
|
raise CompareError(f'工作簿缺少 sheet「{sheet}」')
|
||||||
|
probe = wb[sheet]
|
||||||
|
max_col = max(int(probe.max_column or 1),
|
||||||
|
max(col(c) for c in config.COMPARE_CLEAR_COLS),
|
||||||
|
col(config.COMPARE_REMARK_COL))
|
||||||
|
header_row, cols = _locate_columns(probe, max_col)
|
||||||
|
raw_store, raw_item, group_store, group_item = _locate_group_cols(
|
||||||
|
probe, header_row, max_col)
|
||||||
|
cols.update(store=group_store, item=group_item,
|
||||||
|
verify=_locate_title_col(probe, max_col, config.COMPARE_VERIFY_TITLE,
|
||||||
|
config.COMPARE_VERIFY_COL),
|
||||||
|
platform_error=_locate_title_col(
|
||||||
|
probe, max_col, config.COMPARE_PLATFORM_ERROR_TITLE,
|
||||||
|
config.COMPARE_PLATFORM_ERROR_COL))
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
if 'today' not in cols:
|
||||||
|
raise CompareError(f'「{sheet}」前 {config.COMPARE_HEADER_SCAN_ROWS} 行没找到'
|
||||||
|
f'「{config.COMPARE_TODAY_TITLE}」列标题')
|
||||||
|
if 'yesterday' not in cols:
|
||||||
|
raise CompareError(f'「{sheet}」没找到「{config.COMPARE_YESTERDAY_TITLE}」列标题')
|
||||||
|
|
||||||
|
rows, last = _read_cells(path, sheet, max([max_col] + list(cols.values())))
|
||||||
|
base = {'sheet': sheet, 'header_row': header_row, 'cols': cols, 'path': path}
|
||||||
|
|
||||||
|
# 今日遗留回填计划:按 A 门店 + B 原始项目名,取【团购统计】「未消费项目个数」
|
||||||
|
types = config.COMPARE_STATS_TYPES.get(str(action or '').strip(), ())
|
||||||
|
stats = compare_groups.load_unused(path, types)
|
||||||
|
|
||||||
|
# 退款/撤销核销:从本地美团 / 抖音表计数,同门店同项目从今日遗留扣掉
|
||||||
|
store_pool = sorted({str(_cell_value(row, cols['store']) or '').strip()
|
||||||
|
for row in rows} - {''})
|
||||||
|
refund_plan = config.COMPARE_REFUND_GROUPS.get(str(action or '').strip())
|
||||||
|
refund = {'ok': False, 'counts': {}, 'rows': 0, 'unmatched': [], 'message': ''}
|
||||||
|
if refund_plan:
|
||||||
|
local = os.path.join(config.WORK_DIR, share_copy.table_name(
|
||||||
|
refund_plan.get('book') or '', day, config.SHARE_TABLE_EXT))
|
||||||
|
refund = compare_groups.load_refunds(local, refund_plan, store_pool, day)
|
||||||
|
|
||||||
|
fill = compare_groups.build_fill_edits(rows, stats['stats'], raw_store, raw_item,
|
||||||
|
refunds=refund['counts'])
|
||||||
|
base.update(fill=fill, stats=stats, refund=refund)
|
||||||
|
|
||||||
|
if fill.get('skipped'):
|
||||||
|
# 【团购统计】没有该平台数据时不动表:既不能回填今日遗留,滚动 Q 也无法判重
|
||||||
|
return dict(base, last=last, edits={}, kept=0, cleared=0, bad_num=0,
|
||||||
|
prev_today_filled=0, miss_filled=0, skipped='', error=fill['skipped'])
|
||||||
|
|
||||||
|
t_col, y_col = cols['today'], cols['yesterday']
|
||||||
|
# 判重:当前 R 已等于今天的回填值 → 判定今天已填过/滚过,不再重复滚动
|
||||||
|
already = bool(fill['edits']) and all(
|
||||||
|
_same_number(_cell_value(row, t_col),
|
||||||
|
fill['edits'].get(config.COMPARE_DATA_START + i))
|
||||||
|
for i, row in enumerate(rows))
|
||||||
|
if already and not force:
|
||||||
|
return dict(base, last=last, edits={}, kept=0, cleared=0, bad_num=0,
|
||||||
|
prev_today_filled=0, miss_filled=0,
|
||||||
|
skipped='今日遗留已按团购统计回填过(与当前值一致)')
|
||||||
|
|
||||||
|
if last < config.COMPARE_DATA_START:
|
||||||
|
return dict(base, last=0, edits={}, kept=0, cleared=0, bad_num=0,
|
||||||
|
prev_today_filled=0, miss_filled=0, skipped='无数据行')
|
||||||
|
|
||||||
|
clear_cols = [col(c) for c in config.COMPARE_CLEAR_COLS]
|
||||||
|
miss_col = cols.get('miss')
|
||||||
|
x_col = col(config.COMPARE_REMARK_COL)
|
||||||
|
keep_re = re.compile(config.COMPARE_KEEP_REMARK_RE)
|
||||||
|
|
||||||
|
prev_today_filled = sum(1 for row in rows
|
||||||
|
if _cell_value(row, t_col) not in (None, ''))
|
||||||
|
miss_filled = sum(1 for row in rows
|
||||||
|
if miss_col and _cell_value(row, miss_col) not in (None, ''))
|
||||||
|
|
||||||
|
edits = {}
|
||||||
|
kept = cleared = bad_num = 0
|
||||||
|
for offset, row in enumerate(rows):
|
||||||
|
row_no = config.COMPARE_DATA_START + offset
|
||||||
|
# X 列(无表头备注):空 或「某某前消费」→ 昨日遗留保留;其它备注 → 清空
|
||||||
|
remark = _cell_value(row, x_col)
|
||||||
|
text = str(remark).strip() if remark is not None else ''
|
||||||
|
keep = (not text) or bool(keep_re.search(text))
|
||||||
|
if keep:
|
||||||
|
kept += 1
|
||||||
|
else:
|
||||||
|
cleared += 1
|
||||||
|
|
||||||
|
prev_today = _cell_value(row, t_col)
|
||||||
|
miss_val = _cell_value(row, miss_col) if miss_col else None
|
||||||
|
today_num = _to_number(prev_today)
|
||||||
|
miss_num = _to_number(miss_val)
|
||||||
|
if (prev_today not in (None, '') and today_num is None) or \
|
||||||
|
(miss_val not in (None, '') and miss_num is None):
|
||||||
|
bad_num += 1 # 非数字(错误值/文本)当 0 处理,单独计数提示
|
||||||
|
|
||||||
|
row_edits = {c: None for c in clear_cols}
|
||||||
|
if miss_col:
|
||||||
|
row_edits[miss_col] = None # 漏核销清空
|
||||||
|
# 昨日遗留 = 昨天的今日遗留 - 漏核销(缺哪边按 0 算);两边都空则清空
|
||||||
|
if keep and (prev_today not in (None, '') or miss_val not in (None, '')):
|
||||||
|
q = (today_num or 0.0) - (miss_num or 0.0)
|
||||||
|
row_edits[y_col] = int(q) if float(q).is_integer() else round(q, 2)
|
||||||
|
else:
|
||||||
|
row_edits[y_col] = None # 按备注清空 / 无值
|
||||||
|
if fill['edits']:
|
||||||
|
row_edits[t_col] = fill['edits'].get(row_no) # 今日遗留 = 未消费
|
||||||
|
edits[row_no] = row_edits
|
||||||
|
|
||||||
|
return dict(base, last=last, edits=edits, kept=kept, cleared=cleared, bad_num=bad_num,
|
||||||
|
prev_today_filled=prev_today_filled, miss_filled=miss_filled, skipped='')
|
||||||
|
|
||||||
|
|
||||||
|
def _verify_sheet(path, sheet, plan):
|
||||||
|
"""写盘/重算后重新读行,按 E/F 分组核 W 列。"""
|
||||||
|
cols = plan['cols']
|
||||||
|
rows, _ = _read_cells(path, sheet, max(int(v) for v in cols.values()))
|
||||||
|
return compare_groups.verify(rows, cols)
|
||||||
|
|
||||||
|
|
||||||
|
def _fill_verify(result, verify):
|
||||||
|
# groups 是明细用的中间结构(几千项),不塞进运行结果
|
||||||
|
result['verify'] = {k: v for k, v in verify.items() if k != 'groups'}
|
||||||
|
result['groups_total'] = verify['total_groups']
|
||||||
|
result['groups_ok'] = verify['ok_groups']
|
||||||
|
result['unbalanced'] = verify['unbalanced']
|
||||||
|
result['unbalanced_count'] = verify['unbalanced_count']
|
||||||
|
result['verified'] = verify['ok']
|
||||||
|
|
||||||
|
|
||||||
|
def _log_stats(plan, sheet, target):
|
||||||
|
stats = plan.get('stats') or {}
|
||||||
|
if not stats.get('ok'):
|
||||||
|
config.log(f'「{sheet}」团购统计不可用:{stats.get("message") or "未知原因"}', 'WARN')
|
||||||
|
return
|
||||||
|
config.log(stats.get('message') or '')
|
||||||
|
day = stats.get('date') or ''
|
||||||
|
if stats.get('stats') and day and day != target.isoformat():
|
||||||
|
config.log(f'【{config.COMPARE_STATS_SHEET}】消费日期 {day} 与营业日 '
|
||||||
|
f'{target.isoformat()} 不一致,可能未贴当天数据,回填结果需复核', 'WARN')
|
||||||
|
|
||||||
|
|
||||||
|
def _log_refund(plan, sheet):
|
||||||
|
"""记录退款/撤销核销的取数与冲减结果。"""
|
||||||
|
refund = plan.get('refund') or {}
|
||||||
|
fill = plan.get('fill') or {}
|
||||||
|
if not refund.get('ok'):
|
||||||
|
if refund.get('message'):
|
||||||
|
config.log(f'「{sheet}」退款冲减跳过:{refund["message"]}', 'WARN')
|
||||||
|
return
|
||||||
|
config.log(refund.get('message') or '')
|
||||||
|
applied = fill.get('refund_applied') or []
|
||||||
|
if applied:
|
||||||
|
heads = ';'.join(f'{a["store"]}/{a["item"]} -{a["count"]}' for a in applied[:6])
|
||||||
|
config.log(f'「{sheet}」退款/撤销核销冲减:{len(applied)} 个门店项目,'
|
||||||
|
f'共 {sum(a["count"] for a in applied)} 笔:{heads}')
|
||||||
|
leftover = fill.get('refund_unmatched') or []
|
||||||
|
if leftover:
|
||||||
|
heads = ';'.join(f'{u["store"]}/{u["item"]} {u["count"]}笔' for u in leftover[:6])
|
||||||
|
config.log(f'「{sheet}」{len(leftover)} 个退款门店项目在对比表里没有对应行,未冲减:'
|
||||||
|
f'{heads}', 'WARN')
|
||||||
|
|
||||||
|
|
||||||
|
def run(day=None, action='check_meituan', dry_run=False, use_com=True, force=False,
|
||||||
|
progress_from=0, progress_to=0):
|
||||||
|
"""执行对比 sheet 日滚动 + 今日遗留回填 + 分组验证。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
day: 营业日(决定总表副本文件名),默认今天。
|
||||||
|
action: ``check_meituan`` / ``check_douyin``,决定处理哪张 sheet 与取数类型。
|
||||||
|
dry_run: 只报告计划,不写文件。
|
||||||
|
use_com: 写盘后用 WPS/Excel COM 重算,让 W 列按新数据得出结果。
|
||||||
|
force: 忽略「今天已回填/滚动过」的判重。
|
||||||
|
progress_from / progress_to: 进度区间(0~100)。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict(ok, message, path, sheet, rows, kept, cleared, skipped, stats_date,
|
||||||
|
groups_total, groups_ok, unbalanced, unbalanced_count, verified, verify)
|
||||||
|
"""
|
||||||
|
target = _parse_day(day) or date.today()
|
||||||
|
path = master_path(target)
|
||||||
|
wanted = (config.COMPARE_SHEET_DOUYIN if str(action or '').strip() == config.ACTION_DOUYIN
|
||||||
|
else config.COMPARE_SHEET_MEITUAN)
|
||||||
|
result = {'ok': False, 'message': '', 'path': path, 'sheet': wanted,
|
||||||
|
'rows': 0, 'kept': 0, 'cleared': 0, 'skipped': '', 'com': None,
|
||||||
|
'stats_date': '', 'groups_total': 0, 'groups_ok': 0,
|
||||||
|
'unbalanced': [], 'unbalanced_count': 0, 'verified': False,
|
||||||
|
'meal_adjust': [], 'meal_skipped': [],
|
||||||
|
'refund_rows': 0, 'refund_applied': [], 'refund_unmatched': []}
|
||||||
|
|
||||||
|
if not os.path.isfile(path):
|
||||||
|
result['message'] = f'未找到马敏团购总表副本:{path}(请先从共享盘复制)'
|
||||||
|
return result
|
||||||
|
|
||||||
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
|
try:
|
||||||
|
sheet = _find_sheet(wb.sheetnames, wanted)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
if not sheet:
|
||||||
|
result['message'] = f'总表里没有「{wanted}」sheet'
|
||||||
|
return result
|
||||||
|
result['sheet'] = sheet
|
||||||
|
|
||||||
|
if progress_from or progress_to:
|
||||||
|
config.progress(int(progress_from))
|
||||||
|
|
||||||
|
plan = _plan_sheet(path, sheet, action, force, target)
|
||||||
|
cols = plan['cols']
|
||||||
|
fill = plan.get('fill') or {}
|
||||||
|
result['rows'] = len(plan['edits'])
|
||||||
|
result['fill_rows'] = fill.get('filled', 0)
|
||||||
|
result['kept'] = plan.get('kept', 0)
|
||||||
|
result['cleared'] = plan.get('cleared', 0)
|
||||||
|
result['stats_date'] = (plan.get('stats') or {}).get('date') or ''
|
||||||
|
_log_stats(plan, sheet, target)
|
||||||
|
_log_refund(plan, sheet)
|
||||||
|
result['refund_rows'] = (plan.get('refund') or {}).get('rows', 0)
|
||||||
|
result['refund_applied'] = fill.get('refund_applied') or []
|
||||||
|
result['refund_unmatched'] = fill.get('refund_unmatched') or []
|
||||||
|
|
||||||
|
if plan.get('error'):
|
||||||
|
result['message'] = f'「{sheet}」中止:{plan["error"]}'
|
||||||
|
config.log(result['message'], 'WARN')
|
||||||
|
return result
|
||||||
|
|
||||||
|
if plan['skipped']:
|
||||||
|
verify = _verify_sheet(path, sheet, plan)
|
||||||
|
_fill_verify(result, verify)
|
||||||
|
result.update(ok=True, skipped=plan['skipped'],
|
||||||
|
message=f'「{sheet}」跳过:{plan["skipped"]};分组 {verify["total_groups"]} 组,'
|
||||||
|
f'平 {verify["ok_groups"]},不平 {verify["unbalanced_count"]}')
|
||||||
|
config.log(result['message'])
|
||||||
|
return result
|
||||||
|
|
||||||
|
config.log(f'「{sheet}」表头第 {plan["header_row"]} 行:分组列 '
|
||||||
|
f'{letter(cols["store"])}/{letter(cols["item"])},验证列 {letter(cols["verify"])},'
|
||||||
|
f'昨日遗留 {letter(cols["yesterday"])}、今日遗留 {letter(cols["today"])}'
|
||||||
|
+ (f'、漏核销 {letter(cols["miss"])}' if cols.get('miss')
|
||||||
|
else f'(未找到「{config.COMPARE_MISS_TITLE}」列,跳过该列)'))
|
||||||
|
config.log(f'「{sheet}」今日遗留回填:{fill.get("filled", 0)} 行非零'
|
||||||
|
+ ('(来源【%s】)' % config.COMPARE_STATS_SHEET if fill.get('edits')
|
||||||
|
else '(%s)' % (fill.get('skipped') or '无数据')))
|
||||||
|
if fill.get('unmatched'):
|
||||||
|
# 常见于面值券别名(如「1240代1500随心兑」)在团购统计里没有对应核销项目名,
|
||||||
|
# 回填为 0;只作提示,真正影响结果的行会在分组明细里体现。
|
||||||
|
config.log(f'「{sheet}」{len(fill["unmatched"])} 个项目在团购统计里没有记录,今日遗留留空:'
|
||||||
|
+ '、'.join(fill['unmatched'][:10]))
|
||||||
|
config.log(f'「{sheet}」数据行 {config.COMPARE_DATA_START}~{plan["last"]}:'
|
||||||
|
f'清空 {"".join(config.COMPARE_CLEAR_COLS)}'
|
||||||
|
+ ('/漏核销' if cols.get('miss') else '')
|
||||||
|
+ f',昨日遗留 = 表内原今日遗留({plan.get("prev_today_filled", 0)} 个非空)'
|
||||||
|
+ (f' - 漏核销({plan.get("miss_filled", 0)} 个非空)' if cols.get('miss')
|
||||||
|
else ' - 0(无漏核销列)'))
|
||||||
|
if plan.get('bad_num'):
|
||||||
|
config.log(f'「{sheet}」{plan["bad_num"]} 行的今日遗留/漏核销不是数字,已按 0 参与计算,'
|
||||||
|
f'请人工复核这些行', 'WARN')
|
||||||
|
config.log(f'「{sheet}」{config.COMPARE_REMARK_COL} 列备注过滤:昨日遗留保留 {plan.get("kept", 0)} 行'
|
||||||
|
f'(备注为空或含「前消费」),清空 {plan.get("cleared", 0)} 行(其它备注内容)')
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
verify = _verify_sheet(path, sheet, plan)
|
||||||
|
_fill_verify(result, verify)
|
||||||
|
preview, _, _ = compare_groups.build_meal_edits(verify.get('groups') or {})
|
||||||
|
config.log(f'[演练]「{sheet}」分组验证(未重算,读旧缓存):{verify["total_groups"]} 组,'
|
||||||
|
f'平 {verify["ok_groups"]},不平 {verify["unbalanced_count"]}'
|
||||||
|
+ (f';{len(preview)} 行将写平台结错' if preview else ''))
|
||||||
|
result.update(ok=True,
|
||||||
|
message=f'[演练]「{sheet}」将处理 {len(plan["edits"])} 行、'
|
||||||
|
f'回填今日遗留 {fill.get("filled", 0)} 行(不写文件)')
|
||||||
|
return result
|
||||||
|
|
||||||
|
try:
|
||||||
|
_write_sheet(path, sheet, plan['edits'])
|
||||||
|
except (OSError, CompareError, zipfile.BadZipFile) as e:
|
||||||
|
result['message'] = f'「{sheet}」写盘失败:{e}'
|
||||||
|
config.log(result['message'], 'WARN')
|
||||||
|
return result
|
||||||
|
|
||||||
|
if progress_to:
|
||||||
|
config.progress(int(progress_to))
|
||||||
|
|
||||||
|
# 写盘后重算一次,让 W 列「验证」公式按新数据得出结果
|
||||||
|
if use_com:
|
||||||
|
result['com_after'] = com_refresh.refresh(path, sheets=[sheet])
|
||||||
|
if not result['com_after'].get('ok'):
|
||||||
|
config.log(f'滚动后重算失败(W 列读的是旧缓存值):'
|
||||||
|
f'{result["com_after"].get("message")}', 'WARN')
|
||||||
|
else:
|
||||||
|
config.log(f'「{sheet}」未启用 COM 重算,分组验证读的是旧缓存 W,结果仅供参考', 'WARN')
|
||||||
|
|
||||||
|
verify = _verify_sheet(path, sheet, plan)
|
||||||
|
|
||||||
|
# 前面步骤跑完仍不平、且是双人餐/三人餐的配对 → 在【平台结错】补 1 / -2(-3)
|
||||||
|
meal_edits, meal_detail, meal_skipped = compare_groups.build_meal_edits(
|
||||||
|
verify.get('groups') or {})
|
||||||
|
if meal_skipped:
|
||||||
|
config.log(f'「{sheet}」{len(meal_skipped)} 对双人餐/三人餐未修正(基础行不为正):'
|
||||||
|
+ ';'.join(f'{d["store"]}/{d["item"]} 基础{d["sum"]:+g}'
|
||||||
|
for d in meal_skipped[:5]), 'WARN')
|
||||||
|
if meal_edits:
|
||||||
|
heads = ';'.join(f'{d["store"]}/{d["item"]} N={d["times"]} '
|
||||||
|
f'餐行J={d["meal_j"]} 基础行J={d["base_j"]}'
|
||||||
|
for d in meal_detail[:6])
|
||||||
|
config.log(f'「{sheet}」{len(meal_detail)} 对双人餐/三人餐仍不平,'
|
||||||
|
f'写【{config.COMPARE_PLATFORM_ERROR_TITLE}】:{heads}')
|
||||||
|
j_col = cols['platform_error']
|
||||||
|
try:
|
||||||
|
_write_sheet(path, sheet, {row: {j_col: value}
|
||||||
|
for row, value in meal_edits.items()})
|
||||||
|
except (OSError, CompareError, zipfile.BadZipFile) as e:
|
||||||
|
config.log(f'「{sheet}」平台结错写入失败:{e}', 'WARN')
|
||||||
|
else:
|
||||||
|
if use_com:
|
||||||
|
result['com_meal'] = com_refresh.refresh(path, sheets=[sheet])
|
||||||
|
if not result['com_meal'].get('ok'):
|
||||||
|
config.log(f'平台结错后重算失败(验证读旧缓存):'
|
||||||
|
f'{result["com_meal"].get("message")}', 'WARN')
|
||||||
|
else:
|
||||||
|
config.log(f'「{sheet}」未启用 COM 重算,平台结错后的验证读旧缓存', 'WARN')
|
||||||
|
verify = _verify_sheet(path, sheet, plan)
|
||||||
|
|
||||||
|
result['meal_adjust'] = meal_detail
|
||||||
|
result['meal_skipped'] = meal_skipped
|
||||||
|
_fill_verify(result, verify)
|
||||||
|
if verify['ok']:
|
||||||
|
config.log(f'「{sheet}」分组验证通过:{verify["total_groups"]} 组全部为 0')
|
||||||
|
else:
|
||||||
|
heads = ';'.join(f'{g["store"]}/{g["item"]} {g["diff"]:+g}'
|
||||||
|
for g in verify['unbalanced'][:10])
|
||||||
|
config.log(f'「{sheet}」分组验证不平:{verify["unbalanced_count"]}/'
|
||||||
|
f'{verify["total_groups"]} 组不为 0,前几组:{heads}', 'WARN')
|
||||||
|
|
||||||
|
result.update(ok=True,
|
||||||
|
message=f'「{sheet}」完成:处理 {len(plan["edits"])} 行,'
|
||||||
|
f'今日遗留回填 {fill.get("filled", 0)} 行'
|
||||||
|
+ (f',平台结错修正 {len(meal_detail)} 对' if meal_detail else '')
|
||||||
|
+ f';分组 {verify["total_groups"]} 组,'
|
||||||
|
f'平 {verify["ok_groups"]},不平 {verify["unbalanced_count"]}')
|
||||||
|
config.log(result['message'])
|
||||||
|
return result
|
||||||
@@ -0,0 +1,152 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""CRM 门店归属数据层:券号 → 内部门店 / 品牌。
|
||||||
|
|
||||||
|
为什么不按门店名匹配:美团门店名与内部门店名是两套口径(改名 / 错字 / 别名,
|
||||||
|
如「大渡口店」实际是「春晖路CEO会馆」),字符串匹配只能到 89%,剩下的必须人工。
|
||||||
|
**券号是订单级唯一关联**:CRM 团购核销记录里同一条数据就带 ``ticketCode`` +
|
||||||
|
``shopName`` + ``shopId``,与美团收益明细的「券号」join,实测命中 100%。
|
||||||
|
|
||||||
|
数据来自 ``crm_sdk``(执行机按插件 ``requires.sdks`` 下发挂载):
|
||||||
|
* 门店主数据:``stores.Catalog``(品牌 → 门店,含 OLD 旧店,按名称反查品牌)
|
||||||
|
* 核销明细:``reports.list_all(client, 'groupData', reportDate=日)``
|
||||||
|
|
||||||
|
SDK 未挂载 / CRM 未登录时**不阻断主流程**:返回 ``ok=False``,由调用方降级提示。
|
||||||
|
"""
|
||||||
|
import datetime
|
||||||
|
|
||||||
|
from .. import config
|
||||||
|
|
||||||
|
|
||||||
|
def _sdk():
|
||||||
|
"""延迟 import,SDK 未挂载时返回 None(不抛,便于降级)。"""
|
||||||
|
try:
|
||||||
|
import crm_sdk # noqa: WPS433 - 运行时由执行机挂载
|
||||||
|
return crm_sdk
|
||||||
|
except ImportError:
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def available():
|
||||||
|
"""crm_sdk 是否可用(插件被单独拷贝/未下发 SDK 时为 False)。"""
|
||||||
|
return _sdk() is not None
|
||||||
|
|
||||||
|
|
||||||
|
def _day_range(days, window=None):
|
||||||
|
"""把日期集合按 ±N 天展开成待查日期列表(升序去重)。"""
|
||||||
|
window = config.CRM_DATE_WINDOW if window is None else int(window)
|
||||||
|
out = set()
|
||||||
|
for d in days or ():
|
||||||
|
base = _to_date(d)
|
||||||
|
if not base:
|
||||||
|
continue
|
||||||
|
for delta in range(-window, window + 1):
|
||||||
|
out.add((base + datetime.timedelta(days=delta)).isoformat())
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
|
||||||
|
def _to_date(value):
|
||||||
|
"""兼容 date / datetime / 'YYYY-MM-DD' / 'YYYY-MM-DD HH:MM:SS'。"""
|
||||||
|
if isinstance(value, datetime.datetime):
|
||||||
|
return value.date()
|
||||||
|
if isinstance(value, datetime.date):
|
||||||
|
return value
|
||||||
|
text = str(value or '').strip()[:10]
|
||||||
|
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||||
|
try:
|
||||||
|
return datetime.datetime.strptime(text, fmt).date()
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _client():
|
||||||
|
"""构建 CRM 客户端:优先复用落盘登录态,失效时用 SDK 内置凭证做纯 API 登录。
|
||||||
|
|
||||||
|
凭证由 ``crm_sdk.creds`` 解密(插件/界面都不出现账号密码);验证码 OCR 失败时
|
||||||
|
**直接失败**,不走 ``ensure_login`` 的钉钉扫码兜底,避免无人值守时挂等 300 秒。
|
||||||
|
"""
|
||||||
|
sdk = _sdk()
|
||||||
|
if sdk is None:
|
||||||
|
return None, None, '未挂载 crm_sdk(插件需声明 requires.sdks)'
|
||||||
|
try:
|
||||||
|
if not sdk.auth.is_session_valid(log=config.log):
|
||||||
|
res = sdk.auth.login_by_password(log=config.log)
|
||||||
|
if not res.get('success'):
|
||||||
|
return None, None, f"CRM 登录失败:{res.get('message') or '未知原因'}"
|
||||||
|
config.log(f"CRM 登录:{res.get('message') or '账号密码登录成功'}")
|
||||||
|
except Exception as e: # noqa: BLE001 - 缺凭证/网络异常都降级为提示
|
||||||
|
return None, None, f'CRM 登录异常:{e}'
|
||||||
|
session = sdk.auth.build_session()
|
||||||
|
if session is None:
|
||||||
|
return None, None, 'CRM 登录态不可用(Cookie 缺失)'
|
||||||
|
return sdk, sdk.CrmClient(session, log=config.log), ''
|
||||||
|
|
||||||
|
|
||||||
|
def load(days, *, window=None, progress_from=0, progress_to=0):
|
||||||
|
"""拉取指定日期窗口内全部团购核销记录,建「券号 → 门店」索引。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
days: 美团收益明细里出现的验券日期(``date`` / ``str`` 均可)
|
||||||
|
window: 前后各多看几天(默认 :data:`config.CRM_DATE_WINDOW`)
|
||||||
|
progress_from / progress_to: 进度区间(0~100),逐日拉取时上报
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``{"ok", "message", "tickets": {券号: {shop, shop_id, brand, date}},
|
||||||
|
"days": [...], "count": n}``
|
||||||
|
"""
|
||||||
|
empty = {'ok': False, 'message': '', 'tickets': {}, 'days': [], 'count': 0}
|
||||||
|
wanted = _day_range(days, window)
|
||||||
|
if not wanted:
|
||||||
|
empty['message'] = '收益明细里没有可解析的验券日期,跳过门店归属'
|
||||||
|
return empty
|
||||||
|
|
||||||
|
sdk, client, err = _client()
|
||||||
|
if err:
|
||||||
|
empty['message'] = err
|
||||||
|
return empty
|
||||||
|
|
||||||
|
# 门店主数据:品牌 → 门店(用于给 shopName 反查品牌 + 校验门店名是否在册)
|
||||||
|
try:
|
||||||
|
catalog = sdk.stores.Catalog.load(client)
|
||||||
|
except Exception as e: # noqa: BLE001 - 网络/权限异常降级
|
||||||
|
empty['message'] = f'拉取 CRM 门店树失败:{e}'
|
||||||
|
return empty
|
||||||
|
if not len(catalog):
|
||||||
|
# 接口对未认证/无授权账号返回 S0 + 空数组,不是 401,必须按失败处理
|
||||||
|
empty['message'] = 'CRM 门店树为空(登录态失效或无门店授权)'
|
||||||
|
return empty
|
||||||
|
config.log(f'CRM 门店主数据:{len(catalog)} 家 / 品牌 {"/".join(catalog.brands)}')
|
||||||
|
|
||||||
|
tickets = {}
|
||||||
|
total_days = len(wanted)
|
||||||
|
span = max(0, int(progress_to) - int(progress_from))
|
||||||
|
for idx, day in enumerate(wanted, 1):
|
||||||
|
try:
|
||||||
|
rows = sdk.reports.list_all(client, config.CRM_GROUP_REPORT,
|
||||||
|
reportDate=day, page_size=config.CRM_PAGE_SIZE)
|
||||||
|
except Exception as e: # noqa: BLE001 - 单日失败不影响整体
|
||||||
|
config.log(f'CRM {day} 团购核销取数失败(跳过):{e}', 'WARN')
|
||||||
|
continue
|
||||||
|
for row in rows or ():
|
||||||
|
code = str(row.get('ticketCode') or '').strip()
|
||||||
|
shop = str(row.get('shopName') or '').strip()
|
||||||
|
if not code or not shop:
|
||||||
|
continue
|
||||||
|
tickets[code] = {
|
||||||
|
'shop': shop,
|
||||||
|
'shop_id': str(row.get('shopId') or '').strip(),
|
||||||
|
'brand': catalog.brand_of(shop),
|
||||||
|
'date': day,
|
||||||
|
}
|
||||||
|
config.log(f'CRM {day}:{len(rows or [])} 行(累计券号 {len(tickets)})')
|
||||||
|
if span:
|
||||||
|
config.progress(int(progress_from + span * idx / total_days))
|
||||||
|
|
||||||
|
return {
|
||||||
|
'ok': bool(tickets),
|
||||||
|
'message': (f'CRM 券号 {len(tickets)} 条({wanted[0]}~{wanted[-1]})' if tickets
|
||||||
|
else f'{wanted[0]}~{wanted[-1]} 未取到 CRM 核销记录'),
|
||||||
|
'tickets': tickets,
|
||||||
|
'days': wanted,
|
||||||
|
'count': len(tickets),
|
||||||
|
}
|
||||||
@@ -1,58 +1,44 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""美团核对:团购收益明细 + 预订收益明细 → 订单收入明细表,并算三口径当天合计。
|
"""美团核对:团购收益明细 → 订单收入明细表(2026-11 新版 31 列模板)。
|
||||||
|
|
||||||
* 删除团购明细的「订单类型/订单号」;预订明细归一化字段后合并(订单信息→套餐名)
|
* 按导出表头取值,映射到目标表 A~AB(映射见 :data:`config.DAILY_EXPORT_TO_TARGET`);
|
||||||
* 每次清空 ``订单收入明细表`` 第 4 行到真实末行的 A~AI,再整体重贴(幂等)
|
新版导出把「收益类型 / 业务类型」两个名字对调,映射里已按 11.24 真实数据校正;
|
||||||
* 公式列 AC/AD/AF/AG/AH/AI 按行下拉;AD=营业日(验券 hour<10 算前一天)
|
* 取数条件:``验券/退款/调整时间`` 的**日期等于营业日**(不做 10 点切日偏移),
|
||||||
* 明细 P 合计 / 透视 G 复算 / 报表 P 合计三者交叉校验
|
全量保留(含总收入为负的退款/撤销行);
|
||||||
|
* AC~AI 是模板自带的辅助公式(计数 / 验券时间 / 品项名称 / 下单时间 / 验证 / 佣金检测),
|
||||||
|
按目标表第 4 行下拉,行号相对引用随之平移;
|
||||||
|
* 写盘用 zip+XML 只替换目标 sheet(表内有 8 个透视 + 6 个外部链接,openpyxl 保存会丢);
|
||||||
|
* 明细/透视/报表 三口径合计交叉校验。
|
||||||
"""
|
"""
|
||||||
import glob
|
import glob
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
from collections import defaultdict
|
import zipfile
|
||||||
from datetime import datetime, timedelta
|
from datetime import date, datetime, timedelta
|
||||||
|
|
||||||
import openpyxl
|
import openpyxl
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
from . import com_refresh, share_copy
|
from . import com_refresh, share_copy, sheet_xml
|
||||||
|
|
||||||
COL_AI = 35
|
_REF_RE = re.compile(r'(\$?)([A-Z]{1,3})(\$?)(\d+)')
|
||||||
COL_AD = 30
|
|
||||||
# 团购收益明细 31 列(导出表的实际列序)
|
|
||||||
GROUP_COLS = (
|
|
||||||
'订单类型', '订单号', '消费门店名称', 'CRM门店名称', '券号', '核销时间', '验券时间',
|
|
||||||
'业务类型', '团购类型', '商品名称', '数量', '总收入', '技术服务费', '营销费用',
|
|
||||||
'结算价', '项目一世', '项目一世数量', '项目一世金额', '技术费(项目一)', '营销费(项目一)',
|
|
||||||
'项目二世', '项目二世数量', '项目二世金额', '技术费(项目二)', '营销费(项目二)',
|
|
||||||
'项目三世', '项目三世数量', '项目三世金额', '技术费(项目三)', '营销费(项目三)', '备注'
|
|
||||||
)
|
|
||||||
# 目标表 A~AB:团购 31 列去掉 订单类型/订单号/关联买单订单号/券号
|
|
||||||
TARGET_COLS = tuple(c for c in GROUP_COLS
|
|
||||||
if c not in ('订单类型', '订单号', '关联买单订单号/券号'))
|
|
||||||
G_IDX = {name: i for i, name in enumerate(GROUP_COLS)}
|
|
||||||
|
|
||||||
|
# 预订明细按表头名映射到目标列(目标没有的列忽略)
|
||||||
def _last_data_row(ws, start):
|
BOOKING_TARGET = {
|
||||||
last = start - 1
|
'消费门店': 11, '消费门店名称': 11, '门店': 11,
|
||||||
for r in range(start, int(ws.max_row or 0) + 1):
|
'券号': 5, '券码': 5, '核销码': 5,
|
||||||
if any(ws.cell(r, c).value is not None for c in range(1, 5)):
|
'验券时间': 7, '核销时间': 7, '使用时间': 7,
|
||||||
last = r
|
'套餐名': 9, '商品名称': 9, '商品名': 9, '订单信息': 9, '项目名称': 9,
|
||||||
return last
|
'总收入': 17, '收入': 17, '到账金额': 17,
|
||||||
|
'结算价': 16, '预计收入': 16, '商家实收': 16,
|
||||||
|
'业务类型': 3, '订单类型': 4, '下单时间': 6,
|
||||||
def _to_number(value):
|
}
|
||||||
if value is None or value == '':
|
|
||||||
return 0.0
|
|
||||||
if isinstance(value, (int, float)):
|
|
||||||
return float(value)
|
|
||||||
return float(str(value).replace(',', '').replace('¥', '').strip() or 0)
|
|
||||||
|
|
||||||
|
|
||||||
def _as_date(value):
|
def _as_date(value):
|
||||||
if isinstance(value, datetime):
|
if isinstance(value, datetime):
|
||||||
return value.date()
|
return value.date()
|
||||||
if hasattr(value, 'year') and hasattr(value, 'month') and hasattr(value, 'day'):
|
if isinstance(value, date):
|
||||||
return value
|
return value
|
||||||
text = str(value or '').strip()
|
text = str(value or '').strip()
|
||||||
m = re.match(r'(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})', text)
|
m = re.match(r'(\d{4})[-/年](\d{1,2})[-/月](\d{1,2})', text)
|
||||||
@@ -64,201 +50,275 @@ def _as_date(value):
|
|||||||
return None
|
return None
|
||||||
|
|
||||||
|
|
||||||
def _prev_month_last_day(day):
|
def _business_day(value):
|
||||||
first = day.replace(day=1)
|
"""营业日:验券 hour < 10 算前一天(与明细表 AD 列公式同一口径)。"""
|
||||||
return first - timedelta(days=1)
|
d = value
|
||||||
|
if isinstance(d, datetime):
|
||||||
|
day, hour = d.date(), d.hour
|
||||||
def business_day(value, prev_month_last_day):
|
elif isinstance(d, date):
|
||||||
"""复刻 Excel AD:验券 hour<10 算前一天;1 号凌晨算上月最后一天。"""
|
day, hour = d, 0
|
||||||
d = _as_date(value)
|
else:
|
||||||
if not d:
|
text = str(value or '').strip()
|
||||||
|
m = re.match(r'(\d{4})[-/](\d{1,2})[-/](\d{1,2})[ T](\d{1,2}):', text)
|
||||||
|
if m:
|
||||||
|
batch = [int(x) for x in m.groups()]
|
||||||
|
day, hour = date(*batch[:3]), batch[3]
|
||||||
|
else:
|
||||||
|
day, hour = _as_date(text), 0
|
||||||
|
if day is None:
|
||||||
return None
|
return None
|
||||||
hour = value.hour if isinstance(value, datetime) else 0
|
return day - timedelta(days=1) if hour < 10 else day
|
||||||
if hour < 10:
|
|
||||||
if d.day == 1:
|
|
||||||
return prev_month_last_day
|
|
||||||
return d - timedelta(days=1)
|
|
||||||
return d
|
|
||||||
|
|
||||||
|
|
||||||
def _sum_cached(ws, income_col, target=None):
|
def _to_number(value):
|
||||||
"""读缓存列求和。target 给定时按 AD 营业日(30) 与 C 业务类型(3) 筛选。"""
|
if value is None or isinstance(value, bool):
|
||||||
total = 0.0
|
return None
|
||||||
for r in range(config.DAILY_DATA_START, int(ws.max_row or 0) + 1):
|
if isinstance(value, (int, float)):
|
||||||
if target is not None:
|
return float(value)
|
||||||
day_val = ws.cell(r, 30).value # AD 营业日(日号)
|
text = str(value).strip().replace(',', '').replace('¥', '')
|
||||||
if day_val is None or int(day_val) != target.day:
|
if not text:
|
||||||
continue
|
return None
|
||||||
if str(ws.cell(r, 3).value or '').strip() in config.DAILY_EXCLUDE_BUSINESS:
|
try:
|
||||||
continue
|
return float(text)
|
||||||
v = ws.cell(r, income_col).value
|
except ValueError:
|
||||||
if isinstance(v, (int, float)):
|
return None
|
||||||
total += float(v)
|
|
||||||
return round(total, 2)
|
|
||||||
|
|
||||||
|
|
||||||
def _write_formulas(ws, row):
|
def _reset_if_needed(ws):
|
||||||
ws.cell(row, 29).value = f'=IF(OR(O{row}="",O{row}=0),0,O{row})'
|
"""导出的 dimension 常写成 1×1 或百万行,read_only 下会读不到/白扫。"""
|
||||||
ws.cell(row, 30).value = (
|
rows, cols = ws.max_row or 1, ws.max_column or 1
|
||||||
f'=IF(HOUR(G{row})<10,IF(DAY(INT(G{row}))=1,$AE$2,DAY(INT(G{row}))-1),'
|
if rows <= 1 or cols <= 1 or rows > 100000 or cols > 1000:
|
||||||
f'DAY(INT(G{row})))')
|
ws.reset_dimensions()
|
||||||
ws.cell(row, 32).value = f'=IF(J{row}="其他","否","是")'
|
|
||||||
ws.cell(row, 33).value = f'=VLOOKUP(C{row},基础信息!$A$3:$B$1973,2,0)'
|
|
||||||
ws.cell(row, 34).value = f'=VLOOKUP(D{row},基础信息!$E$2:$F$12924,2,0)'
|
|
||||||
ws.cell(row, 35).value = f'=IF(AC{row}=0,0,ROUND(O{row}/AC{row},2))'
|
|
||||||
|
|
||||||
|
|
||||||
def _read_rows(path, header_row):
|
def _shift_formula(formula, delta):
|
||||||
|
"""把模板公式的相对行号整体平移 delta($ 绝对引用不动)。"""
|
||||||
|
if not formula or delta == 0:
|
||||||
|
return formula
|
||||||
|
|
||||||
|
def repl(m):
|
||||||
|
col_abs, col, row_abs, row = m.groups()
|
||||||
|
if row_abs:
|
||||||
|
return m.group(0)
|
||||||
|
return f'{col_abs}{col}{row_abs}{int(row) + delta}'
|
||||||
|
|
||||||
|
return _REF_RE.sub(repl, formula)
|
||||||
|
|
||||||
|
|
||||||
|
def _read_export(path):
|
||||||
|
"""读团购收益明细导出:返回数据行(list),表头行取 config.PROFIT_HEADER_ROW。"""
|
||||||
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
try:
|
try:
|
||||||
ws = wb[wb.sheetnames[0]]
|
ws = wb[wb.sheetnames[0]]
|
||||||
rows = list(ws.iter_rows(min_row=header_row + 1, values_only=True))
|
_reset_if_needed(ws)
|
||||||
return [list(r) for r in rows if any(v is not None for v in r)]
|
header = next(ws.iter_rows(min_row=config.PROFIT_HEADER_ROW,
|
||||||
|
max_row=config.PROFIT_HEADER_ROW, values_only=True), ())
|
||||||
|
width = len(header) or 1
|
||||||
|
rows = []
|
||||||
|
for row in ws.iter_rows(min_row=config.PROFIT_HEADER_ROW + 1,
|
||||||
|
max_col=width, values_only=True):
|
||||||
|
if row and row[0] is not None:
|
||||||
|
rows.append(list(row))
|
||||||
|
return rows
|
||||||
finally:
|
finally:
|
||||||
wb.close()
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
def _normalize_booking(row):
|
def _read_booking(path, target):
|
||||||
"""预订明细按列名映射到团购 31 列;订单信息 → 套餐名。"""
|
"""预订收益明细:按表头名映射到目标列,返回目标列顺序的行(28 列)。"""
|
||||||
out = [''] * len(GROUP_COLS)
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
aliases = {
|
try:
|
||||||
'消费门店名称': ('消费门店名称', '门店', '消费门店'),
|
ws = wb[wb.sheetnames[0]]
|
||||||
'CRM门店名称': ('CRM门店名称', 'CRM门店'),
|
_reset_if_needed(ws)
|
||||||
'券号': ('券号', '券码', '核销码'),
|
header = next(ws.iter_rows(min_row=config.PROFIT_HEADER_ROW,
|
||||||
'验券时间': ('验券时间', '核销时间', '使用时间'),
|
max_row=config.PROFIT_HEADER_ROW, values_only=True), ())
|
||||||
'核销时间': ('核销时间', '验券时间'),
|
names = [str(h or '').strip() for h in header]
|
||||||
'业务类型': ('业务类型',),
|
width = len(names) or 1
|
||||||
'团购类型': ('团购类型', '订单类型'),
|
out = []
|
||||||
'商品名称': ('套餐名', '商品名称', '商品名', '订单信息', '项目名称'),
|
for row in ws.iter_rows(min_row=config.PROFIT_HEADER_ROW + 1,
|
||||||
'数量': ('数量', '核销数量'),
|
max_col=width, values_only=True):
|
||||||
'总收入': ('总收入', '收入', '到账金额'),
|
if not row or row[0] is None:
|
||||||
'技术服务费': ('技术服务费', '服务费'),
|
continue
|
||||||
'营销费用': ('营销费用', '营销费'),
|
values = [None] * 28
|
||||||
'结算价': ('结算价', '预计收入', '商家实收'),
|
for name, value in zip(names, row):
|
||||||
}
|
col = BOOKING_TARGET.get(name)
|
||||||
for target, names in aliases.items():
|
if col:
|
||||||
for name in names:
|
values[col - 1] = value
|
||||||
if name in row:
|
if _business_day(values[6]) != target:
|
||||||
out[G_IDX[target]] = row[name]
|
continue
|
||||||
break
|
out.append(values)
|
||||||
return out
|
return out
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _template_formulas(path, sheet):
|
||||||
|
"""读目标表第 4 行 AC~AI 的公式,作为下拉模板。"""
|
||||||
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=False)
|
||||||
|
try:
|
||||||
|
ws = wb[sheet]
|
||||||
|
_reset_if_needed(ws)
|
||||||
|
row = next(ws.iter_rows(min_row=config.DAILY_DATA_START,
|
||||||
|
max_row=config.DAILY_DATA_START,
|
||||||
|
min_col=config.DAILY_HELPER_FIRST,
|
||||||
|
max_col=config.DAILY_HELPER_LAST,
|
||||||
|
values_only=True), ())
|
||||||
|
return [c if isinstance(c, str) and c.startswith('=') else None for c in row]
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _last_data_row(path, sheet):
|
||||||
|
"""目标表现有数据末行(A 列非空)。"""
|
||||||
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
|
try:
|
||||||
|
ws = wb[sheet]
|
||||||
|
_reset_if_needed(ws)
|
||||||
|
last = config.DAILY_DATA_START - 1
|
||||||
|
for offset, row in enumerate(ws.iter_rows(min_row=config.DAILY_DATA_START,
|
||||||
|
max_col=1, values_only=True)):
|
||||||
|
if row and row[0] not in (None, ''):
|
||||||
|
last = config.DAILY_DATA_START + offset
|
||||||
|
return last
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _sum_cached(ws, income_col, target=None):
|
||||||
|
"""读缓存列求和;target 给定时按 AD 验券时间(30) 与 C 业务类型(3) 筛选。"""
|
||||||
|
total = 0.0
|
||||||
|
width = max(income_col, 30, 3)
|
||||||
|
for row in ws.iter_rows(min_row=config.DAILY_DATA_START, max_col=width, values_only=True):
|
||||||
|
cells = list(row) + [None] * (width - len(row))
|
||||||
|
if target is not None:
|
||||||
|
day_val = cells[29]
|
||||||
|
if day_val is None or int(day_val) != target.day:
|
||||||
|
continue
|
||||||
|
if str(cells[2] or '').strip() in config.DAILY_EXCLUDE_BUSINESS:
|
||||||
|
continue
|
||||||
|
value = cells[income_col - 1]
|
||||||
|
if isinstance(value, (int, float)):
|
||||||
|
total += float(value)
|
||||||
|
return round(total, 2)
|
||||||
|
|
||||||
|
|
||||||
def run(table_path='', day=None, dry_run=False, use_com=None):
|
def run(table_path='', day=None, dry_run=False, use_com=None):
|
||||||
work = os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR)
|
work = config.WORK_DIR
|
||||||
target = _as_date(day) or _prev_month_last_day(datetime.now().date() + timedelta(days=1))
|
target = _as_date(day) or date.today()
|
||||||
prev_last = _prev_month_last_day(target)
|
|
||||||
|
|
||||||
result = {'ok': False, 'message': '', 'path': '', 'total': 0.0,
|
result = {'ok': False, 'message': '', 'path': '', 'total': 0.0,
|
||||||
'pivot_total': 0.0, 'report_total': 0.0, 'consistent': False,
|
'pivot_total': 0.0, 'report_total': 0.0, 'consistent': False,
|
||||||
'detail_rows': 0, 'groups': 0}
|
'detail_rows': 0, 'skipped_day': 0, 'replaced': 0}
|
||||||
src = str(table_path or '').strip()
|
src = str(table_path or '').strip()
|
||||||
if not src:
|
if not src:
|
||||||
pairs = glob.glob(os.path.join(work, share_copy.table_name(
|
cands = glob.glob(os.path.join(work, share_copy.table_name(
|
||||||
config.SHARE_TABLE_KEYWORD, target, config.SHARE_TABLE_EXT)))
|
config.SHARE_TABLE_KEYWORD, target, config.SHARE_TABLE_EXT)))
|
||||||
src = pairs[0] if pairs else ''
|
src = cands[0] if cands else ''
|
||||||
if not src or not os.path.isfile(src):
|
if not src or not os.path.isfile(src):
|
||||||
result['message'] = f'未找到本地美团核对表副本:{src or work}(请先从共享盘复制)'
|
result['message'] = f'未找到本地美团核对表副本:{src or work}(请先从共享盘复制)'
|
||||||
return result
|
return result
|
||||||
|
|
||||||
wb = openpyxl.load_workbook(src, data_only=False)
|
wb = openpyxl.load_workbook(src, read_only=True, data_only=True)
|
||||||
try:
|
try:
|
||||||
if config.DAILY_SHEET not in wb.sheetnames:
|
if config.DAILY_SHEET not in wb.sheetnames:
|
||||||
result['message'] = f'{os.path.basename(src)} 缺少【{config.DAILY_SHEET}】'
|
result['message'] = f'{os.path.basename(src)} 缺少【{config.DAILY_SHEET}】'
|
||||||
return result
|
return result
|
||||||
ws = wb[config.DAILY_SHEET]
|
finally:
|
||||||
last = _last_data_row(ws, config.DAILY_DATA_START)
|
|
||||||
if last >= config.DAILY_DATA_START:
|
|
||||||
for r in range(config.DAILY_DATA_START, last + 1):
|
|
||||||
for c in range(1, COL_AI + 1):
|
|
||||||
ws.cell(r, c).value = None
|
|
||||||
start = config.DAILY_DATA_START
|
|
||||||
|
|
||||||
detail = []
|
|
||||||
for p in sorted(glob.glob(os.path.join(work, config.DETAIL_GLOB))):
|
|
||||||
if os.path.basename(p).startswith('金色湖畔_'):
|
|
||||||
continue
|
|
||||||
detail.extend(_read_rows(p, config.PROFIT_HEADER_ROW))
|
|
||||||
for p in sorted(glob.glob(os.path.join(work, '预订收益明细_*.xlsx'))):
|
|
||||||
raw = _read_rows(p, config.PROFIT_HEADER_ROW)
|
|
||||||
if not raw:
|
|
||||||
continue
|
|
||||||
header = raw[0]
|
|
||||||
for r in raw[1:]:
|
|
||||||
detail.append(_normalize_booking(dict(zip(header, r))))
|
|
||||||
|
|
||||||
picked = []
|
|
||||||
for row in detail:
|
|
||||||
if max(G_IDX.get('总收入', 0), G_IDX.get('结算价', 0)) >= len(row):
|
|
||||||
continue
|
|
||||||
if _to_number(row[G_IDX['总收入']]) <= 0:
|
|
||||||
continue
|
|
||||||
if str(row[G_IDX['业务类型']] or '').strip() in config.DAILY_EXCLUDE_BUSINESS:
|
|
||||||
continue
|
|
||||||
if business_day(row[G_IDX['验券时间']], prev_last) != target:
|
|
||||||
continue
|
|
||||||
picked.append(row)
|
|
||||||
|
|
||||||
groups = defaultdict(float)
|
|
||||||
for i, row in enumerate(picked):
|
|
||||||
r = start + i
|
|
||||||
for c, name in enumerate(TARGET_COLS, start=1):
|
|
||||||
ws.cell(r, c).value = row[G_IDX[name]]
|
|
||||||
_write_formulas(ws, r)
|
|
||||||
key = (str(row[G_IDX['消费门店名称']] or '').strip(),
|
|
||||||
str(row[G_IDX['商品名称']] or '').strip())
|
|
||||||
groups[key] += _to_number(row[G_IDX['结算价']])
|
|
||||||
result['detail_rows'] = len(picked)
|
|
||||||
result['groups'] = len(groups)
|
|
||||||
|
|
||||||
detail_total = round(sum(_to_number(r[G_IDX['结算价']]) for r in picked), 2)
|
|
||||||
pivot_total = round(sum(groups.values()), 2)
|
|
||||||
report_total = pivot_total
|
|
||||||
consistent = abs(pivot_total - detail_total) < 0.01
|
|
||||||
|
|
||||||
result.update(total=detail_total, pivot_total=pivot_total,
|
|
||||||
report_total=report_total, consistent=consistent)
|
|
||||||
|
|
||||||
if dry_run:
|
|
||||||
result.update(ok=True, message=f'[演练] 将贴 {len(picked)} 行;三口径合计 '
|
|
||||||
f'{detail_total:.2f}')
|
|
||||||
return result
|
|
||||||
|
|
||||||
wb.close()
|
wb.close()
|
||||||
|
|
||||||
# 保存后真正刷新透视缓存 + 公式,再读三口径(读不到则保留上面的复算值)
|
# 先确认导出明细齐全,再动表(缺文件时一张表都不清)
|
||||||
do_com = config.USE_COM_REFRESH if use_com is None else bool(use_com)
|
sources = [p for p in config.glob_files(config.DETAIL_GLOB)
|
||||||
refresh = com_refresh.refresh(src, sheets=['透视', config.DAILY_SHEET,
|
if not os.path.basename(p).startswith('金色湖畔_')]
|
||||||
config.REPORT_SHEET]) if do_com else \
|
if not sources:
|
||||||
{'ok': False, 'engine': '', 'message': '未启用 COM 刷新'}
|
result['message'] = (f'未找到团购收益明细({config.DETAIL_GLOB}),'
|
||||||
result['com_refresh'] = refresh
|
f'已跳过且未改动【{config.DAILY_SHEET}】;搜索目录:'
|
||||||
if refresh.get('ok'):
|
+ ';'.join(config.search_dirs()))
|
||||||
try:
|
|
||||||
wb2 = openpyxl.load_workbook(src, read_only=True, data_only=True)
|
|
||||||
try:
|
|
||||||
pivot_total = _sum_cached(wb2['透视'], 7)
|
|
||||||
report_total = _sum_cached(wb2[config.REPORT_SHEET], 16)
|
|
||||||
finally:
|
|
||||||
wb2.close()
|
|
||||||
except Exception as e:
|
|
||||||
config.log(f'COM 刷新后读合计失败,沿用复算值:{e}', 'WARN')
|
|
||||||
elif do_com:
|
|
||||||
config.log(f'透视未刷新({refresh.get("message")}),三口径为按明细复算值', 'WARN')
|
|
||||||
|
|
||||||
consistent = max(detail_total, pivot_total, report_total) - \
|
|
||||||
min(detail_total, pivot_total, report_total) < 0.01
|
|
||||||
result.update(ok=True, path=src, total=detail_total, pivot_total=pivot_total,
|
|
||||||
report_total=report_total, consistent=consistent,
|
|
||||||
message=f'已贴 {len(picked)} 行到【{config.DAILY_SHEET}】;'
|
|
||||||
f'明细/透视/报表合计 {detail_total:.2f}/'
|
|
||||||
f'{pivot_total:.2f}/{report_total:.2f}'
|
|
||||||
+ ('' if consistent else '(不一致!)'))
|
|
||||||
if not consistent:
|
|
||||||
config.log('三口径合计不一致,请检查报表公式与透视缓存', 'WARN')
|
|
||||||
return result
|
return result
|
||||||
finally:
|
|
||||||
|
rows = []
|
||||||
|
skipped = 0
|
||||||
|
exclude = tuple(str(x).strip() for x in config.DAILY_EXCLUDE_BUSINESS)
|
||||||
|
for path in sources:
|
||||||
|
for raw in _read_export(path):
|
||||||
|
if _business_day(raw[config.DAILY_TIME_COL - 1]) != target:
|
||||||
|
skipped += 1
|
||||||
|
continue
|
||||||
|
# 目标 B(收益类型)取导出 4(业务类型:团购/其他)
|
||||||
|
if exclude and str(raw[3] or '').strip() in exclude:
|
||||||
|
continue
|
||||||
|
rows.append([raw[src_i - 1] if src_i - 1 < len(raw) else None
|
||||||
|
for src_i, _tgt in config.DAILY_EXPORT_TO_TARGET])
|
||||||
|
|
||||||
|
booking_files = config.glob_files('预订收益明细_*.xlsx')
|
||||||
|
for path in booking_files:
|
||||||
|
rows.extend(_read_booking(path, target))
|
||||||
|
if booking_files:
|
||||||
|
config.log(f'预订收益明细 {len(booking_files)} 份已并入')
|
||||||
|
|
||||||
|
result.update(detail_rows=len(rows), skipped_day=skipped)
|
||||||
|
if not rows:
|
||||||
|
result['message'] = (f'【{config.DAILY_SHEET}】营业日 {target} 没有可贴的明细'
|
||||||
|
f'(导出里其它日期 {skipped} 行),未改动表')
|
||||||
|
return result
|
||||||
|
|
||||||
|
start = config.DAILY_DATA_START
|
||||||
|
values = {start + i: row for i, row in enumerate(rows)}
|
||||||
|
template = _template_formulas(src, config.DAILY_SHEET)
|
||||||
|
formulas = {start + i: [_shift_formula(f, i) if f else None for f in template]
|
||||||
|
for i in range(len(rows))}
|
||||||
|
last_old = _last_data_row(src, config.DAILY_SHEET)
|
||||||
|
result['replaced'] = max(0, last_old - start + 1)
|
||||||
|
|
||||||
|
detail_total = round(sum(_to_number(row[15]) or 0.0 for row in rows), 2)
|
||||||
|
result.update(total=detail_total, pivot_total=detail_total, report_total=detail_total,
|
||||||
|
consistent=True)
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
result.update(ok=True,
|
||||||
|
message=f'[演练] 将贴 {len(rows)} 行到【{config.DAILY_SHEET}】'
|
||||||
|
f'(替换原 {result["replaced"]} 行);明细合计 {detail_total:.2f}')
|
||||||
|
return result
|
||||||
|
|
||||||
|
try:
|
||||||
|
sheet_xml.write_rows(src, config.DAILY_SHEET, values, formulas,
|
||||||
|
start_row=start, last_row=last_old)
|
||||||
|
except (OSError, RuntimeError, zipfile.BadZipFile) as e:
|
||||||
|
result['message'] = f'写入【{config.DAILY_SHEET}】失败:{e}'
|
||||||
|
config.log(result['message'], 'WARN')
|
||||||
|
return result
|
||||||
|
result['path'] = src
|
||||||
|
|
||||||
|
do_com = config.USE_COM_REFRESH if use_com is None else bool(use_com)
|
||||||
|
refresh = com_refresh.refresh(src, sheets=['透视', config.DAILY_SHEET,
|
||||||
|
config.REPORT_SHEET]) if do_com else \
|
||||||
|
{'ok': False, 'engine': '', 'message': '未启用 COM 刷新'}
|
||||||
|
result['com_refresh'] = refresh
|
||||||
|
|
||||||
|
pivot_total, report_total = detail_total, detail_total
|
||||||
|
if refresh.get('ok'):
|
||||||
try:
|
try:
|
||||||
wb.close()
|
wb2 = openpyxl.load_workbook(src, read_only=True, data_only=True)
|
||||||
except Exception:
|
try:
|
||||||
pass
|
pivot_total = _sum_cached(wb2['透视'], 7)
|
||||||
|
report_total = _sum_cached(wb2[config.REPORT_SHEET], 16)
|
||||||
|
finally:
|
||||||
|
wb2.close()
|
||||||
|
except Exception as e: # noqa: BLE001 - 读不到就沿用复算值
|
||||||
|
config.log(f'COM 刷新后读合计失败,沿用复算值:{e}', 'WARN')
|
||||||
|
elif do_com:
|
||||||
|
config.log(f'透视未刷新({refresh.get("message")}),三口径为明细复算值', 'WARN')
|
||||||
|
|
||||||
|
consistent = abs(pivot_total - report_total) < 0.01
|
||||||
|
note = ''
|
||||||
|
if abs(detail_total - pivot_total) >= 0.01:
|
||||||
|
note = (f';明细含 10 点前验券行,比透视多 '
|
||||||
|
f'{detail_total - pivot_total:.2f}(透视按 10 点切日归属前一天)')
|
||||||
|
result.update(ok=True, total=detail_total, pivot_total=pivot_total,
|
||||||
|
report_total=report_total, consistent=consistent,
|
||||||
|
message=f'已贴 {len(rows)} 行到【{config.DAILY_SHEET}】'
|
||||||
|
f'(原 {result["replaced"]} 行);明细 {detail_total:.2f}、'
|
||||||
|
f'透视 {pivot_total:.2f}、报表 {report_total:.2f}'
|
||||||
|
+ note + ('' if consistent else '(透视与报表不一致!)'))
|
||||||
|
if not consistent:
|
||||||
|
config.log('透视与报表合计不一致,请检查报表公式引用范围', 'WARN')
|
||||||
|
return result
|
||||||
|
|||||||
@@ -12,7 +12,6 @@
|
|||||||
|
|
||||||
与美团侧一致:openpyxl 读值、zip+XML 写值(保留透视/公式),共享盘全程只读。
|
与美团侧一致:openpyxl 读值、zip+XML 写值(保留透视/公式),共享盘全程只读。
|
||||||
"""
|
"""
|
||||||
import glob
|
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
from datetime import date, datetime, timedelta
|
from datetime import date, datetime, timedelta
|
||||||
@@ -22,7 +21,7 @@ from openpyxl.utils import column_index_from_string as col
|
|||||||
from openpyxl.utils import get_column_letter as letter
|
from openpyxl.utils import get_column_letter as letter
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
from . import com_refresh, share_copy
|
from . import base_info_sync, com_refresh, share_copy
|
||||||
|
|
||||||
|
|
||||||
def _as_date(value):
|
def _as_date(value):
|
||||||
@@ -43,9 +42,17 @@ def _as_date(value):
|
|||||||
def _to_number(value):
|
def _to_number(value):
|
||||||
if value is None or value == '':
|
if value is None or value == '':
|
||||||
return 0.0
|
return 0.0
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return 0.0
|
||||||
if isinstance(value, (int, float)):
|
if isinstance(value, (int, float)):
|
||||||
return float(value)
|
return float(value)
|
||||||
return float(str(value).replace(',', '').replace('¥', '').replace('%', '').strip() or 0)
|
text = str(value).replace(',', '').replace('¥', '').replace('%', '').strip()
|
||||||
|
if not text:
|
||||||
|
return 0.0
|
||||||
|
try:
|
||||||
|
return float(text)
|
||||||
|
except ValueError:
|
||||||
|
return 0.0 # 透视/报表里混着表头文本,按 0 算
|
||||||
|
|
||||||
|
|
||||||
def _col(s):
|
def _col(s):
|
||||||
@@ -57,6 +64,9 @@ def _read_export_detail(path):
|
|||||||
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
try:
|
try:
|
||||||
ws = wb[wb.sheetnames[0]]
|
ws = wb[wb.sheetnames[0]]
|
||||||
|
# 平台导出的 dimension 可能写成 1×1(实测 11 月版本),read_only 下会读到 0 行
|
||||||
|
if (ws.max_row or 1) <= 1 or (ws.max_column or 1) <= 1:
|
||||||
|
ws.reset_dimensions()
|
||||||
hi = _col(config.DY_DETAIL_PASTE_LAST_COL)
|
hi = _col(config.DY_DETAIL_PASTE_LAST_COL)
|
||||||
rows = [list(r) for r in ws.iter_rows(min_row=config.DY_HEADER_ROW + 1,
|
rows = [list(r) for r in ws.iter_rows(min_row=config.DY_HEADER_ROW + 1,
|
||||||
min_col=1, max_col=hi, values_only=True)]
|
min_col=1, max_col=hi, values_only=True)]
|
||||||
@@ -67,24 +77,28 @@ def _read_export_detail(path):
|
|||||||
wb.close()
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
def _detail_file(work_dir):
|
|
||||||
files = sorted(glob.glob(os.path.join(work_dir, config.DOUYIN_DETAIL_GLOB)))
|
|
||||||
return files[-1] if files else ''
|
|
||||||
|
|
||||||
|
|
||||||
def _local_table(day):
|
def _local_table(day):
|
||||||
return os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR,
|
return os.path.join(config.WORK_DIR,
|
||||||
share_copy.table_name(config.DOUYIN_SHARE_KEYWORD, day,
|
share_copy.table_name(config.DOUYIN_SHARE_KEYWORD, day,
|
||||||
config.SHARE_TABLE_EXT))
|
config.SHARE_TABLE_EXT))
|
||||||
|
|
||||||
|
|
||||||
|
def _match_day(value, target):
|
||||||
|
"""BS/BQ 这类辅助列存的是「日号数字」,不是日期;两种都要能对上营业日。"""
|
||||||
|
if isinstance(value, bool):
|
||||||
|
return False
|
||||||
|
if isinstance(value, (int, float)):
|
||||||
|
return int(value) == target.day
|
||||||
|
return _as_date(value) == target
|
||||||
|
|
||||||
|
|
||||||
def _sum_filtered(ws, time_col, status_col, income_col, target):
|
def _sum_filtered(ws, time_col, status_col, income_col, target):
|
||||||
"""按 时间=营业日 & 状态=已核销 过滤,累计预计收入(转数字)。"""
|
"""按 时间=营业日 & 状态=已核销 过滤,累计预计收入(转数字)。"""
|
||||||
t, s, i = _col(time_col), _col(status_col), _col(income_col)
|
t, s, i = _col(time_col), _col(status_col), _col(income_col)
|
||||||
total = 0.0
|
total = 0.0
|
||||||
count = 0
|
count = 0
|
||||||
for r in range(config.DY_DETAIL_DATA_START, int(ws.max_row or 0) + 1):
|
for r in range(config.DY_DETAIL_DATA_START, int(ws.max_row or 0) + 1):
|
||||||
if _as_date(ws.cell(r, t).value) != target:
|
if not _match_day(ws.cell(r, t).value, target):
|
||||||
continue
|
continue
|
||||||
if str(ws.cell(r, s).value or '').strip() != config.DY_STATUS_VALUE:
|
if str(ws.cell(r, s).value or '').strip() != config.DY_STATUS_VALUE:
|
||||||
continue
|
continue
|
||||||
@@ -116,48 +130,16 @@ def _write_detail_values(table_path, rows):
|
|||||||
[('核销明细', rows, 1, config.DY_DETAIL_DATA_START)])
|
[('核销明细', rows, 1, config.DY_DETAIL_DATA_START)])
|
||||||
|
|
||||||
|
|
||||||
def _base_info_check(workbook, dry_run=False):
|
def _base_info_layout():
|
||||||
"""【报表】O/P 门店/项目与【基础信息】比对,新增项写回本地副本。"""
|
return base_info_sync.layout(base_info_sync.LAYOUT_DOUYIN)
|
||||||
if config.REPORT_SHEET not in workbook.sheetnames or \
|
|
||||||
config.DY_BASE_SHEET not in workbook.sheetnames:
|
|
||||||
return {'ok': False, 'message': '缺少【报表】或【基础信息】',
|
def _base_info_scan(workbook):
|
||||||
'new_shops': [], 'new_items': []}
|
"""【报表】A/B 与【基础信息】A/E 比对(与美团同一套逻辑),只读不写。
|
||||||
report = workbook[config.REPORT_SHEET]
|
|
||||||
base = workbook[config.DY_BASE_SHEET]
|
``workbook`` 必须是 data_only 打开的,否则报表读到的是 VLOOKUP 公式文本。
|
||||||
shop_col = _col(config.DY_REPORT_SHOP_COL)
|
"""
|
||||||
item_col = _col(config.DY_REPORT_ITEM_COL)
|
return base_info_sync.scan(workbook, _base_info_layout())
|
||||||
pairs = []
|
|
||||||
for r in range(config.REPORT_DATA_START, int(report.max_row or 0) + 1):
|
|
||||||
shop = str(report.cell(r, shop_col).value or '').strip()
|
|
||||||
item = str(report.cell(r, item_col).value or '').strip()
|
|
||||||
if shop and shop != '0' and (shop, item) not in pairs:
|
|
||||||
pairs.append((shop, item))
|
|
||||||
known = set()
|
|
||||||
for r in range(config.DY_BASE_INFO_ROW, int(base.max_row or 0) + 1):
|
|
||||||
v = str(base.cell(r, 1).value or '').strip()
|
|
||||||
if v and v != '0':
|
|
||||||
known.add(v)
|
|
||||||
new_shops = [s for s, _ in pairs if s and s not in known]
|
|
||||||
new_items = []
|
|
||||||
for _, item in pairs:
|
|
||||||
if '【' in item and '】' in item:
|
|
||||||
name = item.split('【', 1)[1].split('】', 1)[0].strip()
|
|
||||||
if name and name not in known:
|
|
||||||
new_items.append(name)
|
|
||||||
changed = 0
|
|
||||||
if not dry_run:
|
|
||||||
r = max(int(base.max_row or 0) + 1, config.DY_BASE_INFO_ROW)
|
|
||||||
for name in dict.fromkeys(new_shops + new_items):
|
|
||||||
if name in known:
|
|
||||||
continue
|
|
||||||
base.cell(r, 1, name)
|
|
||||||
known.add(name)
|
|
||||||
r += 1
|
|
||||||
changed += 1
|
|
||||||
return {'ok': True, 'new_shops': new_shops, 'new_items': new_items,
|
|
||||||
'written': changed,
|
|
||||||
'message': f'基础信息检查:新增门店 {len(new_shops)} / 项目 {len(new_items)}'
|
|
||||||
+ ('' if dry_run else f',写入 {changed} 行')}
|
|
||||||
|
|
||||||
|
|
||||||
def run(day=None, dry_run=False, use_com=None):
|
def run(day=None, dry_run=False, use_com=None):
|
||||||
@@ -171,7 +153,8 @@ def run(day=None, dry_run=False, use_com=None):
|
|||||||
result['message'] = f'未找到本地抖音核对表副本:{table}(请先从共享盘复制)'
|
result['message'] = f'未找到本地抖音核对表副本:{table}(请先从共享盘复制)'
|
||||||
return result
|
return result
|
||||||
|
|
||||||
export = _detail_file(config.WORK_DIR)
|
# 核销明细导出优先找抖音分支目录,其次过程表
|
||||||
|
export = config.latest_file(config.DOUYIN_DETAIL_GLOB)
|
||||||
if not export:
|
if not export:
|
||||||
result['message'] = f'未找到导出的核销明细({config.DOUYIN_DETAIL_GLOB})'
|
result['message'] = f'未找到导出的核销明细({config.DOUYIN_DETAIL_GLOB})'
|
||||||
return result
|
return result
|
||||||
@@ -209,7 +192,7 @@ def run(day=None, dry_run=False, use_com=None):
|
|||||||
pivot_total=pivot_total, report_total=report_total,
|
pivot_total=pivot_total, report_total=report_total,
|
||||||
convert_total=convert_total, consistent=consistent)
|
convert_total=convert_total, consistent=consistent)
|
||||||
|
|
||||||
base_info = _base_info_check(wb, dry_run=True)
|
base_info = _base_info_scan(wb)
|
||||||
result['base_info'] = base_info
|
result['base_info'] = base_info
|
||||||
|
|
||||||
if dry_run:
|
if dry_run:
|
||||||
@@ -220,16 +203,11 @@ def run(day=None, dry_run=False, use_com=None):
|
|||||||
return result
|
return result
|
||||||
|
|
||||||
_write_detail_values(table, rows)
|
_write_detail_values(table, rows)
|
||||||
# 基础信息写入需要可保存的 workbook;zip+XML 不影响,单独用 openpyxl 追加
|
# 基础信息写入需要可保存的 workbook;zip+XML 不影响,单独用 openpyxl 追加。
|
||||||
|
# 直接复用扫描结果,不再重读报表(重读会拿到公式文本,曾把 A 列写坏)。
|
||||||
if base_info.get('ok') and (base_info['new_shops'] or base_info['new_items']):
|
if base_info.get('ok') and (base_info['new_shops'] or base_info['new_items']):
|
||||||
wb2 = openpyxl.load_workbook(table)
|
changed = base_info_sync.write_changes(table, base_info, _base_info_layout())
|
||||||
try:
|
base_info['written'] = changed
|
||||||
written = _base_info_check(wb2, dry_run=False)
|
|
||||||
if written.get('written'):
|
|
||||||
wb2.save(table)
|
|
||||||
result['base_info'] = written
|
|
||||||
finally:
|
|
||||||
wb2.close()
|
|
||||||
|
|
||||||
# 保存后真正刷新透视缓存 + 公式,再从缓存读四口径
|
# 保存后真正刷新透视缓存 + 公式,再从缓存读四口径
|
||||||
do_com = config.USE_COM_REFRESH if use_com is None else bool(use_com)
|
do_com = config.USE_COM_REFRESH if use_com is None else bool(use_com)
|
||||||
|
|||||||
@@ -7,7 +7,8 @@
|
|||||||
抖音【报表】N~Z →【平台-抖音】A~M(数据第 5 行起)
|
抖音【报表】N~Z →【平台-抖音】A~M(数据第 5 行起)
|
||||||
CRM【团购统计】A~I →【团购统计】A~I(同结构,数据第 2 行起)
|
CRM【团购统计】A~I →【团购统计】A~I(同结构,数据第 2 行起)
|
||||||
|
|
||||||
**共享盘全程只读**,只写本地 ``_work/`` 副本;zip+XML 直接改值,不用 openpyxl save。
|
**共享盘全程只读**,只写本地「过程表」里的马敏总表副本(两条分支共用一份);
|
||||||
|
zip+XML 直接改值,不用 openpyxl save。
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
@@ -19,6 +20,7 @@ from xml.sax.saxutils import escape
|
|||||||
import openpyxl
|
import openpyxl
|
||||||
from openpyxl.utils import column_index_from_string as col
|
from openpyxl.utils import column_index_from_string as col
|
||||||
from openpyxl.utils import get_column_letter as letter
|
from openpyxl.utils import get_column_letter as letter
|
||||||
|
from openpyxl.utils.datetime import to_excel as _to_excel
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
from . import share_copy
|
from . import share_copy
|
||||||
@@ -70,12 +72,12 @@ def _sheet_xml_path(zf, sheet_name):
|
|||||||
|
|
||||||
|
|
||||||
def _master_path(day):
|
def _master_path(day):
|
||||||
return os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR,
|
return os.path.join(config.WORK_DIR,
|
||||||
f'{config.LINK_BOOK}{day.month}.{day.day}.xlsx')
|
f'{config.LINK_BOOK}{day.month}.{day.day}.xlsx')
|
||||||
|
|
||||||
|
|
||||||
def _local_path(day, keyword):
|
def _local_path(day, keyword):
|
||||||
return os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR,
|
return os.path.join(config.WORK_DIR,
|
||||||
share_copy.table_name(keyword, day, config.SHARE_TABLE_EXT))
|
share_copy.table_name(keyword, day, config.SHARE_TABLE_EXT))
|
||||||
|
|
||||||
|
|
||||||
@@ -90,11 +92,18 @@ def _read_values(path, sheet, c0, c1, start_row):
|
|||||||
if sheet not in wb.sheetnames:
|
if sheet not in wb.sheetnames:
|
||||||
return []
|
return []
|
||||||
ws = wb[sheet]
|
ws = wb[sheet]
|
||||||
|
# 模板/导出的 dimension 可能没写(None / 1×1),read_only 下会读不到
|
||||||
|
if (ws.max_row or 1) <= 1 or (ws.max_column or 1) <= 1:
|
||||||
|
ws.reset_dimensions()
|
||||||
rows = [list(row) for row in ws.iter_rows(min_row=start_row,
|
rows = [list(row) for row in ws.iter_rows(min_row=start_row,
|
||||||
min_col=col(c0), max_col=col(c1),
|
min_col=col(c0), max_col=col(c1),
|
||||||
values_only=True)]
|
values_only=True)]
|
||||||
while rows and all(v is None for v in rows[-1]):
|
while rows and all(v is None for v in rows[-1]):
|
||||||
rows.pop()
|
rows.pop()
|
||||||
|
# 报表 I~P 是固定行数的公式块,透视行变少时尾部会整段 #N/A,绝不能贴进总表
|
||||||
|
rows = [r for r in rows
|
||||||
|
if not (isinstance(r[0], str) and r[0].startswith('#'))
|
||||||
|
and r[0] not in (None, '')]
|
||||||
return rows
|
return rows
|
||||||
finally:
|
finally:
|
||||||
wb.close()
|
wb.close()
|
||||||
@@ -105,6 +114,12 @@ def _make_cell(row_no, cnum, value, style=''):
|
|||||||
s_attr = f' s="{style}"' if style else ''
|
s_attr = f' s="{style}"' if style else ''
|
||||||
if isinstance(value, bool):
|
if isinstance(value, bool):
|
||||||
return f'<c r="{letters}{row_no}"{s_attr} t="b"><v>{int(value)}</v></c>'
|
return f'<c r="{letters}{row_no}"{s_attr} t="b"><v>{int(value)}</v></c>'
|
||||||
|
if isinstance(value, (datetime, date)):
|
||||||
|
# 日期必须写 Excel 序列号并按原单元格日期格式显示;写成 inlineStr 会退化为文本,
|
||||||
|
# 透视表按日期分组 / 日期匹配公式都会失效(19xx 序列号不影响,本表为 1900 日期系统)。
|
||||||
|
serial = _to_excel(value)
|
||||||
|
num = int(serial) if float(serial).is_integer() else serial
|
||||||
|
return f'<c r="{letters}{row_no}"{s_attr}><v>{num}</v></c>'
|
||||||
if isinstance(value, (int, float)):
|
if isinstance(value, (int, float)):
|
||||||
return f'<c r="{letters}{row_no}"{s_attr}><v>{value}</v></c>'
|
return f'<c r="{letters}{row_no}"{s_attr}><v>{value}</v></c>'
|
||||||
return (f'<c r="{letters}{row_no}"{s_attr} t="inlineStr">'
|
return (f'<c r="{letters}{row_no}"{s_attr} t="inlineStr">'
|
||||||
@@ -134,6 +149,18 @@ def _set_row_values(row_xml, row_no, values, lo, hi):
|
|||||||
return head + ''.join(cell for _, cell in keep) + '</row>'
|
return head + ''.join(cell for _, cell in keep) + '</row>'
|
||||||
|
|
||||||
|
|
||||||
|
def _row_style_map(row_xml):
|
||||||
|
"""解析单行 XML,返回 {列号: 样式 s 值}(用于新增行沿用上一行格式)。"""
|
||||||
|
out = {}
|
||||||
|
if not row_xml:
|
||||||
|
return out
|
||||||
|
for m in _CELL_RE.finditer(row_xml):
|
||||||
|
sm = re.search(r'\bs="(\d+)"', m.group(3) or '')
|
||||||
|
if sm:
|
||||||
|
out[_col_num(m.group(1))] = sm.group(1)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
def _patch_sheet_xml(xml_text, rows, start_row, start_col):
|
def _patch_sheet_xml(xml_text, rows, start_row, start_col):
|
||||||
existing = {}
|
existing = {}
|
||||||
for m in _ROW_RE.finditer(xml_text):
|
for m in _ROW_RE.finditer(xml_text):
|
||||||
@@ -159,9 +186,16 @@ def _patch_sheet_xml(xml_text, rows, start_row, start_col):
|
|||||||
_make_cell(row_no, cnum, value) for cnum, value in sorted(values.items())) + '</row>'
|
_make_cell(row_no, cnum, value) for cnum, value in sorted(values.items())) + '</row>'
|
||||||
if old:
|
if old:
|
||||||
out = out.replace(old, new, 1)
|
out = out.replace(old, new, 1)
|
||||||
|
col_styles = {}
|
||||||
|
if needed > last_existing:
|
||||||
|
# 新增行没有原单元格可继承样式:向上回看最多 20 行,同列取最近的 s=,
|
||||||
|
# 否则日期序列号会以「常规」格式显示成 4xxxx 这类裸数字。
|
||||||
|
for row_no in range(last_existing, max(start_row - 1, last_existing - 20), -1):
|
||||||
|
for cnum, style in _row_style_map(existing.get(row_no)).items():
|
||||||
|
col_styles.setdefault(cnum, style)
|
||||||
added = ''.join(
|
added = ''.join(
|
||||||
f'<row r="{row_no}">' + ''.join(
|
f'<row r="{row_no}">' + ''.join(
|
||||||
_make_cell(row_no, lo + offset, value)
|
_make_cell(row_no, lo + offset, value, col_styles.get(lo + offset, ''))
|
||||||
for offset, value in enumerate(rows[row_no - start_row]) if value is not None)
|
for offset, value in enumerate(rows[row_no - start_row]) if value is not None)
|
||||||
+ '</row>'
|
+ '</row>'
|
||||||
for row_no in range(last_existing + 1, max(needed, last_existing) + 1))
|
for row_no in range(last_existing + 1, max(needed, last_existing) + 1))
|
||||||
@@ -195,8 +229,7 @@ def _write_master(path, jobs):
|
|||||||
if info.filename in patches:
|
if info.filename in patches:
|
||||||
dst.writestr(zi, patches.pop(info.filename).encode('utf-8'))
|
dst.writestr(zi, patches.pop(info.filename).encode('utf-8'))
|
||||||
else:
|
else:
|
||||||
with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
dst.writestr(zi, zf.read(info))
|
||||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
|
||||||
for name, data in patches.items():
|
for name, data in patches.items():
|
||||||
dst.writestr(name, data.encode('utf-8'))
|
dst.writestr(name, data.encode('utf-8'))
|
||||||
finally:
|
finally:
|
||||||
@@ -232,7 +265,7 @@ def run(day=None, douyin_dir='', crm_dir='', dry_run=False, jobs_filter=None):
|
|||||||
if not wanted or 'douyin' in wanted:
|
if not wanted or 'douyin' in wanted:
|
||||||
dy = _local_path(target, config.DOUYIN_SHARE_KEYWORD)
|
dy = _local_path(target, config.DOUYIN_SHARE_KEYWORD)
|
||||||
if not os.path.isfile(dy):
|
if not os.path.isfile(dy):
|
||||||
dy = os.path.join(str(douyin_dir or config.DOUYIN_WORK_DIR).strip('"'),
|
dy = os.path.join(str(douyin_dir or config.OUT_DIR).strip('"'),
|
||||||
f'{config.DOUYIN_TABLE_PREFIX}{target.month}.{target.day}.xlsx')
|
f'{config.DOUYIN_TABLE_PREFIX}{target.month}.{target.day}.xlsx')
|
||||||
if os.path.isfile(dy):
|
if os.path.isfile(dy):
|
||||||
values = _read_values(dy, config.REPORT_SHEET, *config.DOUYIN_REPORT_COLS,
|
values = _read_values(dy, config.REPORT_SHEET, *config.DOUYIN_REPORT_COLS,
|
||||||
|
|||||||
@@ -0,0 +1,150 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""核对前置预检:导出明细 / 核对表 / 马敏总表 / CRM 支付数据齐不齐、日期对不对。
|
||||||
|
|
||||||
|
预检只读目录与文件名,不打开、也不写任何表。任一项 error 不通过,调用方应立即中止该分支——
|
||||||
|
否则后续「先清空【订单收入明细表】/【核销明细】再重贴」会在缺文件时把表清空。
|
||||||
|
|
||||||
|
判定规则:
|
||||||
|
|
||||||
|
* 必填项缺失 → error;
|
||||||
|
* 选填项(预订收益明细,账号无预订业务时本就没有)缺失 → 仅 WARN;
|
||||||
|
* 明细文件名必须能解析出日期,且营业日落在区间内(单日即等于营业日);
|
||||||
|
* 同一类明细出现 2 份及以上 → error。`daily_detail.run()` 会把匹配到的文件**全部合并**,
|
||||||
|
目录里多留一份历史明细就会串天,所以要求只留当天那份。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
from datetime import date, datetime
|
||||||
|
|
||||||
|
from .. import config
|
||||||
|
from . import share_copy
|
||||||
|
|
||||||
|
BRANCH_MEITUAN = 'check_meituan'
|
||||||
|
BRANCH_DOUYIN = 'check_douyin'
|
||||||
|
|
||||||
|
# 分支 → ((名称, glob, 是否必填), ...)
|
||||||
|
_BRANCH_SOURCES = {
|
||||||
|
BRANCH_MEITUAN: (
|
||||||
|
('团购收益明细', '团购收益明细_*.xlsx', True),
|
||||||
|
('预订收益明细', '预订收益明细_*.xlsx', False),
|
||||||
|
),
|
||||||
|
BRANCH_DOUYIN: (
|
||||||
|
('核销明细', '核销明细*.xlsx', True),
|
||||||
|
),
|
||||||
|
}
|
||||||
|
|
||||||
|
_DATE_RE = re.compile(r'(\d{4})\D?(\d{1,2})\D?(\d{1,2})')
|
||||||
|
|
||||||
|
|
||||||
|
def _as_date(value):
|
||||||
|
if isinstance(value, datetime):
|
||||||
|
return value.date()
|
||||||
|
if isinstance(value, date):
|
||||||
|
return value
|
||||||
|
text = str(value or '').strip()[:10]
|
||||||
|
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||||
|
try:
|
||||||
|
return datetime.strptime(text, fmt).date()
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def dates_in_name(name):
|
||||||
|
"""从文件名里取出所有日期(升序去重),取不到返回空列表。"""
|
||||||
|
out = []
|
||||||
|
for m in _DATE_RE.finditer(os.path.basename(str(name))):
|
||||||
|
try:
|
||||||
|
d = date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||||
|
except ValueError:
|
||||||
|
continue
|
||||||
|
if 2000 <= d.year <= 2100 and d not in out:
|
||||||
|
out.append(d)
|
||||||
|
return sorted(out)
|
||||||
|
|
||||||
|
|
||||||
|
def _item(name, ok, level, message, **extra):
|
||||||
|
item = {'name': name, 'ok': bool(ok), 'level': level, 'message': message}
|
||||||
|
item.update(extra)
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def _check_table(name, path):
|
||||||
|
exists = os.path.isfile(path)
|
||||||
|
return _item(name, exists, 'ok' if exists else 'error',
|
||||||
|
'' if exists else f'未找到{name}:{path}', path=path)
|
||||||
|
|
||||||
|
|
||||||
|
def _check_files(name, pattern, day, required=True):
|
||||||
|
paths = config.glob_files(pattern)
|
||||||
|
if not paths:
|
||||||
|
level = 'error' if required else 'warn'
|
||||||
|
tail = '' if required else '(选填,缺省视为当天无预订业务)'
|
||||||
|
return _item(name, not required, level,
|
||||||
|
f'未找到{name}({pattern}){tail};搜索目录:'
|
||||||
|
+ ';'.join(config.search_dirs()),
|
||||||
|
pattern=pattern, files=[])
|
||||||
|
files = [os.path.basename(p) for p in paths]
|
||||||
|
if len(paths) > 1:
|
||||||
|
return _item(name, False, 'error',
|
||||||
|
f'{name}有 {len(paths)} 份,合并时会串天;只保留营业日当天那一份:'
|
||||||
|
+ '、'.join(files), pattern=pattern, files=files)
|
||||||
|
|
||||||
|
dates = dates_in_name(files[0])
|
||||||
|
if not dates:
|
||||||
|
return _item(name, True, 'warn',
|
||||||
|
f'{name}文件名解析不出日期,无法校验是否属于营业日:{files[0]}',
|
||||||
|
pattern=pattern, files=files)
|
||||||
|
start, end = dates[0], dates[-1]
|
||||||
|
if start <= day <= end:
|
||||||
|
return _item(name, True, 'ok', '',
|
||||||
|
pattern=pattern, files=files, range=[start.isoformat(), end.isoformat()])
|
||||||
|
return _item(name, False, 'error',
|
||||||
|
f'{name}日期 {start}~{end} 不含营业日 {day}:{files[0]}',
|
||||||
|
pattern=pattern, files=files, range=[start.isoformat(), end.isoformat()])
|
||||||
|
|
||||||
|
|
||||||
|
def _crm_path(day, crm_dir=''):
|
||||||
|
root = str(crm_dir or config.CRM_EXPORT_DIR).strip().strip('"')
|
||||||
|
return os.path.join(root, f'{config.CRM_GROUP_PAY_PREFIX}-{day:%Y%m%d}.xlsx')
|
||||||
|
|
||||||
|
|
||||||
|
def run(day=None, action=BRANCH_MEITUAN, crm_dir=''):
|
||||||
|
"""执行预检。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
day: 营业日(date / str),空则今天。
|
||||||
|
action: ``check_meituan`` / ``check_douyin``。
|
||||||
|
crm_dir: CRM 导出目录,空则用 ``config.CRM_EXPORT_DIR``。
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
dict: ``ok`` / ``day`` / ``action`` / ``checks`` / ``errors`` / ``warns`` / ``message``
|
||||||
|
"""
|
||||||
|
target = _as_date(day) or date.today()
|
||||||
|
act = action if action in _BRANCH_SOURCES else BRANCH_MEITUAN
|
||||||
|
keyword = config.SHARE_TABLE_KEYWORD if act == BRANCH_MEITUAN else config.DOUYIN_SHARE_KEYWORD
|
||||||
|
|
||||||
|
checks = [
|
||||||
|
_check_table(f'{keyword}核对表副本',
|
||||||
|
os.path.join(config.WORK_DIR,
|
||||||
|
share_copy.table_name(keyword, target, config.SHARE_TABLE_EXT))),
|
||||||
|
_check_table('马敏团购总表副本',
|
||||||
|
os.path.join(config.WORK_DIR,
|
||||||
|
f'{config.LINK_BOOK}{target.month}.{target.day}.xlsx')),
|
||||||
|
]
|
||||||
|
for name, pattern, required in _BRANCH_SOURCES[act]:
|
||||||
|
checks.append(_check_files(name, pattern, target, required))
|
||||||
|
if act == BRANCH_MEITUAN:
|
||||||
|
checks.append(_check_table('CRM 团购支付数据', _crm_path(target, crm_dir)))
|
||||||
|
|
||||||
|
errors = [c for c in checks if not c['ok']]
|
||||||
|
warns = [c for c in checks if c['ok'] and c['level'] == 'warn']
|
||||||
|
ok = not errors
|
||||||
|
if ok:
|
||||||
|
message = '前置预检通过:' + '、'.join(c['name'] for c in checks) \
|
||||||
|
+ (f';{len(warns)} 项提示见上' if warns else '')
|
||||||
|
else:
|
||||||
|
message = f'前置预检未通过({len(errors)} 项):' + ';'.join(
|
||||||
|
c['message'] for c in errors)
|
||||||
|
return {'ok': ok, 'day': target.isoformat(), 'action': act,
|
||||||
|
'checks': checks, 'errors': errors, 'warns': warns, 'message': message}
|
||||||
@@ -1,17 +1,18 @@
|
|||||||
# -*- coding: utf-8 -*-
|
# -*- coding: utf-8 -*-
|
||||||
"""从共享盘复制「昨天」的表到本地副本(**共享盘全程只读,绝不回写**)。
|
"""从共享盘复制「昨天」的表到本地副本(**共享盘全程只读,绝不回写**)。
|
||||||
|
|
||||||
源在共享盘,目标在本机 ``WORK_DIR/_work/``,文件名日期同步替换::
|
源在共享盘,目标在本机过程表目录(``<根>\\过程表``,各分支共用),文件名日期同步替换::
|
||||||
|
|
||||||
源(共享盘,只读)
|
源(共享盘,只读)
|
||||||
1111/TG/2026年11月/11.10/美团11.10.xlsx / 抖音11.10.xlsx
|
1111/TG/2026年11月/11.10/美团11.10.xlsx / 抖音11.10.xlsx
|
||||||
1111/TG/2026年11月/11.10/马敏团购总表11.10.xlsx
|
1111/TG/2026年11月/11.10/马敏团购总表11.10.xlsx
|
||||||
目标(本地副本)
|
目标(本地副本 = 过程表)
|
||||||
D:\\资料\\财务\\新美大平台核对\\_work\\美团11.11.xlsx
|
D:\\资料\\财务\\团购数据核对\\过程表\\美团11.11.xlsx
|
||||||
D:\\资料\\财务\\新美大平台核对\\_work\\抖音11.11.xlsx
|
D:\\资料\\财务\\团购数据核对\\过程表\\抖音11.11.xlsx
|
||||||
D:\\资料\\财务\\新美大平台核对\\_work\\马敏团购总表11.11.xlsx
|
D:\\资料\\财务\\团购数据核对\\过程表\\马敏团购总表11.11.xlsx
|
||||||
|
|
||||||
两张核对表复制到本地后,后续所有处理都只改本地副本。
|
两张核对表与总表复制到本地后,后续所有处理都只改本地副本;马敏总表只此一份,
|
||||||
|
美团/抖音两条分支先后贴入同一副本,不会按分支分叉。
|
||||||
"""
|
"""
|
||||||
import os
|
import os
|
||||||
import re
|
import re
|
||||||
@@ -72,7 +73,7 @@ def copy_prev_table(share_root='', keyword='', ext='', day=None, local_dir='', d
|
|||||||
prev = target - timedelta(days=1)
|
prev = target - timedelta(days=1)
|
||||||
|
|
||||||
src_path = _pick_source(day_dir(root, prev), kw, prev, suffix)
|
src_path = _pick_source(day_dir(root, prev), kw, prev, suffix)
|
||||||
dst_dir = str(local_dir or os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR))
|
dst_dir = str(local_dir or config.WORK_DIR)
|
||||||
dst_path = os.path.join(dst_dir, table_name(kw, target, suffix))
|
dst_path = os.path.join(dst_dir, table_name(kw, target, suffix))
|
||||||
result = {'ok': False, 'message': '', 'src': src_path, 'dst': dst_path, 'skipped': False}
|
result = {'ok': False, 'message': '', 'src': src_path, 'dst': dst_path, 'skipped': False}
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,133 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""xlsx 单 sheet 行级改写(zip+XML):保留透视 / 外部链接 / 其它 sheet。
|
||||||
|
|
||||||
|
订单收入明细表有 8 个透视 + 6 个外部链接,openpyxl 保存会把它们丢掉,
|
||||||
|
所以整个插件里凡是写这类工作簿都走这里:只替换目标 sheet 的 XML,
|
||||||
|
其它部件原样搬运。
|
||||||
|
|
||||||
|
对外只有 :func:`write_rows`:
|
||||||
|
``values`` = ``{行号: [第1列, 第2列, ...]}``,``formulas`` = ``{行号: [公式...]}``
|
||||||
|
(公式只从 ``config.DAILY_HELPER_FIRST`` 起写,用于 AC~AI 辅助列)。
|
||||||
|
"""
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import zipfile
|
||||||
|
from xml.sax.saxutils import escape
|
||||||
|
|
||||||
|
from openpyxl.utils import get_column_letter as letter
|
||||||
|
|
||||||
|
from .. import config
|
||||||
|
from .paste_to_master import _CELL_RE, _ROW_RE, _col_num, _make_cell, _sheet_xml_path
|
||||||
|
from .zipio import open_zip
|
||||||
|
|
||||||
|
|
||||||
|
def _cell_styles(row_xml):
|
||||||
|
out = {}
|
||||||
|
if not row_xml:
|
||||||
|
return out
|
||||||
|
for m in _CELL_RE.finditer(row_xml):
|
||||||
|
sm = re.search(r'\bs="(\d+)"', m.group(3) or '')
|
||||||
|
if sm:
|
||||||
|
out[_col_num(m.group(1))] = sm.group(1)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def _formula_cell(row_no, cnum, formula, style=''):
|
||||||
|
s_attr = f' s="{style}"' if style else ''
|
||||||
|
body = formula[1:] if formula.startswith('=') else formula
|
||||||
|
return f'<c r="{letter(cnum)}{row_no}"{s_attr}><f>{escape(body)}</f></c>'
|
||||||
|
|
||||||
|
|
||||||
|
def _build_row(row_no, values, formulas, styles, formula_from):
|
||||||
|
cells = []
|
||||||
|
for idx, value in enumerate(values or []):
|
||||||
|
if value is None or value == '':
|
||||||
|
continue
|
||||||
|
cnum = idx + 1
|
||||||
|
cells.append(_make_cell(row_no, cnum, value, styles.get(cnum, '')))
|
||||||
|
for idx, formula in enumerate(formulas or []):
|
||||||
|
if formula:
|
||||||
|
cnum = formula_from + idx
|
||||||
|
cells.append(_formula_cell(row_no, cnum, formula, styles.get(cnum, '')))
|
||||||
|
return f'<row r="{row_no}">' + ''.join(cells) + '</row>'
|
||||||
|
|
||||||
|
|
||||||
|
def patch_rows(xml_text, values, formulas, start_row, last_row, formula_from):
|
||||||
|
"""把 values/formulas 写进 sheet XML(替换 [start_row, last_row] 内的行)。"""
|
||||||
|
existing = {}
|
||||||
|
for m in _ROW_RE.finditer(xml_text):
|
||||||
|
mm = re.search(r'\br="(\d+)"', '<row' + (m.group(1) or '') + '>')
|
||||||
|
if mm:
|
||||||
|
existing[int(mm.group(1))] = m.group(0)
|
||||||
|
|
||||||
|
end = max(max(values) if values else start_row - 1, last_row or 0)
|
||||||
|
style_cache = {}
|
||||||
|
|
||||||
|
def styles_for(row_no):
|
||||||
|
if row_no in style_cache:
|
||||||
|
return style_cache[row_no]
|
||||||
|
out = {}
|
||||||
|
if row_no in existing:
|
||||||
|
out = _cell_styles(existing[row_no])
|
||||||
|
else:
|
||||||
|
for r in range(row_no - 1, max(start_row - 1, (last_row or 0) - 20), -1):
|
||||||
|
if r in existing:
|
||||||
|
out = _cell_styles(existing[r])
|
||||||
|
break
|
||||||
|
style_cache[row_no] = out
|
||||||
|
return out
|
||||||
|
|
||||||
|
pieces, pos, handled = [], 0, set()
|
||||||
|
for m in _ROW_RE.finditer(xml_text):
|
||||||
|
mm = re.search(r'\br="(\d+)"', '<row' + (m.group(1) or '') + '>')
|
||||||
|
if not mm:
|
||||||
|
continue
|
||||||
|
row_no = int(mm.group(1))
|
||||||
|
if row_no < start_row or row_no > end:
|
||||||
|
continue
|
||||||
|
pieces.append(xml_text[pos:m.start()])
|
||||||
|
pieces.append(_build_row(row_no, values.get(row_no), formulas.get(row_no),
|
||||||
|
styles_for(row_no), formula_from))
|
||||||
|
pos = m.end()
|
||||||
|
handled.add(row_no)
|
||||||
|
pieces.append(xml_text[pos:])
|
||||||
|
out = ''.join(pieces)
|
||||||
|
|
||||||
|
missing = [r for r in range(start_row, end + 1) if r not in handled]
|
||||||
|
if missing:
|
||||||
|
extra = ''.join(_build_row(r, values.get(r), formulas.get(r),
|
||||||
|
styles_for(r), formula_from) for r in missing)
|
||||||
|
out = out.replace('</sheetData>', extra + '</sheetData>', 1)
|
||||||
|
return out
|
||||||
|
|
||||||
|
|
||||||
|
def write_rows(path, sheet, values, formulas=None, start_row=None, last_row=None):
|
||||||
|
"""改写一个 sheet 的行(values 从第 1 列起;formulas 从辅助列起)。
|
||||||
|
|
||||||
|
``last_row`` 传表里原来的末行,用来把多余旧行清空。
|
||||||
|
"""
|
||||||
|
formulas = formulas or {}
|
||||||
|
if not values:
|
||||||
|
return
|
||||||
|
start_row = min(values) if start_row is None else start_row
|
||||||
|
zf = open_zip(path)
|
||||||
|
tmp = path + '.xml.tmp'
|
||||||
|
try:
|
||||||
|
xml_path = _sheet_xml_path(zf, sheet)
|
||||||
|
if not xml_path:
|
||||||
|
raise RuntimeError(f'工作簿里找不到 sheet「{sheet}」的 XML')
|
||||||
|
text = zf.read(xml_path).decode('utf-8', 'replace')
|
||||||
|
patched = patch_rows(text, values, formulas, start_row, last_row or 0,
|
||||||
|
config.DAILY_HELPER_FIRST)
|
||||||
|
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||||
|
for info in zf.infolist():
|
||||||
|
if info.is_dir():
|
||||||
|
continue
|
||||||
|
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||||
|
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||||
|
zi.external_attr = info.external_attr
|
||||||
|
data = patched.encode('utf-8') if info.filename == xml_path else zf.read(info)
|
||||||
|
dst.writestr(zi, data)
|
||||||
|
finally:
|
||||||
|
zf.close()
|
||||||
|
os.replace(tmp, path)
|
||||||
@@ -0,0 +1,305 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""门店归属:把美团收益明细的「消费门店」翻译成内部门店 + 品牌。
|
||||||
|
|
||||||
|
从 XQ0041 迁入(2026-11):XQ0041 只保留导表与到账统计表维护,门店归属归本插件。
|
||||||
|
|
||||||
|
两步走,都不依赖字符串模糊匹配:
|
||||||
|
|
||||||
|
1. **券号 join**(主):``crm_store`` 拉到的「券号 → CRM 门店」与收益明细的券号对齐,
|
||||||
|
命中即得到内部门店(订单级唯一,实测 100%);
|
||||||
|
2. **映射表复用**(补):历史命中过的「美团门店名 → 内部门店」落盘累积,
|
||||||
|
本期虽然没取到券号(跨月补单 / CRM 未同步)也能直接翻译。
|
||||||
|
|
||||||
|
产物 ``门店核对_起_止.xlsx``(写到本地工作目录,不改动任何表):
|
||||||
|
|
||||||
|
* ``门店映射``:美团门店名 → 内部门店 / 品牌 / CRM 门店ID / 命中单数
|
||||||
|
* ``门店汇总``:按内部门店汇总订单数与金额(财务按店核对用)
|
||||||
|
* ``未匹配``:券号与映射表都没对上的订单,人工确认一次后可写回映射表
|
||||||
|
|
||||||
|
映射表冲突(同一美团门店名对到多个内部门店,常见于通兑券跨店核销)按票数取众数,
|
||||||
|
并在「门店映射」的备注列标出,便于人工复核。
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
from collections import defaultdict
|
||||||
|
from datetime import datetime
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
from openpyxl.styles import Alignment, Font, PatternFill
|
||||||
|
from openpyxl.utils import get_column_letter
|
||||||
|
|
||||||
|
from .. import config
|
||||||
|
from . import crm_store
|
||||||
|
|
||||||
|
# 收益明细里用到的列(按表头关键词定位,不写死列号)
|
||||||
|
COL_TICKET = '券号'
|
||||||
|
COL_SHOP = '消费门店'
|
||||||
|
COL_TIME = '验券/退款/调整时间'
|
||||||
|
COL_GROSS = '总收入(元)'
|
||||||
|
COL_NET = '结算价'
|
||||||
|
COL_FEE = '平台技术服务费(元)'
|
||||||
|
COL_MARKETING = '商家营销费用(元)'
|
||||||
|
COL_CHANNEL = '渠道佣金(元)'
|
||||||
|
|
||||||
|
_HEADER_FILL = PatternFill('solid', fgColor='DDEBF7')
|
||||||
|
_WARN_FILL = PatternFill('solid', fgColor='FCE4D6')
|
||||||
|
|
||||||
|
|
||||||
|
def _find_col(header, keyword, *, exact=True):
|
||||||
|
"""按表头关键词定位列下标(0 起);``exact=False`` 时用前缀/包含。"""
|
||||||
|
for idx, name in enumerate(header):
|
||||||
|
text = str(name or '').strip()
|
||||||
|
if (text == keyword) if exact else (keyword in text):
|
||||||
|
return idx
|
||||||
|
return -1
|
||||||
|
|
||||||
|
|
||||||
|
def _latest_detail():
|
||||||
|
"""修改时间最新的团购收益明细(先分支目录、再过程表;金色湖畔前缀天然不匹配)。"""
|
||||||
|
return config.latest_file(config.DETAIL_GLOB)
|
||||||
|
|
||||||
|
|
||||||
|
def _to_float(value):
|
||||||
|
"""金额转 float;'--'/空/异常一律 0(明细里退款行的负数要保留)。"""
|
||||||
|
if value is None or value == '':
|
||||||
|
return 0.0
|
||||||
|
try:
|
||||||
|
return float(str(value).replace(',', '').strip())
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return 0.0
|
||||||
|
|
||||||
|
|
||||||
|
def _load_map():
|
||||||
|
"""读累积映射表;损坏/缺失时返回空表(不阻断)。"""
|
||||||
|
path = os.path.join(config.OUT_DIR, config.STORE_MAP_FILE)
|
||||||
|
if not os.path.exists(path):
|
||||||
|
return {'shops': {}}
|
||||||
|
try:
|
||||||
|
with open(path, encoding='utf-8') as fp:
|
||||||
|
data = json.load(fp)
|
||||||
|
except (OSError, ValueError) as e:
|
||||||
|
config.log(f'门店映射表读取失败,按空表处理:{e}', 'WARN')
|
||||||
|
return {'shops': {}}
|
||||||
|
if not isinstance(data, dict) or not isinstance(data.get('shops'), dict):
|
||||||
|
return {'shops': {}}
|
||||||
|
return data
|
||||||
|
|
||||||
|
|
||||||
|
def _save_map(data):
|
||||||
|
os.makedirs(config.OUT_DIR, exist_ok=True)
|
||||||
|
path = os.path.join(config.OUT_DIR, config.STORE_MAP_FILE)
|
||||||
|
tmp = f'{path}.tmp'
|
||||||
|
with open(tmp, 'w', encoding='utf-8') as fp:
|
||||||
|
json.dump(data, fp, ensure_ascii=False, indent=2)
|
||||||
|
os.replace(tmp, path)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def _read_detail(path):
|
||||||
|
"""读收益明细:返回 (表头, 数据行列表, 列下标字典)。"""
|
||||||
|
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||||
|
try:
|
||||||
|
ws = wb[wb.sheetnames[0]]
|
||||||
|
header = list(next(ws.iter_rows(min_row=config.DETAIL_HEADER_ROW,
|
||||||
|
max_row=config.DETAIL_HEADER_ROW,
|
||||||
|
max_col=ws.max_column, values_only=True)))
|
||||||
|
cols = {
|
||||||
|
'ticket': _find_col(header, COL_TICKET),
|
||||||
|
'shop': _find_col(header, COL_SHOP),
|
||||||
|
'time': _find_col(header, COL_TIME),
|
||||||
|
'gross': _find_col(header, COL_GROSS),
|
||||||
|
'net': _find_col(header, COL_NET, exact=False),
|
||||||
|
'fee': _find_col(header, COL_FEE),
|
||||||
|
'marketing': _find_col(header, COL_MARKETING),
|
||||||
|
'channel': _find_col(header, COL_CHANNEL),
|
||||||
|
}
|
||||||
|
missing = [k for k in ('ticket', 'shop', 'time') if cols[k] < 0]
|
||||||
|
if missing:
|
||||||
|
raise RuntimeError(f'收益明细缺少必需列:{missing}'
|
||||||
|
f'(表头第 {config.DETAIL_HEADER_ROW} 行)')
|
||||||
|
rows = []
|
||||||
|
for row in ws.iter_rows(min_row=config.DETAIL_DATA_START, max_col=len(header),
|
||||||
|
values_only=True):
|
||||||
|
if not any(v not in (None, '') for v in row):
|
||||||
|
continue
|
||||||
|
rows.append(row)
|
||||||
|
return header, rows, cols
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
|
def _day_of(value):
|
||||||
|
return crm_store._to_date(value)
|
||||||
|
|
||||||
|
|
||||||
|
def _write_output(path, mapped_names, summary, unmatched):
|
||||||
|
"""写门店核对 xlsx(新建文件,不动台账)。"""
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
head_font = Font(bold=True)
|
||||||
|
|
||||||
|
# ---------- sheet1 门店映射 ----------
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = '门店映射'
|
||||||
|
head = ['美团门店名', '内部门店', '品牌', 'CRM门店ID', '累计命中单数', '备注']
|
||||||
|
ws.append(head)
|
||||||
|
for idx, (name, info) in enumerate(sorted(mapped_names.items()), 1):
|
||||||
|
votes = info.get('votes') or {}
|
||||||
|
note = ''
|
||||||
|
if len(votes) > 1:
|
||||||
|
others = {k: v for k, v in votes.items() if k != info.get('shop')}
|
||||||
|
if others:
|
||||||
|
note = '另有 ' + '、'.join(f'{k}({v})' for k, v in others.items()) + ' 单(跨店核销)'
|
||||||
|
ws.append([name, info.get('shop', ''), info.get('brand', ''), info.get('shop_id', ''),
|
||||||
|
sum(votes.values()) or info.get('hits', 0), note])
|
||||||
|
if note:
|
||||||
|
for cell in ws[idx + 1]:
|
||||||
|
cell.fill = _WARN_FILL
|
||||||
|
|
||||||
|
# ---------- sheet2 门店汇总 ----------
|
||||||
|
ws2 = wb.create_sheet('门店汇总')
|
||||||
|
ws2.append(['内部门店', '品牌', '订单数', '总收入', '结算价', '平台技术服务费',
|
||||||
|
'商家营销费用', '渠道佣金'])
|
||||||
|
total = [0, 0.0, 0.0, 0.0, 0.0, 0.0]
|
||||||
|
for shop in sorted(summary, key=lambda s: (summary[s]['brand'], s)):
|
||||||
|
item = summary[shop]
|
||||||
|
ws2.append([shop, item['brand'], item['count'], round(item['gross'], 2),
|
||||||
|
round(item['net'], 2), round(item['fee'], 2),
|
||||||
|
round(item['marketing'], 2), round(item['channel'], 2)])
|
||||||
|
total[0] += item['count']
|
||||||
|
total[1] += item['gross']
|
||||||
|
total[2] += item['net']
|
||||||
|
total[3] += item['fee']
|
||||||
|
total[4] += item['marketing']
|
||||||
|
total[5] += item['channel']
|
||||||
|
ws2.append(['合计', '', total[0]] + [round(x, 2) for x in total[1:]])
|
||||||
|
|
||||||
|
# ---------- sheet3 未匹配 ----------
|
||||||
|
ws3 = wb.create_sheet('未匹配')
|
||||||
|
ws3.append(['券号', '美团门店', '验券时间', '总收入', '说明'])
|
||||||
|
for row in unmatched:
|
||||||
|
ws3.append(row)
|
||||||
|
|
||||||
|
for sheet in (ws, ws2, ws3):
|
||||||
|
for cell in sheet[1]:
|
||||||
|
cell.font = head_font
|
||||||
|
cell.fill = _HEADER_FILL
|
||||||
|
cell.alignment = Alignment(horizontal='center')
|
||||||
|
sheet.freeze_panes = 'A2'
|
||||||
|
for col in range(1, sheet.max_column + 1):
|
||||||
|
width = max((len(str(sheet.cell(r, col).value or ''))
|
||||||
|
for r in range(1, min(sheet.max_row, 200) + 1)), default=8)
|
||||||
|
sheet.column_dimensions[get_column_letter(col)].width = min(46, max(10, width + 6))
|
||||||
|
|
||||||
|
wb.save(path)
|
||||||
|
return path
|
||||||
|
|
||||||
|
|
||||||
|
def run(detail_path='', dry_run=False, progress_from=78, progress_to=88):
|
||||||
|
"""执行门店归属核对。
|
||||||
|
|
||||||
|
Args:
|
||||||
|
detail_path: 指定收益明细;空则取目录内最新一份
|
||||||
|
dry_run: 只统计不写文件(映射表也不落盘)
|
||||||
|
progress_from / progress_to: 拉 CRM 时的进度区间(0~100)
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
``{"ok", "message", "path", "mapped", "unmapped", "stores", "conflicts"}``
|
||||||
|
"""
|
||||||
|
if not crm_store.available():
|
||||||
|
return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0,
|
||||||
|
'conflicts': [], 'message': '未挂载 crm_sdk,跳过门店归属(需插件声明 requires.sdks)'}
|
||||||
|
|
||||||
|
path = detail_path or _latest_detail()
|
||||||
|
if not path or not os.path.exists(path):
|
||||||
|
return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0,
|
||||||
|
'conflicts': [], 'message': '未找到团购收益明细,无法做门店归属'}
|
||||||
|
|
||||||
|
config.log(f'门店归属:读收益明细 {os.path.basename(path)}')
|
||||||
|
header, rows, cols = _read_detail(path)
|
||||||
|
|
||||||
|
# 1) 收集日期 → 拉 CRM 券号表
|
||||||
|
days = {d for d in (_day_of(r[cols['time']]) for r in rows if cols['time'] < len(r)) if d}
|
||||||
|
if not days:
|
||||||
|
return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0,
|
||||||
|
'conflicts': [], 'message': '收益明细的「验券/退款/调整时间」全为空,跳过门店归属'}
|
||||||
|
config.log(f'门店归属:明细 {len(rows)} 行,验券日期 {min(days)}~{max(days)}({len(days)} 天)')
|
||||||
|
crm = crm_store.load(days, progress_from=progress_from, progress_to=progress_to)
|
||||||
|
if not crm.get('ok'):
|
||||||
|
return {'ok': False, 'path': '', 'mapped': 0, 'unmapped': 0, 'stores': 0,
|
||||||
|
'conflicts': [], 'message': crm.get('message') or 'CRM 券号取数为空'}
|
||||||
|
config.log(crm.get('message') or '')
|
||||||
|
tickets = crm['tickets']
|
||||||
|
|
||||||
|
# 2) 券号 join,累积映射表
|
||||||
|
store = _load_map()
|
||||||
|
shops = store['shops']
|
||||||
|
summary = defaultdict(lambda: {'brand': '', 'count': 0, 'gross': 0.0, 'net': 0.0,
|
||||||
|
'fee': 0.0, 'marketing': 0.0, 'channel': 0.0})
|
||||||
|
unmatched = []
|
||||||
|
mapped_cnt = unmapped_cnt = 0
|
||||||
|
conflicts = []
|
||||||
|
|
||||||
|
for row in rows:
|
||||||
|
def cell(key):
|
||||||
|
idx = cols[key]
|
||||||
|
return row[idx] if 0 <= idx < len(row) else None
|
||||||
|
|
||||||
|
name = str(cell('shop') or '').strip()
|
||||||
|
code = str(cell('ticket') or '').strip()
|
||||||
|
if not name:
|
||||||
|
continue
|
||||||
|
hit = tickets.get(code)
|
||||||
|
info = shops.get(name) or {}
|
||||||
|
shop = (hit or {}).get('shop') or info.get('shop') or ''
|
||||||
|
if not shop:
|
||||||
|
unmapped_cnt += 1
|
||||||
|
unmatched.append([code, name, str(cell('time') or '')[:19],
|
||||||
|
round(_to_float(cell('gross')), 2), 'CRM 与映射表均未命中'])
|
||||||
|
continue
|
||||||
|
mapped_cnt += 1
|
||||||
|
|
||||||
|
# 命中结果回写映射表(票数累计,冲突交给备注列提示)
|
||||||
|
votes = info.get('votes') or {}
|
||||||
|
if hit:
|
||||||
|
votes[shop] = int(votes.get(shop, 0)) + 1
|
||||||
|
entry = shops.setdefault(name, {})
|
||||||
|
entry['votes'] = votes
|
||||||
|
entry['shop'] = max(votes, key=votes.get) if votes else shop
|
||||||
|
entry['shop_id'] = (hit or {}).get('shop_id') or info.get('shop_id', '')
|
||||||
|
entry['brand'] = (hit or {}).get('brand') or info.get('brand', '')
|
||||||
|
entry['updated'] = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||||
|
|
||||||
|
item = summary[shop]
|
||||||
|
item['brand'] = entry['brand'] or item['brand']
|
||||||
|
item['count'] += 1
|
||||||
|
item['gross'] += _to_float(cell('gross'))
|
||||||
|
item['net'] += _to_float(cell('net'))
|
||||||
|
item['fee'] += _to_float(cell('fee'))
|
||||||
|
item['marketing'] += _to_float(cell('marketing'))
|
||||||
|
item['channel'] += _to_float(cell('channel'))
|
||||||
|
|
||||||
|
conflicts = [f'{k} → {v["shop"]}' for k, v in shops.items()
|
||||||
|
if len(v.get('votes') or {}) > 1]
|
||||||
|
|
||||||
|
out_from, out_to = min(days).isoformat(), max(days).isoformat()
|
||||||
|
out_name = f'{config.STORE_OUT_PREFIX}_{out_from.replace("-", "")}_{out_to.replace("-", "")}.xlsx'
|
||||||
|
out_path = os.path.join(config.OUT_DIR, out_name)
|
||||||
|
|
||||||
|
if dry_run:
|
||||||
|
message = (f'[演练] 门店归属 {mapped_cnt}/{mapped_cnt + unmapped_cnt} 行,'
|
||||||
|
f'覆盖 {len(summary)} 家内部门店,未匹配 {unmapped_cnt} 行;不写文件')
|
||||||
|
config.log(message)
|
||||||
|
return {'ok': True, 'path': '', 'mapped': mapped_cnt, 'unmapped': unmapped_cnt,
|
||||||
|
'stores': len(summary), 'conflicts': conflicts, 'message': message}
|
||||||
|
|
||||||
|
config.ensure_dirs()
|
||||||
|
_write_output(out_path, shops, summary, unmatched)
|
||||||
|
saved_map = _save_map(store)
|
||||||
|
message = (f'门店归属完成:{mapped_cnt}/{mapped_cnt + unmapped_cnt} 行已归属,'
|
||||||
|
f'{len(summary)} 家内部门店;未匹配 {unmapped_cnt} 行;'
|
||||||
|
f'结果 {os.path.basename(out_path)},映射表 {os.path.basename(saved_map)}')
|
||||||
|
if conflicts:
|
||||||
|
message += f';{len(conflicts)} 家门店存在跨店核销(见备注列)'
|
||||||
|
config.log(message)
|
||||||
|
return {'ok': True, 'path': out_path, 'mapped': mapped_cnt, 'unmapped': unmapped_cnt,
|
||||||
|
'stores': len(summary), 'conflicts': conflicts, 'message': message}
|
||||||
@@ -2,8 +2,8 @@
|
|||||||
"schema_version": 1,
|
"schema_version": 1,
|
||||||
"id": "xq0085",
|
"id": "xq0085",
|
||||||
"name": "团购数据核对",
|
"name": "团购数据核对",
|
||||||
"version": "1.0.0",
|
"version": "1.1.0",
|
||||||
"description": "团购数据核对(美团+抖音两条独立分支,共享盘只读):先把当天核对表从共享盘只读复制到本地 _work,后续全部在本地副本上处理。美团核对:团购+预订收益明细合并贴入订单收入明细表、明细/透视/报表三口径合计校验、报表 #N/A 基础信息补维护、报表 I~P 按值贴入马敏总表平台-新美大与 CRM 团购统计。抖音核对:导出核销明细 A~BR 重贴核销明细、明细/透视/报表/转换四口径预计收入合计校验、报表 O/P 基础信息补维护、报表 N~Z 按值贴入平台-抖音。",
|
"description": "团购数据核对(美团 + 抖音两条独立分支;通联扫码统计表已拆到 XQ0082)。两条分支都先把当天的核对表从共享盘复制到本地「过程表」,后续全部在本地副本上处理。美团核对:团购+预订收益明细合并贴入订单收入明细表、明细/透视/报表三口径合计校验、报表 #N/A 基础信息补维护、门店归属(CRM 券号 join,输出门店核对表)、报表 I~P 按值贴入马敏总表平台-新美大与 CRM 团购统计。抖音核对:导出核销明细 A~BR 重贴核销明细、明细/透视/报表/转换四口径预计收入合计校验、报表 O/P 基础信息补维护、报表 N~Z 按值贴入平台-抖音。两条分支最后都做对比表核对:滚动昨日遗留、按团购统计未消费回填今日遗留、退款/撤销核销冲减、按门店+项目分组校验验证列(二选一/四选一合并)、双人餐/三人餐按倍数补平台结错。",
|
||||||
"category": "财务",
|
"category": "财务",
|
||||||
"icon": "",
|
"icon": "",
|
||||||
"platform": "",
|
"platform": "",
|
||||||
@@ -12,7 +12,13 @@
|
|||||||
"capabilities": [
|
"capabilities": [
|
||||||
"xq0085"
|
"xq0085"
|
||||||
],
|
],
|
||||||
"requires": {},
|
"requires": {
|
||||||
|
"sdks": {
|
||||||
|
"crm_sdk": {
|
||||||
|
"compat": "^0.3"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
},
|
||||||
"permissions": {
|
"permissions": {
|
||||||
"platforms": []
|
"platforms": []
|
||||||
},
|
},
|
||||||
@@ -37,9 +43,9 @@
|
|||||||
},
|
},
|
||||||
"save_dir": {
|
"save_dir": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
"title": "本地工作目录",
|
"title": "本地工作根目录",
|
||||||
"default": "",
|
"default": "",
|
||||||
"description": "留空= D:\\资料\\财务\\新美大平台核对"
|
"description": "留空= D:\\资料\\财务\\团购数据核对,其下固定四个子目录:美团\\(美团导出与产物)、抖音\\(抖音导出与产物)、通联\\(扫码统计工作簿与各类导出)、过程表\\(共享盘复制来的核对表与马敏总表,美团/抖音共用一份)。填了则按填的根目录建同样四个子目录"
|
||||||
},
|
},
|
||||||
"share_root": {
|
"share_root": {
|
||||||
"type": "string",
|
"type": "string",
|
||||||
@@ -51,7 +57,7 @@
|
|||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"title": "从共享盘复制当天的表到本地(只读)",
|
"title": "从共享盘复制当天的表到本地(只读)",
|
||||||
"default": true,
|
"default": true,
|
||||||
"description": "把昨天的美团/抖音核对表与马敏团购总表复制成本地当天的日期副本;共享盘全程只读、绝不写入;本地副本已存在则跳过"
|
"description": "把昨天的美团/抖音核对表与马敏团购总表复制成本地「过程表」里当天的日期副本;共享盘全程只读、绝不写入;本地副本已存在则跳过"
|
||||||
},
|
},
|
||||||
"run_daily_detail": {
|
"run_daily_detail": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
@@ -63,12 +69,30 @@
|
|||||||
"title": "美团-基础信息补维护(报表 #N/A)",
|
"title": "美团-基础信息补维护(报表 #N/A)",
|
||||||
"default": true
|
"default": true
|
||||||
},
|
},
|
||||||
|
"run_store_map": {
|
||||||
|
"type": "boolean",
|
||||||
|
"title": "美团-门店归属(CRM 券号)",
|
||||||
|
"default": true,
|
||||||
|
"description": "用 CRM 团购核销的券号把美团「消费门店」翻译成内部门店 + 品牌,输出「门店核对_起_止.xlsx」(门店映射 / 门店汇总 / 未匹配)与累积映射表;不改动任何表。需要执行机已挂载 crm_sdk,未挂载/CRM 未登录时只告警跳过"
|
||||||
|
},
|
||||||
"run_paste_master": {
|
"run_paste_master": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"title": "按值贴入马敏总表(只写本地副本)",
|
"title": "按值贴入马敏总表(只写本地副本)",
|
||||||
"default": true,
|
"default": true,
|
||||||
"description": "美团分支贴平台-新美大+CRM团购统计;抖音分支贴平台-抖音;只写本地 _work 副本"
|
"description": "美团分支贴平台-新美大+CRM团购统计;抖音分支贴平台-抖音;只写本地 _work 副本"
|
||||||
},
|
},
|
||||||
|
"run_compare": {
|
||||||
|
"type": "boolean",
|
||||||
|
"title": "核对-对比表滚动+今日遗留回填",
|
||||||
|
"default": true,
|
||||||
|
"description": "马敏总表副本里「新美大对比 (2)」/「抖音对比(2)」:清空 I/J/K 与漏核销列,今日遗留滚到昨日遗留,按【团购统计】「未消费项目个数」回填今日遗留,再从美团【订单收入明细表】/ 抖音【核销明细】统计退款与撤销核销(按基础信息映射门店项目)扣减,最后按 E 门店 + F 项目分组校验 W 验证列(二选一/四选一合并看,组内求和为 0 才算平);双人餐/三人餐仍不平时按差额倍数 N 在【平台结错】写 N 与 -2N/-3N;不平只出明细"
|
||||||
|
},
|
||||||
|
"compare_force": {
|
||||||
|
"type": "boolean",
|
||||||
|
"title": "核对-强制重跑",
|
||||||
|
"default": false,
|
||||||
|
"description": "关闭时若今日遗留已等于按团购统计算出的回填值,判定今天已填过/滚过并跳过;开启则强制重跑一遍"
|
||||||
|
},
|
||||||
"run_douyin_daily": {
|
"run_douyin_daily": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"title": "抖音-核销明细重贴+四口径合计",
|
"title": "抖音-核销明细重贴+四口径合计",
|
||||||
|
|||||||
@@ -0,0 +1,12 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>团购数据核对</title>
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
<script type="module" src="/src/main.js"></script>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
+1579
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
|||||||
|
{
|
||||||
|
"name": "xq0085-ui",
|
||||||
|
"private": true,
|
||||||
|
"version": "1.0.0",
|
||||||
|
"type": "module",
|
||||||
|
"scripts": {
|
||||||
|
"dev": "vite",
|
||||||
|
"build": "vite build"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@element-plus/icons-vue": "^2.3.2",
|
||||||
|
"element-plus": "^2.14.5",
|
||||||
|
"vue": "^3.5.13"
|
||||||
|
},
|
||||||
|
"devDependencies": {
|
||||||
|
"@vitejs/plugin-vue": "^5.2.1",
|
||||||
|
"vite": "^6.0.3"
|
||||||
|
},
|
||||||
|
"allowScripts": {
|
||||||
|
"esbuild@0.25.12": true
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,368 @@
|
|||||||
|
<template>
|
||||||
|
<div class="page">
|
||||||
|
<!-- 方案工具条:方案供「定时任务」按 config_id 引用,到点自动取方案最新参数 -->
|
||||||
|
<div class="toolbar">
|
||||||
|
<span class="spacer" />
|
||||||
|
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
|
||||||
|
<i />{{ lastSavedAt ? '已保存 ' + lastSavedAt : '尚未保存' }}
|
||||||
|
</span>
|
||||||
|
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||||
|
placeholder="当前配置(自动保存)" @change="onSchemeChange">
|
||||||
|
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||||
|
</el-select>
|
||||||
|
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||||
|
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||||
|
@click="removeScheme">删除</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 内联提示 -->
|
||||||
|
<div v-if="notice" class="notice" :class="'is-' + notice.type">
|
||||||
|
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '!') }}</span>
|
||||||
|
<span>{{ notice.text }}</span>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 01 核对分支 -->
|
||||||
|
<section class="sec">
|
||||||
|
<div class="sec-head">
|
||||||
|
<span class="sec-badge">01</span>
|
||||||
|
<span class="sec-name">核对分支</span>
|
||||||
|
<span class="sec-line" />
|
||||||
|
<span class="sec-tag">{{ actionLabel }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="sec-body">
|
||||||
|
<el-form label-position="top">
|
||||||
|
<el-radio-group v-model="form.action" class="mode-group" :disabled="running">
|
||||||
|
<el-radio value="check_meituan" border class="mode-card">
|
||||||
|
<span class="m-title">美团核对</span>
|
||||||
|
<span class="m-desc">明细合并 → 基础信息 → 门店归属 → 贴总表 → 新美大对比</span>
|
||||||
|
</el-radio>
|
||||||
|
<el-radio value="check_douyin" border class="mode-card">
|
||||||
|
<span class="m-title">抖音核对</span>
|
||||||
|
<span class="m-desc">核销明细重贴 → 四口径 → 基础信息 → 贴总表 → 抖音对比</span>
|
||||||
|
</el-radio>
|
||||||
|
</el-radio-group>
|
||||||
|
<div class="tip">
|
||||||
|
两条分支相互独立:都会先从共享盘只读复制当天的表到本地「过程表」,后续只改本地副本,共享盘不写入。
|
||||||
|
通联扫码统计表已拆到独立插件「通联数据核对(XQ0082)」。
|
||||||
|
</div>
|
||||||
|
</el-form>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 02 营业日与目录 -->
|
||||||
|
<section class="sec">
|
||||||
|
<div class="sec-head">
|
||||||
|
<span class="sec-badge">02</span>
|
||||||
|
<span class="sec-name">营业日与目录</span>
|
||||||
|
<span class="sec-line" />
|
||||||
|
</div>
|
||||||
|
<div class="sec-body">
|
||||||
|
<el-form label-position="top">
|
||||||
|
<div class="grid">
|
||||||
|
<el-form-item label="核对营业日">
|
||||||
|
<el-date-picker v-model="form.daily_day" type="date" value-format="YYYY-MM-DD"
|
||||||
|
placeholder="留空 = 今天" :disabled="running" clearable style="width: 100%" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="本地工作根目录">
|
||||||
|
<div class="dir-ctrl">
|
||||||
|
<el-input v-model="form.save_dir" class="dir-input" :disabled="running" clearable
|
||||||
|
placeholder="留空 = D:\资料\财务\团购数据核对" />
|
||||||
|
<el-button class="dir-btn" :disabled="running" :loading="pickingDir === 'save_dir'"
|
||||||
|
@click="pickDir('save_dir')">选择</el-button>
|
||||||
|
</div>
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="grid">
|
||||||
|
<el-form-item label="共享核对表根目录(只读)">
|
||||||
|
<div class="dir-ctrl">
|
||||||
|
<el-input v-model="form.share_root" class="dir-input" :disabled="running" clearable
|
||||||
|
placeholder="留空 = \\caiwu01\共享文件夹\1111\TG" />
|
||||||
|
<el-button class="dir-btn" :disabled="running" :loading="pickingDir === 'share_root'"
|
||||||
|
@click="pickDir('share_root')">选择</el-button>
|
||||||
|
</div>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="从共享盘复制当天的表(只读)">
|
||||||
|
<el-switch v-model="form.copy_share_table" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="tip">
|
||||||
|
根目录下固定三个子目录:<b>美团</b> / <b>抖音</b> / <b>过程表</b>。
|
||||||
|
共享盘只做读取,本地副本已存在时会跳过复制。
|
||||||
|
</div>
|
||||||
|
</el-form>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 03 执行步骤 -->
|
||||||
|
<section class="sec">
|
||||||
|
<div class="sec-head">
|
||||||
|
<span class="sec-badge">03</span>
|
||||||
|
<span class="sec-name">本次执行的步骤</span>
|
||||||
|
<span class="sec-line" />
|
||||||
|
<span class="sec-tag">{{ stepSummary }}</span>
|
||||||
|
</div>
|
||||||
|
<div class="sec-body">
|
||||||
|
<el-form label-position="top">
|
||||||
|
<div v-if="form.action === 'check_meituan'" class="switch-row">
|
||||||
|
<el-form-item label="订单收入明细(合并+合计)">
|
||||||
|
<el-switch v-model="form.run_daily_detail" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="基础信息补维护">
|
||||||
|
<el-switch v-model="form.run_base_info" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="门店归属(CRM 券号)">
|
||||||
|
<el-switch v-model="form.run_store_map" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="按值贴入马敏总表">
|
||||||
|
<el-switch v-model="form.run_paste_master" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div v-else-if="form.action === 'check_douyin'" class="switch-row">
|
||||||
|
<el-form-item label="核销明细重贴 + 四口径">
|
||||||
|
<el-switch v-model="form.run_douyin_daily" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="基础信息补维护(O/P)">
|
||||||
|
<el-switch v-model="form.run_douyin_base" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="按值贴入马敏总表">
|
||||||
|
<el-switch v-model="form.run_paste_master" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<div class="tip">
|
||||||
|
<template v-if="form.action === 'check_meituan'">
|
||||||
|
门店归属需要执行机已挂载 <b>crm_sdk</b>;未挂载或 CRM 未登录时只告警跳过,不影响其它步骤。
|
||||||
|
</template>
|
||||||
|
<template v-else>
|
||||||
|
抖音分支会同时贴【团购统计】,对比表的回填与 C/D 公式都依赖它。
|
||||||
|
</template>
|
||||||
|
</div>
|
||||||
|
</el-form>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 04 对比表核对 -->
|
||||||
|
<section class="sec">
|
||||||
|
<div class="sec-head">
|
||||||
|
<span class="sec-badge">04</span>
|
||||||
|
<span class="sec-name">对比表核对</span>
|
||||||
|
<span class="sec-line" />
|
||||||
|
</div>
|
||||||
|
<div class="sec-body">
|
||||||
|
<el-form label-position="top">
|
||||||
|
<div class="switch-row">
|
||||||
|
<el-form-item label="滚动 + 回填 + 分组验证">
|
||||||
|
<el-switch v-model="form.run_compare" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="强制重跑(忽略判重)">
|
||||||
|
<el-switch v-model="form.compare_force" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="tip">
|
||||||
|
清 I/J/K 与漏核销 → 今日遗留滚到昨日遗留 → 按【团购统计】未消费回填 → 退款/撤销核销冲减
|
||||||
|
→ 按 E 门店 + F 项目分组校验 W(二选一/四选一合并)→ 双人餐/三人餐仍不平时按 N 倍补【平台结错】。
|
||||||
|
不平只出明细,不会让整次执行失败。
|
||||||
|
</div>
|
||||||
|
</el-form>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 05 运行选项 -->
|
||||||
|
<section class="sec">
|
||||||
|
<div class="sec-head">
|
||||||
|
<span class="sec-badge">05</span>
|
||||||
|
<span class="sec-name">运行选项</span>
|
||||||
|
<span class="sec-line" />
|
||||||
|
</div>
|
||||||
|
<div class="sec-body">
|
||||||
|
<el-form label-position="top">
|
||||||
|
<div class="switch-row">
|
||||||
|
<el-form-item label="用 COM 刷新透视/公式">
|
||||||
|
<el-switch v-model="form.use_com_refresh" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="只核对不写入">
|
||||||
|
<el-switch v-model="form.dry_run" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="调试日志">
|
||||||
|
<el-switch v-model="form.debug_mode" :disabled="running" />
|
||||||
|
</el-form-item>
|
||||||
|
</div>
|
||||||
|
<div class="tip">
|
||||||
|
关闭 COM 后透视不会真正刷新,三口径/四口径与 W 验证读的都是旧缓存,只适合排查文件问题。
|
||||||
|
</div>
|
||||||
|
</el-form>
|
||||||
|
</div>
|
||||||
|
</section>
|
||||||
|
|
||||||
|
<!-- 操作 -->
|
||||||
|
<div class="actions">
|
||||||
|
<el-button type="primary" class="btn-run" :loading="running" @click="start">
|
||||||
|
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||||
|
</el-button>
|
||||||
|
<el-button :disabled="running" @click="preflight">预检(只读演练)</el-button>
|
||||||
|
<el-button v-if="running" type="danger" plain :loading="stopping" @click="forceStop">
|
||||||
|
强制停止
|
||||||
|
</el-button>
|
||||||
|
<span class="spacer" />
|
||||||
|
<el-button :disabled="running" @click="restoreLastFields">恢复上次参数</el-button>
|
||||||
|
<el-button :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||||
|
<el-button text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||||
|
</div>
|
||||||
|
|
||||||
|
<!-- 运行态 -->
|
||||||
|
<div v-if="running" class="runline">
|
||||||
|
<span class="pulse" />
|
||||||
|
<span>正在执行,日志与进度实时显示在工作台下方「运行日志」区</span>
|
||||||
|
<span class="pct">{{ progress }}%</span>
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
|
</template>
|
||||||
|
|
||||||
|
<script setup>
|
||||||
|
import { computed, ref } from 'vue'
|
||||||
|
import { ElMessage } from 'element-plus'
|
||||||
|
import { usePluginUI } from './usePluginUI'
|
||||||
|
|
||||||
|
const DEFAULTS = () => ({
|
||||||
|
action: 'check_meituan',
|
||||||
|
daily_day: '',
|
||||||
|
save_dir: '',
|
||||||
|
share_root: '',
|
||||||
|
copy_share_table: true,
|
||||||
|
run_daily_detail: true,
|
||||||
|
run_base_info: true,
|
||||||
|
run_store_map: true,
|
||||||
|
run_paste_master: true,
|
||||||
|
run_compare: true,
|
||||||
|
compare_force: false,
|
||||||
|
run_douyin_daily: true,
|
||||||
|
run_douyin_base: true,
|
||||||
|
use_com_refresh: true,
|
||||||
|
dry_run: false,
|
||||||
|
debug_mode: false,
|
||||||
|
})
|
||||||
|
|
||||||
|
const preview = ref(false) // 「预检」时临时把 dry_run 打开
|
||||||
|
|
||||||
|
const {
|
||||||
|
form, notice, lastSavedAt, running, progress, stopping,
|
||||||
|
saveNow, resetDefaults, restoreLastFields,
|
||||||
|
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||||
|
run, forceStop,
|
||||||
|
} = usePluginUI({
|
||||||
|
defaults: DEFAULTS,
|
||||||
|
validate() {
|
||||||
|
const a = form.action
|
||||||
|
if (a === 'check_meituan'
|
||||||
|
&& !(form.run_daily_detail || form.run_base_info || form.run_store_map
|
||||||
|
|| form.run_paste_master || form.run_compare)) {
|
||||||
|
ElMessage.warning('美团核对至少要勾选一个步骤')
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
if (a === 'check_douyin'
|
||||||
|
&& !(form.run_douyin_daily || form.run_douyin_base
|
||||||
|
|| form.run_paste_master || form.run_compare)) {
|
||||||
|
ElMessage.warning('抖音核对至少要勾选一个步骤')
|
||||||
|
return false
|
||||||
|
}
|
||||||
|
return true
|
||||||
|
},
|
||||||
|
buildPayload(f) {
|
||||||
|
const t = (v) => (v || '').trim()
|
||||||
|
return {
|
||||||
|
action: f.action,
|
||||||
|
daily_day: t(f.daily_day),
|
||||||
|
save_dir: t(f.save_dir),
|
||||||
|
share_root: t(f.share_root),
|
||||||
|
copy_share_table: !!f.copy_share_table,
|
||||||
|
run_daily_detail: !!f.run_daily_detail,
|
||||||
|
run_base_info: !!f.run_base_info,
|
||||||
|
run_store_map: !!f.run_store_map,
|
||||||
|
run_paste_master: !!f.run_paste_master,
|
||||||
|
run_compare: !!f.run_compare,
|
||||||
|
compare_force: !!f.compare_force,
|
||||||
|
run_douyin_daily: !!f.run_douyin_daily,
|
||||||
|
run_douyin_base: !!f.run_douyin_base,
|
||||||
|
use_com_refresh: !!f.use_com_refresh,
|
||||||
|
dry_run: !!(f.dry_run || preview.value),
|
||||||
|
debug_mode: !!f.debug_mode,
|
||||||
|
}
|
||||||
|
},
|
||||||
|
})
|
||||||
|
|
||||||
|
const ACTION_LABEL = {
|
||||||
|
check_meituan: '美团核对',
|
||||||
|
check_douyin: '抖音核对',
|
||||||
|
}
|
||||||
|
const actionLabel = computed(() => ACTION_LABEL[form.action] || '美团核对')
|
||||||
|
|
||||||
|
const stepSummary = computed(() => {
|
||||||
|
if (form.action === 'check_douyin') {
|
||||||
|
const n = [form.run_douyin_daily, form.run_douyin_base, form.run_paste_master,
|
||||||
|
form.run_compare].filter(Boolean).length
|
||||||
|
return `已选 ${n} 步`
|
||||||
|
}
|
||||||
|
const n = [form.run_daily_detail, form.run_base_info, form.run_store_map,
|
||||||
|
form.run_paste_master, form.run_compare].filter(Boolean).length
|
||||||
|
return `已选 ${n} 步`
|
||||||
|
})
|
||||||
|
|
||||||
|
function start() {
|
||||||
|
run()
|
||||||
|
}
|
||||||
|
|
||||||
|
// 预检:以 dry_run 跑一遍(预检 + 读取明细/对比表,全程不写文件)
|
||||||
|
async function preflight() {
|
||||||
|
if (running.value) return
|
||||||
|
preview.value = true
|
||||||
|
try {
|
||||||
|
await run()
|
||||||
|
} finally {
|
||||||
|
preview.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// 调用壳子本机接口打开原生「选择文件夹」对话框(仅返回路径)
|
||||||
|
const pickingDir = ref('')
|
||||||
|
async function pickDir(field) {
|
||||||
|
pickingDir.value = field
|
||||||
|
try {
|
||||||
|
const r = await fetch('/api/dialog/directory', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ title: '选择目录', current: form[field] || '' }),
|
||||||
|
})
|
||||||
|
const d = await r.json().catch(() => ({}))
|
||||||
|
if (!r.ok) throw new Error(d.detail || d.error || ('HTTP ' + r.status))
|
||||||
|
if (d.path) form[field] = d.path
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.warning('打开文件夹选择失败:' + e.message)
|
||||||
|
} finally {
|
||||||
|
pickingDir.value = ''
|
||||||
|
}
|
||||||
|
}
|
||||||
|
</script>
|
||||||
|
|
||||||
|
<style scoped>
|
||||||
|
/* 插件差异样式:只用壳子 token,不写字面色值;左右内边距由壳子提供 */
|
||||||
|
.mode-group { display: grid; grid-template-columns: repeat(2, 1fr); gap: var(--space-3); width: 100%; }
|
||||||
|
.mode-group :deep(.el-radio) {
|
||||||
|
height: auto;
|
||||||
|
width: 100%;
|
||||||
|
margin: 0;
|
||||||
|
padding: 10px 14px;
|
||||||
|
align-items: flex-start;
|
||||||
|
white-space: normal; /* element-plus 默认 nowrap,会把卡片撑出容器 */
|
||||||
|
}
|
||||||
|
.mode-group :deep(.el-radio__input) { margin-top: 2px; }
|
||||||
|
.mode-group :deep(.el-radio__label) { display: block; line-height: 1.5; white-space: normal; }
|
||||||
|
.m-title { display: block; font-weight: 600; }
|
||||||
|
.m-desc { display: block; font-size: 12px; opacity: 0.65; }
|
||||||
|
.dir-ctrl { display: flex; align-items: center; gap: var(--space-2); width: 100%; }
|
||||||
|
.dir-ctrl .dir-input { flex: 1 1 auto; min-width: 0; }
|
||||||
|
.dir-ctrl .dir-btn { flex: 0 0 auto; }
|
||||||
|
.switch-row { display: flex; flex-wrap: wrap; gap: 0 var(--space-5); }
|
||||||
|
.switch-row :deep(.el-form-item) { margin-bottom: 12px; min-width: 150px; }
|
||||||
|
.sec-tag { flex: 0 0 auto; font-size: 12px; opacity: 0.6; white-space: nowrap; }
|
||||||
|
</style>
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
export const PLUGIN_ID = 'xq0085'
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
import { createApp } from 'vue'
|
||||||
|
import ElementPlus from 'element-plus'
|
||||||
|
import 'element-plus/dist/index.css'
|
||||||
|
// 注意顺序:style.css 必须在 element-plus 之后引入,才能覆盖 --el-* 变量映射到壳子 token
|
||||||
|
import './style.css'
|
||||||
|
import App from './App.vue'
|
||||||
|
|
||||||
|
createApp(App).use(ElementPlus).mount('#app')
|
||||||
@@ -0,0 +1,431 @@
|
|||||||
|
/* ============================================================
|
||||||
|
插件 UI 基础样式(规范 v3 · 对齐壳子「白底面板 + 描边卡」)
|
||||||
|
- token 与壳子 frontend/src/style.css 同源(权威源 design-app/styles.css)
|
||||||
|
- Element Plus 变量映射到壳子 token
|
||||||
|
- 版式类:page / toolbar / notice / sec / grid / tip / actions / badge / table
|
||||||
|
规则:插件内只用 var(--xxx),不写字面色值;左右内边距由壳子提供,不要重复加
|
||||||
|
============================================================ */
|
||||||
|
|
||||||
|
:root {
|
||||||
|
/* 底色与卡面 */
|
||||||
|
--canvas: #F2F4F8;
|
||||||
|
--surface: #FFFFFF;
|
||||||
|
--field: #F5F6FA;
|
||||||
|
--subtle: #F7F8FC;
|
||||||
|
|
||||||
|
/* 描边 */
|
||||||
|
--line: #E8EAF1;
|
||||||
|
--line-soft: #F0F2F7;
|
||||||
|
--line-btn: #E3E6EF;
|
||||||
|
|
||||||
|
/* 文字五阶 */
|
||||||
|
--t1: #12141B;
|
||||||
|
--t2: #3C4250;
|
||||||
|
--t3: #6E7686;
|
||||||
|
--t4: #A3AAB8;
|
||||||
|
--t5: #C6CBD6;
|
||||||
|
|
||||||
|
/* 主色(靛蓝) */
|
||||||
|
--brand: #4F5AE8;
|
||||||
|
--brand-ink: #3D47D4;
|
||||||
|
--brand-soft: #EEF0FE;
|
||||||
|
--brand-track: #DDE1F8;
|
||||||
|
--brand-hover: #4550E0;
|
||||||
|
|
||||||
|
/* 语义色 */
|
||||||
|
--good: #0E9F76; --good-ink: #0B8A66; --good-soft: #EBF7F2; --good-line: #D3EDE3;
|
||||||
|
--warn: #D98218; --warn-ink: #B4700F; --warn-soft: #FDF3E4; --warn-line: rgba(217, 130, 24, .28);
|
||||||
|
--danger: #E5484D; --danger-ink: #CC3B40; --danger-soft: #FDEDED; --danger-line: #F6D7D8;
|
||||||
|
|
||||||
|
/* 圆角 */
|
||||||
|
--r-row: 8px;
|
||||||
|
--r-field: 9px;
|
||||||
|
--r-btn: 10px;
|
||||||
|
--r-sub: 12px;
|
||||||
|
--r-card: 14px;
|
||||||
|
--r-pill: 999px;
|
||||||
|
|
||||||
|
/* 阴影(插件内基本不用,保持与壳子同值) */
|
||||||
|
--sh-card: 0 2px 8px rgba(18, 20, 31, .05);
|
||||||
|
--sh-float: 0 8px 24px rgba(18, 20, 31, .10);
|
||||||
|
--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);
|
||||||
|
--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);
|
||||||
|
|
||||||
|
/* 字体 */
|
||||||
|
--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;
|
||||||
|
--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||||
|
--f-mono: "JetBrains Mono", "SFMono-Regular", Consolas, "Liberation Mono", Menlo, monospace;
|
||||||
|
|
||||||
|
/* 间距 */
|
||||||
|
--space-1: 4px;
|
||||||
|
--space-1-5: 6px;
|
||||||
|
--space-2: 8px;
|
||||||
|
--space-2-5: 10px;
|
||||||
|
--space-3: 12px;
|
||||||
|
--space-4: 16px;
|
||||||
|
--space-5: 20px;
|
||||||
|
--space-6: 28px;
|
||||||
|
|
||||||
|
--dur: .15s;
|
||||||
|
--ease: cubic-bezier(.22, 1, .36, 1);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- Element Plus → 壳子 token ---------- */
|
||||||
|
:root {
|
||||||
|
--el-color-primary: var(--brand);
|
||||||
|
--el-color-primary-light-3: #7A83EE;
|
||||||
|
--el-color-primary-light-5: #A6ACF4;
|
||||||
|
--el-color-primary-light-7: #C9CDF9;
|
||||||
|
--el-color-primary-light-8: #DDE0FB;
|
||||||
|
--el-color-primary-light-9: var(--brand-soft);
|
||||||
|
--el-color-primary-dark-2: var(--brand-ink);
|
||||||
|
|
||||||
|
--el-color-success: var(--good);
|
||||||
|
--el-color-success-light-9: var(--good-soft);
|
||||||
|
--el-color-warning: var(--warn);
|
||||||
|
--el-color-warning-light-9: var(--warn-soft);
|
||||||
|
--el-color-danger: var(--danger);
|
||||||
|
--el-color-danger-light-9: var(--danger-soft);
|
||||||
|
--el-color-error: var(--danger);
|
||||||
|
|
||||||
|
--el-text-color-primary: var(--t1);
|
||||||
|
--el-text-color-regular: var(--t2);
|
||||||
|
--el-text-color-secondary: var(--t3);
|
||||||
|
--el-text-color-placeholder: var(--t4);
|
||||||
|
|
||||||
|
--el-border-color: var(--line);
|
||||||
|
--el-border-color-light: var(--line);
|
||||||
|
--el-border-color-lighter: var(--line-soft);
|
||||||
|
--el-border-color-extra-light: var(--line-soft);
|
||||||
|
--el-fill-color-blank: var(--surface);
|
||||||
|
--el-fill-color-light: var(--field);
|
||||||
|
--el-bg-color: var(--surface);
|
||||||
|
|
||||||
|
--el-border-radius-base: var(--r-field);
|
||||||
|
--el-border-radius-small: var(--r-field);
|
||||||
|
--el-font-family: var(--f-cn);
|
||||||
|
--el-font-size-base: 12.5px;
|
||||||
|
--el-box-shadow-light: var(--sh-card);
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 基础重置 ---------- */
|
||||||
|
* { box-sizing: border-box; }
|
||||||
|
|
||||||
|
html, body {
|
||||||
|
margin: 0;
|
||||||
|
padding: 0;
|
||||||
|
background: var(--surface);
|
||||||
|
color: var(--t1);
|
||||||
|
font-family: var(--f-cn);
|
||||||
|
font-size: 12.5px;
|
||||||
|
line-height: 1.5;
|
||||||
|
-webkit-font-smoothing: antialiased;
|
||||||
|
}
|
||||||
|
|
||||||
|
#app { padding: 0; }
|
||||||
|
|
||||||
|
/* ---------- 页面:只排垂直节奏(左右 24px 由壳子给) ---------- */
|
||||||
|
.page {
|
||||||
|
width: 100%;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: var(--space-4);
|
||||||
|
padding: 2px 0 20px;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 工具条:方案下拉 + 存为方案 + 删除 + 已保存胶囊 ---------- */
|
||||||
|
.toolbar {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
min-height: 32px;
|
||||||
|
}
|
||||||
|
.toolbar .spacer { flex: 1; }
|
||||||
|
.scheme-sel { width: 200px; }
|
||||||
|
|
||||||
|
.saved {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 6px;
|
||||||
|
height: 22px;
|
||||||
|
padding: 0 9px;
|
||||||
|
border-radius: var(--r-pill);
|
||||||
|
background: var(--good-soft);
|
||||||
|
border: 1px solid var(--good-line);
|
||||||
|
color: var(--good-ink);
|
||||||
|
font: 500 11px/1 var(--f-cn);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.saved i { width: 5px; height: 5px; border-radius: 50%; background: var(--good); }
|
||||||
|
.saved.is-idle { background: var(--field); border-color: var(--line); color: var(--t4); }
|
||||||
|
.saved.is-idle i { background: var(--t5); }
|
||||||
|
|
||||||
|
/* ---------- 提示条(替代顶部大横幅) ---------- */
|
||||||
|
.notice {
|
||||||
|
display: flex;
|
||||||
|
align-items: flex-start;
|
||||||
|
gap: var(--space-2);
|
||||||
|
padding: 9px 12px;
|
||||||
|
border-radius: var(--r-sub);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
background: var(--subtle);
|
||||||
|
font: 400 12px/18px var(--f-cn);
|
||||||
|
color: var(--t2);
|
||||||
|
}
|
||||||
|
.notice .n-ico { flex: 0 0 auto; font-weight: 700; }
|
||||||
|
.notice.is-warn { background: var(--warn-soft); border-color: var(--warn-line); color: var(--warn-ink); }
|
||||||
|
.notice.is-error { background: var(--danger-soft); border-color: var(--danger-line); color: var(--danger-ink); }
|
||||||
|
.notice.is-ok { background: var(--good-soft); border-color: var(--good-line); color: var(--good-ink); }
|
||||||
|
|
||||||
|
/* ---------- 分区卡:与壳子列表卡/表格卡同一套 ---------- */
|
||||||
|
.sec {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--r-sub);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.sec-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
padding: 10px 14px;
|
||||||
|
background: var(--subtle);
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.sec-badge {
|
||||||
|
width: 20px;
|
||||||
|
height: 20px;
|
||||||
|
border-radius: 6px;
|
||||||
|
display: inline-grid;
|
||||||
|
place-items: center;
|
||||||
|
font: 600 10.5px/1 var(--f-num);
|
||||||
|
color: var(--brand-ink);
|
||||||
|
background: var(--brand-soft);
|
||||||
|
flex-shrink: 0;
|
||||||
|
}
|
||||||
|
.sec-name { font: 600 13px/18px var(--f-cn); color: var(--t1); white-space: nowrap; }
|
||||||
|
.sec-line { flex: 1; height: 1px; background: var(--line-soft); }
|
||||||
|
.sec-body { padding: 14px 14px 6px; }
|
||||||
|
|
||||||
|
/* ---------- 栅格与表单 ---------- */
|
||||||
|
.grid {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(240px, 1fr));
|
||||||
|
gap: 0 16px;
|
||||||
|
}
|
||||||
|
.grid-switch { grid-template-columns: repeat(auto-fit, minmax(200px, 1fr)); }
|
||||||
|
/* 日期行紧跟在开关行后,补一点呼吸 */
|
||||||
|
.grid-date { margin-top: 4px; }
|
||||||
|
.grid .el-form-item { margin-bottom: 12px; }
|
||||||
|
.grid .el-form-item__label {
|
||||||
|
padding-bottom: 6px !important;
|
||||||
|
font-weight: 500;
|
||||||
|
color: var(--t2);
|
||||||
|
}
|
||||||
|
.grid .el-input,
|
||||||
|
.grid .el-select,
|
||||||
|
.grid .el-date-editor,
|
||||||
|
.grid .el-input-number { width: 100% !important; }
|
||||||
|
|
||||||
|
/* ---------- 说明文字 ---------- */
|
||||||
|
.tip {
|
||||||
|
margin-top: var(--space-2);
|
||||||
|
font: 400 11.5px/1.65 var(--f-cn);
|
||||||
|
color: var(--t3);
|
||||||
|
}
|
||||||
|
.tip b { color: var(--t2); font-weight: 600; }
|
||||||
|
|
||||||
|
/* ---------- 执行摘要(操作区上方一行低调说明) ---------- */
|
||||||
|
.plan { display: flex; align-items: baseline; gap: var(--space-2); font-size: 11.5px; line-height: 1.6; color: var(--t3); }
|
||||||
|
.plan .p-tag { flex: 0 0 auto; font-weight: 600; color: var(--brand-ink); }
|
||||||
|
.plan .p-text { min-width: 0; }
|
||||||
|
.plan.is-empty .p-text { color: var(--warn); }
|
||||||
|
|
||||||
|
/* ---------- 操作区 ---------- */
|
||||||
|
.actions {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: var(--space-2);
|
||||||
|
flex-wrap: wrap;
|
||||||
|
padding-top: 14px;
|
||||||
|
border-top: 1px solid var(--line-soft);
|
||||||
|
}
|
||||||
|
.actions .spacer { flex: 1; }
|
||||||
|
.btn-run {
|
||||||
|
min-width: 150px;
|
||||||
|
height: 34px;
|
||||||
|
border: none;
|
||||||
|
border-radius: var(--r-btn);
|
||||||
|
background: var(--brand);
|
||||||
|
color: #fff;
|
||||||
|
font: 600 12.5px/18px var(--f-cn);
|
||||||
|
letter-spacing: 1px;
|
||||||
|
box-shadow: var(--sh-brand);
|
||||||
|
transition: background var(--dur), box-shadow var(--dur), transform .06s;
|
||||||
|
}
|
||||||
|
.btn-run:hover { background: var(--brand-hover); }
|
||||||
|
.btn-run:active { transform: translateY(1px); box-shadow: var(--sh-brand-sm); }
|
||||||
|
.btn-run.is-loading { pointer-events: none; }
|
||||||
|
|
||||||
|
/* ---------- 状态胶囊(与壳子表格状态列同款) ---------- */
|
||||||
|
.badge {
|
||||||
|
display: inline-flex;
|
||||||
|
align-items: center;
|
||||||
|
gap: 5px;
|
||||||
|
height: 22px;
|
||||||
|
padding: 0 9px;
|
||||||
|
border: 1px solid transparent;
|
||||||
|
border-radius: 6px;
|
||||||
|
font: 500 11px/1 var(--f-cn);
|
||||||
|
white-space: nowrap;
|
||||||
|
}
|
||||||
|
.badge i { width: 5px; height: 5px; border-radius: 50%; flex-shrink: 0; }
|
||||||
|
.badge.ok { color: var(--good-ink); background: var(--good-soft); border-color: var(--good-line); }
|
||||||
|
.badge.ok i { background: var(--good); }
|
||||||
|
.badge.warn { color: var(--warn-ink); background: var(--warn-soft); border-color: var(--warn-line); }
|
||||||
|
.badge.warn i { background: var(--warn); }
|
||||||
|
.badge.bad { color: var(--danger-ink); background: var(--danger-soft); border-color: var(--danger-line); }
|
||||||
|
.badge.bad i { background: var(--danger); }
|
||||||
|
.badge.idle { color: var(--t3); background: var(--field); border-color: var(--line); }
|
||||||
|
.badge.idle i { background: var(--t5); }
|
||||||
|
|
||||||
|
/* ---------- 表格(插件内需要列表时用;与壳子表格同口径) ---------- */
|
||||||
|
.table-card {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--r-sub);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.table-head {
|
||||||
|
display: flex;
|
||||||
|
align-items: center;
|
||||||
|
justify-content: space-between;
|
||||||
|
gap: var(--space-3);
|
||||||
|
padding: 12px 16px;
|
||||||
|
background: var(--subtle);
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
font: 600 13.5px/20px var(--f-cn);
|
||||||
|
color: var(--t1);
|
||||||
|
}
|
||||||
|
.table { width: 100%; border-collapse: collapse; table-layout: fixed; }
|
||||||
|
.table th {
|
||||||
|
padding: 10px 16px;
|
||||||
|
text-align: center;
|
||||||
|
font: 500 11px/16px var(--f-cn);
|
||||||
|
color: var(--t3);
|
||||||
|
background: var(--surface);
|
||||||
|
border-bottom: 1px solid var(--line);
|
||||||
|
}
|
||||||
|
.table td {
|
||||||
|
padding: 10px 16px;
|
||||||
|
text-align: center;
|
||||||
|
border-bottom: 1px solid var(--line-soft);
|
||||||
|
font: 400 12px/18px var(--f-cn);
|
||||||
|
color: var(--t2);
|
||||||
|
}
|
||||||
|
.table tr:last-child td { border-bottom: 0; }
|
||||||
|
.table tbody tr { transition: background var(--dur); }
|
||||||
|
.table tbody tr:hover { background: var(--field); }
|
||||||
|
.table td.is-name { text-align: left; font-weight: 600; color: var(--t1); }
|
||||||
|
.table th.is-name { text-align: left; }
|
||||||
|
|
||||||
|
/* ---------- 运行态一行文字(进度由壳子 RunIndicator 展示) ---------- */
|
||||||
|
.runline { display: flex; align-items: center; gap: var(--space-2); font-size: 12px; color: var(--t3); }
|
||||||
|
.runline .pct { font: 600 12px/1 var(--f-num); color: var(--brand-ink); font-variant-numeric: tabular-nums; }
|
||||||
|
.pulse { width: 7px; height: 7px; border-radius: 50%; background: var(--brand); animation: pulse 1.4s ease-out infinite; }
|
||||||
|
@keyframes pulse {
|
||||||
|
0% { box-shadow: 0 0 0 0 var(--brand-soft); }
|
||||||
|
70% { box-shadow: 0 0 0 7px transparent; }
|
||||||
|
100% { box-shadow: 0 0 0 0 transparent; }
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ============================================================
|
||||||
|
v3.1 扩展:步骤卡 / 行式设置项 / 折叠说明
|
||||||
|
- 适用于「互斥步骤」「开关+联动下拉」「大段流程说明」
|
||||||
|
- 仍然只用 token,不写字面色值
|
||||||
|
============================================================ */
|
||||||
|
|
||||||
|
/* ---------- 步骤卡(互斥单选,≤4 项) ---------- */
|
||||||
|
.step-cards {
|
||||||
|
display: grid;
|
||||||
|
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
|
||||||
|
gap: var(--space-2-5);
|
||||||
|
}
|
||||||
|
.step-card {
|
||||||
|
position: relative;
|
||||||
|
display: flex;
|
||||||
|
flex-direction: column;
|
||||||
|
gap: 3px;
|
||||||
|
padding: 11px 32px 11px 13px;
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--r-sub);
|
||||||
|
cursor: pointer;
|
||||||
|
transition: border-color var(--dur), background var(--dur), box-shadow var(--dur);
|
||||||
|
}
|
||||||
|
.step-card:hover { border-color: var(--brand-track); background: var(--subtle); }
|
||||||
|
.step-card.on {
|
||||||
|
border-color: var(--brand);
|
||||||
|
background: var(--brand-soft);
|
||||||
|
box-shadow: inset 0 0 0 1px var(--brand-soft);
|
||||||
|
}
|
||||||
|
.step-card .sc-title { font: 600 13px/18px var(--f-cn); color: var(--t1); }
|
||||||
|
.step-card.on .sc-title { color: var(--brand-ink); }
|
||||||
|
.step-card .sc-desc { font: 400 11.5px/1.6 var(--f-cn); color: var(--t3); }
|
||||||
|
.step-card .sc-check {
|
||||||
|
position: absolute; top: 10px; right: 10px;
|
||||||
|
width: 16px; height: 16px; color: var(--brand);
|
||||||
|
}
|
||||||
|
.step-cards.is-disabled .step-card { opacity: .55; pointer-events: none; }
|
||||||
|
.sr-only {
|
||||||
|
position: absolute; width: 1px; height: 1px; padding: 0; margin: -1px;
|
||||||
|
overflow: hidden; clip: rect(0, 0, 0, 0); white-space: nowrap; border: 0;
|
||||||
|
}
|
||||||
|
|
||||||
|
/* ---------- 行式设置项(标题+说明在左,控件在右) ---------- */
|
||||||
|
.rows {
|
||||||
|
display: flex; flex-direction: column; gap: var(--space-2);
|
||||||
|
padding: var(--space-2);
|
||||||
|
background: var(--subtle);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--r-sub);
|
||||||
|
}
|
||||||
|
.row {
|
||||||
|
display: flex; align-items: center; justify-content: space-between;
|
||||||
|
gap: var(--space-4);
|
||||||
|
padding: 9px 12px;
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--line-soft);
|
||||||
|
border-radius: var(--r-field);
|
||||||
|
}
|
||||||
|
.row .r-main { min-width: 0; }
|
||||||
|
.row .r-title { font: 500 12.5px/18px var(--f-cn); color: var(--t1); }
|
||||||
|
.row .r-desc { margin-top: 1px; font: 400 11.5px/1.6 var(--f-cn); color: var(--t3); }
|
||||||
|
.row .r-ctrl { flex: 0 0 auto; }
|
||||||
|
.row.is-hidden { display: none; }
|
||||||
|
|
||||||
|
/* ---------- 折叠说明(流程说明气泡卡片) ---------- */
|
||||||
|
.help {
|
||||||
|
background: var(--surface);
|
||||||
|
border: 1px solid var(--line);
|
||||||
|
border-radius: var(--r-sub);
|
||||||
|
overflow: hidden;
|
||||||
|
}
|
||||||
|
.help > summary {
|
||||||
|
display: flex; align-items: center; justify-content: space-between;
|
||||||
|
gap: var(--space-2); padding: 10px 14px;
|
||||||
|
background: var(--subtle);
|
||||||
|
font: 600 12.5px/18px var(--f-cn); color: var(--t2);
|
||||||
|
cursor: pointer; list-style: none;
|
||||||
|
}
|
||||||
|
.help > summary::-webkit-details-marker { display: none; }
|
||||||
|
.help[open] > summary { border-bottom: 1px solid var(--line); }
|
||||||
|
.help .h-arrow { color: var(--t4); transition: transform var(--dur); font-size: 11px; }
|
||||||
|
.help[open] .h-arrow { transform: rotate(180deg); }
|
||||||
|
.help-body {
|
||||||
|
padding: 12px 14px;
|
||||||
|
font: 400 12px/1.8 var(--f-cn); color: var(--t3);
|
||||||
|
}
|
||||||
|
.help-body b { color: var(--t2); font-weight: 600; }
|
||||||
|
.help-body .hb-line + .hb-line { margin-top: 6px; }
|
||||||
@@ -0,0 +1,356 @@
|
|||||||
|
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
|
||||||
|
//
|
||||||
|
// 与 v1 的差异(适配当前壳子):
|
||||||
|
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
|
||||||
|
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
|
||||||
|
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
|
||||||
|
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
|
||||||
|
// 不能再当成普通失败提示。
|
||||||
|
//
|
||||||
|
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
|
||||||
|
// 执行状态机(执行/强停/WS 进度 + 轮询兜底/未登录重试)。
|
||||||
|
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||||
|
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||||
|
import { PLUGIN_ID } from './api'
|
||||||
|
|
||||||
|
async function j(url, opts) {
|
||||||
|
const res = await fetch(url, opts)
|
||||||
|
if (res.status === 401) {
|
||||||
|
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||||
|
}
|
||||||
|
if (!res.ok) {
|
||||||
|
let msg = `HTTP ${res.status}`
|
||||||
|
try {
|
||||||
|
msg = (await res.json()).detail || msg
|
||||||
|
} catch (_) { /* 保留默认 */ }
|
||||||
|
throw Object.assign(new Error(msg), { code: res.status, status: res.status })
|
||||||
|
}
|
||||||
|
return res.json()
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||||
|
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||||
|
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify(data),
|
||||||
|
})
|
||||||
|
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
|
||||||
|
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||||
|
const saveScheme = (name, fields) => j('/api/plugin-configs', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||||
|
})
|
||||||
|
const deleteScheme = (cfgId) =>
|
||||||
|
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||||
|
const startRun = (fields) => j('/api/runs', {
|
||||||
|
method: 'POST',
|
||||||
|
headers: { 'Content-Type': 'application/json' },
|
||||||
|
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||||
|
})
|
||||||
|
const getRun = (runId) => j(`/api/runs/${runId}`)
|
||||||
|
const stopRun = (runId) => j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||||
|
|
||||||
|
function connectWS(onEvent) {
|
||||||
|
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||||
|
+ location.host + '/ws')
|
||||||
|
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||||
|
return ws
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---- 工具 ----
|
||||||
|
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||||
|
|
||||||
|
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
|
||||||
|
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
|
||||||
|
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
|
||||||
|
function readSavedAt() {
|
||||||
|
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
|
||||||
|
}
|
||||||
|
function writeSavedAt(v) {
|
||||||
|
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
|
||||||
|
// (空数组可能是有意配置,如「留空=不筛选」)
|
||||||
|
function mergeSaved(form, saved) {
|
||||||
|
Object.keys(form).forEach((k) => {
|
||||||
|
const v = saved ? saved[k] : undefined
|
||||||
|
if (v === undefined || v === null || v === '') return
|
||||||
|
form[k] = Array.isArray(v) ? [...v] : v
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
export function usePluginUI(opts = {}) {
|
||||||
|
const { defaults, validate, buildPayload } = opts
|
||||||
|
|
||||||
|
const form = reactive(defaults ? defaults() : {})
|
||||||
|
const loaded = ref(false)
|
||||||
|
const needLogin = ref(false)
|
||||||
|
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
|
||||||
|
const lastSavedAt = ref(readSavedAt())
|
||||||
|
const running = ref(false)
|
||||||
|
const progress = ref(0)
|
||||||
|
const stopping = ref(false)
|
||||||
|
|
||||||
|
let ws = null
|
||||||
|
let runId = ''
|
||||||
|
let pollTimer = null
|
||||||
|
let saveTimer = null
|
||||||
|
|
||||||
|
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
|
||||||
|
const notify = (type, text) => { notice.value = type ? { type, text } : null }
|
||||||
|
|
||||||
|
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||||
|
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
|
||||||
|
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
|
||||||
|
onMounted(async () => {
|
||||||
|
try {
|
||||||
|
const saved = await loadConfig()
|
||||||
|
mergeSaved(form, saved)
|
||||||
|
} catch (e) {
|
||||||
|
if (e.code === 401) needLogin.value = true
|
||||||
|
}
|
||||||
|
loaded.value = true
|
||||||
|
refreshSchemes()
|
||||||
|
})
|
||||||
|
|
||||||
|
watch(form, () => {
|
||||||
|
if (!loaded.value || running.value) return
|
||||||
|
clearTimeout(saveTimer)
|
||||||
|
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||||
|
}, { deep: true })
|
||||||
|
|
||||||
|
async function saveNow(explicit) {
|
||||||
|
try {
|
||||||
|
await saveConfig(clone(form))
|
||||||
|
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||||
|
writeSavedAt(lastSavedAt.value)
|
||||||
|
if (explicit) ElMessage.success('配置已保存到本机')
|
||||||
|
} catch (e) {
|
||||||
|
if (e.code === 401) needLogin.value = true
|
||||||
|
else ElMessage.error('配置保存失败:' + e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function resetDefaults() {
|
||||||
|
Object.assign(form, defaults ? defaults(form) : {})
|
||||||
|
notify(null)
|
||||||
|
ElMessage.info('已恢复默认配置')
|
||||||
|
}
|
||||||
|
|
||||||
|
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
|
||||||
|
async function restoreLastFields() {
|
||||||
|
try {
|
||||||
|
const r = await loadLastFields()
|
||||||
|
const fields = r.fields || {}
|
||||||
|
if (!Object.keys(fields).length) {
|
||||||
|
ElMessage.info('暂无上次执行参数')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
mergeSaved(form, fields)
|
||||||
|
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
|
||||||
|
} catch (e) {
|
||||||
|
if (e.code === 401) needLogin.value = true
|
||||||
|
else ElMessage.error('恢复上次参数失败:' + e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 多配置方案 ----------
|
||||||
|
const schemes = ref([])
|
||||||
|
const schemeSel = ref('')
|
||||||
|
const schemeOptions = computed(() => [
|
||||||
|
{ value: '', label: '当前配置(自动保存)' },
|
||||||
|
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||||
|
])
|
||||||
|
|
||||||
|
async function refreshSchemes() {
|
||||||
|
try {
|
||||||
|
const r = await listSchemes()
|
||||||
|
schemes.value = r.configs || []
|
||||||
|
} catch (_) { /* 方案是辅助能力,失败静默 */ }
|
||||||
|
}
|
||||||
|
|
||||||
|
function onSchemeChange(id) {
|
||||||
|
if (!id) return
|
||||||
|
const s = schemes.value.find((x) => x.id === id)
|
||||||
|
if (!s) return
|
||||||
|
mergeSaved(form, s.fields)
|
||||||
|
ElMessage.success(`已应用方案「${s.name}」`)
|
||||||
|
}
|
||||||
|
|
||||||
|
async function saveSchemeAs() {
|
||||||
|
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||||
|
let name = ''
|
||||||
|
try {
|
||||||
|
({ value: name } = await ElMessageBox.prompt(
|
||||||
|
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||||
|
'存为配置方案',
|
||||||
|
{
|
||||||
|
inputValue: cur ? cur.name : '',
|
||||||
|
confirmButtonText: '保存方案',
|
||||||
|
cancelButtonText: '取消',
|
||||||
|
inputPattern: /\S/,
|
||||||
|
inputErrorMessage: '请输入方案名称',
|
||||||
|
},
|
||||||
|
))
|
||||||
|
} catch (_) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
name = String(name).trim()
|
||||||
|
if (!name) return
|
||||||
|
const dup = schemes.value.find((x) => x.name === name)
|
||||||
|
if (dup) {
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(
|
||||||
|
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||||
|
'覆盖已有方案',
|
||||||
|
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' },
|
||||||
|
)
|
||||||
|
} catch (_) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
const r = await saveScheme(name, clone(form))
|
||||||
|
await refreshSchemes()
|
||||||
|
schemeSel.value = r.config ? r.config.id : ''
|
||||||
|
ElMessage.success(`方案「${name}」已保存`)
|
||||||
|
} catch (e) {
|
||||||
|
if (e.code === 401) needLogin.value = true
|
||||||
|
else ElMessage.error('方案保存失败:' + e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function removeScheme() {
|
||||||
|
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||||
|
if (!s) return
|
||||||
|
try {
|
||||||
|
await ElMessageBox.confirm(
|
||||||
|
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||||
|
'删除方案',
|
||||||
|
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' },
|
||||||
|
)
|
||||||
|
} catch (_) {
|
||||||
|
return
|
||||||
|
}
|
||||||
|
try {
|
||||||
|
await deleteScheme(s.id)
|
||||||
|
schemeSel.value = ''
|
||||||
|
await refreshSchemes()
|
||||||
|
ElMessage.success('方案已删除')
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error('方案删除失败:' + e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------- 执行 ----------
|
||||||
|
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
|
||||||
|
async function run(action) {
|
||||||
|
if (running.value) return
|
||||||
|
if (needLogin.value) {
|
||||||
|
try {
|
||||||
|
await loadConfig()
|
||||||
|
needLogin.value = false
|
||||||
|
} catch (_) {
|
||||||
|
notify('error', '登录态未就绪,请稍后重试')
|
||||||
|
return
|
||||||
|
}
|
||||||
|
}
|
||||||
|
if (validate && !validate(action)) return
|
||||||
|
await saveNow(false)
|
||||||
|
notify(null)
|
||||||
|
running.value = true
|
||||||
|
progress.value = 0
|
||||||
|
try {
|
||||||
|
const payload = buildPayload ? buildPayload(form) : clone(form)
|
||||||
|
if (action) payload.action = action
|
||||||
|
const r = await startRun(payload)
|
||||||
|
runId = r.run_id
|
||||||
|
connect()
|
||||||
|
startPolling()
|
||||||
|
} catch (e) {
|
||||||
|
running.value = false
|
||||||
|
stopPolling()
|
||||||
|
if (e.code === 401) {
|
||||||
|
needLogin.value = true
|
||||||
|
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
|
||||||
|
} else if (e.code === 409) {
|
||||||
|
// 壳子「入队确认」里用户点了取消
|
||||||
|
notify('warn', '已取消加入执行队列,本次没有启动')
|
||||||
|
} else {
|
||||||
|
notify('error', '启动执行失败:' + e.message)
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
async function forceStop() {
|
||||||
|
if (!runId || stopping.value) return
|
||||||
|
stopping.value = true
|
||||||
|
try {
|
||||||
|
await stopRun(runId)
|
||||||
|
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||||
|
} catch (e) {
|
||||||
|
ElMessage.error('停止失败:' + e.message)
|
||||||
|
} finally {
|
||||||
|
stopping.value = false
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function connect() {
|
||||||
|
if (ws && ws.readyState <= 1) return
|
||||||
|
ws = connectWS((ev) => {
|
||||||
|
if (ev.run_id && ev.run_id !== runId) return
|
||||||
|
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||||
|
// 用户强制停止 / 排队取消 / 排队超时 → 「已取消」,不显示成「执行失败」
|
||||||
|
else if (ev.t === 'run_done') ev.ok ? finished() : (ev.status === 'cancelled' ? cancelled(ev.error) : failed(ev.error || '执行失败'))
|
||||||
|
})
|
||||||
|
ws.onclose = () => { ws = null }
|
||||||
|
}
|
||||||
|
|
||||||
|
function startPolling() {
|
||||||
|
stopPolling()
|
||||||
|
pollTimer = setInterval(async () => {
|
||||||
|
if (!runId) return
|
||||||
|
try {
|
||||||
|
const r = await getRun(runId)
|
||||||
|
if (r.status === 'done') finished(r.result?.summary)
|
||||||
|
else if (r.status === 'cancelled') cancelled(r.error)
|
||||||
|
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||||
|
} catch (_) { /* 下轮再试 */ }
|
||||||
|
}, 5000)
|
||||||
|
}
|
||||||
|
|
||||||
|
function stopPolling() {
|
||||||
|
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||||
|
}
|
||||||
|
|
||||||
|
function finished(summary) {
|
||||||
|
stopPolling()
|
||||||
|
running.value = false
|
||||||
|
progress.value = 100
|
||||||
|
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
|
||||||
|
if (summary) notify('ok', summary)
|
||||||
|
}
|
||||||
|
|
||||||
|
// 用户主动停止 / 排队取消 / 排队超时:不算失败,给中性的「已取消」提示
|
||||||
|
function cancelled(err) {
|
||||||
|
stopPolling()
|
||||||
|
running.value = false
|
||||||
|
notify('warn', '任务已取消:' + (err || '用户已停止'))
|
||||||
|
}
|
||||||
|
|
||||||
|
function failed(err) {
|
||||||
|
stopPolling()
|
||||||
|
running.value = false
|
||||||
|
notify('error', '执行失败:' + err)
|
||||||
|
}
|
||||||
|
|
||||||
|
return {
|
||||||
|
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||||
|
saveNow, resetDefaults, restoreLastFields,
|
||||||
|
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||||
|
run, forceStop,
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,20 @@
|
|||||||
|
import { defineConfig } from 'vite'
|
||||||
|
import vue from '@vitejs/plugin-vue'
|
||||||
|
|
||||||
|
// 插件 UI 由壳子托管在 /pui/xq0085/ 下,构建产物输出到插件包 ui/ 目录。
|
||||||
|
// dev 端口 5185(避开已占用的 5180~5182),代理到本机壳子 8799。
|
||||||
|
export default defineConfig({
|
||||||
|
plugins: [vue()],
|
||||||
|
base: '/pui/xq0085/',
|
||||||
|
build: {
|
||||||
|
outDir: '../ui',
|
||||||
|
emptyOutDir: true,
|
||||||
|
},
|
||||||
|
server: {
|
||||||
|
port: 5185,
|
||||||
|
proxy: {
|
||||||
|
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||||
|
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||||
|
},
|
||||||
|
},
|
||||||
|
})
|
||||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
|||||||
|
<!doctype html>
|
||||||
|
<html lang="zh-CN">
|
||||||
|
<head>
|
||||||
|
<meta charset="UTF-8" />
|
||||||
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
|
<title>团购数据核对</title>
|
||||||
|
<script type="module" crossorigin src="/pui/xq0085/assets/index-DUDJolhg.js"></script>
|
||||||
|
<link rel="stylesheet" crossorigin href="/pui/xq0085/assets/index-noJ2T9TO.css">
|
||||||
|
</head>
|
||||||
|
<body>
|
||||||
|
<div id="app"></div>
|
||||||
|
</body>
|
||||||
|
</html>
|
||||||
@@ -0,0 +1,162 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""XQ0085 基础信息维护:美团 / 抖音同一套逻辑(报表 A/B → 基础信息 A/E,写 A/B(+C)/E/F)。
|
||||||
|
|
||||||
|
回归点:抖音曾读【报表】O/P(VLOOKUP 结果列)并与 A 列比对,且写入阶段读到公式文本,
|
||||||
|
会把 `=+VLOOKUP(...)` 写进基础信息 A 列。
|
||||||
|
运行:.venv\\Scripts\\python.exe -m unittest tests.unit.test_xq0085_base_info -v
|
||||||
|
"""
|
||||||
|
import importlib
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
|
||||||
|
PLUGIN_DIR = os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||||
|
'plugins', 'XQ0001-0100', 'XQ0085 团购数据核对')
|
||||||
|
PKG = 'xq85_base_test'
|
||||||
|
|
||||||
|
|
||||||
|
def _load_modules():
|
||||||
|
if PKG not in sys.modules:
|
||||||
|
pkg = types.ModuleType(PKG)
|
||||||
|
pkg.__path__ = [PLUGIN_DIR]
|
||||||
|
sys.modules[PKG] = pkg
|
||||||
|
cfg = importlib.import_module(PKG + '.config')
|
||||||
|
bi = importlib.import_module(PKG + '.logic.base_info_sync')
|
||||||
|
return cfg, bi
|
||||||
|
|
||||||
|
|
||||||
|
class BaseInfoTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.cfg, self.bi = _load_modules()
|
||||||
|
self.cfg.set_work_dir(self.tmp.name, 'check_douyin')
|
||||||
|
self.path = os.path.join(self.tmp.name, '抖音9.30.xlsx')
|
||||||
|
self.dy = self.bi.layout(self.bi.LAYOUT_DOUYIN)
|
||||||
|
self._make_book()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def _make_book(self):
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
rep = wb.active
|
||||||
|
rep.title = self.cfg.REPORT_SHEET
|
||||||
|
# 报表 A/B 是平台原文;O/P 是 VLOOKUP 结果列(不应被当成新增项来源)
|
||||||
|
rows = [
|
||||||
|
('金色印象(八一路店)', '【龙手足道】80分钟足疗', '八一路行政会馆', '龙手足道'),
|
||||||
|
('新店X(测试店)', '【印象贵足】90分钟足浴', None, None),
|
||||||
|
]
|
||||||
|
for i, (shop, item, o_val, p_val) in enumerate(rows, start=self.cfg.REPORT_DATA_START):
|
||||||
|
rep.cell(i, 1, shop)
|
||||||
|
rep.cell(i, 2, item)
|
||||||
|
rep.cell(i, 15, o_val)
|
||||||
|
rep.cell(i, 16, p_val)
|
||||||
|
base = wb.create_sheet(self.cfg.DY_BASE_SHEET)
|
||||||
|
base.cell(4, 1, '核销门店')
|
||||||
|
base.cell(4, 3, '品牌')
|
||||||
|
base.cell(4, 5, '商品名称')
|
||||||
|
base.cell(5, 1, '金色印象(八一路店)')
|
||||||
|
base.cell(5, 2, '八一路行政会馆')
|
||||||
|
base.cell(5, 3, '金色印象')
|
||||||
|
base.cell(5, 5, '【龙手足道】80分钟足疗')
|
||||||
|
base.cell(5, 6, '龙手足道')
|
||||||
|
wb.save(self.path)
|
||||||
|
|
||||||
|
def _open(self, data_only=True):
|
||||||
|
return openpyxl.load_workbook(self.path, data_only=data_only)
|
||||||
|
|
||||||
|
def test_scan_uses_report_ab_not_op(self):
|
||||||
|
wb = self._open()
|
||||||
|
try:
|
||||||
|
res = self.bi.scan(wb, self.dy)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
self.assertTrue(res['ok'], res['message'])
|
||||||
|
self.assertEqual([e['crm'] for e in res['new_shops']], ['新店X(测试店)'])
|
||||||
|
# 【印象贵足】命中关键词规则,且基础信息里没有 → 应作为新项目
|
||||||
|
self.assertEqual([e['internal'] for e in res['new_items']], ['印象贵足'])
|
||||||
|
|
||||||
|
def test_case_insensitive_shop(self):
|
||||||
|
"""VLOOKUP 大小写不敏感:HiFi / HIFI 不能算新门店,也不能重复计数。"""
|
||||||
|
wb = openpyxl.load_workbook(self.path)
|
||||||
|
try:
|
||||||
|
base = wb[self.cfg.DY_BASE_SHEET]
|
||||||
|
base.cell(5, 1, '重庆 : 金色印象·HIFI影音·按摩足疗(松牌路店)')
|
||||||
|
rep = wb[self.cfg.REPORT_SHEET]
|
||||||
|
for r in range(self.cfg.REPORT_DATA_START, self.cfg.REPORT_DATA_START + 2):
|
||||||
|
rep.cell(r, 1, '重庆 : 金色印象·HiFi影音·按摩足疗(松牌路店)')
|
||||||
|
wb.save(self.path)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
wb = self._open()
|
||||||
|
try:
|
||||||
|
res = self.bi.scan(wb, self.dy)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
self.assertEqual(res['new_shops'], [])
|
||||||
|
|
||||||
|
def test_apply_writes_abef(self):
|
||||||
|
wb = self._open()
|
||||||
|
try:
|
||||||
|
res = self.bi.scan(wb, self.dy)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
wb = self._open(data_only=False)
|
||||||
|
try:
|
||||||
|
changed = self.bi.apply(wb, res, self.dy)
|
||||||
|
wb.save(self.path)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
self.assertEqual(changed, 2)
|
||||||
|
|
||||||
|
wb = self._open()
|
||||||
|
try:
|
||||||
|
base = wb[self.cfg.DY_BASE_SHEET]
|
||||||
|
self.assertEqual(base.cell(6, 1).value, '新店X(测试店)')
|
||||||
|
self.assertEqual(base.cell(6, 2).value, '新店X(测试店)') # 猜不到则同名
|
||||||
|
self.assertEqual(base.cell(6, 5).value, '【印象贵足】90分钟足浴')
|
||||||
|
self.assertEqual(base.cell(6, 6).value, '印象贵足')
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
# 幂等:再扫一次应无新增
|
||||||
|
wb = self._open()
|
||||||
|
try:
|
||||||
|
again = self.bi.scan(wb, self.dy)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
self.assertEqual(again['new_shops'], [])
|
||||||
|
self.assertEqual(again['new_items'], [])
|
||||||
|
|
||||||
|
def test_formula_text_is_ignored(self):
|
||||||
|
wb = openpyxl.load_workbook(self.path)
|
||||||
|
try:
|
||||||
|
rep = wb[self.cfg.REPORT_SHEET]
|
||||||
|
for r in range(self.cfg.REPORT_DATA_START, rep.max_row + 1):
|
||||||
|
rep.cell(r, 1, '=+VLOOKUP(A{},基础信息!$A$5:$B$1992,2,0)'.format(r))
|
||||||
|
wb.save(self.path)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
wb = self._open(data_only=False)
|
||||||
|
try:
|
||||||
|
res = self.bi.scan(wb, self.dy)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
self.assertEqual(res['new_shops'], [])
|
||||||
|
self.assertEqual(res['new_items'], [])
|
||||||
|
|
||||||
|
def test_meituan_layout_rows(self):
|
||||||
|
lay = self.bi.layout(self.bi.LAYOUT_MEITUAN)
|
||||||
|
self.assertEqual(lay['shop_row'], self.cfg.BASE_INFO_ROW)
|
||||||
|
self.assertEqual(lay['item_row'], self.cfg.BASE_ITEM_ROW)
|
||||||
|
self.assertEqual(lay['shop_limit'], self.cfg.BASE_INFO_VLOOKUP_MAX)
|
||||||
|
self.assertEqual(self.dy['shop_limit'], self.cfg.DY_BASE_INFO_VLOOKUP_MAX)
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,235 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""XQ0085 对比表日滚动冒烟:IJK/漏核销清空、今日遗留→昨日遗留、幂等跳过。
|
||||||
|
|
||||||
|
用临时工作簿验证 zip+XML 写入不破坏其它列,且重复运行不会把昨日遗留抹掉。
|
||||||
|
运行:.venv\\Scripts\\python.exe -m unittest tests.unit.test_xq0085_compare -v
|
||||||
|
"""
|
||||||
|
import importlib
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
|
||||||
|
PLUGIN_DIR = os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||||
|
'plugins', 'XQ0001-0100', 'XQ0085 团购数据核对')
|
||||||
|
PKG = 'xq85_compare_test'
|
||||||
|
|
||||||
|
|
||||||
|
def _load_modules():
|
||||||
|
if PKG not in sys.modules:
|
||||||
|
pkg = types.ModuleType(PKG)
|
||||||
|
pkg.__path__ = [PLUGIN_DIR]
|
||||||
|
sys.modules[PKG] = pkg
|
||||||
|
cfg = importlib.import_module(PKG + '.config')
|
||||||
|
cs = importlib.import_module(PKG + '.logic.compare_sheets')
|
||||||
|
return cfg, cs
|
||||||
|
|
||||||
|
|
||||||
|
class CompareSheetTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.cfg, self.cs = _load_modules()
|
||||||
|
self.cfg.set_work_dir(self.tmp.name, 'check_meituan')
|
||||||
|
os.makedirs(self.cfg.WORK_DIR, exist_ok=True)
|
||||||
|
today = date.today()
|
||||||
|
self.path = os.path.join(
|
||||||
|
self.cfg.WORK_DIR, f'马敏团购总表{today.month}.{today.day}.xlsx')
|
||||||
|
self._make_book()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def _make_book(self):
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = self.cfg.COMPARE_SHEET_MEITUAN
|
||||||
|
header = {1: '门店', 2: '核销项目名称', 5: '门店', 6: '核销项目名称',
|
||||||
|
9: 'I列', 10: '平台结错', 11: 'K列',
|
||||||
|
14: '漏核销', 17: '昨日遗留', 18: '今日遗留', 19: '备注', 23: '验证'}
|
||||||
|
for c, title in header.items():
|
||||||
|
ws.cell(1, c, title)
|
||||||
|
# A/B 是透视原始名(回填今日遗留用),E/F 是分组列;测试里两者相同
|
||||||
|
self.groups = {5: ('门店A', '项目X'), 6: ('门店B', '二选一'), 7: ('门店C', '专项采耳')}
|
||||||
|
# X 列(24)是无表头备注列:空 / 含「前消费」→ 昨日遗留保留,其它备注 → 清空
|
||||||
|
remarks = {5: None, 6: '2026年10月31日前消费', 7: '其他项目待处理'}
|
||||||
|
for r in range(5, 8):
|
||||||
|
for c in (1, 5):
|
||||||
|
ws.cell(r, c, self.groups[r][0])
|
||||||
|
for c in (2, 6):
|
||||||
|
ws.cell(r, c, self.groups[r][1])
|
||||||
|
ws.cell(r, 9, 100 + r)
|
||||||
|
ws.cell(r, 11, 300 + r)
|
||||||
|
ws.cell(r, 14, 900 + r)
|
||||||
|
ws.cell(r, 17, 1000 + r)
|
||||||
|
ws.cell(r, 18, 2000 + r)
|
||||||
|
ws.cell(r, 19, '备注{}'.format(r))
|
||||||
|
ws.cell(r, 23, 0)
|
||||||
|
if remarks[r]:
|
||||||
|
ws.cell(r, 24, remarks[r])
|
||||||
|
# 今日遗留回填来源:美团 = 美团 + 点评
|
||||||
|
stats = wb.create_sheet(self.cfg.COMPARE_STATS_SHEET)
|
||||||
|
stats.append(['团购类型', '消费日期', '门店', '核销项目名称', '核销项目个数',
|
||||||
|
'核销项目总价', '未消费项目个数', '未消费项目总价', '已消费项目个数'])
|
||||||
|
for kind, store, item, unused in (
|
||||||
|
('美团', '门店A', '项目X', 3), ('点评', '门店A', '项目X', 2),
|
||||||
|
('美团', '门店B', '二选一', 7), ('美团', '门店C', '专项采耳', 1)):
|
||||||
|
stats.append([kind, None, store, item, 0, 0, unused, 0, 0])
|
||||||
|
wb.save(self.path)
|
||||||
|
|
||||||
|
def _values(self, sheet):
|
||||||
|
wb = openpyxl.load_workbook(self.path, data_only=True)
|
||||||
|
try:
|
||||||
|
ws = wb[sheet]
|
||||||
|
return {r: {c: ws.cell(r, c).value for c in (1, 9, 10, 11, 14, 17, 18, 19, 24)}
|
||||||
|
for r in range(5, 8)}
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
def test_roll_and_clear(self):
|
||||||
|
res = self.cs.run(day=date.today(), action='check_meituan',
|
||||||
|
dry_run=False, use_com=False)
|
||||||
|
self.assertTrue(res['ok'], res['message'])
|
||||||
|
self.assertEqual(res['kept'], 2, 'X 为空或含「前消费」应保留')
|
||||||
|
self.assertEqual(res['cleared'], 1, '其它备注应清空昨日遗留')
|
||||||
|
rows = self._values(self.cfg.COMPARE_SHEET_MEITUAN)
|
||||||
|
filled = {5: 5, 6: 7, 7: 1} # 门店A/项目X=美团3+点评2,门店B/二选一=7,门店C/专项采耳=1
|
||||||
|
for r in range(5, 8):
|
||||||
|
got = rows[r]
|
||||||
|
self.assertIsNone(got[9], 'I 列应清空')
|
||||||
|
self.assertIsNone(got[10], 'J 列应清空')
|
||||||
|
self.assertIsNone(got[11], 'K 列应清空')
|
||||||
|
self.assertIsNone(got[14], '漏核销列应清空')
|
||||||
|
self.assertEqual(got[18], filled[r], '今日遗留应回填为团购统计未消费数')
|
||||||
|
self.assertEqual(got[1], self.groups[r][0], 'A 列应保留')
|
||||||
|
self.assertEqual(got[19], '备注{}'.format(r), '其它列应保留')
|
||||||
|
# 昨日遗留 = 昨天的今日遗留 - 漏核销:2005-905 / 2006-906
|
||||||
|
self.assertEqual(rows[5][17], 1100, 'X 为空 → 昨日遗留保留(R-S)')
|
||||||
|
self.assertEqual(rows[6][17], 1100, 'X 含「前消费」→ 昨日遗留保留(R-S)')
|
||||||
|
self.assertIsNone(rows[7][17], 'X 是其它备注 → 昨日遗留清空')
|
||||||
|
self.assertTrue(res['verify']['ok'], '组内 W 全为 0 应通过验证')
|
||||||
|
self.assertEqual(res['groups_total'], 3)
|
||||||
|
self.assertEqual(res['unbalanced_count'], 0)
|
||||||
|
|
||||||
|
def test_yesterday_equals_today_minus_miss(self):
|
||||||
|
"""昨日遗留 = 今日遗留 - 漏核销;没有今日遗留就是 0 - 漏核销;两列随后清空。"""
|
||||||
|
wb = openpyxl.load_workbook(self.path)
|
||||||
|
try:
|
||||||
|
ws = wb[self.cfg.COMPARE_SHEET_MEITUAN]
|
||||||
|
ws.cell(5, 18).value = 7
|
||||||
|
ws.cell(5, 14).value = 2 # R=7,S=2 → 5
|
||||||
|
ws.cell(6, 18).value = None
|
||||||
|
ws.cell(6, 14).value = 4 # 无今日遗留 → 0-4 = -4
|
||||||
|
ws.cell(7, 18).value = 3
|
||||||
|
ws.cell(7, 14).value = None # R=3,无漏核销 → 3
|
||||||
|
for r in (5, 6, 7):
|
||||||
|
ws.cell(r, 24).value = None # 清掉备注,避免干扰
|
||||||
|
wb.save(self.path)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
res = self.cs.run(day=date.today(), action='check_meituan',
|
||||||
|
dry_run=False, use_com=False)
|
||||||
|
self.assertTrue(res['ok'], res['message'])
|
||||||
|
rows = self._values(self.cfg.COMPARE_SHEET_MEITUAN)
|
||||||
|
self.assertEqual(rows[5][17], 5)
|
||||||
|
self.assertEqual(rows[6][17], -4)
|
||||||
|
self.assertEqual(rows[7][17], 3)
|
||||||
|
filled = {5: 5, 6: 7, 7: 1}
|
||||||
|
for r in (5, 6, 7):
|
||||||
|
self.assertEqual(rows[r][18], filled[r], '今日遗留应回填为团购统计未消费数')
|
||||||
|
self.assertIsNone(rows[r][14], '漏核销应清空')
|
||||||
|
|
||||||
|
def test_both_empty_clears_yesterday(self):
|
||||||
|
"""今日遗留与漏核销都为空时不写 0,直接清空昨日遗留。"""
|
||||||
|
wb = openpyxl.load_workbook(self.path)
|
||||||
|
try:
|
||||||
|
ws = wb[self.cfg.COMPARE_SHEET_MEITUAN]
|
||||||
|
for r in (5, 6, 7):
|
||||||
|
ws.cell(r, 18).value = None
|
||||||
|
ws.cell(r, 14).value = None
|
||||||
|
ws.cell(r, 24).value = None
|
||||||
|
wb.save(self.path)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
res = self.cs.run(day=date.today(), action='check_meituan',
|
||||||
|
dry_run=False, use_com=False, force=True)
|
||||||
|
self.assertTrue(res['ok'], res['message'])
|
||||||
|
rows = self._values(self.cfg.COMPARE_SHEET_MEITUAN)
|
||||||
|
filled = {5: 5, 6: 7, 7: 1}
|
||||||
|
for r in (5, 6, 7):
|
||||||
|
self.assertIsNone(rows[r][17], '今日遗留与漏核销都空时昨日遗留清空')
|
||||||
|
self.assertIsNone(rows[r][14], '漏核销应清空')
|
||||||
|
self.assertEqual(rows[r][18], filled[r], '今日遗留仍按团购统计回填')
|
||||||
|
|
||||||
|
def test_verify_column_failure(self):
|
||||||
|
"""组内 W 求和不为 0 时应判定不平,并列出门店/项目/差额。"""
|
||||||
|
wb = openpyxl.load_workbook(self.path)
|
||||||
|
try:
|
||||||
|
wb[self.cfg.COMPARE_SHEET_MEITUAN].cell(6, 23, 5)
|
||||||
|
wb.save(self.path)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
res = self.cs.run(day=date.today(), action='check_meituan',
|
||||||
|
dry_run=False, use_com=False)
|
||||||
|
self.assertTrue(res['ok'])
|
||||||
|
self.assertFalse(res['verify']['ok'], '门店B/二选一 组和为 5 应判不平')
|
||||||
|
self.assertEqual(res['unbalanced_count'], 1)
|
||||||
|
self.assertEqual(res['unbalanced'][0]['store'], '门店B')
|
||||||
|
self.assertEqual(res['unbalanced'][0]['item'], '二选一')
|
||||||
|
self.assertEqual(res['unbalanced'][0]['diff'], 5)
|
||||||
|
|
||||||
|
def test_meal_adjust_writes_platform_error(self):
|
||||||
|
"""双人餐 -1、基础 +2 仍不平时,平台结错写 1 / -2。"""
|
||||||
|
wb = openpyxl.load_workbook(self.path)
|
||||||
|
try:
|
||||||
|
ws = wb[self.cfg.COMPARE_SHEET_MEITUAN]
|
||||||
|
for c in (1, 5):
|
||||||
|
ws.cell(5, c).value = '门店A'
|
||||||
|
ws.cell(6, c).value = '门店A'
|
||||||
|
ws.cell(5, 2).value = '印象贵足'
|
||||||
|
ws.cell(6, 2).value = '印象贵足双人餐'
|
||||||
|
ws.cell(5, 6).value = '印象贵足'
|
||||||
|
ws.cell(6, 6).value = '印象贵足双人餐'
|
||||||
|
ws.cell(5, 23).value = 2
|
||||||
|
ws.cell(6, 23).value = -1
|
||||||
|
wb.save(self.path)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
res = self.cs.run(day=date.today(), action='check_meituan',
|
||||||
|
dry_run=False, use_com=False)
|
||||||
|
self.assertTrue(res['ok'], res['message'])
|
||||||
|
self.assertEqual(len(res['meal_adjust']), 1, '应识别 1 对双人餐')
|
||||||
|
wb = openpyxl.load_workbook(self.path, data_only=True)
|
||||||
|
try:
|
||||||
|
ws = wb[self.cfg.COMPARE_SHEET_MEITUAN]
|
||||||
|
self.assertEqual(ws.cell(6, 10).value, 1, '双人餐行平台结错应为 1')
|
||||||
|
self.assertEqual(ws.cell(5, 10).value, -2, '基础行平台结错应为 -2')
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
def test_sheet_name_normalized(self):
|
||||||
|
"""工作簿里是全角「抖音对比(2)」,配置若写半角/带空格也应能匹配。"""
|
||||||
|
self.assertEqual(
|
||||||
|
self.cs._find_sheet(['抖音对比 (2)'], self.cfg.COMPARE_SHEET_DOUYIN),
|
||||||
|
'抖音对比 (2)')
|
||||||
|
self.assertEqual(
|
||||||
|
self.cs._find_sheet(['抖音对比(2)'], '抖音对比 (2)'),
|
||||||
|
'抖音对比(2)')
|
||||||
|
|
||||||
|
def test_idempotent_skip(self):
|
||||||
|
self.cs.run(day=date.today(), action='check_meituan', dry_run=False, use_com=False)
|
||||||
|
res = self.cs.run(day=date.today(), action='check_meituan', dry_run=False, use_com=False)
|
||||||
|
self.assertTrue(res['ok'], res['message'])
|
||||||
|
self.assertTrue(res['skipped'], '第二次应判定今天已滚动过')
|
||||||
|
rows = self._values(self.cfg.COMPARE_SHEET_MEITUAN)
|
||||||
|
self.assertEqual(rows[5][17], 1100, '重复运行不应抹掉 X 为空行的昨日遗留')
|
||||||
|
self.assertEqual(rows[6][17], 1100, '重复运行不应抹掉含「前消费」行的昨日遗留')
|
||||||
|
self.assertIsNone(rows[7][17], 'X 为其它备注的行昨日遗留已被清空,重跑也不应回填')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,249 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""XQ0085 分组验证 + 今日遗留回填:归并、回填、组内求和、``-`` 跳过。
|
||||||
|
|
||||||
|
运行:.venv\\Scripts\\python.exe -m unittest tests.unit.test_xq0085_compare_groups -v
|
||||||
|
"""
|
||||||
|
import importlib
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
|
||||||
|
PLUGIN_DIR = os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||||
|
'plugins', 'XQ0001-0100', 'XQ0085 团购数据核对')
|
||||||
|
PKG = 'xq85_groups_test'
|
||||||
|
|
||||||
|
|
||||||
|
def _load_modules():
|
||||||
|
if PKG not in sys.modules:
|
||||||
|
pkg = types.ModuleType(PKG)
|
||||||
|
pkg.__path__ = [PLUGIN_DIR]
|
||||||
|
sys.modules[PKG] = pkg
|
||||||
|
cfg = importlib.import_module(PKG + '.config')
|
||||||
|
cg = importlib.import_module(PKG + '.logic.compare_groups')
|
||||||
|
return cfg, cg
|
||||||
|
|
||||||
|
|
||||||
|
COLS = {'store': 1, 'item': 2, 'verify': 3}
|
||||||
|
|
||||||
|
|
||||||
|
class CompareGroupsTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.cfg, self.cg = _load_modules()
|
||||||
|
self.cfg.set_work_dir(self.tmp.name, 'check_meituan')
|
||||||
|
os.makedirs(self.cfg.WORK_DIR, exist_ok=True)
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
# ---------- 归并 ----------
|
||||||
|
def test_norm_item_merges_groups(self):
|
||||||
|
self.assertEqual(self.cg.norm_item('艾养耳道'), '二选一')
|
||||||
|
self.assertEqual(self.cg.norm_item('头舒耳道'), '二选一')
|
||||||
|
self.assertEqual(self.cg.norm_item('二选一'), '二选一')
|
||||||
|
self.assertEqual(self.cg.norm_item('专项采耳'), '四选一')
|
||||||
|
self.assertEqual(self.cg.norm_item('五行火罐'), '四选一')
|
||||||
|
self.assertEqual(self.cg.norm_item('四选一'), '四选一')
|
||||||
|
|
||||||
|
def test_unlisted_item_stays_alone(self):
|
||||||
|
self.assertEqual(self.cg.norm_item('艾灸耳道'), '艾灸耳道')
|
||||||
|
self.assertEqual(self.cg.norm_item('龙手足道'), '龙手足道')
|
||||||
|
self.assertEqual(self.cg.norm_item(''), '')
|
||||||
|
|
||||||
|
# ---------- 今日遗留回填 ----------
|
||||||
|
def test_fill_edits_by_raw_name(self):
|
||||||
|
rows = [['门店A', '艾养耳道'], ['门店A', '头舒耳道'], ['门店A', '二选一'],
|
||||||
|
['门店B', '项目X']]
|
||||||
|
stats = {('门店A', '艾养耳道'): 2, ('门店A', '头舒耳道'): 1,
|
||||||
|
('门店A', '二选一'): 3, ('门店B', '项目X'): 0}
|
||||||
|
out = self.cg.build_fill_edits(rows, stats, 1, 2)
|
||||||
|
self.assertEqual(out['edits'], {5: 2, 6: 1, 7: 3, 8: None}, '0 应写空')
|
||||||
|
self.assertEqual(out['filled'], 3)
|
||||||
|
self.assertEqual(out['unmatched'], [])
|
||||||
|
|
||||||
|
def test_fill_unmatched_keeps_blank(self):
|
||||||
|
out = self.cg.build_fill_edits([['门店A', '艾灸耳道']],
|
||||||
|
{('门店A', '项目X'): 1}, 1, 2)
|
||||||
|
self.assertIsNone(out['edits'][5])
|
||||||
|
self.assertEqual(out['unmatched'], ['艾灸耳道'])
|
||||||
|
|
||||||
|
def test_fill_without_stats_keeps_sheet(self):
|
||||||
|
out = self.cg.build_fill_edits([['门店A', '项目X']], {}, 1, 2)
|
||||||
|
self.assertEqual(out['edits'], {}, '团购统计为空时不产计划,保持原值')
|
||||||
|
self.assertTrue(out['skipped'])
|
||||||
|
|
||||||
|
# ---------- 退款/撤销核销冲减 ----------
|
||||||
|
def test_refund_subtracts_exact_row(self):
|
||||||
|
rows = [['门店A', '项目X'], ['门店A', '项目Y']]
|
||||||
|
stats = {('门店A', '项目X'): 5, ('门店A', '项目Y'): 3}
|
||||||
|
out = self.cg.build_fill_edits(rows, stats, 1, 2, refunds={('门店A', '项目X'): 2})
|
||||||
|
self.assertEqual(out['edits'], {5: 3, 6: 3}, '同门店同项目扣掉 2')
|
||||||
|
self.assertEqual(out['refund_applied'][0]['count'], 2)
|
||||||
|
|
||||||
|
def test_refund_falls_back_to_group(self):
|
||||||
|
"""基础信息把专项采耳映射成四选一,表里只有专项采耳行 → 扣在组内行上。"""
|
||||||
|
rows = [['门店A', '专项采耳'], ['门店A', '专项头疗']]
|
||||||
|
stats = {('门店A', '专项采耳'): 2}
|
||||||
|
out = self.cg.build_fill_edits(rows, stats, 1, 2, refunds={('门店A', '四选一'): 1})
|
||||||
|
self.assertEqual(out['edits'][5], 1, '组内第一行扣 1')
|
||||||
|
self.assertEqual(out['refund_unmatched'], [])
|
||||||
|
|
||||||
|
def test_refund_without_row_is_reported(self):
|
||||||
|
rows = [['门店A', '项目X']]
|
||||||
|
out = self.cg.build_fill_edits(rows, {('门店A', '项目X'): 0}, 1, 2,
|
||||||
|
refunds={('门店B', '项目Z'): 3})
|
||||||
|
self.assertEqual(out['edits'], {5: None})
|
||||||
|
self.assertEqual(out['refund_unmatched'],
|
||||||
|
[{'store': '门店B', 'item': '项目Z', 'count': 3}])
|
||||||
|
|
||||||
|
def test_load_refunds_maps_store_and_item(self):
|
||||||
|
path = os.path.join(self.cfg.WORK_DIR, '美团1.1.xlsx')
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
base = wb.active
|
||||||
|
base.title = self.cfg.COMPARE_BASE_INFO_SHEET
|
||||||
|
base.append(['消费门店名称', '门店', '品牌', None, '套餐名', None])
|
||||||
|
base.append(['成都 : 金色印象(北城天街店)', '北城天街CEO会馆', '金色印象', None,
|
||||||
|
'【龙手足道】80分钟', '龙手足道'])
|
||||||
|
detail = wb.create_sheet('订单收入明细表')
|
||||||
|
detail.cell(3, 1, '账户名称')
|
||||||
|
detail.cell(3, 3, '业务类型')
|
||||||
|
detail.cell(3, 9, '套餐名')
|
||||||
|
detail.cell(3, 11, '消费门店')
|
||||||
|
detail.cell(3, 32, '品项名称')
|
||||||
|
rows = [
|
||||||
|
('已消费退', '【龙手足道】80分钟', '重庆 : 金色印象·HIFI(北城天街店)', '龙手足道'),
|
||||||
|
('撤销核销', '【龙手足道】80分钟', '重庆 : 金色印象·HIFI(北城天街店)', '龙手足道'),
|
||||||
|
('已核销', '【龙手足道】80分钟', '重庆 : 金色印象·HIFI(北城天街店)', '龙手足道'),
|
||||||
|
('已消费退', '【未知商品】', '重庆 : 不存在(未知店)', ''),
|
||||||
|
]
|
||||||
|
for i, (status, product, store, item) in enumerate(rows, 4):
|
||||||
|
detail.cell(i, 3, status)
|
||||||
|
detail.cell(i, 9, product)
|
||||||
|
detail.cell(i, 11, store)
|
||||||
|
detail.cell(i, 32, item)
|
||||||
|
wb.save(path)
|
||||||
|
|
||||||
|
out = self.cg.load_refunds(path, self.cfg.COMPARE_REFUND_GROUPS['check_meituan'],
|
||||||
|
['北城天街CEO会馆'])
|
||||||
|
self.assertTrue(out['ok'])
|
||||||
|
self.assertEqual(out['rows'], 3, '「已核销」不算')
|
||||||
|
self.assertEqual(out['counts'], {('北城天街CEO会馆', '龙手足道'): 2})
|
||||||
|
self.assertEqual(len(out['unmatched']), 1)
|
||||||
|
|
||||||
|
# ---------- 分组验证 ----------
|
||||||
|
def test_group_sum_zero_is_balanced(self):
|
||||||
|
rows = [['门店A', '艾养耳道', 2], ['门店A', '头舒耳道', -1],
|
||||||
|
['门店A', '二选一', -1]]
|
||||||
|
out = self.cg.verify(rows, COLS)
|
||||||
|
self.assertTrue(out['ok'])
|
||||||
|
self.assertEqual(out['total_groups'], 1)
|
||||||
|
self.assertEqual(out['ok_groups'], 1)
|
||||||
|
self.assertEqual(out['unbalanced_count'], 0)
|
||||||
|
|
||||||
|
def test_group_sum_nonzero_is_unbalanced(self):
|
||||||
|
rows = [['门店A', '艾养耳道', 2], ['门店A', '二选一', -1]]
|
||||||
|
out = self.cg.verify(rows, COLS)
|
||||||
|
self.assertFalse(out['ok'])
|
||||||
|
self.assertEqual(out['unbalanced_count'], 1)
|
||||||
|
self.assertEqual(out['unbalanced'][0]['store'], '门店A')
|
||||||
|
self.assertEqual(out['unbalanced'][0]['item'], '二选一')
|
||||||
|
self.assertEqual(out['unbalanced'][0]['diff'], 1)
|
||||||
|
|
||||||
|
def test_dash_and_blank_rows_are_skipped(self):
|
||||||
|
rows = [['门店A', '项目X', '-'], ['门店A', '项目Y', None],
|
||||||
|
['门店B', '项目Z', 0]]
|
||||||
|
out = self.cg.verify(rows, COLS)
|
||||||
|
self.assertTrue(out['ok'])
|
||||||
|
self.assertEqual(out['total_groups'], 1, '整组都是 - / 空时不参与')
|
||||||
|
self.assertEqual(out['skipped_rows'], 2)
|
||||||
|
|
||||||
|
def test_bad_value_makes_group_unbalanced(self):
|
||||||
|
rows = [['门店A', '项目X', 0], ['门店A', '项目X', '#DIV/0!']]
|
||||||
|
out = self.cg.verify(rows, COLS)
|
||||||
|
self.assertFalse(out['ok'])
|
||||||
|
self.assertEqual(out['bad_rows'], 1)
|
||||||
|
self.assertEqual(out['unbalanced'][0]['bad'][0][0], 6)
|
||||||
|
|
||||||
|
# ---------- 双人餐/三人餐平台结错 ----------
|
||||||
|
@staticmethod
|
||||||
|
def _group(total, rows):
|
||||||
|
return {'sum': total, 'count': len(rows), 'skipped': 0,
|
||||||
|
'bad': [], 'row_ids': list(rows)}
|
||||||
|
|
||||||
|
def test_meal_adjust_pair(self):
|
||||||
|
groups = {('门店A', '印象贵足'): self._group(2, [5]),
|
||||||
|
('门店A', '印象贵足双人餐'): self._group(-1, [6])}
|
||||||
|
edits, detail, _ = self.cg.build_meal_edits(groups)
|
||||||
|
self.assertEqual(edits, {6: 1, 5: -2}, '餐行 +1、基础行 -2')
|
||||||
|
self.assertEqual(detail[0]['base'], '印象贵足')
|
||||||
|
|
||||||
|
def test_meal_adjust_three_people(self):
|
||||||
|
groups = {('门店A', '龙手足道'): self._group(3, [5]),
|
||||||
|
('门店A', '龙手足道三人餐'): self._group(-1, [6])}
|
||||||
|
edits, _, _ = self.cg.build_meal_edits(groups)
|
||||||
|
self.assertEqual(edits, {6: 1, 5: -3}, '三人餐基础行写 -3')
|
||||||
|
|
||||||
|
def test_meal_skips_balanced_meal_row(self):
|
||||||
|
groups = {('门店A', '印象贵足'): self._group(2, [5]),
|
||||||
|
('门店A', '印象贵足双人餐'): self._group(0, [6])}
|
||||||
|
edits, _, _ = self.cg.build_meal_edits(groups)
|
||||||
|
self.assertEqual(edits, {}, '餐行自己平的就不动')
|
||||||
|
|
||||||
|
def test_meal_skips_without_base(self):
|
||||||
|
groups = {('门店A', '印象贵足双人餐'): self._group(-1, [6])}
|
||||||
|
edits, _, _ = self.cg.build_meal_edits(groups)
|
||||||
|
self.assertEqual(edits, {}, '没有基础项目行无法配对')
|
||||||
|
|
||||||
|
def test_meal_accumulates_on_base(self):
|
||||||
|
groups = {('门店A', '龙手足道'): self._group(5, [5]),
|
||||||
|
('门店A', '龙手足道双人餐'): self._group(-1, [6]),
|
||||||
|
('门店A', '龙手足道三人餐'): self._group(-1, [7])}
|
||||||
|
edits, _, _ = self.cg.build_meal_edits(groups)
|
||||||
|
self.assertEqual(edits, {6: 1, 7: 1, 5: -5}, '基础行遇到多餐应累加')
|
||||||
|
|
||||||
|
def test_meal_scales_by_deficit(self):
|
||||||
|
"""餐行 -3、基础 +6 → 餐行 J=3、基础 J=-6(按差额倍数)。"""
|
||||||
|
groups = {('门店A', '印象贵足'): self._group(6, [5]),
|
||||||
|
('门店A', '印象贵足双人餐'): self._group(-3, [6])}
|
||||||
|
edits, detail, _ = self.cg.build_meal_edits(groups)
|
||||||
|
self.assertEqual(edits, {6: 3, 5: -6})
|
||||||
|
self.assertEqual(detail[0]['times'], 3)
|
||||||
|
|
||||||
|
def test_meal_skips_negative_base(self):
|
||||||
|
groups = {('门店A', '龙手足道'): self._group(-7, [5]),
|
||||||
|
('门店A', '龙手足道双人餐'): self._group(-1, [6])}
|
||||||
|
edits, detail, skipped = self.cg.build_meal_edits(groups)
|
||||||
|
self.assertEqual(edits, {}, '基础行为负时写 -2 只会扩大差额,应跳过')
|
||||||
|
self.assertEqual(len(skipped), 1)
|
||||||
|
self.assertEqual(skipped[0]['base'], '龙手足道')
|
||||||
|
|
||||||
|
# ---------- 团购统计取数 ----------
|
||||||
|
def test_load_unused_filters_type(self):
|
||||||
|
path = os.path.join(self.cfg.WORK_DIR, '马敏团购总表1.1.xlsx')
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = self.cfg.COMPARE_STATS_SHEET
|
||||||
|
ws.append(['团购类型', '消费日期', '门店', '核销项目名称', '核销项目个数',
|
||||||
|
'核销项目总价', '未消费项目个数', '未消费项目总价', '已消费项目个数'])
|
||||||
|
for kind, store, item, unused in (
|
||||||
|
('美团', '门店A', '项目X', 3), ('点评', '门店A', '项目X', 2),
|
||||||
|
('抖音', '门店A', '项目X', 9)):
|
||||||
|
ws.append([kind, None, store, item, 0, 0, unused, 0, 0])
|
||||||
|
wb.save(path)
|
||||||
|
|
||||||
|
out = self.cg.load_unused(path, self.cfg.COMPARE_STATS_TYPES['check_meituan'])
|
||||||
|
self.assertTrue(out['ok'])
|
||||||
|
self.assertEqual(out['stats'][('门店A', '项目X')], 5, '美团 + 点评 应合计')
|
||||||
|
self.assertEqual(len(out['stats']), 1)
|
||||||
|
|
||||||
|
out = self.cg.load_unused(path, self.cfg.COMPARE_STATS_TYPES['check_douyin'])
|
||||||
|
self.assertEqual(out['stats'][('门店A', '项目X')], 9, '抖音只取抖音类型')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,98 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""XQ0085 按值贴入:日期列必须落成 Excel 序列号 + 日期格式,不能退化成文本。
|
||||||
|
|
||||||
|
回归点:CRM「团购统计」的消费日期原先被写成 inlineStr,透视按日期分组失效;
|
||||||
|
新增行还需沿用上一行同列样式,否则日期显示成裸数字。
|
||||||
|
运行:.venv\\Scripts\\python.exe -m unittest tests.unit.test_xq0085_paste_date -v
|
||||||
|
"""
|
||||||
|
import importlib
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
from datetime import date, datetime
|
||||||
|
|
||||||
|
import openpyxl
|
||||||
|
|
||||||
|
PLUGIN_DIR = os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||||
|
'plugins', 'XQ0001-0100', 'XQ0085 团购数据核对')
|
||||||
|
PKG = 'xq85_paste_test'
|
||||||
|
SHEET = '团购统计'
|
||||||
|
FMT = 'yyyy\\-mm\\-dd'
|
||||||
|
|
||||||
|
|
||||||
|
def _load_modules():
|
||||||
|
if PKG not in sys.modules:
|
||||||
|
pkg = types.ModuleType(PKG)
|
||||||
|
pkg.__path__ = [PLUGIN_DIR]
|
||||||
|
sys.modules[PKG] = pkg
|
||||||
|
cfg = importlib.import_module(PKG + '.config')
|
||||||
|
paste = importlib.import_module(PKG + '.logic.paste_to_master')
|
||||||
|
return cfg, paste
|
||||||
|
|
||||||
|
|
||||||
|
class PasteDateTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.cfg, self.paste = _load_modules()
|
||||||
|
self.path = os.path.join(self.tmp.name, '总表.xlsx')
|
||||||
|
self._make_book()
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def _make_book(self):
|
||||||
|
wb = openpyxl.Workbook()
|
||||||
|
ws = wb.active
|
||||||
|
ws.title = SHEET
|
||||||
|
for c, title in enumerate(['团购类型', '消费日期', '门店', '项目', '个数', '总价'], start=1):
|
||||||
|
ws.cell(1, c, title)
|
||||||
|
for r in range(2, 5):
|
||||||
|
ws.cell(r, 1, '美团')
|
||||||
|
cell = ws.cell(r, 2, datetime(2026, 9, 29))
|
||||||
|
cell.number_format = FMT
|
||||||
|
ws.cell(r, 3, '门店{}'.format(r))
|
||||||
|
ws.cell(r, 4, '项目')
|
||||||
|
ws.cell(r, 5, 1)
|
||||||
|
ws.cell(r, 6, 100)
|
||||||
|
wb.save(self.path)
|
||||||
|
|
||||||
|
def test_datetime_written_as_serial(self):
|
||||||
|
serial = self.paste._make_cell(9, 2, datetime(2026, 9, 30))
|
||||||
|
self.assertNotIn('inlineStr', serial)
|
||||||
|
self.assertIn('<v>', serial)
|
||||||
|
|
||||||
|
plain = self.paste._make_cell(9, 3, '美团')
|
||||||
|
self.assertIn('inlineStr', plain)
|
||||||
|
|
||||||
|
def test_patch_keeps_date_type_and_format(self):
|
||||||
|
rows = [['美团', datetime(2026, 9, 30), '门店A', '项目', 2, 258]] * 5
|
||||||
|
self.paste._write_master(self.path, [(SHEET, rows, 1, 2)])
|
||||||
|
|
||||||
|
wb = openpyxl.load_workbook(self.path, read_only=True)
|
||||||
|
try:
|
||||||
|
ws = wb[SHEET]
|
||||||
|
for r in (2, 5, 6):
|
||||||
|
cell = ws.cell(row=r, column=2)
|
||||||
|
self.assertIsInstance(cell.value, datetime, '第{}行日期应为 datetime'.format(r))
|
||||||
|
self.assertEqual(cell.value.date(), date(2026, 9, 30))
|
||||||
|
self.assertEqual(cell.number_format, FMT, '第{}行日期格式丢失'.format(r))
|
||||||
|
self.assertEqual(ws.cell(row=6, column=1).value, '美团')
|
||||||
|
self.assertEqual(ws.cell(row=6, column=5).value, 2)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
def test_empty_date_stays_empty(self):
|
||||||
|
rows = [['美团', None, '门店A', '项目', 1, 1]]
|
||||||
|
self.paste._write_master(self.path, [(SHEET, rows, 1, 2)])
|
||||||
|
wb = openpyxl.load_workbook(self.path, read_only=True)
|
||||||
|
try:
|
||||||
|
self.assertIsNone(wb[SHEET].cell(row=2, column=2).value)
|
||||||
|
finally:
|
||||||
|
wb.close()
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
@@ -0,0 +1,115 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""XQ0085 核对前置预检:缺明细 / 日期不符 / 同类多份必须拦截,且不能动表。
|
||||||
|
|
||||||
|
运行:.venv\\Scripts\\python.exe -m unittest tests.unit.test_xq0085_preflight -v
|
||||||
|
"""
|
||||||
|
import importlib
|
||||||
|
import os
|
||||||
|
import sys
|
||||||
|
import tempfile
|
||||||
|
import types
|
||||||
|
import unittest
|
||||||
|
from datetime import date
|
||||||
|
|
||||||
|
PLUGIN_DIR = os.path.join(
|
||||||
|
os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))),
|
||||||
|
'plugins', 'XQ0001-0100', 'XQ0085 团购数据核对')
|
||||||
|
PKG = 'xq85_preflight_test'
|
||||||
|
DAY = date(2026, 9, 30)
|
||||||
|
|
||||||
|
|
||||||
|
def _load_modules():
|
||||||
|
if PKG not in sys.modules:
|
||||||
|
pkg = types.ModuleType(PKG)
|
||||||
|
pkg.__path__ = [PLUGIN_DIR]
|
||||||
|
sys.modules[PKG] = pkg
|
||||||
|
cfg = importlib.import_module(PKG + '.config')
|
||||||
|
pf = importlib.import_module(PKG + '.logic.preflight')
|
||||||
|
return cfg, pf
|
||||||
|
|
||||||
|
|
||||||
|
class PreflightTest(unittest.TestCase):
|
||||||
|
def setUp(self):
|
||||||
|
self.tmp = tempfile.TemporaryDirectory()
|
||||||
|
self.root = self.tmp.name
|
||||||
|
self.cfg, self.pf = _load_modules()
|
||||||
|
self.cfg.set_work_dir(self.root, 'check_meituan')
|
||||||
|
for d in (self.cfg.WORK_DIR, self.cfg.OUT_DIR, os.path.join(self.root, '抖音'),
|
||||||
|
os.path.join(self.root, 'crm')):
|
||||||
|
os.makedirs(d, exist_ok=True)
|
||||||
|
self._touch(os.path.join(self.cfg.WORK_DIR, '美团9.30.xlsx'))
|
||||||
|
self._touch(os.path.join(self.cfg.WORK_DIR, '抖音9.30.xlsx'))
|
||||||
|
self._touch(os.path.join(self.cfg.WORK_DIR, '马敏团购总表9.30.xlsx'))
|
||||||
|
self._touch(os.path.join(self.root, 'crm', '团购支付数据-20260930.xlsx'))
|
||||||
|
self.crm_dir = os.path.join(self.root, 'crm')
|
||||||
|
|
||||||
|
def tearDown(self):
|
||||||
|
self.tmp.cleanup()
|
||||||
|
|
||||||
|
def _touch(self, path):
|
||||||
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||||
|
with open(path, 'w', encoding='utf-8') as f:
|
||||||
|
f.write('x')
|
||||||
|
|
||||||
|
def _detail(self, name, folder=None):
|
||||||
|
path = os.path.join(folder or self.cfg.OUT_DIR, name)
|
||||||
|
self._touch(path)
|
||||||
|
return path
|
||||||
|
|
||||||
|
def _run(self, action='check_meituan'):
|
||||||
|
self.cfg.set_work_dir(self.root, action)
|
||||||
|
return self.pf.run(day=DAY, action=action, crm_dir=self.crm_dir)
|
||||||
|
|
||||||
|
def test_all_ready(self):
|
||||||
|
self._detail('团购收益明细_20260930_20260930.xlsx')
|
||||||
|
self._detail('预订收益明细_20260930_20260930.xlsx')
|
||||||
|
res = self._run()
|
||||||
|
self.assertTrue(res['ok'], res['message'])
|
||||||
|
self.assertEqual(res['errors'], [])
|
||||||
|
|
||||||
|
def test_missing_group_detail_blocks(self):
|
||||||
|
res = self._run()
|
||||||
|
self.assertFalse(res['ok'])
|
||||||
|
self.assertTrue(any('团购收益明细' in c['name'] for c in res['errors']))
|
||||||
|
|
||||||
|
def test_booking_detail_optional(self):
|
||||||
|
self._detail('团购收益明细_20260930_20260930.xlsx')
|
||||||
|
res = self._run()
|
||||||
|
self.assertTrue(res['ok'], res['message'])
|
||||||
|
self.assertTrue(any('预订收益明细' in c['name'] for c in res['warns']))
|
||||||
|
|
||||||
|
def test_wrong_day_blocks(self):
|
||||||
|
self._detail('团购收益明细_20260928_20260929.xlsx')
|
||||||
|
res = self._run()
|
||||||
|
self.assertFalse(res['ok'])
|
||||||
|
self.assertTrue(any('不含营业日' in c['message'] for c in res['errors']))
|
||||||
|
|
||||||
|
def test_multiple_files_blocks(self):
|
||||||
|
self._detail('团购收益明细_20260930_20260930.xlsx')
|
||||||
|
self._detail('团购收益明细_20260929_20260929.xlsx')
|
||||||
|
res = self._run()
|
||||||
|
self.assertFalse(res['ok'])
|
||||||
|
self.assertTrue(any('串天' in c['message'] for c in res['errors']))
|
||||||
|
|
||||||
|
def test_missing_master_blocks(self):
|
||||||
|
self._detail('团购收益明细_20260930_20260930.xlsx')
|
||||||
|
os.remove(os.path.join(self.cfg.WORK_DIR, '马敏团购总表9.30.xlsx'))
|
||||||
|
res = self._run()
|
||||||
|
self.assertFalse(res['ok'])
|
||||||
|
self.assertTrue(any('总表' in c['name'] for c in res['errors']))
|
||||||
|
|
||||||
|
def test_douyin_branch_needs_detail_only(self):
|
||||||
|
self._detail('核销明细_2026-09-30_2026-09-30.xlsx',
|
||||||
|
os.path.join(self.root, '抖音'))
|
||||||
|
res = self._run('check_douyin')
|
||||||
|
self.assertTrue(res['ok'], res['message'])
|
||||||
|
|
||||||
|
def test_dates_in_name(self):
|
||||||
|
self.assertEqual(self.pf.dates_in_name('团购收益明细_20260930_20260930.xlsx'), [DAY])
|
||||||
|
self.assertEqual(self.pf.dates_in_name('核销明细_2026-09-29_2026-09-30.xlsx'),
|
||||||
|
[date(2026, 9, 29), DAY])
|
||||||
|
self.assertEqual(self.pf.dates_in_name('团购收益明细.xlsx'), [])
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == '__main__':
|
||||||
|
unittest.main()
|
||||||
Reference in New Issue
Block a user