feat(xq0041): 迁出美团/抖音核对,导表支持断点续传(v1.3.17)
This commit is contained in:
@@ -22,9 +22,10 @@ plugins/XQ0001-0100/XQ0041 新美大平台核对/
|
|||||||
│ ├── meituan_login.py # ensure_login:四态 classify、30s 残留会话试探、人工登录等待(_wait_backend)、
|
│ ├── meituan_login.py # ensure_login:四态 classify、30s 残留会话试探、人工登录等待(_wait_backend)、
|
||||||
│ │ # 登录态原子落盘四件套(_save_login_state)
|
│ │ # 登录态原子落盘四件套(_save_login_state)
|
||||||
│ ├── payment_download.py# 打款记录:iframe 定位、paymentlist 查询、10 分钟记录复用、paymentdownload
|
│ ├── payment_download.py# 打款记录:iframe 定位、paymentlist 查询、10 分钟记录复用、paymentdownload
|
||||||
│ │ # 生成(限流重试)、paymenthistory 轮询认领、直下落盘
|
│ │ # 生成(限流重试)、paymenthistory 轮询认领、直下落盘、超时记待续
|
||||||
│ └── profit_download.py # 收益明细:门店/类型取值、按类型完整性复用、request 生成、list 轮询
|
│ ├── profit_download.py # 收益明细:门店/类型取值、按类型完整性复用、request 生成、list 轮询
|
||||||
│ # (等全部 downloadStatus=2)、downloadLink 补取、逐文件直下
|
│ │ # (等所选类型 downloadStatus=2)、downloadLink 补取、逐文件直下
|
||||||
|
│ └── resume_state.py # 断点续传状态:待续任务(区间+记录 id)落盘/读取/清理
|
||||||
├── logic/
|
├── logic/
|
||||||
│ ├── __init__.py # 逻辑层包声明
|
│ ├── __init__.py # 逻辑层包声明
|
||||||
│ ├── merge_ledger.py # 台账增量合并:选表、真实末行/最大时间扫描、明细过滤、备份、
|
│ ├── merge_ledger.py # 台账增量合并:选表、真实末行/最大时间扫描、明细过滤、备份、
|
||||||
@@ -151,8 +152,11 @@ iframe 内实测 DOM 与对应动作(`_FILL_JS`):
|
|||||||
- 落盘前 `settle 8s` + 复检 backend,`_save_login_state` 原子写四件套(临时文件 + `os.replace`;Cookie 头按域过滤排除 passport/certificates/report/lx/dreport;storage 单值 >100KB 跳过)。
|
- 落盘前 `settle 8s` + 复检 backend,`_save_login_state` 原子写四件套(临时文件 + `os.replace`;Cookie 头按域过滤排除 passport/certificates/report/lx/dreport;storage 单值 >100KB 跳过)。
|
||||||
|
|
||||||
### 4. 两类下载(payment_download / profit_download)
|
### 4. 两类下载(payment_download / profit_download)
|
||||||
- 打款:`_find_frame` 按 `merchant-bill` 关键字 ≤30s 定位 iframe → 查询(`totalCount` 判空)→ 复用(`timeInterval` 含起始日 + `downloadLink` + `addTime ≤ REUSE_MAX_AGE_MIN(10) 分钟`)→ 生成(限流 `N 秒` 等待重试 ≤3,其它错误直接失败)→ 轮询认领(新增 id,120s 超时)→ 直下;
|
- 打款:`_find_frame` 按 `merchant-bill` 关键字 ≤30s 定位 iframe → 查询(`totalCount` 判空)→ 复用(`timeInterval` 含起始日 + `downloadLink` + `addTime ≤ REUSE_MAX_AGE_MIN(10) 分钟`;有续传状态时豁免时效)→ 有同区间「已登记未出链接」记录则**接着等不重复提交**,否则生成(限流 `N 秒` 等待重试 ≤3,其它错误直接失败)→ 轮询认领(跟踪 id,`RECORD_SECONDS` 单次 300s)→ 直下;超时不算失败,记待续并返回 `pending`;
|
||||||
- 收益:门店/类型取值(交集过滤)→ 拉近 30 天记录按 `productCodeName` 分组取最新 → **齐全且新鲜才复用,否则整体重新生成** → 生成同三分支 → 轮询等全部就绪 → 去重后逐文件取链接(空则 `downloadLink?id=` 补)→ 直下,至少 1 个成功即 ok;
|
- 收益:门店/类型取值(交集过滤)→ 拉近 30 天记录按 `productCodeName` 分组取最新 → **齐全且新鲜才复用,否则重新生成**(重新生成前清空旧记录,避免 5 分钟内没出表就把过期数据当结果)→ 有同区间未就绪记录则接着等,否则生成 → 轮询等所选类型全部就绪 → 去重后逐文件取链接(空则 `downloadLink?id=` 补)→ 直下,至少 1 个成功即 ok;超时把已就绪的先下载完,**平台有记录但没就绪**的类型记待续;**平台连记录都没有**的类型视为本次未产出(该业务可能无数据),WARN 跳过、不算待续,避免永远卡住;
|
||||||
|
- 断点续传(`data/resume_state.py`):待续任务落盘 `%LOCALAPPDATA%\37duAutomation\xq0041_pending.json`(键 `<公司>/<payment|profit>`,值含区间与记录 id),下次运行先按 id 认领、出表即下载,不重复提交生成任务;下载成功清键;**只有「团购收益明细」待续才跳过核对**(核对只读台账 + 团购明细),打款记录/预订明细待续照常核对;
|
||||||
|
- 下载方式 `download_mode`:`resume`(默认)按上面认领/复用;`fresh` 忽略续传状态与已有记录,一律重新提交生成任务(旧记录作废,避免半套数据)。两种方式都是**每张表最多等 300 秒**,没出就跳过记待续、继续下一张;收益明细一次任务产多张表,**按勾选类型数累计预算**(团购+预订=600 秒,全部出齐提前结束);待续表名汇总进 `detail.pending_tables`(多家导出带公司前缀),并写进本次 summary;
|
||||||
|
- 等待策略 `wait_mode`:`skip`(默认)按上面的 5 分钟/表跳过;`until_done` 不限时等所选表全部出齐(`deadline=None`,想一次跑完时用),只受执行机单次执行超时(壳默认 6 小时)与用户强停约束;状态在进等待前已落盘,被中断后下次运行按待续接着下载;
|
||||||
- `download_file`:`.part` 流式写入 → `os.replace` 原子替换;HTTP 非 200 / 异常 / <1024 字节均 WARN 重试 ≤3(间隔 2s),耗尽返回 0;`read_xlsx_summary` 用 openpyxl 只读核验 sheet 与行列数;
|
- `download_file`:`.part` 流式写入 → `os.replace` 原子替换;HTTP 非 200 / 异常 / <1024 字节均 WARN 重试 ≤3(间隔 2s),耗尽返回 0;`read_xlsx_summary` 用 openpyxl 只读核验 sheet 与行列数;
|
||||||
- `dry_run`:两类下载均提前返回 `[演练] …`,不生成不落盘。
|
- `dry_run`:两类下载均提前返回 `[演练] …`,不生成不落盘。
|
||||||
|
|
||||||
@@ -203,7 +207,10 @@ iframe 内实测 DOM 与对应动作(`_FILL_JS`):
|
|||||||
| `DETAIL_GLOB` / `HEADER_ROW` / `DATA_START_ROW` | `团购收益明细_*.xlsx` / `2` / `3` | 明细选表与表头行 |
|
| `DETAIL_GLOB` / `HEADER_ROW` / `DATA_START_ROW` | `团购收益明细_*.xlsx` / `2` / `3` | 明细选表与表头行 |
|
||||||
| `SHARE_ROOT` / `LINK_BOOK` / `LINK_SHEET` | `\\caiwu01\共享文件夹\1111\TG` / `马敏团购总表` / `资金组取数` | 外部引用工作簿与取数 sheet |
|
| `SHARE_ROOT` / `LINK_BOOK` / `LINK_SHEET` | `\\caiwu01\共享文件夹\1111\TG` / `马敏团购总表` / `资金组取数` | 外部引用工作簿与取数 sheet |
|
||||||
| `LOGIN_WAIT` / `BACKEND_STABLE` / `SETTLE_WAIT` / `POLL_SECONDS` | `600` / `20` / `8` / `2` | 人工登录超时 / 稳定判定 / 落盘前等待 / 轮询 |
|
| `LOGIN_WAIT` / `BACKEND_STABLE` / `SETTLE_WAIT` / `POLL_SECONDS` | `600` / `20` / `8` / `2` | 人工登录超时 / 稳定判定 / 落盘前等待 / 轮询 |
|
||||||
| `RECORD_SECONDS` / `REUSE_MAX_AGE_MIN` | `120` / `10` | 账单生成轮询上限 / 复用时效(分钟) |
|
| `RECORD_SECONDS` / `REUSE_MAX_AGE_MIN` | `300` / `10` | 单次等待出表上限(超时记待续)/ 复用时效(分钟) |
|
||||||
|
| `PENDING_STATE_PATH` | `%LOCALAPPDATA%\37duAutomation\xq0041_pending.json` | 断点续传状态(待续任务的记录 id) |
|
||||||
|
| `DOWNLOAD_MODES` | `resume` / `fresh` | 下载方式:断点续传(默认)/ 全新下载(强制重新提交) |
|
||||||
|
| `WAIT_MODES` | `skip` / `until_done` | 等待策略:每表 5 分钟跳过(默认)/ 一次等到底(不限时) |
|
||||||
| `RETRY_MAX` / `HEADLESS` | `3` / `False` | 全局重试次数 / 必须可见浏览器 |
|
| `RETRY_MAX` / `HEADLESS` | `3` / `False` | 全局重试次数 / 必须可见浏览器 |
|
||||||
| `SESSIONS_DIR` 及四件套 | `%LOCALAPPDATA%\37duAutomation\.sessions\meituan_*` | 登录态快照(cookies/header/tokens/meta) |
|
| `SESSIONS_DIR` 及四件套 | `%LOCALAPPDATA%\37duAutomation\.sessions\meituan_*` | 登录态快照(cookies/header/tokens/meta) |
|
||||||
| `get_browser_profile_dir()` | `%LOCALAPPDATA%\37duAutomation\browser_sessions\xq0041` | 独立浏览器 profile(登录态跨次保留) |
|
| `get_browser_profile_dir()` | `%LOCALAPPDATA%\37duAutomation\browser_sessions\xq0041` | 独立浏览器 profile(登录态跨次保留) |
|
||||||
@@ -214,7 +221,7 @@ iframe 内实测 DOM 与对应动作(`_FILL_JS`):
|
|||||||
- 登录超时 / 落盘前离开后台 → `ensure_login` 返回失败 → RuntimeError「登录失败:…」;读 Cookies、storage、窗口全屏/置顶失败 → WARN 降级继续;
|
- 登录超时 / 落盘前离开后台 → `ensure_login` 返回失败 → RuntimeError「登录失败:…」;读 Cookies、storage、窗口全屏/置顶失败 → WARN 降级继续;
|
||||||
- 页面接口非 200 / 非 JSON → WARN + 返回 None,进入「重试 ≤3 → 业务分支判失败」链路;
|
- 页面接口非 200 / 非 JSON → WARN + 返回 None,进入「重试 ≤3 → 业务分支判失败」链路;
|
||||||
- 生成任务:限流按「N 秒」提示等待重试 ≤3 次(可恢复),其它业务错误直接失败不重试(防重复创建任务);
|
- 生成任务:限流按「N 秒」提示等待重试 ≤3 次(可恢复),其它业务错误直接失败不重试(防重复创建任务);
|
||||||
- 记录 120 秒未生成 / 缺 downloadLink / 全部下载失败 → 判失败;下载非 200 / 异常 / <1KB → 重试 3 次后判失败;单文件失败(收益)WARN 跳过,凑不齐 1 个才整体失败;
|
- 记录 300 秒未出表 → **不算失败**:已就绪的先下载,剩余记待续(`pending`),下次运行接着等;缺 downloadLink / 全部下载失败 → 判失败;下载非 200 / 异常 / <1KB → 重试 3 次后判失败;单文件失败(收益)WARN 跳过,凑不齐 1 个才整体失败;
|
||||||
- 台账/明细选表、sheet、表头、时间列任何缺失 → ok=False message → RuntimeError「并入台账失败:…」;sheet XML 结构异常 → RuntimeError 且不改原文件;
|
- 台账/明细选表、sheet、表头、时间列任何缺失 → ok=False message → RuntimeError「并入台账失败:…」;sheet XML 结构异常 → RuntimeError 且不改原文件;
|
||||||
- 更新核对统计失败(缺 sheet / 无日期行 / 补链异常)→ 仅 WARN 不中断;日期行缺失、行 XML 缺失 → WARN 跳过;共享盘不可达 → WARN 照写公式;
|
- 更新核对统计失败(缺 sheet / 无日期行 / 补链异常)→ 仅 WARN 不中断;日期行缺失、行 XML 缺失 → WARN 跳过;共享盘不可达 → WARN 照写公式;
|
||||||
- 失败即整段终止并带类目前缀(登录/打款记录/收益明细/并入台账),浏览器由 `finally` 保证关闭,已成功落盘的文件不回滚;
|
- 失败即整段终止并带类目前缀(登录/打款记录/收益明细/并入台账),浏览器由 `finally` 保证关闭,已成功落盘的文件不回滚;
|
||||||
@@ -234,4 +241,4 @@ npm run build
|
|||||||
.venv\Scripts\python.exe tools\agent_cli.py publish dist-plugin\xq0041_v1.1.7.zip --id xq0041 --version 1.1.7 --admin puddy --password 123456 --base http://172.30.30.243:8800
|
.venv\Scripts\python.exe tools\agent_cli.py publish dist-plugin\xq0041_v1.1.7.zip --id xq0041 --version 1.1.7 --admin puddy --password 123456 --base http://172.30.30.243:8800
|
||||||
```
|
```
|
||||||
|
|
||||||
产物:`dist-plugin/xq0041_v<版本>.zip`(zip 根含 plugin.json,排除 `ui-src`、`__pycache__`、`debug`、`.sessions`、`_pack.py`、`*.pyc`)。依赖:`DrissionPage>=4.1`、`requests>=2.28`、`openpyxl>=3.1`(requirements.txt 声明)。运行超时未单独声明(跟随壳默认 6 小时,可在客户端设置页调整;人工登录最长 600 秒、账单轮询 120 秒/类目)。
|
产物:`dist-plugin/xq0041_v<版本>.zip`(zip 根含 plugin.json,排除 `ui-src`、`__pycache__`、`debug`、`.sessions`、`_pack.py`、`*.pyc`)。依赖:`DrissionPage>=4.1`、`requests>=2.28`、`openpyxl>=3.1`(requirements.txt 声明)。运行超时未单独声明(跟随壳默认 6 小时,可在客户端设置页调整;人工登录最长 600 秒、账单单次等待 300 秒/类目,超时记待续下次续传)。
|
||||||
|
|||||||
@@ -31,14 +31,14 @@
|
|||||||
│ ├─ 同区间记录 ≤10 分钟 → 复用;否则 POST paymentdownload
|
│ ├─ 同区间记录 ≤10 分钟 → 复用;否则 POST paymentdownload
|
||||||
│ │ (限流「N 秒」→ 等 N+3s 重试 ≤3;其它错误直接失败)
|
│ │ (限流「N 秒」→ 等 N+3s 重试 ≤3;其它错误直接失败)
|
||||||
│ ├─ GET paymenthistory 轮询新增记录
|
│ ├─ GET paymenthistory 轮询新增记录
|
||||||
│ │ (必须带 downloadFileType=6 + 分页,120s 超时)
|
│ │ (必须带 downloadFileType=6 + 分页,单次 300s,超时记待续)
|
||||||
│ └─ requests 直下 downloadLink → 打款记录_起_止.xlsx [45% / 65%]
|
│ └─ requests 直下 downloadLink → 打款记录_起_止.xlsx [45% / 65%]
|
||||||
├─ [codes=1/11] profit_download.download
|
├─ [codes=1/11] profit_download.download
|
||||||
│ ├─ 收益明细页 → queryAllShopIds(空→[0])+ productCodeList(1团购/11预订)
|
│ ├─ 收益明细页 → queryAllShopIds(空→[0])+ productCodeList(1团购/11预订)
|
||||||
│ ├─ 近 30 天记录:勾选类型齐全且均 ≤10 分钟 → 复用;
|
│ ├─ 近 30 天记录:勾选类型齐全且均 ≤10 分钟 → 复用;
|
||||||
│ │ 任一缺失/过期 → 整体重新生成(防「只拿到团购、预订缺失」半套数据)
|
│ │ 任一缺失/过期 → 整体重新生成(防「只拿到团购、预订缺失」半套数据)
|
||||||
│ ├─ POST request(downloadFileType=201,限流同打款三分支)
|
│ ├─ POST request(downloadFileType=201,限流同打款三分支)
|
||||||
│ ├─ GET list 轮询:新增记录全部 downloadStatus=2 才收齐(120s 超时)
|
│ ├─ GET list 轮询:所选类型全部 downloadStatus=2 才收齐(单次 300s,超时先下已就绪、剩余待续)
|
||||||
│ └─ downloadLink(空则 downloadLink?id= 补取)→ 逐文件直下 [60% / 95%]
|
│ └─ downloadLink(空则 downloadLink?id= 补取)→ 逐文件直下 [60% / 95%]
|
||||||
└─ finally:browser.close_page(无论成败关闭浏览器)
|
└─ finally:browser.close_page(无论成败关闭浏览器)
|
||||||
└─> [do_reconcile] merge_ledger.run [65% / 10%]
|
└─> [do_reconcile] merge_ledger.run [65% / 10%]
|
||||||
@@ -86,14 +86,14 @@
|
|||||||
- 打开 `PAYMENT_PAGE_URL`(`e.dianping.com/app/merchant-platform/…?iUrl=…` 外壳 → iframe `h5.dianping.com/app/merchant-bill-static/index.html#/paymentrecord`),`_find_frame` 按 URL 关键字 `merchant-bill` 轮询定位 iframe(≤30 秒),找不到 → 失败「未找到账单 iframe(登录态可能已失效)」;
|
- 打开 `PAYMENT_PAGE_URL`(`e.dianping.com/app/merchant-platform/…?iUrl=…` 外壳 → iframe `h5.dianping.com/app/merchant-bill-static/index.html#/paymentrecord`),`_find_frame` 按 URL 关键字 `merchant-bill` 轮询定位 iframe(≤30 秒),找不到 → 失败「未找到账单 iframe(登录态可能已失效)」;
|
||||||
- ① 查询 `POST /gw/smartBill/paymentlist`(`payTime=起,止`、`pageIndex=0/pageSize=10`,页面同款顺序:先查出数据下载按钮才可用):`totalCount=0` → 失败「{起}~{止} 没有打款记录」;
|
- ① 查询 `POST /gw/smartBill/paymentlist`(`payTime=起,止`、`pageIndex=0/pageSize=10`,页面同款顺序:先查出数据下载按钮才可用):`totalCount=0` → 失败「{起}~{止} 没有打款记录」;
|
||||||
- ② 复用判定:`GET paymenthistory` 里 `timeInterval` 含起始日、有 `downloadLink`、`addTime` 距今 ≤10 分钟的记录 → 直接复用(不重复生成,规避限流);过期或没有 → `POST /gw/smartBill/paymentdownload`(同查询条件 + `downloadFileType=6`),成功判定 `code==200`;限流时解析 message 中「N 秒」等待 `N+3` 秒后重试(≤3 次),其它错误直接失败;
|
- ② 复用判定:`GET paymenthistory` 里 `timeInterval` 含起始日、有 `downloadLink`、`addTime` 距今 ≤10 分钟的记录 → 直接复用(不重复生成,规避限流);过期或没有 → `POST /gw/smartBill/paymentdownload`(同查询条件 + `downloadFileType=6`),成功判定 `code==200`;限流时解析 message 中「N 秒」等待 `N+3` 秒后重试(≤3 次),其它错误直接失败;
|
||||||
- ③ 轮询 `GET paymenthistory?pageIndex=0&pageSize=20&downloadFileType=6`(**必须带 `downloadFileType` 与分页参数,缺了 `code=500`**),按「新增 id(不在生成前 id 集合)+ `timeInterval` 含起始日」认领本次记录,120 秒超时 → 失败;
|
- ③ 轮询 `GET paymenthistory?pageIndex=0&pageSize=20&downloadFileType=6`(**必须带 `downloadFileType` 与分页参数,缺了 `code=500`**),按「新增 id(不在生成前 id 集合)+ `timeInterval` 含起始日」认领本次记录;单次只等 300 秒,超时把跟踪的 id 落盘(`xq0041_pending.json`)并返回 `pending`;下次运行发现同区间「已登记未出链接」记录就直接接着等,出表即下载,不重复提交生成任务;
|
||||||
- ④ `browser.download_file`:requests 流式下载预签名 `downloadLink`(UA 头、300s 超时、128KB 分块)写 `.part`,HTTP 非 200 / 异常 / 文件 <1024 字节均删除重试 ≤3 次(间隔 2s),成功 `os.replace` 原子落盘 → `打款记录_YYYYMMDD[_YYYYMMDD].xlsx`;随后 `read_xlsx_summary`(openpyxl 只读)核对 sheet/行列数并输出大小。
|
- ④ `browser.download_file`:requests 流式下载预签名 `downloadLink`(UA 头、300s 超时、128KB 分块)写 `.part`,HTTP 非 200 / 异常 / 文件 <1024 字节均删除重试 ≤3 次(间隔 2s),成功 `os.replace` 原子落盘 → `打款记录_YYYYMMDD[_YYYYMMDD].xlsx`;随后 `read_xlsx_summary`(openpyxl 只读)核对 sheet/行列数并输出大小。
|
||||||
|
|
||||||
### 4. 收益明细下载(进度 → 60%/95%,codes 非空时)
|
### 4. 收益明细下载(进度 → 60%/95%,codes 非空时)
|
||||||
- 打开 `PROFIT_PAGE_URL`(`e.dianping.com/finance/web/payment/download/list`)+ 4 秒首屏等待;
|
- 打开 `PROFIT_PAGE_URL`(`e.dianping.com/finance/web/payment/download/list`)+ 4 秒首屏等待;
|
||||||
- ① `GET queryAllShopIds` → `data.availableShopIds`(空 → WARN 回退 `[0]` 全部门店);`GET productCodeList` → `[{1,团购},{11,预订}]`,`want = 勾选 codes ∩ 平台类型`(交集为空 → 全要);
|
- ① `GET queryAllShopIds` → `data.availableShopIds`(空 → WARN 回退 `[0]` 全部门店);`GET productCodeList` → `[{1,团购},{11,预订}]`,`want = 勾选 codes ∩ 平台类型`(交集为空 → 全要);
|
||||||
- ② 复用判定:拉近 30 天记录,按 `timeInterval` 含起始日 + `downloadStatus==2` 过滤,按 `productCodeName` 分组取最新;**勾选的每个类型都有记录且全部 ≤10 分钟** → 复用;任一类型缺失或过期 → 整体重新生成(保证团购 + 预订一次任务同时产出、两份都就绪);
|
- ② 复用判定:拉近 30 天记录,按 `timeInterval` 含起始日 + `downloadStatus==2` 过滤,按 `productCodeName` 分组取最新;**勾选的每个类型都有记录且全部 ≤10 分钟** → 复用;任一类型缺失或过期 → 整体重新生成(保证团购 + 预订一次任务同时产出、两份都就绪);
|
||||||
- ③ `POST downloadManagement/request`(`beginDate/endDate`、`productCodeList=want`、`shopIdList`、`downloadFileType=201`),`code==200` 受理;限流「N 秒」→ 等 `N+3` 秒重试 ≤3,其它错误直接失败;随后轮询 `GET list?pageSize=20&pageNum=1&beginDate&endDate`,按新增 id + `timeInterval` 认领,`downloadStatus==2` 为就绪、非 2 为生成中,**等全部就绪才 break**(120 秒超时 → 失败);
|
- ③ `POST downloadManagement/request`(`beginDate/endDate`、`productCodeList=want`、`shopIdList`、`downloadFileType=201`),`code==200` 受理;限流「N 秒」→ 等 `N+3` 秒重试 ≤3,其它错误直接失败;随后轮询 `GET list?pageSize=20&pageNum=1&beginDate&endDate`,按新增 id + `timeInterval` 认领,`downloadStatus==2` 为就绪、非 2 为生成中,**等所选类型全部就绪才 break**;预算=每类 300 秒 × 勾选类型数(团购+预订=600 秒,出齐提前结束),超时 → 已就绪的先下载,剩余类型记待续(`pending`),下次运行接着等;
|
||||||
- ④ 同类型去重取最新,逐文件取 `downloadLink`(为空 → `GET downloadLink?id=<记录id>` 补取,仍空 → WARN 跳过该文件),requests 直下 → `团购收益明细_起_止.xlsx` / `预订收益明细_起_止.xlsx`;至少 1 个成功即 `ok=True`,全部失败 → 失败「收益明细全部下载失败」;
|
- ④ 同类型去重取最新,逐文件取 `downloadLink`(为空 → `GET downloadLink?id=<记录id>` 补取,仍空 → WARN 跳过该文件),requests 直下 → `团购收益明细_起_止.xlsx` / `预订收益明细_起_止.xlsx`;至少 1 个成功即 `ok=True`,全部失败 → 失败「收益明细全部下载失败」;
|
||||||
- `finally: browser.close_page(page)`:登录失败、任一类目下载失败、异常冒泡均保证浏览器关闭。
|
- `finally: browser.close_page(page)`:登录失败、任一类目下载失败、异常冒泡均保证浏览器关闭。
|
||||||
|
|
||||||
@@ -141,7 +141,10 @@
|
|||||||
| 打款查询 totalCount=0 | 判失败「{起}~{止} 没有打款记录」 |
|
| 打款查询 totalCount=0 | 判失败「{起}~{止} 没有打款记录」 |
|
||||||
| 生成任务命中限流(message 含「N 秒」) | 等 N+3 秒后重试,最多 3 次 |
|
| 生成任务命中限流(message 含「N 秒」) | 等 N+3 秒后重试,最多 3 次 |
|
||||||
| 生成任务提交失败(其它错误 / 3 次耗尽 / 无响应) | 判失败「生成任务提交失败:{msg}」 |
|
| 生成任务提交失败(其它错误 / 3 次耗尽 / 无响应) | 判失败「生成任务提交失败:{msg}」 |
|
||||||
| 打款/收益记录 120 秒未生成完成 | 判失败(「120s 内未拿到可下载记录」/「未拿到可下载的收益明细」) |
|
| 单张表 300 秒未出表 | 跳过这张表、记待续(`pending` + `pending_tables`),继续下一张;下次运行接着查;仅「团购收益明细」待续时跳过核对 |
|
||||||
|
| 平台上连记录都没有的收益类型 | 视为本次未产出(业务可能无数据)→ WARN 跳过,不记待续,避免永远卡在待续 |
|
||||||
|
| 下载方式选「全新下载」(`download_mode=fresh`) | 忽略待续状态与已有记录,一律重新提交生成任务;仍按每张表 300 秒跳过/记待续 |
|
||||||
|
| 等待策略选「一次等到底」(`wait_mode=until_done`) | 不限时等所选表全部出齐(收益按张数累计、出齐提前结束);受执行机单次执行超时(默认 6 小时)与强停约束,被中断也留待续状态 |
|
||||||
| 打款记录缺 downloadLink | 判失败「记录里没有 downloadLink(可能仍在生成)」 |
|
| 打款记录缺 downloadLink | 判失败「记录里没有 downloadLink(可能仍在生成)」 |
|
||||||
| 收益记录 downloadLink 为空 | 用 `downloadLink?id=` 补取;仍空 WARN 跳过该文件 |
|
| 收益记录 downloadLink 为空 | 用 `downloadLink?id=` 补取;仍空 WARN 跳过该文件 |
|
||||||
| 收益部分文件成功、部分失败 | 至少 1 个成功即整体成功;全部失败才判失败 |
|
| 收益部分文件成功、部分失败 | 至少 1 个成功即整体成功;全部失败才判失败 |
|
||||||
|
|||||||
@@ -20,8 +20,8 @@
|
|||||||
对美团经营宝(`ecom.meituan.com` 登录,后端点评商家平台 `e.dianping.com` 取数)做账单自动下载与本地台账核对:打开官方页面(登录态复用本机固定 profile,过期时人工完成登录含选商家),按日期区间下载**打款记录**(h5 账单 iframe,按打款时间)与**团购/预订收益明细**(PC 商户中心,按验券时间),再把新产生的收益**增量并入月份台账**(AF~AP 公式同步下拉),最后按日期把核对统计表整行的「马敏团购总表」同源取数公式换成当天那份文件:
|
对美团经营宝(`ecom.meituan.com` 登录,后端点评商家平台 `e.dianping.com` 取数)做账单自动下载与本地台账核对:打开官方页面(登录态复用本机固定 profile,过期时人工完成登录含选商家),按日期区间下载**打款记录**(h5 账单 iframe,按打款时间)与**团购/预订收益明细**(PC 商户中心,按验券时间),再把新产生的收益**增量并入月份台账**(AF~AP 公式同步下拉),最后按日期把核对统计表整行的「马敏团购总表」同源取数公式换成当天那份文件:
|
||||||
|
|
||||||
1. 登录:打开经营宝 → 30 秒内残留会话有效直接复用(不打扰人工),否则全屏置顶窗口等人工登录 ≤600 秒(账密/短信/扫码 + **手动选商家**),「进入后台连续稳定 20 秒」判定完成,登录态原子落盘 `meituan_*` 四件套;
|
1. 登录:打开经营宝 → 30 秒内残留会话有效直接复用(不打扰人工),否则全屏置顶窗口等人工登录 ≤600 秒(账密/短信/扫码 + **手动选商家**),「进入后台连续稳定 20 秒」判定完成,登录态原子落盘 `meituan_*` 四件套;
|
||||||
2. 打款记录下载:定位 `merchant-bill` iframe → 查询(0 条判失败)→ 同区间记录 ≤10 分钟复用否则生成(限流「N 秒」等待重试 ≤3)→ 轮询 `paymenthistory` 认领(120s 超时)→ 预签名 `downloadLink` requests 直下;
|
2. 打款记录下载:定位 `merchant-bill` iframe → 查询(0 条判失败)→ 同区间记录 ≤10 分钟复用否则生成(限流「N 秒」等待重试 ≤3)→ 轮询 `paymenthistory` 认领(单次 300s,超时记待续下次续传)→ 预签名 `downloadLink` requests 直下;
|
||||||
3. 收益明细下载:取门店(空回退全部)与类型(团购 1 / 预订 11)→ 近 30 天记录**按类型齐全且 ≤10 分钟**才复用、否则整体重新生成 → 生成后轮询等**全部** `downloadStatus=2` → 链接空则补取 → 逐文件直下;
|
3. 收益明细下载:取门店(空回退全部)与类型(团购 1 / 预订 11)→ 近 30 天记录**按类型齐全且 ≤10 分钟**才复用、否则重新生成 → 生成后轮询等**所选类型全部** `downloadStatus=2`(每类 300s 累计,2 类共 600s,出齐提前结束;超时先下已就绪的、剩余记待续)→ 链接空则补取 → 逐文件直下;
|
||||||
4. 并入台账:取月份最新台账与最新明细,按「验券/退款/调整时间」最大时间过滤新行,`shutil.copy2` 备份后**只改目标 sheet 的 XML**(清尾部空公式行、`</sheetData>` 前插行、更新 dimension、AF~AP 内联/共享公式逐行下拉),其余部件逐字节拷贝;
|
4. 并入台账:取月份最新台账与最新明细,按「验券/退款/调整时间」最大时间过滤新行,`shutil.copy2` 备份后**只改目标 sheet 的 XML**(清尾部空公式行、`</sheetData>` 前插行、更新 dimension、AF~AP 内联/共享公式逐行下拉),其余部件逐字节拷贝;
|
||||||
5. 更新核对统计:按 A 列日期定位行号(纯核对时整表所有日期行,幂等),扫整行所有 `[n]资金组取数!$B$xx` 同源公式(实测 V/W/Y/Z)把 `[n]` 换成当天那份总表的链接,已是目标编号的单元格保留不动;外部链接能复用复用、缺的同步维护 5 处部件新增;共享盘不可达仅告警、公式照写;
|
5. 更新核对统计:按 A 列日期定位行号(纯核对时整表所有日期行,幂等),扫整行所有 `[n]资金组取数!$B$xx` 同源公式(实测 V/W/Y/Z)把 `[n]` 换成当天那份总表的链接,已是目标编号的单元格保留不动;外部链接能复用复用、缺的同步维护 5 处部件新增;共享盘不可达仅告警、公式照写;
|
||||||
6. 结果输出:三类 xlsx 落保存目录(默认 `D:\资料\财务\新美大平台核对`),summary 汇报下载文件数/并入行数/补链行数;失败语义:登录、打款、收益、并入台账失败报错终止,补链失败仅告警不中断。
|
6. 结果输出:三类 xlsx 落保存目录(默认 `D:\资料\财务\新美大平台核对`),summary 汇报下载文件数/并入行数/补链行数;失败语义:登录、打款、收益、并入台账失败报错终止,补链失败仅告警不中断。
|
||||||
@@ -52,11 +52,11 @@
|
|||||||
14. 打款查询空数据分支:`totalCount=0` → 判「没有打款记录」失败,不发起生成;
|
14. 打款查询空数据分支:`totalCount=0` → 判「没有打款记录」失败,不发起生成;
|
||||||
15. 打款记录复用分支:`timeInterval` 匹配 + 有 `downloadLink` + 生成时间 ≤10 分钟 → 复用;过期重新生成;
|
15. 打款记录复用分支:`timeInterval` 匹配 + 有 `downloadLink` + 生成时间 ≤10 分钟 → 复用;过期重新生成;
|
||||||
16. 打款生成限流分支:message 解析「N 秒」→ 等 N+3 秒重试(≤3 次);其它业务错误直接失败不重试;
|
16. 打款生成限流分支:message 解析「N 秒」→ 等 N+3 秒重试(≤3 次);其它业务错误直接失败不重试;
|
||||||
17. 打款记录认领:`paymenthistory` 新增 id + `timeInterval` 匹配,120 秒超时判失败;
|
17. 打款记录认领:`paymenthistory` 新增 id + `timeInterval` 匹配,单次 300 秒未出表 → 待续(不算失败,下次运行接着下载);
|
||||||
18. 收益门店与类型取值:`availableShopIds` 空 → 回退 `[0]` 全部;`want` = 勾选 ∩ 平台类型,交集空则全要;
|
18. 收益门店与类型取值:`availableShopIds` 空 → 回退 `[0]` 全部;`want` = 勾选 ∩ 平台类型,交集空则全要;
|
||||||
19. 收益复用完整性判断:勾选类型齐全且均 ≤10 分钟 → 复用;任一缺失/过期 → 整体重新生成(防半套数据);
|
19. 收益复用完整性判断:勾选类型齐全且均 ≤10 分钟 → 复用;任一缺失/过期 → 整体重新生成(防半套数据);
|
||||||
20. 收益生成限流分支:与打款同三分支(限流等待重试 / 提交失败);
|
20. 收益生成限流分支:与打款同三分支(限流等待重试 / 提交失败);
|
||||||
21. 收益轮询双态:新记录 `downloadStatus=2` 就绪、非 2 生成中,等**全部就绪**才收齐(120s 超时);
|
21. 收益轮询双态:新记录 `downloadStatus=2` 就绪、非 2 生成中,等**所选类型全部就绪**才收齐(预算=每类 300 秒×类型数,出齐提前结束;超时先下已就绪、剩余待续);
|
||||||
22. 收益链接补取:记录 `downloadLink` 为空 → `downloadLink?id=` 二次取;仍空 → WARN 跳过该文件;
|
22. 收益链接补取:记录 `downloadLink` 为空 → `downloadLink?id=` 二次取;仍空 → WARN 跳过该文件;
|
||||||
23. 收益部分成功判定:至少 1 个文件成功即 ok;全部失败才判失败;
|
23. 收益部分成功判定:至少 1 个文件成功即 ok;全部失败才判失败;
|
||||||
24. `dry_run` 演练分支:下载只报将做什么,台账/统计只报行数,不落盘不改文件;
|
24. `dry_run` 演练分支:下载只报将做什么,台账/统计只报行数,不落盘不改文件;
|
||||||
@@ -91,9 +91,9 @@
|
|||||||
12. 打款查询失败 / `totalCount=0` → 分别判「打款记录查询失败」「{起}~{止} 没有打款记录」;
|
12. 打款查询失败 / `totalCount=0` → 分别判「打款记录查询失败」「{起}~{止} 没有打款记录」;
|
||||||
13. 生成任务命中限流(message 含「N 秒」)→ 等 N+3 秒重试 ≤3 次(可恢复异常);
|
13. 生成任务命中限流(message 含「N 秒」)→ 等 N+3 秒重试 ≤3 次(可恢复异常);
|
||||||
14. 生成任务提交失败(其它业务错误 / 3 次耗尽 / 无响应)→ 判失败「生成任务提交失败:{msg}」(不重复创建任务);
|
14. 生成任务提交失败(其它业务错误 / 3 次耗尽 / 无响应)→ 判失败「生成任务提交失败:{msg}」(不重复创建任务);
|
||||||
15. 打款记录 120 秒未生成 → 判失败「120s 内未拿到可下载记录」;
|
15. 打款记录 300 秒未出表 → 不判失败:记待续,下次运行接着等并直接下载;
|
||||||
16. 打款记录缺 `downloadLink` → 判失败「记录里没有 downloadLink(可能仍在生成)」;
|
16. 打款记录缺 `downloadLink` → 判失败「记录里没有 downloadLink(可能仍在生成)」;
|
||||||
17. 收益明细 120 秒未收齐 → 判失败「未拿到可下载的收益明细(120s 内未完成)」;
|
17. 收益明细 300 秒未收齐 → 先下载已就绪的类型;平台有记录但没就绪的类型记待续(下次续传),平台连记录都没有的类型视为未产出,WARN 跳过、不算待续;
|
||||||
18. 收益记录 `downloadLink` 取不到 → WARN 跳过该文件;全部取不到/下载失败 → 判失败「收益明细全部下载失败」;
|
18. 收益记录 `downloadLink` 取不到 → WARN 跳过该文件;全部取不到/下载失败 → 判失败「收益明细全部下载失败」;
|
||||||
19. 文件下载 HTTP 非 200 / 网络异常 / <1024 字节(坏文件)→ 各 WARN 重试 ≤3 次(间隔 2s、`.part` 原子替换),耗尽返回 0 判失败;
|
19. 文件下载 HTTP 非 200 / 网络异常 / <1024 字节(坏文件)→ 各 WARN 重试 ≤3 次(间隔 2s、`.part` 原子替换),耗尽返回 0 判失败;
|
||||||
20. 门店列表取不到 → WARN 回退 `[0]`(全部门店)继续;
|
20. 门店列表取不到 → WARN 回退 `[0]`(全部门店)继续;
|
||||||
|
|||||||
@@ -5,9 +5,10 @@
|
|||||||
|
|
||||||
* ``download`` → 只导表:登录经营宝下载打款记录 / 团购收益明细 / 预订收益明细;
|
* ``download`` → 只导表:登录经营宝下载打款记录 / 团购收益明细 / 预订收益明细;
|
||||||
* ``check_settlement`` → 到账统计核对:新美大到账统计的核对
|
* ``check_settlement`` → 到账统计核对:新美大到账统计的核对
|
||||||
(并入台账 → 门店归属 → 更新核对统计)。
|
(并入台账 → 更新核对统计)。
|
||||||
|
|
||||||
美团核对 / 抖音核对已迁到 XQ0085 团购数据核对插件,本插件不再做。
|
美团核对 / 抖音核对 / 门店归属(CRM 券号)都已迁到 XQ0085 团购数据核对插件,
|
||||||
|
本插件只做导表与到账统计表维护,不再声明 crm_sdk 依赖。
|
||||||
|
|
||||||
``download_before`` 可在核对前先下载;不勾则读本机已有表(只校验文件存在)。
|
``download_before`` 可在核对前先下载;不勾则读本机已有表(只校验文件存在)。
|
||||||
|
|
||||||
@@ -28,7 +29,7 @@ from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
|||||||
|
|
||||||
from . import config
|
from . import config
|
||||||
from .data import browser, meituan_login, payment_download, profit_download
|
from .data import browser, meituan_login, payment_download, profit_download
|
||||||
from .logic import merge_ledger, stat_links, store_map
|
from .logic import merge_ledger, stat_links
|
||||||
|
|
||||||
|
|
||||||
def _parse_day(s):
|
def _parse_day(s):
|
||||||
@@ -85,12 +86,15 @@ def _missing_inputs(action, work_dir):
|
|||||||
class Xq0041Plugin(ScenePlugin):
|
class Xq0041Plugin(ScenePlugin):
|
||||||
id = 'xq0041'
|
id = 'xq0041'
|
||||||
name = '新美大平台核对'
|
name = '新美大平台核对'
|
||||||
version = '1.3.13'
|
version = '1.3.17'
|
||||||
description = ('美团数据导出与到账统计核对:两个独立动作——「只导表」(下载打款记录/团购/'
|
description = ('美团数据导出与到账统计核对:两个独立动作——「只导表」(下载打款记录/团购/'
|
||||||
'预订收益明细)、「到账统计核对」(新美大到账统计:并台账 → 门店归属 → '
|
'预订收益明细)、「到账统计核对」(新美大到账统计:并入台账 → 更新核对统计)。'
|
||||||
'更新核对统计)。美团核对与抖音核对已迁到 XQ0085 团购数据核对插件。'
|
'美团核对/抖音核对/门店归属已迁到 XQ0085 团购数据核对插件。'
|
||||||
'界面可配账号密码自动填好,登录/验证码/选商家/选版本由人工完成;'
|
'界面可配账号密码自动填好,登录/验证码/选商家/选版本由人工完成;'
|
||||||
'金色印象与金色湖畔各自独立浏览器档案与调试端口,登录态互不干扰')
|
'金色印象与金色湖畔各自独立浏览器档案与调试端口,登录态互不干扰;'
|
||||||
|
'导表支持断点续传:每张表最多等 5 分钟(团购+预订合计 10 分钟,出齐提前结束),'
|
||||||
|
'没出就跳过记待续,下次运行接着下载;界面可切「断点续传 / 全新下载」'
|
||||||
|
'与「每表 5 分钟跳过 / 一次等到底」')
|
||||||
platform = '' # 插件自带登录(经营宝 SSO + 选商家),不用底座共享登录态
|
platform = '' # 插件自带登录(经营宝 SSO + 选商家),不用底座共享登录态
|
||||||
uses_month = False
|
uses_month = False
|
||||||
capabilities = ['xq0041']
|
capabilities = ['xq0041']
|
||||||
@@ -105,6 +109,11 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
'format': 'password'},
|
'format': 'password'},
|
||||||
'run_mode': {'type': 'string', 'title': '执行模式', 'default': config.RUN_MODE_FULL,
|
'run_mode': {'type': 'string', 'title': '执行模式', 'default': config.RUN_MODE_FULL,
|
||||||
'enum': [config.RUN_MODE_FULL, config.RUN_MODE_EXPORT_ONLY]},
|
'enum': [config.RUN_MODE_FULL, config.RUN_MODE_EXPORT_ONLY]},
|
||||||
|
'download_mode': {'type': 'string', 'title': '下载方式',
|
||||||
|
'default': config.DOWNLOAD_MODE_RESUME,
|
||||||
|
'enum': list(config.DOWNLOAD_MODES)},
|
||||||
|
'wait_mode': {'type': 'string', 'title': '等待策略',
|
||||||
|
'default': config.WAIT_SKIP, 'enum': list(config.WAIT_MODES)},
|
||||||
'export_companies': {'type': 'array', 'title': '导出范围(仅导出模式生效)',
|
'export_companies': {'type': 'array', 'title': '导出范围(仅导出模式生效)',
|
||||||
'default': ['a', 'b'], 'items': {'type': 'string'}},
|
'default': ['a', 'b'], 'items': {'type': 'string'}},
|
||||||
'action': {'type': 'string', 'title': '执行动作',
|
'action': {'type': 'string', 'title': '执行动作',
|
||||||
@@ -121,7 +130,6 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
'save_dir': {'type': 'string', 'title': '保存目录', 'default': ''},
|
'save_dir': {'type': 'string', 'title': '保存目录', 'default': ''},
|
||||||
'force_login': {'type': 'boolean', 'title': '强制重新登录', 'default': False},
|
'force_login': {'type': 'boolean', 'title': '强制重新登录', 'default': False},
|
||||||
'run_merge': {'type': 'boolean', 'title': '并入台账', 'default': True},
|
'run_merge': {'type': 'boolean', 'title': '并入台账', 'default': True},
|
||||||
'run_store_map': {'type': 'boolean', 'title': '门店归属(CRM 券号)', 'default': True},
|
|
||||||
'run_links': {'type': 'boolean', 'title': '更新核对统计', 'default': True},
|
'run_links': {'type': 'boolean', 'title': '更新核对统计', 'default': True},
|
||||||
'dry_run': {'type': 'boolean', 'title': '只核对不写入', 'default': False},
|
'dry_run': {'type': 'boolean', 'title': '只核对不写入', 'default': False},
|
||||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||||
@@ -138,6 +146,11 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
action = _resolve_action(fields)
|
action = _resolve_action(fields)
|
||||||
run_mode = config.normalize_run_mode(fields.get('run_mode'))
|
run_mode = config.normalize_run_mode(fields.get('run_mode'))
|
||||||
export_only = run_mode == config.RUN_MODE_EXPORT_ONLY
|
export_only = run_mode == config.RUN_MODE_EXPORT_ONLY
|
||||||
|
# 下载方式:断点续传(默认,认领上次没出表的账单)/ 全新下载(强制重新提交)
|
||||||
|
download_mode = config.normalize_download_mode(fields.get('download_mode'))
|
||||||
|
resume = download_mode == config.DOWNLOAD_MODE_RESUME
|
||||||
|
# 等待策略:每表 5 分钟跳过(默认)/ 一次等到底(不限时)
|
||||||
|
wait_mode = config.normalize_wait_mode(fields.get('wait_mode'))
|
||||||
if export_only and action != config.ACTION_DOWNLOAD:
|
if export_only and action != config.ACTION_DOWNLOAD:
|
||||||
raise RuntimeError('「仅导出」模式不做核对;要核对请把执行模式切成「含写表」')
|
raise RuntimeError('「仅导出」模式不做核对;要核对请把执行模式切成「含写表」')
|
||||||
|
|
||||||
@@ -156,7 +169,6 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
|
|
||||||
dry_run = bool(fields.get('dry_run'))
|
dry_run = bool(fields.get('dry_run'))
|
||||||
run_merge = bool(fields.get('run_merge', True))
|
run_merge = bool(fields.get('run_merge', True))
|
||||||
run_store_map = bool(fields.get('run_store_map', True))
|
|
||||||
run_links = bool(fields.get('run_links', True))
|
run_links = bool(fields.get('run_links', True))
|
||||||
force_login = bool(fields.get('force_login'))
|
force_login = bool(fields.get('force_login'))
|
||||||
# 保存目录同时是台账目录:并入台账 / 更新核对统计都读它
|
# 保存目录同时是台账目录:并入台账 / 更新核对统计都读它
|
||||||
@@ -199,6 +211,8 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
if do_download:
|
if do_download:
|
||||||
plan.append('先下载' if do_check else
|
plan.append('先下载' if do_check else
|
||||||
'公司 ' + ' + '.join(c['short'] for c in companies))
|
'公司 ' + ' + '.join(c['short'] for c in companies))
|
||||||
|
plan.append('断点续传' if resume else '全新下载')
|
||||||
|
plan.append('一次等到底' if wait_mode == config.WAIT_UNTIL_DONE else '每表最多等 5 分钟')
|
||||||
if pay_on:
|
if pay_on:
|
||||||
plan.append(f'打款记录 {pay_from}~{pay_to}')
|
plan.append(f'打款记录 {pay_from}~{pay_to}')
|
||||||
if codes:
|
if codes:
|
||||||
@@ -206,7 +220,6 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
plan.append(f'{name}收益明细 {profit_from}~{profit_to}')
|
plan.append(f'{name}收益明细 {profit_from}~{profit_to}')
|
||||||
if check_settlement:
|
if check_settlement:
|
||||||
plan.append('并入台账' if run_merge else '')
|
plan.append('并入台账' if run_merge else '')
|
||||||
plan.append('门店归属(CRM 券号)' if run_store_map else '')
|
|
||||||
plan.append('更新核对统计' if run_links else '')
|
plan.append('更新核对统计' if run_links else '')
|
||||||
plan = [p for p in plan if p]
|
plan = [p for p in plan if p]
|
||||||
config.log('本次执行:' + ';'.join(plan) + f';目录 {save_dir}'
|
config.log('本次执行:' + ';'.join(plan) + f';目录 {save_dir}'
|
||||||
@@ -216,8 +229,9 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
|
|
||||||
detail = {'action': action, 'action_label': labels[action],
|
detail = {'action': action, 'action_label': labels[action],
|
||||||
'download_before': download_before, 'run_mode': run_mode,
|
'download_before': download_before, 'run_mode': run_mode,
|
||||||
'pay': None, 'profit': None, 'merge': None, 'store': None,
|
'pending': False, 'pending_tables': [], 'pending_detail': False,
|
||||||
'links': None,
|
'download_mode': download_mode,
|
||||||
|
'pay': None, 'profit': None, 'merge': None, 'links': None,
|
||||||
'results': {}, 'companies': [c['short'] for c in companies]}
|
'results': {}, 'companies': [c['short'] for c in companies]}
|
||||||
files = []
|
files = []
|
||||||
|
|
||||||
@@ -227,11 +241,13 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
dl_end = 60 if do_check else 95
|
dl_end = 60 if do_check else 95
|
||||||
span = (dl_end - 2) / len(jobs)
|
span = (dl_end - 2) / len(jobs)
|
||||||
errors = []
|
errors = []
|
||||||
|
pending = False # 本次有账单还没出表(已记待续,下次运行接着下载)
|
||||||
try:
|
try:
|
||||||
for i, (comp, user, pwd) in enumerate(jobs):
|
for i, (comp, user, pwd) in enumerate(jobs):
|
||||||
config.set_company(comp['id'])
|
config.set_company(comp['id'])
|
||||||
label = comp['short']
|
label = comp['short']
|
||||||
base = 2 + span * i
|
base = 2 + span * i
|
||||||
|
tag_prefix = f'{label} ' if len(jobs) > 1 else '' # 多家导出时待续表加公司前缀
|
||||||
ctx.progress(int(base))
|
ctx.progress(int(base))
|
||||||
if len(jobs) > 1:
|
if len(jobs) > 1:
|
||||||
config.log(f'—— {label}:档案 {comp["profile"]} / 端口 {comp["port"]} ——')
|
config.log(f'—— {label}:档案 {comp["profile"]} / 端口 {comp["port"]} ——')
|
||||||
@@ -248,10 +264,17 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
|
|
||||||
if pay_on:
|
if pay_on:
|
||||||
r1 = payment_download.download(page, pay_from, pay_to, save_dir,
|
r1 = payment_download.download(page, pay_from, pay_to, save_dir,
|
||||||
dry_run)
|
dry_run, resume=resume,
|
||||||
|
wait_mode=wait_mode)
|
||||||
if not r1.get('ok'):
|
if not r1.get('ok'):
|
||||||
raise RuntimeError(f'{label} 打款记录下载失败:{r1.get("message")}')
|
raise RuntimeError(f'{label} 打款记录下载失败:{r1.get("message")}')
|
||||||
config.log(r1.get('message') or '')
|
if r1.get('pending'):
|
||||||
|
pending = True
|
||||||
|
for t in (r1.get('pending_tables') or [config.PAYMENT_NAME_KEY]):
|
||||||
|
detail['pending_tables'].append(f'{tag_prefix}{t}')
|
||||||
|
config.log(r1.get('message') or '', 'WARN')
|
||||||
|
else:
|
||||||
|
config.log(r1.get('message') or '')
|
||||||
if r1.get('empty'):
|
if r1.get('empty'):
|
||||||
# 区间内没有打款记录:正常跳过,不影响收益明细下载与核对
|
# 区间内没有打款记录:正常跳过,不影响收益明细下载与核对
|
||||||
config.log('打款记录区间内无数据,已跳过本项', 'WARN')
|
config.log('打款记录区间内无数据,已跳过本项', 'WARN')
|
||||||
@@ -263,10 +286,21 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
|
|
||||||
if codes:
|
if codes:
|
||||||
r2 = profit_download.download(page, profit_from, profit_to, save_dir,
|
r2 = profit_download.download(page, profit_from, profit_to, save_dir,
|
||||||
codes, dry_run)
|
codes, dry_run, resume=resume,
|
||||||
|
wait_mode=wait_mode)
|
||||||
if not r2.get('ok'):
|
if not r2.get('ok'):
|
||||||
raise RuntimeError(f'{label} 收益明细下载失败:{r2.get("message")}')
|
raise RuntimeError(f'{label} 收益明细下载失败:{r2.get("message")}')
|
||||||
config.log(r2.get('message') or '')
|
if r2.get('pending'):
|
||||||
|
pending = True
|
||||||
|
miss_tables = r2.get('pending_tables') or ['收益明细']
|
||||||
|
for t in miss_tables:
|
||||||
|
detail['pending_tables'].append(f'{tag_prefix}{t}')
|
||||||
|
# 台账那家(ledger=True)的团购明细才是核对输入,缺了才跳过核对
|
||||||
|
if comp.get('ledger') and '团购收益明细' in miss_tables:
|
||||||
|
detail['pending_detail'] = True
|
||||||
|
config.log(r2.get('message') or '', 'WARN')
|
||||||
|
else:
|
||||||
|
config.log(r2.get('message') or '')
|
||||||
files.extend(r2.get('paths') or [])
|
files.extend(r2.get('paths') or [])
|
||||||
if comp.get('ledger'):
|
if comp.get('ledger'):
|
||||||
detail['profit'] = r2
|
detail['profit'] = r2
|
||||||
@@ -288,12 +322,23 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
config.set_company('a')
|
config.set_company('a')
|
||||||
if errors:
|
if errors:
|
||||||
raise RuntimeError(';'.join(errors))
|
raise RuntimeError(';'.join(errors))
|
||||||
|
if pending:
|
||||||
|
detail['pending'] = True
|
||||||
|
|
||||||
# ---------- 核对:到账统计(不依赖浏览器;美团/抖音核对已迁到 xq0085) ----------
|
# ---------- 核对:到账统计(不依赖浏览器;美团/抖音核对已迁到 xq0085) ----------
|
||||||
if do_check:
|
# 核对只读「台账 + 团购收益明细」:只有明细本次没出表才跳过(用旧明细核对会串数据);
|
||||||
|
# 打款记录 / 预订明细待续不影响核对
|
||||||
|
skip_check = bool(check_settlement and detail.get('pending_detail'))
|
||||||
|
if skip_check:
|
||||||
|
config.log('团购收益明细本次没有出表(已记待续),跳过核对以免用上一份旧明细;'
|
||||||
|
'稍后重跑会接着下载,出表后再核对', 'WARN')
|
||||||
|
elif detail.get('pending_tables') and check_settlement:
|
||||||
|
config.log('待续的表不含团购收益明细,核对照常执行(只读台账 + 团购收益明细)')
|
||||||
|
|
||||||
|
if do_check and not skip_check:
|
||||||
ctx.progress(62 if do_download else 5)
|
ctx.progress(62 if do_download else 5)
|
||||||
|
|
||||||
if check_settlement:
|
if check_settlement and not skip_check:
|
||||||
# 之前的核对:新美大到账统计
|
# 之前的核对:新美大到账统计
|
||||||
if run_merge:
|
if run_merge:
|
||||||
m = merge_ledger.run(dry_run=dry_run)
|
m = merge_ledger.run(dry_run=dry_run)
|
||||||
@@ -301,18 +346,6 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
detail['merge'] = m
|
detail['merge'] = m
|
||||||
if not m.get('ok'):
|
if not m.get('ok'):
|
||||||
raise RuntimeError(f'并入台账失败:{m.get("message")}')
|
raise RuntimeError(f'并入台账失败:{m.get("message")}')
|
||||||
if run_store_map:
|
|
||||||
# 门店归属:券号 join CRM,结果单列输出(不动台账)
|
|
||||||
ctx.progress(72 if do_download else 45)
|
|
||||||
sm = store_map.run(dry_run=dry_run,
|
|
||||||
progress_from=(72 if do_download else 45),
|
|
||||||
progress_to=(84 if do_download else 58))
|
|
||||||
config.log(sm.get('message') or '')
|
|
||||||
detail['store'] = sm
|
|
||||||
if not sm.get('ok'):
|
|
||||||
# CRM 未登录 / 未挂载 SDK 时只告警:不影响台账与核对统计
|
|
||||||
config.log(f'门店归属未完成:{sm.get("message")}', 'WARN')
|
|
||||||
|
|
||||||
ctx.progress(88 if do_download else 65)
|
ctx.progress(88 if do_download else 65)
|
||||||
|
|
||||||
if run_links:
|
if run_links:
|
||||||
@@ -329,15 +362,18 @@ class Xq0041Plugin(ScenePlugin):
|
|||||||
|
|
||||||
# ---------- 汇总 ----------
|
# ---------- 汇总 ----------
|
||||||
parts = [detail.get('action_label') or '执行完成']
|
parts = [detail.get('action_label') or '执行完成']
|
||||||
|
if detail.get('pending_tables'):
|
||||||
|
parts.append('待续:' + '、'.join(detail['pending_tables']) + '(下次运行接着下载)')
|
||||||
|
elif detail.get('pending'):
|
||||||
|
parts.append('账单未全部出表,已记待续(重跑接着下载)')
|
||||||
|
if skip_check:
|
||||||
|
parts.append('核对已跳过')
|
||||||
if detail['pay'] and detail['pay'].get('empty'):
|
if detail['pay'] and detail['pay'].get('empty'):
|
||||||
parts.append(f'打款记录 {pay_from}~{pay_to} 无数据')
|
parts.append(f'打款记录 {pay_from}~{pay_to} 无数据')
|
||||||
if files:
|
if files:
|
||||||
parts.append(f'下载 {len(files)} 个文件')
|
parts.append(f'下载 {len(files)} 个文件')
|
||||||
if detail['merge'] and detail['merge'].get('appended'):
|
if detail['merge'] and detail['merge'].get('appended'):
|
||||||
parts.append(f'台账并入 {detail["merge"]["appended"]} 行')
|
parts.append(f'台账并入 {detail["merge"]["appended"]} 行')
|
||||||
if detail['store'] and detail['store'].get('ok'):
|
|
||||||
parts.append(f'门店归属 {detail["store"]["mapped"]} 行 / '
|
|
||||||
f'{detail["store"]["stores"]} 家店')
|
|
||||||
if detail['links'] and detail['links'].get('rows'):
|
if detail['links'] and detail['links'].get('rows'):
|
||||||
parts.append(f'核对统计更新 {len(detail["links"]["rows"])} 行')
|
parts.append(f'核对统计更新 {len(detail["links"]["rows"])} 行')
|
||||||
if not parts:
|
if not parts:
|
||||||
|
|||||||
@@ -60,59 +60,9 @@ SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG'
|
|||||||
LINK_BOOK = '马敏团购总表'
|
LINK_BOOK = '马敏团购总表'
|
||||||
LINK_SHEET = '资金组取数'
|
LINK_SHEET = '资金组取数'
|
||||||
|
|
||||||
# ==================== 订单收入明细表(团购 + 预订合并) ====================
|
# ==================== 其他 ====================
|
||||||
PROFIT_HEADER_ROW = 2 # 团购/预订收益明细的表头行
|
# 订单收入明细 / 基础信息补维护 / 马敏总表粘贴 / 共享核对表复制 / 门店归属(CRM 券号)
|
||||||
DAILY_SHEET = '订单收入明细表' # 共享表里贴明细的 sheet
|
# 都已在 v1.3.13 迁到 XQ0085 团购数据核对插件;本插件只保留导表与到账统计表维护。
|
||||||
DAILY_HEADER_ROW = 3 # 该 sheet 的表头行(数据从第 4 行起)
|
|
||||||
DAILY_DATA_START = 4
|
|
||||||
DAILY_WORK_DIR = '_work' # 共享表拉下来的本地副本目录(共享盘只读)
|
|
||||||
# 汇总时剔除的业务类型(C 列);其余全要
|
|
||||||
DAILY_EXCLUDE_BUSINESS = ('其他',)
|
|
||||||
|
|
||||||
# ==================== 基础信息补维护(报表 #N/A → 新增门店/项目) ====================
|
|
||||||
BASE_SHEET = '基础信息' # A~C:消费门店名称 / 门店 / 品牌;E~F:套餐名 / 品项名称
|
|
||||||
REPORT_SHEET = '报表' # J=VLOOKUP(门店名) K=VLOOKUP(套餐名),查不到显示 #N/A
|
|
||||||
REPORT_DATA_START = 5
|
|
||||||
BASE_INFO_ROW = 3 # 基础信息 A/B/C 的数据起始行(第 2 行是表头)
|
|
||||||
BASE_ITEM_ROW = 2 # E/F 的数据起始行
|
|
||||||
# 报表 J/K 的 VLOOKUP 范围上界(写死在公式里:$A$3:$B$1973 / $E$2:$F$12924)
|
|
||||||
BASE_INFO_VLOOKUP_MAX = 1973
|
|
||||||
BASE_ITEM_VLOOKUP_MAX = 12924
|
|
||||||
BASE_RANGE_WARN_RATIO = 0.9 # 用到 90% 就提醒(只告警,不改公式)
|
|
||||||
|
|
||||||
# ==================== 报表粘贴到马敏团购总表(只写值) ====================
|
|
||||||
# 源 → 目标(字段一一对应,按位置贴,不按表头名)
|
|
||||||
MASTER_SHEET_MEITUAN = '平台-新美大' # 美团【报表】I~P → 本 sheet A~H
|
|
||||||
MASTER_SHEET_DOUYIN = '平台-抖音' # 抖音【报表】N~Z → 本 sheet A~M
|
|
||||||
MEITUAN_REPORT_COLS = ('I', 'P')
|
|
||||||
DOUYIN_REPORT_COLS = ('N', 'Z')
|
|
||||||
MASTER_DATA_START = 5 # 平台-新美大 / 平台-抖音 的数据起始行(表头第 3/4 行)
|
|
||||||
MASTER_SHEET_GROUP_STATS = '团购统计' # CRM 团购支付数据 → 本 sheet(A~I 同结构)
|
|
||||||
GROUP_STATS_DATA_START = 2 # 【团购统计】表头第 1 行,数据从第 2 行起
|
|
||||||
CRM_EXPORT_DIR = r'D:\资料\财务\CRM数据导出'
|
|
||||||
CRM_GROUP_PAY_PREFIX = '团购支付数据' # 文件名:团购支付数据-YYYYMMDD.xlsx
|
|
||||||
DOUYIN_WORK_DIR = r'D:\资料\财务\抖音平台核对'
|
|
||||||
DOUYIN_TABLE_PREFIX = '抖音'
|
|
||||||
DOUYIN_TABLE_EXT = '.xlsx'
|
|
||||||
|
|
||||||
# ==================== 共享盘每日核对表(美团M.D.xlsx) ====================
|
|
||||||
# 结构:{SHARE_ROOT}\2026年11月\11.10\美团11.10.xlsx
|
|
||||||
# 每天把昨天那份复制到今天的日期目录,文件名日期同步替换(内容留给人工填)
|
|
||||||
SHARE_CHECK_ROOT = SHARE_ROOT
|
|
||||||
SHARE_TABLE_KEYWORD = '美团'
|
|
||||||
SHARE_TABLE_EXT = '.xlsx'
|
|
||||||
|
|
||||||
# ==================== 门店归属(美团门店名 → 内部门店/品牌) ====================
|
|
||||||
# 口径差异:美团收益明细的日期是「验券/退款/调整时间」,CRM 团购核销报表按「核销日」归档,
|
|
||||||
# 同一笔单在两边可能差一天;实测按 ±1 天取窗口,券号命中率从 78.6% → 100%。
|
|
||||||
CRM_DATE_WINDOW = 1
|
|
||||||
# CRM 团购核销报表 key(crm_sdk.reports.REPORTS)
|
|
||||||
CRM_GROUP_REPORT = 'groupData'
|
|
||||||
CRM_PAGE_SIZE = 500
|
|
||||||
# 累积映射表(美团门店名 → 内部门店),跨次复用,命中过的门店不必再算
|
|
||||||
STORE_MAP_FILE = '门店映射表.json'
|
|
||||||
# 门店核对结果文件前缀:门店核对_起_止.xlsx
|
|
||||||
STORE_OUT_PREFIX = '门店核对'
|
|
||||||
|
|
||||||
|
|
||||||
def set_work_dir(path=None):
|
def set_work_dir(path=None):
|
||||||
@@ -152,7 +102,7 @@ BACKEND_STABLE = 20 # 后台页连续稳定秒数(/meishi 未登录也
|
|||||||
SETTLE_WAIT = 8 # 进入后台后等首屏请求结束再确认状态
|
SETTLE_WAIT = 8 # 进入后台后等首屏请求结束再确认状态
|
||||||
POLL_SECONDS = 2
|
POLL_SECONDS = 2
|
||||||
POLL_LOG_EVERY = 10 # 轮询等待日志节流(秒),避免 2s 一条刷屏
|
POLL_LOG_EVERY = 10 # 轮询等待日志节流(秒),避免 2s 一条刷屏
|
||||||
RECORD_SECONDS = 120 # 账单生成后轮询记录的最长时间
|
RECORD_SECONDS = 300 # 单次等待账单出表的上限(5 分钟);超时不报错,记待续,下次运行接着下载
|
||||||
REUSE_MAX_AGE_MIN = 10 # 账单复用时效:记录生成时间距今 ≤ N 分钟才复用
|
REUSE_MAX_AGE_MIN = 10 # 账单复用时效:记录生成时间距今 ≤ N 分钟才复用
|
||||||
RETRY_MAX = 3
|
RETRY_MAX = 3
|
||||||
HEADLESS = False # 人工登录必须可见浏览器
|
HEADLESS = False # 人工登录必须可见浏览器
|
||||||
@@ -166,6 +116,9 @@ def _app_data_dir():
|
|||||||
|
|
||||||
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
||||||
|
|
||||||
|
# 断点续传状态:记录本次提交但还没出表的账单任务,下次运行接着等/下载(见 data/resume_state.py)
|
||||||
|
PENDING_STATE_PATH = os.path.join(_app_data_dir(), 'xq0041_pending.json')
|
||||||
|
|
||||||
|
|
||||||
# ==================== 公司与账号档案(对齐 xq0042 的多公司模式) ====================
|
# ==================== 公司与账号档案(对齐 xq0042 的多公司模式) ====================
|
||||||
# 美团经营宝按主体分账号:金色印象(台账那家)与金色湖畔(只导出、不写表)。
|
# 美团经营宝按主体分账号:金色印象(台账那家)与金色湖畔(只导出、不写表)。
|
||||||
@@ -203,6 +156,38 @@ def normalize_run_mode(raw):
|
|||||||
return RUN_MODE_EXPORT_ONLY if text in _RUN_MODE_EXPORT_ONLY_ALIASES else RUN_MODE_FULL
|
return RUN_MODE_EXPORT_ONLY if text in _RUN_MODE_EXPORT_ONLY_ALIASES else RUN_MODE_FULL
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 下载方式(断点续传 / 全新下载) ====================
|
||||||
|
# resume(默认):先认领上次没出表的账单 + 平台已在生成的记录,出表就下载;
|
||||||
|
# 单张表最多等 RECORD_SECONDS(5 分钟),没出就跳过记待续,下次运行接着下。
|
||||||
|
# fresh:不复用、不认领,一律重新提交生成任务(取最新数据;平台排队慢时要从头等)。
|
||||||
|
DOWNLOAD_MODE_RESUME = 'resume'
|
||||||
|
DOWNLOAD_MODE_FRESH = 'fresh'
|
||||||
|
DOWNLOAD_MODES = (DOWNLOAD_MODE_RESUME, DOWNLOAD_MODE_FRESH)
|
||||||
|
_FRESH_ALIASES = ('fresh', 'new', '全新', '全新下载', '重新下载', '强制重新下载')
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_download_mode(raw):
|
||||||
|
"""下载方式归一:未配置/未知 → 断点续传。"""
|
||||||
|
text = str(raw or '').strip().lower()
|
||||||
|
return DOWNLOAD_MODE_FRESH if text in _FRESH_ALIASES else DOWNLOAD_MODE_RESUME
|
||||||
|
|
||||||
|
|
||||||
|
# ==================== 等待策略(单表 5 分钟跳过 / 一次等到底) ====================
|
||||||
|
# skip(默认):每张表最多等 RECORD_SECONDS(5 分钟,收益按类型数累计),没出就跳过记待续;
|
||||||
|
# until_done:不限时等出表(想一次跑完时用),受执行机「单次执行超时」(壳默认 6 小时)
|
||||||
|
# 与用户强停约束;被中断也会留待续状态,下次运行接着下载。
|
||||||
|
WAIT_SKIP = 'skip'
|
||||||
|
WAIT_UNTIL_DONE = 'until_done'
|
||||||
|
WAIT_MODES = (WAIT_SKIP, WAIT_UNTIL_DONE)
|
||||||
|
_UNTIL_DONE_ALIASES = ('until_done', 'wait', 'forever', '等到底', '一次等到底', '不限时')
|
||||||
|
|
||||||
|
|
||||||
|
def normalize_wait_mode(raw):
|
||||||
|
"""等待策略归一:未配置/未知 → 每表 5 分钟跳过。"""
|
||||||
|
text = str(raw or '').strip().lower()
|
||||||
|
return WAIT_UNTIL_DONE if text in _UNTIL_DONE_ALIASES else WAIT_SKIP
|
||||||
|
|
||||||
|
|
||||||
def get_company(cid=None):
|
def get_company(cid=None):
|
||||||
"""取公司配置(默认当前档案);未知 id 回退第一家。"""
|
"""取公司配置(默认当前档案);未知 id 回退第一家。"""
|
||||||
key = str(cid if cid is not None else _cur_company).strip().lower()
|
key = str(cid if cid is not None else _cur_company).strip().lower()
|
||||||
|
|||||||
@@ -1,143 +0,0 @@
|
|||||||
# -*- 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 = _sdk()
|
|
||||||
if sdk is None:
|
|
||||||
return None, None, '未挂载 crm_sdk(插件需声明 requires.sdks)'
|
|
||||||
login = sdk.auth.ensure_login(log=config.log)
|
|
||||||
if not login.get('success'):
|
|
||||||
return None, None, f"CRM 登录失败:{login.get('message') or '未知原因'}"
|
|
||||||
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),
|
|
||||||
}
|
|
||||||
@@ -9,6 +9,9 @@
|
|||||||
④ 下载 记录里的 downloadLink(mss-shon 预签名 URL,requests 直下)
|
④ 下载 记录里的 downloadLink(mss-shon 预签名 URL,requests 直下)
|
||||||
|
|
||||||
①②③ 在 iframe 上下文发 XHR,mtgsig 由页面 SDK 自动补。
|
①②③ 在 iframe 上下文发 XHR,mtgsig 由页面 SDK 自动补。
|
||||||
|
|
||||||
|
断点续传:单次只等 5 分钟(config.RECORD_SECONDS),超时不报错——已提交/仍在生成中的
|
||||||
|
记录 id 落盘到 resume_state,下次运行接着等;出表后直接下载,不重复提交生成任务。
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
@@ -16,7 +19,7 @@ import time
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
from . import browser
|
from . import browser, resume_state
|
||||||
|
|
||||||
|
|
||||||
def _find_frame(page, timeout=30):
|
def _find_frame(page, timeout=30):
|
||||||
@@ -56,8 +59,15 @@ def _age_minutes(add_time):
|
|||||||
return 1e9
|
return 1e9
|
||||||
|
|
||||||
|
|
||||||
def download(page, d_from, d_to, save_dir, dry_run=False):
|
def download(page, d_from, d_to, save_dir, dry_run=False, resume=True, wait_mode=config.WAIT_SKIP):
|
||||||
"""下载指定日期区间的打款记录。返回 {ok, path, rows, message}。"""
|
"""下载指定日期区间的打款记录。返回 {ok, path, rows, pending, message}。
|
||||||
|
|
||||||
|
resume=True(默认):先认领上次没出表的记录,接着等,出表即下载;
|
||||||
|
resume=False(全新下载):不复用、不认领,一律重新提交生成任务。
|
||||||
|
wait_mode=skip(默认):单张表最多等 config.RECORD_SECONDS(5 分钟),没出就跳过记待续;
|
||||||
|
wait_mode=until_done:不限时等出表(受执行机单次执行超时/用户强停约束)。
|
||||||
|
"""
|
||||||
|
until_done = wait_mode == config.WAIT_UNTIL_DONE
|
||||||
tag = d_from.replace('-', '') if d_from == d_to else \
|
tag = d_from.replace('-', '') if d_from == d_to else \
|
||||||
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
||||||
match_key = d_from
|
match_key = d_from
|
||||||
@@ -92,72 +102,110 @@ def download(page, d_from, d_to, save_dir, dry_run=False):
|
|||||||
return {'ok': True, 'empty': True, 'rows': 0,
|
return {'ok': True, 'empty': True, 'rows': 0,
|
||||||
'message': f'{d_from}~{d_to} 没有打款记录,跳过'}
|
'message': f'{d_from}~{d_to} 没有打款记录,跳过'}
|
||||||
|
|
||||||
# ② 已有记录时效内复用
|
# ② 历史记录:已出表的(可复用/可续传下载)、仍在生成中的(上次提交的任务)
|
||||||
before = _history_items(frame)
|
before = _history_items(frame)
|
||||||
before_ids = {it.get('id') for it in before}
|
before_ids = {it.get('id') for it in before}
|
||||||
target = None
|
same = [it for it in before if match_key in (it.get('timeInterval') or '')]
|
||||||
cands = [it for it in before
|
cands = [it for it in same if it.get('downloadLink')]
|
||||||
if match_key in (it.get('timeInterval') or '') and it.get('downloadLink')]
|
running = [it for it in same if not it.get('downloadLink')]
|
||||||
fresh = [it for it in cands if _age_minutes(it.get('addTime')) <= config.REUSE_MAX_AGE_MIN]
|
|
||||||
if fresh and not dry_run:
|
|
||||||
target = max(fresh, key=lambda x: str(x.get('addTime') or ''))
|
|
||||||
config.log(f'复用 {_age_minutes(target.get("addTime")):.0f} 分钟前的同区间记录'
|
|
||||||
f'(阈值 {config.REUSE_MAX_AGE_MIN} 分钟),不重复生成')
|
|
||||||
elif cands:
|
|
||||||
config.log('同区间记录已过期,重新生成以取最新数据')
|
|
||||||
|
|
||||||
# ③ 生成 + 轮询
|
company = config.current_company()['id']
|
||||||
|
st = resume_state.load(company, 'payment', d_from, d_to) if resume else None
|
||||||
|
|
||||||
|
target = None
|
||||||
|
if not dry_run and not resume:
|
||||||
|
config.log('「全新下载」:不复用已有账单,重新提交生成任务')
|
||||||
|
elif not dry_run:
|
||||||
|
if cands and st:
|
||||||
|
# 续传:上次提交的同区间账单本次已出表,不再受「N 分钟内才复用」限制
|
||||||
|
target = max(cands, key=lambda x: str(x.get('addTime') or ''))
|
||||||
|
config.log(f'续传:上次提交的同区间记录已出表({target.get("addTime")}),直接下载')
|
||||||
|
elif cands:
|
||||||
|
fresh = [it for it in cands
|
||||||
|
if _age_minutes(it.get('addTime')) <= config.REUSE_MAX_AGE_MIN]
|
||||||
|
if fresh:
|
||||||
|
target = max(fresh, key=lambda x: str(x.get('addTime') or ''))
|
||||||
|
config.log(f'复用 {_age_minutes(target.get("addTime")):.0f} 分钟前的同区间记录'
|
||||||
|
f'(阈值 {config.REUSE_MAX_AGE_MIN} 分钟),不重复生成')
|
||||||
|
else:
|
||||||
|
config.log('同区间记录已过期且无待续任务,重新生成以取最新数据')
|
||||||
|
|
||||||
|
# ③ 接着等已提交的任务 / 提交新任务 + 单次 5 分钟轮询
|
||||||
|
waiting = set()
|
||||||
if not target and not dry_run:
|
if not target and not dry_run:
|
||||||
payload = dict(query)
|
if running and resume:
|
||||||
payload.pop('pageIndex', None)
|
# 平台已登记同区间记录但还没回填链接:就是上次没等到的那份,接着等,不重复提交
|
||||||
payload.pop('pageSize', None)
|
waiting = {it.get('id') for it in running}
|
||||||
payload['downloadFileType'] = config.PAYMENT_FILE_TYPE
|
config.log(f'平台已有 {len(running)} 条同区间账单仍在生成,接着等(不重复提交生成)')
|
||||||
config.log(f'提交账单生成:{json.dumps(payload, ensure_ascii=False)}')
|
else:
|
||||||
for attempt in range(1, config.RETRY_MAX + 1):
|
payload = dict(query)
|
||||||
resp = browser.api_json(frame, 'POST', config.PAYMENT_DOWNLOAD_API, payload)
|
payload.pop('pageIndex', None)
|
||||||
if resp and resp.get('code') == 200:
|
payload.pop('pageSize', None)
|
||||||
config.log('生成任务已受理')
|
payload['downloadFileType'] = config.PAYMENT_FILE_TYPE
|
||||||
break
|
config.log(f'提交账单生成:{json.dumps(payload, ensure_ascii=False)}')
|
||||||
msg = (resp or {}).get('message') or '无响应'
|
for attempt in range(1, config.RETRY_MAX + 1):
|
||||||
wait = _throttle_seconds(msg)
|
resp = browser.api_json(frame, 'POST', config.PAYMENT_DOWNLOAD_API, payload)
|
||||||
if wait and attempt < config.RETRY_MAX:
|
if resp and resp.get('code') == 200:
|
||||||
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试({attempt}/{config.RETRY_MAX})',
|
config.log('生成任务已受理')
|
||||||
'WARN')
|
break
|
||||||
time.sleep(wait + 3)
|
msg = (resp or {}).get('message') or '无响应'
|
||||||
continue
|
wait = _throttle_seconds(msg)
|
||||||
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
|
if wait and attempt < config.RETRY_MAX:
|
||||||
|
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试'
|
||||||
|
f'({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||||
|
time.sleep(wait + 3)
|
||||||
|
continue
|
||||||
|
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
|
||||||
|
|
||||||
|
# 落盘待续:超时后下次运行按这些 id 接着等,不再重复提交生成任务
|
||||||
|
resume_state.save(company, 'payment', d_from, d_to, ids=waiting,
|
||||||
|
since=min([str(it.get('addTime') or '') for it in running] or
|
||||||
|
[time.strftime('%Y-%m-%d %H:%M:%S')]))
|
||||||
|
|
||||||
# 平台是「先登记一条记录(此时 downloadLink 为空)→ 文件生成完再回填链接」,
|
# 平台是「先登记一条记录(此时 downloadLink 为空)→ 文件生成完再回填链接」,
|
||||||
# 所以必须等 downloadLink 出现才算就绪,否则一命中空记录就退出等待(3 秒即失败)。
|
# 所以必须等 downloadLink 出现才算就绪,否则一命中空记录就退出等待(3 秒即失败)。
|
||||||
deadline = time.time() + config.RECORD_SECONDS
|
deadline = None if until_done else time.time() + config.RECORD_SECONDS
|
||||||
waited = 0
|
waited = 0
|
||||||
last_log = -config.POLL_LOG_EVERY
|
last_log = -config.POLL_LOG_EVERY
|
||||||
while time.time() < deadline:
|
if until_done:
|
||||||
|
config.log('等待策略:一次等到底(不限时,等出表为止;受执行超时/强停约束)')
|
||||||
|
while deadline is None or time.time() < deadline:
|
||||||
time.sleep(config.POLL_SECONDS)
|
time.sleep(config.POLL_SECONDS)
|
||||||
waited += config.POLL_SECONDS
|
waited += config.POLL_SECONDS
|
||||||
items = _history_items(frame)
|
items = _history_items(frame)
|
||||||
hits = [it for it in items
|
# 跟踪两拨记录:已认领的(续传/上次提交)+ 本次提交后新登记的
|
||||||
if it.get('id') not in before_ids
|
fresh = [it for it in items if it.get('id') not in before_ids
|
||||||
and match_key in (it.get('timeInterval') or '')]
|
and match_key in (it.get('timeInterval') or '')]
|
||||||
ready = [it for it in hits if it.get('downloadLink')]
|
if waiting:
|
||||||
|
pool = [it for it in items if it.get('id') in waiting]
|
||||||
|
pool += [it for it in fresh if it.get('id') not in waiting]
|
||||||
|
else:
|
||||||
|
pool = fresh
|
||||||
|
waiting |= {it.get('id') for it in pool}
|
||||||
|
ready = [it for it in pool if it.get('downloadLink')]
|
||||||
if ready:
|
if ready:
|
||||||
# 同区间可能登记多条(重试/多业务),取最新一条
|
# 同区间可能登记多条(重试/多业务),取最新一条
|
||||||
target = max(ready, key=lambda x: str(x.get('addTime') or ''))
|
target = max(ready, key=lambda x: str(x.get('addTime') or ''))
|
||||||
break
|
break
|
||||||
if waited - last_log >= config.POLL_LOG_EVERY:
|
if waited - last_log >= config.POLL_LOG_EVERY:
|
||||||
last_log = waited
|
last_log = waited
|
||||||
if hits:
|
limit = '不限时' if until_done else f'上限 {config.RECORD_SECONDS // 60} 分钟'
|
||||||
config.log(f' 账单生成中({len(hits)} 条记录暂无 downloadLink,'
|
if pool:
|
||||||
f'已等 {waited}s / 上限 {config.RECORD_SECONDS}s)…')
|
config.log(f' 账单生成中({len(pool)} 条记录暂无 downloadLink,'
|
||||||
|
f'已等 {waited // 60} 分钟 / {limit})…')
|
||||||
else:
|
else:
|
||||||
config.log(f' 等待账单生成…(已等 {waited}s)')
|
config.log(f' 等待账单生成…(已等 {waited // 60} 分钟 / {limit})')
|
||||||
|
|
||||||
if dry_run:
|
if dry_run:
|
||||||
return {'ok': True, 'message': f'[演练] 将生成并下载打款记录 {d_from}~{d_to}', 'rows': total}
|
return {'ok': True, 'message': f'[演练] 将生成并下载打款记录 {d_from}~{d_to}', 'rows': total}
|
||||||
|
|
||||||
if not target:
|
if not target:
|
||||||
return {'ok': False,
|
resume_state.save(company, 'payment', d_from, d_to, ids=waiting)
|
||||||
'message': f'{config.RECORD_SECONDS}s 内记录仍未生成完成(无 downloadLink)'}
|
limit = '不限时,本次被中断' if until_done else f'本次已等 {config.RECORD_SECONDS // 60} 分钟'
|
||||||
|
return {'ok': True, 'pending': True, 'rows': total,
|
||||||
|
'pending_tables': [config.PAYMENT_NAME_KEY],
|
||||||
|
'message': f'{config.PAYMENT_NAME_KEY}仍在平台生成中({limit},已记待续),'
|
||||||
|
f'下次运行会接着查,出表即下载'}
|
||||||
|
|
||||||
link = target.get('downloadLink')
|
link = target.get('downloadLink')
|
||||||
if not link:
|
if not link:
|
||||||
@@ -171,4 +219,5 @@ def download(page, d_from, d_to, save_dir, dry_run=False):
|
|||||||
return {'ok': False, 'message': '打款记录下载失败'}
|
return {'ok': False, 'message': '打款记录下载失败'}
|
||||||
info = browser.read_xlsx_summary(path)
|
info = browser.read_xlsx_summary(path)
|
||||||
config.log(f'完成:{os.path.basename(path)}({size / 1024:.0f} KB){info}')
|
config.log(f'完成:{os.path.basename(path)}({size / 1024:.0f} KB){info}')
|
||||||
|
resume_state.clear(company, 'payment')
|
||||||
return {'ok': True, 'path': path, 'rows': info.get('rows'), 'message': '打款记录已下载'}
|
return {'ok': True, 'path': path, 'rows': info.get('rows'), 'message': '打款记录已下载'}
|
||||||
|
|||||||
@@ -11,8 +11,11 @@
|
|||||||
⑤ 链接 GET /finance/ajax/downloadManagement/downloadLink?id=<记录id>(记录里 downloadLink 为空时)
|
⑤ 链接 GET /finance/ajax/downloadManagement/downloadLink?id=<记录id>(记录里 downloadLink 为空时)
|
||||||
⑥ 下载 mss-shon 预签名 URL(requests 直下)
|
⑥ 下载 mss-shon 预签名 URL(requests 直下)
|
||||||
|
|
||||||
复用策略:按业务类型分组取最新一条,**任一类型缺失或过期就整体重新生成**,
|
复用策略:按业务类型分组取最新一条,**任一类缺失或过期就重新生成**,避免半套数据。
|
||||||
避免出现「只拿到团购、预订缺失」的半套数据。
|
|
||||||
|
断点续传:每张表最多等 5 分钟(config.RECORD_SECONDS),勾选几张就累计几分钟
|
||||||
|
(团购+预订=10 分钟,都出齐提前结束);到点不报错——已就绪的先下载,
|
||||||
|
仍生成中的记录 id 落盘到 resume_state,下次运行接着等,不重复提交生成任务。
|
||||||
"""
|
"""
|
||||||
import json
|
import json
|
||||||
import os
|
import os
|
||||||
@@ -20,7 +23,7 @@ import time
|
|||||||
from datetime import datetime
|
from datetime import datetime
|
||||||
|
|
||||||
from .. import config
|
from .. import config
|
||||||
from . import browser
|
from . import browser, resume_state
|
||||||
|
|
||||||
|
|
||||||
def _throttle_seconds(msg):
|
def _throttle_seconds(msg):
|
||||||
@@ -53,10 +56,17 @@ def _expect_names(codes):
|
|||||||
return names
|
return names
|
||||||
|
|
||||||
|
|
||||||
def download(page, d_from, d_to, save_dir, codes=None, dry_run=False):
|
def download(page, d_from, d_to, save_dir, codes=None, dry_run=False, resume=True,
|
||||||
|
wait_mode=config.WAIT_SKIP):
|
||||||
"""下载指定业务类型的收益明细。codes:1=团购、11=预订;None=两者都要。
|
"""下载指定业务类型的收益明细。codes:1=团购、11=预订;None=两者都要。
|
||||||
|
|
||||||
返回 {ok, paths, message}。
|
resume=True(默认):先认领上次没出表的记录,接着等,出表即下载(已就绪的先下);
|
||||||
|
resume=False(全新下载):不复用、不认领,一律重新提交生成任务。
|
||||||
|
wait_mode=skip(默认):每张表最多等 config.RECORD_SECONDS(5 分钟),按勾选类型数累计
|
||||||
|
(都出齐提前结束);到点把已就绪的表下完,没就绪的跳过记待续,下次运行接着查。
|
||||||
|
wait_mode=until_done:不限时等所选表全部出齐(一次跑完,受执行超时/强停约束)。
|
||||||
|
|
||||||
|
返回 {ok, paths, pending, pending_tables, message}。
|
||||||
"""
|
"""
|
||||||
tag = d_from.replace('-', '') if d_from == d_to else \
|
tag = d_from.replace('-', '') if d_from == d_to else \
|
||||||
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
||||||
@@ -80,81 +90,161 @@ def download(page, d_from, d_to, save_dir, codes=None, dry_run=False):
|
|||||||
config.log(f'门店 {len(shop_ids)} 个;本次下载类型:{json.dumps(products, ensure_ascii=False)}'
|
config.log(f'门店 {len(shop_ids)} 个;本次下载类型:{json.dumps(products, ensure_ascii=False)}'
|
||||||
f' → {expect}')
|
f' → {expect}')
|
||||||
|
|
||||||
# ② 已有记录:按类型完整性 + 时效判断
|
# ② 历史记录:已就绪(可复用/续传下载)、仍在生成中的(上次提交的任务)
|
||||||
from datetime import date, timedelta
|
from datetime import date, timedelta
|
||||||
list_from = (date.today() - timedelta(days=30)).isoformat()
|
list_from = (date.today() - timedelta(days=30)).isoformat()
|
||||||
list_to = date.today().isoformat()
|
list_to = date.today().isoformat()
|
||||||
before = _history(page, list_from, list_to)
|
before = _history(page, list_from, list_to)
|
||||||
|
before_ids = {it.get('id') for it in before}
|
||||||
|
same = [it for it in before if d_from in (it.get('timeInterval') or '')]
|
||||||
|
|
||||||
targets = []
|
def _type_key(it):
|
||||||
groups = {}
|
return it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||||
for it in before:
|
|
||||||
if d_from not in (it.get('timeInterval') or ''):
|
|
||||||
continue
|
|
||||||
if it.get('downloadStatus') != 2:
|
|
||||||
continue
|
|
||||||
key = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
|
||||||
groups.setdefault(key, []).append(it)
|
|
||||||
newest = {k: max(v, key=lambda x: str(x.get('addTime') or '')) for k, v in groups.items()}
|
|
||||||
newest = {k: v for k, v in newest.items() if k in expect} # 只看勾选的类型
|
|
||||||
ages = {k: _age_minutes(v.get('addTime')) for k, v in newest.items()}
|
|
||||||
stale = [k for k, a in ages.items() if a > config.REUSE_MAX_AGE_MIN]
|
|
||||||
if all(name in newest for name in expect) and not stale:
|
|
||||||
targets = list(newest.values())
|
|
||||||
config.log('同区间记录齐全且新鲜,直接复用:' +
|
|
||||||
', '.join(f'{k}({ages[k]:.0f}分钟前)' for k in newest))
|
|
||||||
elif newest:
|
|
||||||
config.log(f'已有记录不完整或过期({len(newest)}/{len(expect)} 类,'
|
|
||||||
f'过期:{",".join(stale) or "无"}),重新生成以取最新数据')
|
|
||||||
|
|
||||||
# ③ 生成
|
# 只认勾选的类型(类型名未知的记录也保留,避免漏认上次提交的任务)
|
||||||
if not targets and not dry_run:
|
running = [it for it in same if it.get('downloadStatus') != 2
|
||||||
payload = {
|
and (_type_key(it) in expect or it.get('productCodeName') is None)]
|
||||||
'beginDate': d_from,
|
|
||||||
'endDate': d_to,
|
|
||||||
'productCodeList': want,
|
|
||||||
'shopIdList': shop_ids,
|
|
||||||
'downloadFileType': config.PROFIT_FILE_TYPE,
|
|
||||||
}
|
|
||||||
config.log(f'提交生成:{d_from}~{d_to},类型 {want},门店 {len(shop_ids)} 个')
|
|
||||||
for attempt in range(1, config.RETRY_MAX + 1):
|
|
||||||
resp = browser.api_json(page, 'POST', config.PROFIT_REQUEST_API, payload)
|
|
||||||
if resp and resp.get('code') == 200:
|
|
||||||
config.log('生成任务已受理')
|
|
||||||
break
|
|
||||||
msg = (resp or {}).get('message') or '无响应'
|
|
||||||
wait = _throttle_seconds(msg)
|
|
||||||
if wait and attempt < config.RETRY_MAX:
|
|
||||||
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试({attempt}/{config.RETRY_MAX})',
|
|
||||||
'WARN')
|
|
||||||
time.sleep(wait + 3)
|
|
||||||
continue
|
|
||||||
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
|
|
||||||
|
|
||||||
before_ids = {it.get('id') for it in before}
|
def _newest(items):
|
||||||
deadline = time.time() + config.RECORD_SECONDS
|
"""按业务类型取最新一条(只看勾选的类型)。"""
|
||||||
while time.time() < deadline:
|
groups = {}
|
||||||
time.sleep(config.POLL_SECONDS)
|
for it in items:
|
||||||
items = _history(page, list_from, list_to)
|
key = _type_key(it)
|
||||||
hits = [it for it in items
|
if key in expect:
|
||||||
if it.get('id') not in before_ids and d_from in (it.get('timeInterval') or '')]
|
groups.setdefault(key, []).append(it)
|
||||||
ready = [it for it in hits if it.get('downloadStatus') == 2]
|
return {k: max(v, key=lambda x: str(x.get('addTime') or ''))
|
||||||
pending = [it for it in hits if it.get('downloadStatus') != 2]
|
for k, v in groups.items()}
|
||||||
|
|
||||||
|
ready = _newest([it for it in same if it.get('downloadStatus') == 2])
|
||||||
|
|
||||||
|
company = config.current_company()['id']
|
||||||
|
st = resume_state.load(company, 'profit', d_from, d_to) if resume else None
|
||||||
|
|
||||||
|
need_generate = False
|
||||||
|
if not resume:
|
||||||
|
config.log('「全新下载」:不复用已有明细,重新提交生成任务')
|
||||||
|
ready.clear() # 全新下载:旧记录全部作废,只认本次产出
|
||||||
|
need_generate = True
|
||||||
|
elif st:
|
||||||
|
# 续传:上次提交的部分类型可能已出表,先收下,缺的接着等(不受新鲜度限制)
|
||||||
|
miss = [k for k in expect if k not in ready]
|
||||||
|
config.log(f'续传:同区间已就绪 {len(ready)}/{len(expect)} 类'
|
||||||
|
+ (f',继续等 {"/".join(miss)}' if miss else ',直接下载'))
|
||||||
|
need_generate = bool(miss)
|
||||||
|
else:
|
||||||
|
ages = {k: _age_minutes(v.get('addTime')) for k, v in ready.items()}
|
||||||
|
stale = [k for k, a in ages.items() if a > config.REUSE_MAX_AGE_MIN]
|
||||||
|
if ready and all(name in ready for name in expect) and not stale:
|
||||||
|
config.log('同区间记录齐全且新鲜,直接复用:' +
|
||||||
|
', '.join(f'{k}({ages[k]:.0f}分钟前)' for k in ready))
|
||||||
|
else:
|
||||||
|
# 不完整或过期:重新生成,旧记录作废(否则 5 分钟内没出表会把过期数据当本次结果)
|
||||||
|
need_generate = True
|
||||||
if ready:
|
if ready:
|
||||||
targets = ready
|
config.log(f'已有记录不完整或过期({len(ready)}/{len(expect)} 类,'
|
||||||
if not pending:
|
f'过期:{",".join(stale) or "无"}),重新生成以取最新数据')
|
||||||
|
ready.clear()
|
||||||
|
|
||||||
|
# ③ 接着等已提交的任务 / 提交新任务 + 轮询
|
||||||
|
# 每张表 5 分钟:一次生成任务同时产多种表,按勾选类型数给足预算(都出齐就提前结束);
|
||||||
|
# until_done = 不限时等出表(一次跑完,受执行超时/强停约束)
|
||||||
|
until_done = wait_mode == config.WAIT_UNTIL_DONE
|
||||||
|
budget = None if until_done else config.RECORD_SECONDS * max(1, len(expect))
|
||||||
|
budget_min = (budget or 0) // 60
|
||||||
|
waiting = set()
|
||||||
|
# 续传时平台上已有记录的类型(哪怕没就绪)才算「还在生成」;重新生成只看本次产出的记录
|
||||||
|
seen = set(_newest(same).keys()) if st else set()
|
||||||
|
if not dry_run and need_generate:
|
||||||
|
if running and resume:
|
||||||
|
# 平台已登记同区间记录但还没生成完:就是上次没等到的那份,接着等,不重复提交
|
||||||
|
waiting = {it.get('id') for it in running}
|
||||||
|
config.log(f'平台已有 {len(running)} 条同区间记录仍在生成,接着等(不重复提交生成)')
|
||||||
|
else:
|
||||||
|
payload = {
|
||||||
|
'beginDate': d_from,
|
||||||
|
'endDate': d_to,
|
||||||
|
'productCodeList': want,
|
||||||
|
'shopIdList': shop_ids,
|
||||||
|
'downloadFileType': config.PROFIT_FILE_TYPE,
|
||||||
|
}
|
||||||
|
config.log(f'提交生成:{d_from}~{d_to},类型 {want},门店 {len(shop_ids)} 个')
|
||||||
|
for attempt in range(1, config.RETRY_MAX + 1):
|
||||||
|
resp = browser.api_json(page, 'POST', config.PROFIT_REQUEST_API, payload)
|
||||||
|
if resp and resp.get('code') == 200:
|
||||||
|
config.log('生成任务已受理')
|
||||||
break
|
break
|
||||||
config.log(' 已就绪 %d 条,仍有 %d 条生成中(%s)…' % (
|
msg = (resp or {}).get('message') or '无响应'
|
||||||
len(ready), len(pending),
|
wait = _throttle_seconds(msg)
|
||||||
', '.join(str(it.get('productCodeName')) for it in pending)))
|
if wait and attempt < config.RETRY_MAX:
|
||||||
|
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试'
|
||||||
|
f'({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||||
|
time.sleep(wait + 3)
|
||||||
|
continue
|
||||||
|
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
|
||||||
|
|
||||||
|
# 落盘待续:超时后下次运行按这些 id 接着等,不再重复提交生成任务
|
||||||
|
resume_state.save(company, 'profit', d_from, d_to, ids=waiting,
|
||||||
|
since=min([str(it.get('addTime') or '') for it in running] or
|
||||||
|
[time.strftime('%Y-%m-%d %H:%M:%S')]))
|
||||||
|
|
||||||
|
deadline = None if until_done else time.time() + budget
|
||||||
|
waited = 0
|
||||||
|
last_log = -config.POLL_LOG_EVERY
|
||||||
|
if until_done:
|
||||||
|
config.log('等待策略:一次等到底(不限时,等所选 %d 张表全部出齐;受执行超时/强停约束)'
|
||||||
|
% len(expect))
|
||||||
|
while deadline is None or time.time() < deadline:
|
||||||
|
time.sleep(config.POLL_SECONDS)
|
||||||
|
waited += config.POLL_SECONDS
|
||||||
|
items = _history(page, list_from, list_to)
|
||||||
|
# 跟踪两拨记录:已认领的(续传/上次提交)+ 本次提交后新登记的;
|
||||||
|
# 只看已认领的会漏掉同一任务产出的其它表(比如先出团购、后出预订)
|
||||||
|
fresh = [it for it in items if it.get('id') not in before_ids
|
||||||
|
and d_from in (it.get('timeInterval') or '')]
|
||||||
|
if waiting:
|
||||||
|
pool = [it for it in items if it.get('id') in waiting]
|
||||||
|
pool += [it for it in fresh if it.get('id') not in waiting]
|
||||||
else:
|
else:
|
||||||
config.log(' 等待生成…')
|
pool = fresh
|
||||||
|
waiting |= {it.get('id') for it in pool}
|
||||||
|
seen |= {_type_key(it) for it in pool}
|
||||||
|
for k, it in _newest([it for it in pool
|
||||||
|
if it.get('downloadStatus') == 2]).items():
|
||||||
|
ready[k] = it
|
||||||
|
if all(name in ready for name in expect):
|
||||||
|
break
|
||||||
|
if waited - last_log >= config.POLL_LOG_EVERY:
|
||||||
|
last_log = waited
|
||||||
|
miss = [k for k in expect if k not in ready]
|
||||||
|
limit = ('不限时' if until_done else
|
||||||
|
f'本次上限 {budget_min} 分钟={len(expect)} 张表×'
|
||||||
|
f'{config.RECORD_SECONDS // 60} 分钟')
|
||||||
|
config.log(f' 等待生成(已等 {waited // 60} 分钟 / {limit}):'
|
||||||
|
f'缺 {"/".join(miss)}')
|
||||||
|
|
||||||
|
targets = [ready[k] for k in expect if k in ready]
|
||||||
|
|
||||||
if dry_run:
|
if dry_run:
|
||||||
return {'ok': True, 'message': f'[演练] 将生成并下载收益明细 {d_from}~{d_to}', 'paths': []}
|
return {'ok': True, 'message': f'[演练] 将生成并下载收益明细 {d_from}~{d_to}', 'paths': []}
|
||||||
|
|
||||||
|
missing = [k for k in expect if k not in ready]
|
||||||
|
# 平台连记录都没有的类型:视为本次未产出(该业务可能无数据)→ 告警跳过,不算待续,
|
||||||
|
# 否则会一直卡在待续、永远走不到核对
|
||||||
|
stuck = [k for k in missing if k not in seen]
|
||||||
|
pending_missing = [k for k in missing if k in seen]
|
||||||
|
if stuck:
|
||||||
|
config.log(f'{"、".join(stuck)} 平台上没有对应记录(本次未产出,可能该业务无数据),'
|
||||||
|
f'跳过这张表继续后续流程', 'WARN')
|
||||||
|
pending = bool(pending_missing)
|
||||||
if not targets:
|
if not targets:
|
||||||
return {'ok': False, 'message': f'未拿到可下载的收益明细({config.RECORD_SECONDS}s 内未完成)'}
|
if pending:
|
||||||
|
resume_state.save(company, 'profit', d_from, d_to, ids=waiting)
|
||||||
|
return {'ok': True, 'pending': True, 'paths': [], 'pending_tables': pending_missing,
|
||||||
|
'message': f'{"、".join(pending_missing)}仍在平台生成中'
|
||||||
|
f'({"不限时,本次被中断" if until_done else f"本次已等满 {budget_min} 分钟"}'
|
||||||
|
f',已记待续),下次运行会接着查,出表即下载'}
|
||||||
|
return {'ok': False,
|
||||||
|
'message': f'未拿到可下载的收益明细({"、".join(stuck) or "全部"}本次未产出)'}
|
||||||
|
|
||||||
# ④ 逐个下载(同类型去重取最新)
|
# ④ 逐个下载(同类型去重取最新)
|
||||||
uniq = {}
|
uniq = {}
|
||||||
@@ -187,5 +277,17 @@ def download(page, d_from, d_to, save_dir, codes=None, dry_run=False):
|
|||||||
paths.append(path)
|
paths.append(path)
|
||||||
|
|
||||||
if not paths:
|
if not paths:
|
||||||
|
if pending:
|
||||||
|
resume_state.save(company, 'profit', d_from, d_to, ids=waiting)
|
||||||
|
return {'ok': True, 'pending': True, 'paths': [], 'pending_tables': pending_missing,
|
||||||
|
'message': '已就绪的收益明细下载失败,其余仍在生成;已记待续,稍后重跑接着下载'}
|
||||||
return {'ok': False, 'message': '收益明细全部下载失败'}
|
return {'ok': False, 'message': '收益明细全部下载失败'}
|
||||||
|
|
||||||
|
if pending:
|
||||||
|
resume_state.save(company, 'profit', d_from, d_to, ids=waiting)
|
||||||
|
return {'ok': True, 'pending': True, 'paths': paths, 'pending_tables': pending_missing,
|
||||||
|
'message': f'收益明细已下载 {len(paths)} 个;{"、".join(pending_missing)} 仍在平台生成中'
|
||||||
|
f'(已跳过并记待续),下次运行会接着查,出表即下载'}
|
||||||
|
|
||||||
|
resume_state.clear(company, 'profit')
|
||||||
return {'ok': True, 'paths': paths, 'message': f'收益明细已下载 {len(paths)} 个文件'}
|
return {'ok': True, 'paths': paths, 'message': f'收益明细已下载 {len(paths)} 个文件'}
|
||||||
|
|||||||
@@ -0,0 +1,94 @@
|
|||||||
|
# -*- coding: utf-8 -*-
|
||||||
|
"""断点续传状态(单次等待出表 5 分钟,超时先停,下次运行接着等/下载)。
|
||||||
|
|
||||||
|
平台是「先登记一条记录(downloadLink 为空)→ 文件生成完再回填」,高峰期出表可能十几分钟
|
||||||
|
到几小时。本模块只记「本次提交了但还没拿到文件」的任务,避免下次运行重复提交生成任务:
|
||||||
|
|
||||||
|
键:<公司id>/<任务类型>(payment / profit)
|
||||||
|
值:{"from","to","ids":[记录id...],"since":"提交时间","updated":"最后更新时间"}
|
||||||
|
|
||||||
|
区间变了视为新任务(覆盖旧键);下载成功后由调用方 clear() 清键。
|
||||||
|
状态文件落在 %LOCALAPPDATA%\\37duAutomation\\,不进用户财务目录。
|
||||||
|
"""
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import time
|
||||||
|
|
||||||
|
from .. import config
|
||||||
|
|
||||||
|
|
||||||
|
def _key(company, kind):
|
||||||
|
return f'{company}/{kind}'
|
||||||
|
|
||||||
|
|
||||||
|
def _as_int(value):
|
||||||
|
try:
|
||||||
|
return int(value)
|
||||||
|
except (TypeError, ValueError):
|
||||||
|
return None
|
||||||
|
|
||||||
|
|
||||||
|
def _load_all():
|
||||||
|
try:
|
||||||
|
with open(config.PENDING_STATE_PATH, encoding='utf-8') as f:
|
||||||
|
data = json.load(f)
|
||||||
|
return data if isinstance(data, dict) else {}
|
||||||
|
except (OSError, ValueError):
|
||||||
|
return {}
|
||||||
|
|
||||||
|
|
||||||
|
def _dump_all(data):
|
||||||
|
path = config.PENDING_STATE_PATH
|
||||||
|
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||||
|
tmp = path + '.tmp'
|
||||||
|
with open(tmp, 'w', encoding='utf-8') as f:
|
||||||
|
json.dump(data, f, ensure_ascii=False, indent=2)
|
||||||
|
os.replace(tmp, path)
|
||||||
|
|
||||||
|
|
||||||
|
def load(company, kind, d_from, d_to):
|
||||||
|
"""取该区间未完成的任务;没记录或区间不一致 → None。"""
|
||||||
|
item = _load_all().get(_key(company, kind))
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
return None
|
||||||
|
if item.get('from') != d_from or item.get('to') != d_to:
|
||||||
|
return None
|
||||||
|
ids = [_as_int(i) for i in (item.get('ids') or [])]
|
||||||
|
item['ids'] = [i for i in ids if i is not None]
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def save(company, kind, d_from, d_to, ids=None, since=None):
|
||||||
|
"""登记/更新待续任务;ids 是本次跟踪的记录 id(平台未登记时可为空)。"""
|
||||||
|
data = _load_all()
|
||||||
|
item = data.get(_key(company, kind))
|
||||||
|
if not isinstance(item, dict):
|
||||||
|
item = {}
|
||||||
|
item.update({
|
||||||
|
'from': d_from,
|
||||||
|
'to': d_to,
|
||||||
|
'ids': sorted({i for i in (_as_int(x) for x in (ids or [])) if i is not None}),
|
||||||
|
'updated': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||||
|
})
|
||||||
|
if since:
|
||||||
|
item['since'] = str(since)
|
||||||
|
data[_key(company, kind)] = item
|
||||||
|
try:
|
||||||
|
_dump_all(data)
|
||||||
|
except OSError as e:
|
||||||
|
config.log(f'待续状态写入失败(忽略,不影响本次流程):{e}', 'WARN')
|
||||||
|
return item
|
||||||
|
|
||||||
|
|
||||||
|
def clear(company, kind):
|
||||||
|
"""任务已完成(文件已下载)→ 清键;没有其它待续任务时直接删文件。"""
|
||||||
|
data = _load_all()
|
||||||
|
if data.pop(_key(company, kind), None) is None:
|
||||||
|
return
|
||||||
|
try:
|
||||||
|
if data:
|
||||||
|
_dump_all(data)
|
||||||
|
elif os.path.exists(config.PENDING_STATE_PATH):
|
||||||
|
os.remove(config.PENDING_STATE_PATH)
|
||||||
|
except OSError as e:
|
||||||
|
config.log(f'待续状态清理失败(忽略):{e}', 'WARN')
|
||||||
@@ -1,190 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""从共享盘复制「昨天」的表到本地副本(**共享盘全程只读,绝不回写**)。
|
|
||||||
|
|
||||||
源在共享盘,目标在本机 ``WORK_DIR/_work/``,文件名日期同步替换::
|
|
||||||
|
|
||||||
源(共享盘,只读)
|
|
||||||
1111/TG/2026年11月/11.10/美团11.10.xlsx
|
|
||||||
1111/TG/2026年11月/11.10/马敏团购总表11.10.xlsx
|
|
||||||
目标(本地副本)
|
|
||||||
D:\\资料\\财务\\新美大平台核对\\_work\\美团11.11.xlsx
|
|
||||||
D:\\资料\\财务\\新美大平台核对\\_work\\马敏团购总表11.11.xlsx
|
|
||||||
|
|
||||||
两张表复制到本地后,后续所有处理(明细贴表、报表写值)都只改本地副本。
|
|
||||||
|
|
||||||
要点:
|
|
||||||
|
|
||||||
* **按日期取表**:源文件优先按 ``{关键词}{月}.{日}.xlsx`` 精确匹配;
|
|
||||||
匹配不到再在该日目录里取关键词命中的唯一 xlsx(人工临时改过名的场景);
|
|
||||||
* **跨月自动回退**:1 号的「昨天」在上个月的目录,月份目录按源日期算;
|
|
||||||
* **幂等**:本地目标已存在且非空就跳过,重复运行不会覆盖当天已处理的数据;
|
|
||||||
* **不依赖第三方库**:UNC 路径用标准库只读打开 + 本地写入,缺少凭据时给出提示。
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
from datetime import date, datetime, timedelta
|
|
||||||
|
|
||||||
from .. import config
|
|
||||||
|
|
||||||
|
|
||||||
def _parse_day(value):
|
|
||||||
"""``date`` / ``datetime`` / 'YYYY-MM-DD' 统一成 date;无法解析返回 None。"""
|
|
||||||
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 month_dir(root, day):
|
|
||||||
"""月份目录:``2026年11月``。"""
|
|
||||||
return os.path.join(root, f'{day.year}年{day.month}月')
|
|
||||||
|
|
||||||
|
|
||||||
def day_dir(root, day):
|
|
||||||
"""日期目录:``11.10``(不补零,与共享盘现有命名一致)。"""
|
|
||||||
return os.path.join(month_dir(root, day), f'{day.month}.{day.day}')
|
|
||||||
|
|
||||||
|
|
||||||
def table_name(keyword, day, ext):
|
|
||||||
"""核对表文件名:``美团11.10.xlsx``。"""
|
|
||||||
return f'{keyword}{day.month}.{day.day}{ext}'
|
|
||||||
|
|
||||||
|
|
||||||
def _list_tables(folder, keyword, ext):
|
|
||||||
"""列出目录里关键词 + 后缀命中的 xlsx(排除 Excel 临时文件 ``~$``)。"""
|
|
||||||
try:
|
|
||||||
names = os.listdir(folder)
|
|
||||||
except OSError:
|
|
||||||
return []
|
|
||||||
out = []
|
|
||||||
for name in names:
|
|
||||||
low = name.lower()
|
|
||||||
if name.startswith('~$') or not low.endswith(ext.lower()):
|
|
||||||
continue
|
|
||||||
if keyword and keyword not in name:
|
|
||||||
continue
|
|
||||||
out.append(name)
|
|
||||||
return sorted(out)
|
|
||||||
|
|
||||||
|
|
||||||
def _pick_source(folder, keyword, prev_day, ext):
|
|
||||||
"""在昨天目录里挑源文件:先精确日期,再退化为目录内唯一命中的表。"""
|
|
||||||
exact = os.path.join(folder, table_name(keyword, prev_day, ext))
|
|
||||||
if os.path.isfile(exact):
|
|
||||||
return exact
|
|
||||||
candidates = _list_tables(folder, keyword, ext)
|
|
||||||
if len(candidates) == 1:
|
|
||||||
return os.path.join(folder, candidates[0])
|
|
||||||
return ''
|
|
||||||
|
|
||||||
|
|
||||||
def copy_prev_table(share_root='', keyword='', ext='', day=None, local_dir='', dry_run=False):
|
|
||||||
"""从共享盘昨天目录复制一张表到本地副本(文件名日期同步替换)。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
|
|
||||||
keyword: 文件名关键词(默认 :data:`config.SHARE_TABLE_KEYWORD`,如「美团」)
|
|
||||||
ext: 后缀(默认 :data:`config.SHARE_TABLE_EXT`)
|
|
||||||
day: 目标日期(默认今天)
|
|
||||||
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``,共享盘只读不写入)
|
|
||||||
dry_run: 只检查不复制
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``{"ok", "message", "src", "dst", "skipped"}``
|
|
||||||
"""
|
|
||||||
root = str(share_root or config.SHARE_CHECK_ROOT).strip().strip('"').rstrip('\\/')
|
|
||||||
kw = str(keyword or config.SHARE_TABLE_KEYWORD).strip()
|
|
||||||
suffix = str(ext or config.SHARE_TABLE_EXT).strip()
|
|
||||||
if suffix and not suffix.startswith('.'):
|
|
||||||
suffix = '.' + suffix
|
|
||||||
target = _parse_day(day) or date.today()
|
|
||||||
prev = target - timedelta(days=1)
|
|
||||||
|
|
||||||
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_path = os.path.join(dst_dir, table_name(kw, target, suffix))
|
|
||||||
result = {'ok': False, 'message': '', 'src': src_path, 'dst': dst_path, 'skipped': False}
|
|
||||||
|
|
||||||
if not src_path:
|
|
||||||
folder = day_dir(root, prev)
|
|
||||||
found = _list_tables(folder, kw, suffix)
|
|
||||||
result['message'] = (
|
|
||||||
f'共享盘 {folder} 下没有找到 {kw}*{suffix}'
|
|
||||||
+ (f'(现有:{"、".join(found)})' if found else
|
|
||||||
';若共享盘未连接,请先确认当前机器能访问 ' + root))
|
|
||||||
return result
|
|
||||||
|
|
||||||
if os.path.isfile(dst_path) and os.path.getsize(dst_path) > 0:
|
|
||||||
result.update(ok=True, skipped=True,
|
|
||||||
message=f'本地副本已存在,跳过复制:'
|
|
||||||
f'{os.path.basename(dst_path)}')
|
|
||||||
return result
|
|
||||||
|
|
||||||
if dry_run:
|
|
||||||
result.update(ok=True, message=f'[演练] 将复制 {os.path.basename(src_path)} → '
|
|
||||||
f'{dst_path}')
|
|
||||||
return result
|
|
||||||
|
|
||||||
try:
|
|
||||||
os.makedirs(dst_dir, exist_ok=True)
|
|
||||||
shutil.copy2(src_path, dst_path)
|
|
||||||
except OSError as e:
|
|
||||||
tip = ''
|
|
||||||
if getattr(e, 'winerror', None) in (53, 67, 64, 1219, 1326):
|
|
||||||
tip = '(共享盘网络路径不可达 / 缺少凭据,请确认本机已能访问该共享)'
|
|
||||||
result['message'] = f'复制失败:{e}{tip}'
|
|
||||||
return result
|
|
||||||
|
|
||||||
if not os.path.isfile(dst_path) or os.path.getsize(dst_path) == 0:
|
|
||||||
result['message'] = f'复制后本地副本缺失或为空:{dst_path}'
|
|
||||||
return result
|
|
||||||
|
|
||||||
result.update(ok=True, message=f'已从共享盘复制 {os.path.basename(src_path)} → '
|
|
||||||
f'本地 {os.path.basename(dst_path)}')
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def copy_prev_tables(share_root='', day=None, local_dir='', dry_run=False):
|
|
||||||
"""把昨天的核对表 + 马敏团购总表一起拉到本地副本(共享盘只读)。
|
|
||||||
|
|
||||||
源文件在共享盘 ``{share_root}/{年}月/{月}.{日}/``,本地目标在 ``WORK_DIR/_work/``:
|
|
||||||
|
|
||||||
* 核对表:``美团11.10.xlsx`` → 本地 ``美团11.11.xlsx``
|
|
||||||
* 共享总表:``马敏团购总表11.10.xlsx`` → 本地 ``马敏团购总表11.11.xlsx``
|
|
||||||
|
|
||||||
Args:
|
|
||||||
share_root: 共享根(只读,默认 :data:`config.SHARE_CHECK_ROOT`)
|
|
||||||
day: 目标日期(默认今天;传「核对营业日」时按指定日期)
|
|
||||||
local_dir: 本地副本目录(默认 ``WORK_DIR/_work``)
|
|
||||||
dry_run: 只检查不复制
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``{"ok", "message", "tables": [...], "copied", "skipped", "failed"}``
|
|
||||||
"""
|
|
||||||
jobs = (
|
|
||||||
('核对表', config.SHARE_TABLE_KEYWORD, config.SHARE_TABLE_EXT),
|
|
||||||
('共享总表', config.LINK_BOOK, config.SHARE_TABLE_EXT),
|
|
||||||
)
|
|
||||||
tables = []
|
|
||||||
for label, keyword, ext in jobs:
|
|
||||||
item = copy_prev_table(share_root=share_root, keyword=keyword, ext=ext,
|
|
||||||
day=day, local_dir=local_dir, dry_run=dry_run)
|
|
||||||
item['label'] = label
|
|
||||||
tables.append(item)
|
|
||||||
|
|
||||||
failed = [t for t in tables if not t.get('ok')]
|
|
||||||
return {
|
|
||||||
'ok': not failed,
|
|
||||||
'message': ';'.join(f'{t["label"]}:{t["message"]}' for t in tables),
|
|
||||||
'tables': tables,
|
|
||||||
'copied': sum(1 for t in tables if t.get('ok') and not t.get('skipped')),
|
|
||||||
'skipped': sum(1 for t in tables if t.get('skipped')),
|
|
||||||
'failed': len(failed),
|
|
||||||
}
|
|
||||||
@@ -1,207 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""基础信息补维护:报表里出现新的消费门店 / 新的套餐(项目)时,补进【基础信息】。
|
|
||||||
|
|
||||||
背景(共享表里的公式链)::
|
|
||||||
|
|
||||||
报表 J = IF(B=0,"",VLOOKUP(A,基础信息!$A$3:$B$1973,2,0)) # 美团门店名 → 内部门店
|
|
||||||
报表 K = IF(B=0,"",VLOOKUP(B,基础信息!$E$2:$F$12924,2,0)) # 套餐名 → 品项名称
|
|
||||||
|
|
||||||
VLOOKUP 查不到就显示 #N/A(人工看到的是"乱码")。所以每天要检查报表里有没有
|
|
||||||
新的门店名 / 新的套餐名,补进【基础信息】的 A~C(门店映射)与 E~F(品项映射)。
|
|
||||||
|
|
||||||
自动补的来源:
|
|
||||||
|
|
||||||
* **内部门店 / 品牌**:优先用 ``门店映射表.json``(CRM 券号 join 出来的,最准);
|
|
||||||
没有则按名称相似度给候选,标「待确认」;
|
|
||||||
* **品项名称**:套餐名里的 ``【...】`` 就是品项(如「【龙手足道】80分钟…」→ 龙手足道);
|
|
||||||
提取不到再给空值待人工。
|
|
||||||
|
|
||||||
写入只在**本地副本**上做(共享盘只读),人工确认后自行同步回共享盘。
|
|
||||||
"""
|
|
||||||
import difflib
|
|
||||||
import json
|
|
||||||
import os
|
|
||||||
|
|
||||||
import openpyxl
|
|
||||||
|
|
||||||
from .. import config
|
|
||||||
|
|
||||||
COL_BI_A, COL_BI_B, COL_BI_C = 1, 2, 3 # 基础信息:消费门店名称 / 门店 / 品牌
|
|
||||||
COL_BI_E, COL_BI_F = 5, 6 # 基础信息:套餐名 / 品项名称
|
|
||||||
ITEM_MARK = ('【', '】')
|
|
||||||
|
|
||||||
|
|
||||||
def _norm(name):
|
|
||||||
return str(name or '').strip()
|
|
||||||
|
|
||||||
|
|
||||||
def _is_blank(value):
|
|
||||||
"""报表里透视多出来的 0 行:A/B 为 '0' 或空,不算真实门店/套餐。"""
|
|
||||||
text = str(value if value is not None else '').strip()
|
|
||||||
return text in ('', '0', 'None')
|
|
||||||
|
|
||||||
|
|
||||||
def _read_report_pairs(ws):
|
|
||||||
"""读【报表】A(消费门店名)/ B(套餐名),返回去重后的 (门店名集合, 套餐名集合)。"""
|
|
||||||
shops, items = [], []
|
|
||||||
seen_shop, seen_item = set(), set()
|
|
||||||
last = 0
|
|
||||||
for r in range(config.REPORT_DATA_START, int(ws.max_row) + 1):
|
|
||||||
shop = ws.cell(r, 1).value
|
|
||||||
item = ws.cell(r, 2).value
|
|
||||||
if not _is_blank(shop) or not _is_blank(item):
|
|
||||||
last = r
|
|
||||||
for r in range(config.REPORT_DATA_START, last + 1):
|
|
||||||
shop = _norm(ws.cell(r, 1).value)
|
|
||||||
item = _norm(ws.cell(r, 2).value)
|
|
||||||
if not _is_blank(shop) and shop not in seen_shop:
|
|
||||||
seen_shop.add(shop)
|
|
||||||
shops.append(shop)
|
|
||||||
if not _is_blank(item) and item not in seen_item:
|
|
||||||
seen_item.add(item)
|
|
||||||
items.append(item)
|
|
||||||
return shops, items
|
|
||||||
|
|
||||||
|
|
||||||
def _column_values(ws, col, start_row):
|
|
||||||
"""取某列从 start_row 起的非空值(去首尾空白)与真实末行。"""
|
|
||||||
values = set()
|
|
||||||
last = start_row - 1
|
|
||||||
for r in range(start_row, int(ws.max_row) + 1):
|
|
||||||
value = ws.cell(r, col).value
|
|
||||||
if value not in (None, ''):
|
|
||||||
last = r
|
|
||||||
values.add(_norm(value))
|
|
||||||
return values, last
|
|
||||||
|
|
||||||
|
|
||||||
def _load_shop_map():
|
|
||||||
"""读门店映射表(CRM 券号 join 的产物):美团门店名 → {shop, brand, shop_id}。"""
|
|
||||||
path = os.path.join(config.WORK_DIR, config.STORE_MAP_FILE)
|
|
||||||
if not os.path.exists(path):
|
|
||||||
return {}
|
|
||||||
try:
|
|
||||||
with open(path, encoding='utf-8') as fp:
|
|
||||||
data = json.load(fp)
|
|
||||||
except (OSError, ValueError):
|
|
||||||
return {}
|
|
||||||
shops = data.get('shops') if isinstance(data, dict) else None
|
|
||||||
return shops if isinstance(shops, dict) else {}
|
|
||||||
|
|
||||||
|
|
||||||
def _guess_shop(shop_name, known, mapping):
|
|
||||||
"""新门店 → 内部门店:先查 CRM 映射表,再按名称相似度给候选。"""
|
|
||||||
hit = mapping.get(shop_name)
|
|
||||||
if hit and hit.get('shop'):
|
|
||||||
return hit['shop'], hit.get('brand', ''), 'CRM券号映射'
|
|
||||||
best = difflib.get_close_matches(shop_name, list(known), n=1, cutoff=0.5)
|
|
||||||
if best:
|
|
||||||
return best[0], '', '名称相近(待确认)'
|
|
||||||
return '', '', '待确认'
|
|
||||||
|
|
||||||
|
|
||||||
def _guess_item(item_name):
|
|
||||||
"""套餐名 → 品项名称:取 ``【...】`` 里的词(共享表的人工口径就是这个)。"""
|
|
||||||
text = str(item_name or '')
|
|
||||||
start = text.find(ITEM_MARK[0])
|
|
||||||
end = text.find(ITEM_MARK[1], start + 1)
|
|
||||||
if start >= 0 and end > start:
|
|
||||||
return text[start + 1:end].strip(), '套餐名【】提取'
|
|
||||||
return '', '待人工'
|
|
||||||
|
|
||||||
|
|
||||||
def run(table_path='', dry_run=False):
|
|
||||||
"""检查【报表】里有、而【基础信息】里没有的门店/套餐,并补进本地副本。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
table_path: 共享表的本地副本路径(必填,共享盘只读)
|
|
||||||
dry_run: 只检测不写
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``{"ok", "message", "new_shops": [...], "new_items": [...], "path"}``
|
|
||||||
"""
|
|
||||||
result = {'ok': False, 'message': '', 'new_shops': [], 'new_items': [],
|
|
||||||
'path': table_path or ''}
|
|
||||||
if not table_path or not os.path.exists(table_path):
|
|
||||||
result['message'] = '没有可用的本地副本(共享盘只读,需先拉一份到本地)'
|
|
||||||
return result
|
|
||||||
|
|
||||||
wb = openpyxl.load_workbook(table_path)
|
|
||||||
try:
|
|
||||||
if config.BASE_SHEET not in wb.sheetnames:
|
|
||||||
result['message'] = f'{os.path.basename(table_path)} 缺少「{config.BASE_SHEET}」sheet'
|
|
||||||
return result
|
|
||||||
|
|
||||||
report = wb[config.REPORT_SHEET] if config.REPORT_SHEET in wb.sheetnames else None
|
|
||||||
if report is None:
|
|
||||||
result['message'] = f'缺少「{config.REPORT_SHEET}」sheet,跳过基础信息校验'
|
|
||||||
return result
|
|
||||||
|
|
||||||
shops, items = _read_report_pairs(report)
|
|
||||||
base = wb[config.BASE_SHEET]
|
|
||||||
known_shops, last_a = _column_values(base, COL_BI_A, config.BASE_INFO_ROW)
|
|
||||||
known_items, last_e = _column_values(base, COL_BI_E, config.BASE_ITEM_ROW)
|
|
||||||
|
|
||||||
# 只检查不修改:VLOOKUP 范围是写死的行号,末尾逼近上界时提醒人工扩范围
|
|
||||||
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')
|
|
||||||
|
|
||||||
new_shops = [s for s in shops if s not in known_shops]
|
|
||||||
new_items = [i for i in items if i not in known_items]
|
|
||||||
result['new_shops'] = new_shops
|
|
||||||
result['new_items'] = new_items
|
|
||||||
|
|
||||||
if not new_shops and not new_items:
|
|
||||||
result.update(ok=True, message=f'基础信息已覆盖报表里的 {len(shops)} 家门店 / '
|
|
||||||
f'{len(items)} 个套餐,无需补维护')
|
|
||||||
return result
|
|
||||||
|
|
||||||
mapping = _load_shop_map()
|
|
||||||
shop_rows = []
|
|
||||||
for name in new_shops:
|
|
||||||
shop, brand, source = _guess_shop(name, known_shops, mapping)
|
|
||||||
shop_rows.append({'name': name, 'shop': shop, 'brand': brand, 'source': source})
|
|
||||||
item_rows = []
|
|
||||||
for name in new_items:
|
|
||||||
item, source = _guess_item(name)
|
|
||||||
item_rows.append({'name': name, 'item': item, 'source': source})
|
|
||||||
|
|
||||||
if not dry_run:
|
|
||||||
row = last_a + 1
|
|
||||||
for info in shop_rows:
|
|
||||||
base.cell(row, COL_BI_A).value = info['name']
|
|
||||||
base.cell(row, COL_BI_B).value = info['shop']
|
|
||||||
base.cell(row, COL_BI_C).value = info['brand']
|
|
||||||
row += 1
|
|
||||||
row = last_e + 1
|
|
||||||
for info in item_rows:
|
|
||||||
base.cell(row, COL_BI_E).value = info['name']
|
|
||||||
base.cell(row, COL_BI_F).value = info['item']
|
|
||||||
row += 1
|
|
||||||
wb.save(table_path)
|
|
||||||
|
|
||||||
auto_shop = sum(1 for x in shop_rows if x['source'] == 'CRM券号映射')
|
|
||||||
auto_item = sum(1 for x in item_rows if x['source'] == '套餐名【】提取')
|
|
||||||
result.update(ok=True, shop_rows=shop_rows, item_rows=item_rows,
|
|
||||||
message=(f'{"[演练] " if dry_run else ""}基础信息待补:'
|
|
||||||
f'新增门店 {len(shop_rows)} 个(自动补 {auto_shop},其余待确认)、'
|
|
||||||
f'新增套餐 {len(item_rows)} 个(自动提取品项 {auto_item});'
|
|
||||||
+ ('已写入本地副本,确认后同步回共享盘' if not dry_run
|
|
||||||
else '未写入')))
|
|
||||||
config.log(result['message'])
|
|
||||||
return result
|
|
||||||
finally:
|
|
||||||
wb.close()
|
|
||||||
@@ -1,305 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""订单收入明细:团购 + 预订合并后贴进「订单收入明细表」,算当天结算价合计。
|
|
||||||
|
|
||||||
流程(对应财务人工操作)::
|
|
||||||
|
|
||||||
1. 团购收益明细:删掉 E 订单类型、F 订单号 两列;
|
|
||||||
2. 预订收益明细:转成与团购相同的 31 列(订单信息→套餐名,团购独有列留空);
|
|
||||||
3. 两张表合并(团购在前、预订在后);
|
|
||||||
4. 从第 4 行开始贴进「订单收入明细表」的 A~AB(第 28 项账单周期直接贴 AB,
|
|
||||||
明细里的「关联买单订单号/券号」目标表没有该列,丢弃);
|
|
||||||
5. AC/AD/AF/AG/AH/AI 六列按行下拉公式(与共享表模板一致);
|
|
||||||
6. 筛 AD(营业日)= 目标日、C(业务类型)≠「其他」→ 汇总 P 列结算价。
|
|
||||||
|
|
||||||
营业日口径(照抄共享表公式,别改)::
|
|
||||||
|
|
||||||
AD = IF(HOUR(验券时间)<10, IF(DAY=1, 上月最后一天, DAY-1), DAY)
|
|
||||||
即:凌晨 10 点前核销算前一天;1 号凌晨算上月最后一天。
|
|
||||||
|
|
||||||
**共享盘只读**:表拉到本地 `_work/` 副本上处理,结果不回写共享盘。
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import shutil
|
|
||||||
from datetime import date, datetime, timedelta
|
|
||||||
|
|
||||||
import openpyxl
|
|
||||||
|
|
||||||
from .. import config
|
|
||||||
|
|
||||||
# 团购收益明细的 31 列表头(第 2 行);预订表按名字映射到这套
|
|
||||||
GROUP_COLS = [
|
|
||||||
'账户名称', '线上场景/线下场景', '收益类型', '业务类型', '订单类型', '订单号',
|
|
||||||
'券号', '下单时间', '验券/退款/调整时间', '团购ID/通兑券ID', '套餐名',
|
|
||||||
'消费门店Id', '消费门店', '特殊账期业务', '入账日期', '打款状态', '打款单号',
|
|
||||||
'结算价', '总收入(元)', '技术服务费费率', '平台技术服务费(元)',
|
|
||||||
'商家营销费用(元)', '其他调整(元)', '自配打包费(元)', '自配送费(元)',
|
|
||||||
'渠道佣金(元)', '渠道标签', '备注', '关联纠纷单号', '关联买单订单号/券号',
|
|
||||||
'账单周期',
|
|
||||||
]
|
|
||||||
|
|
||||||
# 贴到目标表的顺序(A~AB 共 28 列):去掉订单类型/订单号,且不含「关联买单订单号/券号」
|
|
||||||
TARGET_COLS = [c for c in GROUP_COLS if c not in ('订单类型', '订单号', '关联买单订单号/券号')]
|
|
||||||
#: 列名 → 在「团购 31 列」里的下标(取值用这个,写入位置用 TARGET_COLS)
|
|
||||||
G_IDX = {name: i for i, name in enumerate(GROUP_COLS)}
|
|
||||||
|
|
||||||
# 公式列(1 起列号):AC/AD/AE/AF/AG/AH/AI
|
|
||||||
COL_AC, COL_AD, COL_AE, COL_AF, COL_AG, COL_AH, COL_AI = 29, 30, 31, 32, 33, 34, 35
|
|
||||||
COL_P = TARGET_COLS.index('结算价') + 1
|
|
||||||
COL_C = TARGET_COLS.index('业务类型') + 1
|
|
||||||
COL_G = TARGET_COLS.index('验券/退款/调整时间') + 1
|
|
||||||
|
|
||||||
|
|
||||||
def _key(name):
|
|
||||||
"""表头归一键:去括号内说明、去空格换行('结算价(总收入-...)' → '结算价')。"""
|
|
||||||
text = str(name or '').strip()
|
|
||||||
for mark in ('(', '('):
|
|
||||||
if mark in text:
|
|
||||||
text = text.split(mark, 1)[0]
|
|
||||||
return text.replace(' ', '').replace('\u3000', '').replace('\n', '')
|
|
||||||
|
|
||||||
|
|
||||||
def _read_table(path, header_row):
|
|
||||||
"""读一张美团导出的明细:返回 ``(表头, 行列表)``(行是 list)。"""
|
|
||||||
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=header_row, max_row=header_row,
|
|
||||||
max_col=ws.max_column, values_only=True)))
|
|
||||||
rows = []
|
|
||||||
for row in ws.iter_rows(min_row=header_row + 1, max_col=len(header),
|
|
||||||
values_only=True):
|
|
||||||
if any(v not in (None, '') for v in row):
|
|
||||||
rows.append(list(row))
|
|
||||||
return header, rows
|
|
||||||
finally:
|
|
||||||
wb.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _to_group_rows(header, rows, *, booking=False):
|
|
||||||
"""把明细行转成团购 31 列顺序;预订表缺的列补 None。"""
|
|
||||||
index = {}
|
|
||||||
for i, name in enumerate(header):
|
|
||||||
index.setdefault(_key(name), i)
|
|
||||||
# 预订的「订单信息」等同于团购的「套餐名」
|
|
||||||
if booking and '套餐名' not in index and '订单信息' in index:
|
|
||||||
index['套餐名'] = index['订单信息']
|
|
||||||
out = []
|
|
||||||
for row in rows:
|
|
||||||
out.append([row[index[_key(col)]] if _key(col) in index and index[_key(col)] < len(row)
|
|
||||||
else None
|
|
||||||
for col in GROUP_COLS])
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _pick(pattern):
|
|
||||||
"""目录里最新的匹配文件。"""
|
|
||||||
import glob
|
|
||||||
paths = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
|
|
||||||
if '_备份' not in p and not os.path.basename(p).startswith('~$')]
|
|
||||||
if not paths:
|
|
||||||
return ''
|
|
||||||
paths.sort(key=os.path.getmtime, reverse=True)
|
|
||||||
return paths[0]
|
|
||||||
|
|
||||||
|
|
||||||
def business_day(value, prev_month_last_day):
|
|
||||||
"""营业日:凌晨 10 点前算前一天;1 号凌晨算上月最后一天。返回 ``date``。"""
|
|
||||||
if isinstance(value, datetime):
|
|
||||||
dt = value
|
|
||||||
elif isinstance(value, date):
|
|
||||||
dt = datetime(value.year, value.month, value.day)
|
|
||||||
else:
|
|
||||||
dt = None
|
|
||||||
text = str(value or '').strip()[:19]
|
|
||||||
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d',
|
|
||||||
'%Y/%m/%d %H:%M:%S', '%Y/%m/%d'):
|
|
||||||
try:
|
|
||||||
dt = datetime.strptime(text, fmt)
|
|
||||||
break
|
|
||||||
except ValueError:
|
|
||||||
continue
|
|
||||||
if dt is None:
|
|
||||||
return None
|
|
||||||
if dt.hour < 10:
|
|
||||||
if dt.day == 1:
|
|
||||||
return prev_month_last_day
|
|
||||||
return dt.date() - timedelta(days=1)
|
|
||||||
return dt.date()
|
|
||||||
|
|
||||||
|
|
||||||
def _prev_month_last_day(day):
|
|
||||||
first = day.replace(day=1)
|
|
||||||
return first - timedelta(days=1)
|
|
||||||
|
|
||||||
|
|
||||||
def _last_data_row(ws, start_row, col=5):
|
|
||||||
"""真实数据末行(E 券号有值的最后一行);无数据返回 ``start_row - 1``。"""
|
|
||||||
last = start_row - 1
|
|
||||||
for r in range(start_row, int(ws.max_row) + 1):
|
|
||||||
if ws.cell(r, col).value not in (None, ''):
|
|
||||||
last = r
|
|
||||||
return last
|
|
||||||
|
|
||||||
|
|
||||||
def _write_formulas(ws, row):
|
|
||||||
"""按行下拉公式(与共享表模板逐字符一致,不能简化)。"""
|
|
||||||
ws.cell(row, COL_AC).value = f'=IF(P{row}>0,1,-1)'
|
|
||||||
ws.cell(row, COL_AD).value = (
|
|
||||||
f'=IF(HOUR(G{row})<10,IF(DAY(INT(G{row}))=1,$AE$2,DAY(INT(G{row}))-1),'
|
|
||||||
f'DAY(INT(G{row})))')
|
|
||||||
ws.cell(row, COL_AF).value = f'=_xlfn.XLOOKUP(I{row},基础信息!E:E,基础信息!F:F)'
|
|
||||||
ws.cell(row, COL_AG).value = f'=F{row}*1'
|
|
||||||
ws.cell(row, COL_AH).value = (
|
|
||||||
f'=IF(AND(AG{row}>$AG$1,OR(AF{row}="龙手足道",AF{row}="印象贵足")),0.6%,3%)')
|
|
||||||
ws.cell(row, COL_AI).value = f'=IF(AH{row}=U{row + 1},"正常","异常")'
|
|
||||||
|
|
||||||
|
|
||||||
def run(table_path='', day=None, dry_run=False):
|
|
||||||
"""合并团购 + 预订明细,贴进订单收入明细表并算当天结算价合计。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
table_path: 共享表的本地副本;空则把共享盘今天的表拉到 ``_work/`` 再处理
|
|
||||||
day: 目标营业日(默认今天)
|
|
||||||
dry_run: 只统计不写表
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``{"ok", "message", "rows", "total", "day", "path", "unmatched"}``
|
|
||||||
"""
|
|
||||||
target = day if isinstance(day, date) else (date.today() if day is None else
|
|
||||||
datetime.strptime(str(day)[:10], '%Y-%m-%d').date())
|
|
||||||
result = {'ok': False, 'message': '', 'rows': 0, 'matched': 0, 'total': 0.0,
|
|
||||||
'pivot_total': 0.0, 'pivot_groups': 0, 'pivot_diff': 0.0,
|
|
||||||
'day': target.isoformat(), 'path': ''}
|
|
||||||
|
|
||||||
# 1) 明细:团购 + 预订
|
|
||||||
group_path = _pick('团购收益明细_*.xlsx')
|
|
||||||
if not group_path:
|
|
||||||
result['message'] = '未找到团购收益明细(团购收益明细_*.xlsx),请先导出'
|
|
||||||
return result
|
|
||||||
group_header, group_rows = _read_table(group_path, config.PROFIT_HEADER_ROW)
|
|
||||||
merged = _to_group_rows(group_header, group_rows)
|
|
||||||
|
|
||||||
booking_path = _pick('预订收益明细_*.xlsx')
|
|
||||||
if booking_path:
|
|
||||||
b_header, b_rows = _read_table(booking_path, config.PROFIT_HEADER_ROW)
|
|
||||||
merged += _to_group_rows(b_header, b_rows, booking=True)
|
|
||||||
config.log(f'合并明细:团购 {len(group_rows)} 行 + 预订 {len(b_rows)} 行')
|
|
||||||
else:
|
|
||||||
config.log(f'合并明细:团购 {len(group_rows)} 行(未找到预订收益明细)')
|
|
||||||
|
|
||||||
if not merged:
|
|
||||||
result['message'] = '收益明细没有数据行'
|
|
||||||
return result
|
|
||||||
|
|
||||||
# 2) 共享表副本(只读共享盘;不回写)
|
|
||||||
if not table_path:
|
|
||||||
table_path = _local_copy(target)
|
|
||||||
if not table_path:
|
|
||||||
result['message'] = '未取到共享盘的订单收入明细表(共享盘不可达或今天的新表未创建)'
|
|
||||||
return result
|
|
||||||
result['path'] = table_path
|
|
||||||
|
|
||||||
# 3) 写表 + 公式下拉
|
|
||||||
wb = openpyxl.load_workbook(table_path)
|
|
||||||
try:
|
|
||||||
if config.DAILY_SHEET not in wb.sheetnames:
|
|
||||||
result['message'] = f'{os.path.basename(table_path)} 缺少 sheet「{config.DAILY_SHEET}」'
|
|
||||||
return result
|
|
||||||
ws = wb[config.DAILY_SHEET]
|
|
||||||
# 每天的流程是「清空 → 重新粘贴」:先把第 4 行到真实末行整段清掉(值+公式),
|
|
||||||
# 不留昨天的数据,保证重复运行结果一致(幂等)。
|
|
||||||
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
|
|
||||||
config.log(f'已清空目标表原有数据:第 {config.DAILY_DATA_START}~{last} 行'
|
|
||||||
f'({last - config.DAILY_DATA_START + 1} 行)')
|
|
||||||
start = config.DAILY_DATA_START
|
|
||||||
|
|
||||||
i_time = G_IDX['验券/退款/调整时间']
|
|
||||||
i_biz = G_IDX['业务类型']
|
|
||||||
i_net = G_IDX['结算价']
|
|
||||||
i_shop = G_IDX['消费门店']
|
|
||||||
i_item = G_IDX['套餐名']
|
|
||||||
i_gross = G_IDX['总收入(元)']
|
|
||||||
i_fee = G_IDX['平台技术服务费(元)']
|
|
||||||
i_mkt = G_IDX['商家营销费用(元)']
|
|
||||||
prev_last = _prev_month_last_day(target)
|
|
||||||
matched = total = 0
|
|
||||||
groups = {}
|
|
||||||
for offset, row in enumerate(merged):
|
|
||||||
r = start + offset
|
|
||||||
for col, name in enumerate(TARGET_COLS, 1):
|
|
||||||
ws.cell(r, col).value = row[G_IDX[name]]
|
|
||||||
_write_formulas(ws, r)
|
|
||||||
|
|
||||||
bday = business_day(row[i_time], prev_last)
|
|
||||||
biz = str(row[i_biz] or '').strip()
|
|
||||||
if bday == target and biz not in config.DAILY_EXCLUDE_BUSINESS:
|
|
||||||
matched += 1
|
|
||||||
total += _num(row[i_net])
|
|
||||||
# 透视口径:按「消费门店 × 套餐名」分组(与【透视】表行列一致)
|
|
||||||
key = (str(row[i_shop] or '').strip(), str(row[i_item] or '').strip())
|
|
||||||
g = groups.setdefault(key, [0, 0.0, 0.0, 0.0, 0.0])
|
|
||||||
g[0] += 1
|
|
||||||
g[1] += _num(row[i_gross])
|
|
||||||
g[2] += _num(row[i_fee])
|
|
||||||
g[3] += _num(row[i_mkt])
|
|
||||||
g[4] += _num(row[i_net])
|
|
||||||
|
|
||||||
if not dry_run:
|
|
||||||
wb.save(table_path)
|
|
||||||
finally:
|
|
||||||
wb.close()
|
|
||||||
|
|
||||||
# 第 4/5 步:三处合计本是同一条链——明细 P → 透视 G(=IF(P>0,1,-1) 那批行的汇总)
|
|
||||||
# → 报表 P(=+G+0,另外 VLOOKUP 基础信息 补品牌/内部门店)。这里全部复算出来并交叉校验。
|
|
||||||
pivot_total = round(sum(g[4] for g in groups.values()), 2)
|
|
||||||
detail_total = round(total, 2)
|
|
||||||
report_total = pivot_total # 报表 P 列公式为 +G+0,与透视 G 等价
|
|
||||||
diff = round(pivot_total - detail_total, 2)
|
|
||||||
consistent = abs(diff) < 0.01
|
|
||||||
result.update(ok=True, rows=len(merged), total=detail_total, matched=matched,
|
|
||||||
pivot_total=pivot_total, pivot_groups=len(groups), pivot_diff=diff,
|
|
||||||
report_total=report_total, consistent=consistent,
|
|
||||||
message=(f'{target.month}.{target.day} 营业日:明细 {len(merged)} 行,'
|
|
||||||
f'命中 {matched} 行(C 列剔除「其他」);'
|
|
||||||
f'明细 P / 透视 G / 报表 P 三处合计 '
|
|
||||||
f'{detail_total:,.2f} / {pivot_total:,.2f} / {report_total:,.2f} 元'
|
|
||||||
f'({len(groups)} 个门店×套餐组合)'
|
|
||||||
+ (',三口径一致' if consistent else f',差异 {diff:,.2f} 需排查')))
|
|
||||||
if not consistent:
|
|
||||||
config.log(result['message'], 'WARN')
|
|
||||||
else:
|
|
||||||
config.log(result['message'])
|
|
||||||
return result
|
|
||||||
|
|
||||||
|
|
||||||
def _num(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 _local_copy(day):
|
|
||||||
"""取当天的本地副本——由 share_copy 从共享盘昨天目录复制而来(共享盘只读)。"""
|
|
||||||
from ..data import share_copy
|
|
||||||
work = os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR)
|
|
||||||
name = share_copy.table_name(config.SHARE_TABLE_KEYWORD, day, config.SHARE_TABLE_EXT)
|
|
||||||
dst = os.path.join(work, name)
|
|
||||||
if os.path.isfile(dst) and os.path.getsize(dst) > 0:
|
|
||||||
config.log(f'使用本地副本:{dst}')
|
|
||||||
return dst
|
|
||||||
# 兼容:本地还没有时,从共享盘当天目录只读拉一份
|
|
||||||
src = os.path.join(share_copy.day_dir(config.SHARE_CHECK_ROOT, day), name)
|
|
||||||
if not os.path.isfile(src):
|
|
||||||
return ''
|
|
||||||
os.makedirs(work, exist_ok=True)
|
|
||||||
shutil.copy2(src, dst)
|
|
||||||
config.log(f'已从共享盘只读拉到本地副本:{dst}')
|
|
||||||
return dst
|
|
||||||
@@ -1,319 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""把美团 / 抖音【报表】与 CRM 团购支付数据按位置贴到马敏团购总表(粘贴为数值)。
|
|
||||||
|
|
||||||
列映射(源列与目标列字段一一对应,按位置贴,不按表头名)::
|
|
||||||
|
|
||||||
美团【报表】I~P(品牌/门店/商品名称/数量/总收入/技术服务费/营销费用/结算价)
|
|
||||||
→ 【平台-新美大】A~H(数据从第 5 行起)
|
|
||||||
抖音【报表】N~Z(品牌/门店/商品名称/数量/商家货款补贴/…/团长服务费)
|
|
||||||
→ 【平台-抖音】A~M(数据从第 5 行起)
|
|
||||||
CRM【团购统计】A~I(团购类型/消费日期/门店/核销项目名称/…/已消费项目个数)
|
|
||||||
→ 【团购统计】A~I(同结构,数据从第 2 行起)
|
|
||||||
|
|
||||||
每个目标 sheet 每次先清空数据区(只清源列覆盖的列),再按位置写入,
|
|
||||||
避免昨天残留;其它列(加上日/减本日/调整后等)原样保留。
|
|
||||||
|
|
||||||
目标马敏团购总表是从共享盘复制到本地 ``_work/`` 的副本——**共享盘全程只读**,
|
|
||||||
所有写值只落本地副本。写入用 zip + XML 直接改单元格值(inlineStr 存文本、<v> 存数字),
|
|
||||||
不走 openpyxl save,避免十几 MB 总表里的透视 / 公式 / 格式被重写丢失。
|
|
||||||
"""
|
|
||||||
import os
|
|
||||||
import re
|
|
||||||
import shutil
|
|
||||||
import zipfile
|
|
||||||
from datetime import date, datetime
|
|
||||||
from xml.sax.saxutils import escape
|
|
||||||
|
|
||||||
import openpyxl
|
|
||||||
from openpyxl.utils import column_index_from_string as col
|
|
||||||
from openpyxl.utils import get_column_letter as letter
|
|
||||||
|
|
||||||
from .. import config
|
|
||||||
|
|
||||||
_CELL_RE = re.compile(r'<c r="([A-Z]+)(\d+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
|
|
||||||
_ROW_RE = re.compile(r'<row([^>]*?)(?:/>|>(.*?)</row>)', re.S)
|
|
||||||
|
|
||||||
|
|
||||||
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 _col_num(letters):
|
|
||||||
n = 0
|
|
||||||
for ch in letters:
|
|
||||||
n = n * 26 + (ord(ch) - 64)
|
|
||||||
return n
|
|
||||||
|
|
||||||
|
|
||||||
def _sheet_xml_path(zf, sheet_name):
|
|
||||||
import xml.etree.ElementTree as ET
|
|
||||||
main = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
|
||||||
rel = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
|
||||||
pkg = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
|
||||||
root = ET.fromstring(zf.read('xl/workbook.xml'))
|
|
||||||
rid = None
|
|
||||||
for s in root.iter(f'{main}sheet'):
|
|
||||||
if s.get('name') == sheet_name:
|
|
||||||
rid = s.get(f'{rel}id')
|
|
||||||
break
|
|
||||||
if not rid:
|
|
||||||
return None
|
|
||||||
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
|
|
||||||
for r in rels.iter(f'{pkg}Relationship'):
|
|
||||||
if r.get('Id') == rid:
|
|
||||||
t = (r.get('Target') or '').lstrip('/')
|
|
||||||
return t if t.startswith('xl/') else 'xl/' + t
|
|
||||||
return None
|
|
||||||
|
|
||||||
|
|
||||||
def _master_path(day):
|
|
||||||
"""马敏团购总表的本地副本(由 share_copy 从共享盘拉来,不回写共享盘)。"""
|
|
||||||
return os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR,
|
|
||||||
f'{config.LINK_BOOK}{day.month}.{day.day}.xlsx')
|
|
||||||
|
|
||||||
|
|
||||||
def _meituan_source(day):
|
|
||||||
"""优先用 daily_detail 处理过的本地副本,否则取共享盘当天表。"""
|
|
||||||
name = f'美团{day.month}.{day.day}.xlsx'
|
|
||||||
local = os.path.join(config.WORK_DIR, config.DAILY_WORK_DIR, name)
|
|
||||||
if os.path.isfile(local):
|
|
||||||
return local
|
|
||||||
from ..data import share_copy
|
|
||||||
return os.path.join(share_copy.day_dir(config.SHARE_CHECK_ROOT, day), name)
|
|
||||||
|
|
||||||
|
|
||||||
def _douyin_source(day, douyin_dir=''):
|
|
||||||
root = str(douyin_dir or config.DOUYIN_WORK_DIR).strip().strip('"')
|
|
||||||
return os.path.join(root, f'{config.DOUYIN_TABLE_PREFIX}{day.month}.{day.day}'
|
|
||||||
f'{config.DOUYIN_TABLE_EXT}')
|
|
||||||
|
|
||||||
|
|
||||||
def _group_pay_source(day, crm_dir=''):
|
|
||||||
"""CRM 导出的团购支付数据:团购支付数据-YYYYMMDD.xlsx(日期即营业日)。"""
|
|
||||||
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 _read_values(path, sheet, c0, c1, start_row):
|
|
||||||
"""读源列的**计算值**(粘贴为数值),去掉尾部全空行。"""
|
|
||||||
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
|
||||||
try:
|
|
||||||
if sheet not in wb.sheetnames:
|
|
||||||
return []
|
|
||||||
ws = wb[sheet]
|
|
||||||
rows = [list(row) for row in ws.iter_rows(min_row=start_row,
|
|
||||||
min_col=col(c0), max_col=col(c1),
|
|
||||||
values_only=True)]
|
|
||||||
while rows and all(v is None for v in rows[-1]):
|
|
||||||
rows.pop()
|
|
||||||
return rows
|
|
||||||
finally:
|
|
||||||
wb.close()
|
|
||||||
|
|
||||||
|
|
||||||
def _make_cell(row_no, cnum, value, style=''):
|
|
||||||
letters = letter(cnum)
|
|
||||||
s_attr = f' s="{style}"' if style else ''
|
|
||||||
if isinstance(value, bool):
|
|
||||||
return f'<c r="{letters}{row_no}"{s_attr} t="b"><v>{int(value)}</v></c>'
|
|
||||||
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} t="inlineStr">'
|
|
||||||
f'<is><t>{escape(str(value))}</t></is></c>')
|
|
||||||
|
|
||||||
|
|
||||||
def _set_row_values(row_xml, row_no, values, lo, hi):
|
|
||||||
"""只替换 lo~hi 列的单元格,其余列(含样式、公式)原样保留。"""
|
|
||||||
keep, styles = [], {}
|
|
||||||
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 lo <= cnum <= hi:
|
|
||||||
continue
|
|
||||||
keep.append((cnum, m.group(0)))
|
|
||||||
for cnum in range(lo, hi + 1):
|
|
||||||
value = values.get(cnum)
|
|
||||||
if value is not None:
|
|
||||||
keep.append((cnum, _make_cell(row_no, cnum, value, styles.get(cnum, ''))))
|
|
||||||
keep.sort(key=lambda x: x[0])
|
|
||||||
attrs = re.match(r'<row([^>]*?)/?>', row_xml)
|
|
||||||
attr_text = attrs.group(1).rstrip() if attrs else ''
|
|
||||||
if not attr_text:
|
|
||||||
attr_text = ' r="%d"' % row_no
|
|
||||||
head = '<row' + attr_text + '>'
|
|
||||||
return head + ''.join(cell for _, cell in keep) + '</row>'
|
|
||||||
|
|
||||||
|
|
||||||
def _patch_sheet_xml(xml_text, rows, start_row, start_col):
|
|
||||||
"""清空目标 sheet 的数据区(仅源列范围)后写入新值,返回新 XML。"""
|
|
||||||
existing = {}
|
|
||||||
for m in _ROW_RE.finditer(xml_text):
|
|
||||||
head = '<row' + m.group(1) + '>'
|
|
||||||
row_no = re.search(r'\br="(\d+)"', head)
|
|
||||||
if row_no:
|
|
||||||
existing[int(row_no.group(1))] = m.group(0)
|
|
||||||
|
|
||||||
width = len(rows[0]) if rows else 0
|
|
||||||
lo, hi = start_col, start_col + max(width - 1, 0)
|
|
||||||
last_existing = max(existing) if existing else start_row - 1
|
|
||||||
needed = start_row + len(rows) - 1
|
|
||||||
|
|
||||||
out = xml_text
|
|
||||||
for row_no in range(start_row, max(needed, last_existing) + 1):
|
|
||||||
values = {}
|
|
||||||
if row_no - start_row < len(rows):
|
|
||||||
for offset, value in enumerate(rows[row_no - start_row]):
|
|
||||||
if value is not None:
|
|
||||||
values[lo + offset] = value
|
|
||||||
old = existing.get(row_no)
|
|
||||||
new = _set_row_values(old, row_no, values, lo, hi) if old else \
|
|
||||||
f'<row r="{row_no}">' + ''.join(
|
|
||||||
_make_cell(row_no, cnum, value) for cnum, value in sorted(values.items())) + '</row>'
|
|
||||||
if old:
|
|
||||||
out = out.replace(old, new, 1)
|
|
||||||
|
|
||||||
added = ''.join(
|
|
||||||
f'<row r="{row_no}">' + ''.join(
|
|
||||||
_make_cell(row_no, lo + offset, value)
|
|
||||||
for offset, value in enumerate(rows[row_no - start_row]) if value is not None)
|
|
||||||
+ '</row>'
|
|
||||||
for row_no in range(last_existing + 1, max(needed, last_existing) + 1)
|
|
||||||
)
|
|
||||||
if added:
|
|
||||||
out = out.replace('</sheetData>', added + '</sheetData>', 1)
|
|
||||||
return out
|
|
||||||
|
|
||||||
|
|
||||||
def _write_master(path, jobs):
|
|
||||||
"""按 sheet 批量替换单元格值,其余 zip 条目原样流式复制。"""
|
|
||||||
from .zipio import open_zip
|
|
||||||
|
|
||||||
zf = open_zip(path)
|
|
||||||
tmp = path + '.paste.tmp'
|
|
||||||
try:
|
|
||||||
patches = {}
|
|
||||||
for sheet_name, rows, start_col, start_row in jobs:
|
|
||||||
xml_path = _sheet_xml_path(zf, sheet_name)
|
|
||||||
if not xml_path:
|
|
||||||
config.log(f'马敏团购总表缺少 sheet「{sheet_name}」,跳过', 'WARN')
|
|
||||||
continue
|
|
||||||
text = zf.read(xml_path).decode('utf-8', 'replace')
|
|
||||||
patches[xml_path] = _patch_sheet_xml(text, rows, start_row, start_col)
|
|
||||||
if not patches:
|
|
||||||
return
|
|
||||||
|
|
||||||
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
|
|
||||||
if info.filename in patches:
|
|
||||||
dst.writestr(zi, patches.pop(info.filename).encode('utf-8'))
|
|
||||||
else:
|
|
||||||
with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
|
||||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
|
||||||
for name, data in patches.items():
|
|
||||||
dst.writestr(name, data.encode('utf-8'))
|
|
||||||
finally:
|
|
||||||
zf.close()
|
|
||||||
# Windows 上必须等源 zip 关闭后才能替换
|
|
||||||
os.replace(tmp, path)
|
|
||||||
|
|
||||||
|
|
||||||
def run(day=None, douyin_dir='', crm_dir='', dry_run=False):
|
|
||||||
"""把美团 / 抖音报表与 CRM 团购支付数据贴进本地总表副本(只写值)。
|
|
||||||
|
|
||||||
Args:
|
|
||||||
day: 核对日期(默认今天)
|
|
||||||
douyin_dir: 抖音表目录(默认 config.DOUYIN_WORK_DIR)
|
|
||||||
crm_dir: CRM 导出目录(默认 config.CRM_EXPORT_DIR)
|
|
||||||
dry_run: 只读源表、不写总表
|
|
||||||
|
|
||||||
Returns:
|
|
||||||
``{"ok", "message", "day", "path", "meituan_rows", "douyin_rows", "group_rows"}``
|
|
||||||
"""
|
|
||||||
target = _parse_day(day) or date.today()
|
|
||||||
result = {'ok': False, 'message': '', 'day': target.isoformat(), 'path': '',
|
|
||||||
'meituan_rows': 0, 'douyin_rows': 0, 'group_rows': 0}
|
|
||||||
master = _master_path(target)
|
|
||||||
if not os.path.isfile(master):
|
|
||||||
result['message'] = f'未找到马敏团购总表的本地副本:{master}(请先从共享盘复制)'
|
|
||||||
return result
|
|
||||||
|
|
||||||
jobs = []
|
|
||||||
mt = _meituan_source(target)
|
|
||||||
if os.path.isfile(mt):
|
|
||||||
values = _read_values(mt, config.REPORT_SHEET, *config.MEITUAN_REPORT_COLS,
|
|
||||||
config.REPORT_DATA_START)
|
|
||||||
if values:
|
|
||||||
jobs.append((config.MASTER_SHEET_MEITUAN, values, 1, config.MASTER_DATA_START))
|
|
||||||
result['meituan_rows'] = len(values)
|
|
||||||
else:
|
|
||||||
config.log(f'{os.path.basename(mt)}【报表】无数据,跳过新美大粘贴', 'WARN')
|
|
||||||
else:
|
|
||||||
config.log(f'未找到美团表:{mt},跳过新美大粘贴', 'WARN')
|
|
||||||
|
|
||||||
dy = _douyin_source(target, douyin_dir)
|
|
||||||
if os.path.isfile(dy):
|
|
||||||
values = _read_values(dy, config.REPORT_SHEET, *config.DOUYIN_REPORT_COLS,
|
|
||||||
config.REPORT_DATA_START)
|
|
||||||
if values:
|
|
||||||
jobs.append((config.MASTER_SHEET_DOUYIN, values, 1, config.MASTER_DATA_START))
|
|
||||||
result['douyin_rows'] = len(values)
|
|
||||||
else:
|
|
||||||
config.log(f'{os.path.basename(dy)}【报表】无数据,跳过抖音粘贴', 'WARN')
|
|
||||||
else:
|
|
||||||
config.log(f'未找到抖音表:{dy},跳过抖音粘贴', 'WARN')
|
|
||||||
|
|
||||||
# CRM 团购支付数据 → 【团购统计】A~I(同结构,表头第 1 行、数据第 2 行起)
|
|
||||||
gp = _group_pay_source(target, crm_dir)
|
|
||||||
if os.path.isfile(gp):
|
|
||||||
values = _read_values(gp, config.MASTER_SHEET_GROUP_STATS, 'A', 'I',
|
|
||||||
config.GROUP_STATS_DATA_START)
|
|
||||||
if values:
|
|
||||||
jobs.append((config.MASTER_SHEET_GROUP_STATS, values, 1,
|
|
||||||
config.GROUP_STATS_DATA_START))
|
|
||||||
result['group_rows'] = len(values)
|
|
||||||
else:
|
|
||||||
config.log(f'{os.path.basename(gp)}【团购统计】无数据,跳过', 'WARN')
|
|
||||||
else:
|
|
||||||
config.log(f'未找到 CRM 团购支付数据:{gp},跳过团购统计粘贴', 'WARN')
|
|
||||||
|
|
||||||
if not jobs:
|
|
||||||
result['message'] = '三张源表都没有可用数据,未写入马敏团购总表'
|
|
||||||
return result
|
|
||||||
|
|
||||||
if dry_run:
|
|
||||||
result.update(ok=True,
|
|
||||||
message=f'[演练] 将贴入 平台-新美大 {result["meituan_rows"]} 行 / '
|
|
||||||
f'平台-抖音 {result["douyin_rows"]} 行 / '
|
|
||||||
f'团购统计 {result["group_rows"]} 行')
|
|
||||||
return result
|
|
||||||
|
|
||||||
try:
|
|
||||||
_write_master(master, jobs)
|
|
||||||
except OSError as e:
|
|
||||||
tip = '(网络路径不可达或无写权限)' if getattr(e, 'winerror', None) in (5, 53, 67, 64) else ''
|
|
||||||
result['message'] = f'写入马敏团购总表失败:{e}{tip}'
|
|
||||||
return result
|
|
||||||
|
|
||||||
result.update(ok=True, path=master,
|
|
||||||
message=f'已按值贴入 平台-新美大 {result["meituan_rows"]} 行 / '
|
|
||||||
f'平台-抖音 {result["douyin_rows"]} 行 / '
|
|
||||||
f'团购统计 {result["group_rows"]} 行')
|
|
||||||
config.log(result['message'])
|
|
||||||
return result
|
|
||||||
@@ -1,305 +0,0 @@
|
|||||||
# -*- coding: utf-8 -*-
|
|
||||||
"""门店归属:把美团收益明细的「消费门店」翻译成内部门店 + 品牌。
|
|
||||||
|
|
||||||
两步走,都不依赖字符串模糊匹配:
|
|
||||||
|
|
||||||
1. **券号 join**(主):``crm_store`` 拉到的「券号 → CRM 门店」与收益明细的券号对齐,
|
|
||||||
命中即得到内部门店(订单级唯一,实测 100%);
|
|
||||||
2. **映射表复用**(补):历史命中过的「美团门店名 → 内部门店」落盘累积,
|
|
||||||
本期虽然没取到券号(跨月补单 / CRM 未同步)也能直接翻译。
|
|
||||||
|
|
||||||
产物 ``门店核对_起_止.xlsx``(与台账同目录,不改动台账本身):
|
|
||||||
|
|
||||||
* ``门店映射``:美团门店名 → 内部门店 / 品牌 / CRM 门店ID / 命中单数
|
|
||||||
* ``门店汇总``:按内部门店汇总订单数与金额(财务按店核对用)
|
|
||||||
* ``未匹配``:券号与映射表都没对上的订单,人工确认一次后可写回映射表
|
|
||||||
|
|
||||||
映射表冲突(同一美团门店名对到多个内部门店,常见于通兑券跨店核销)按票数取众数,
|
|
||||||
并在「门店映射」的备注列标出,便于人工复核。
|
|
||||||
"""
|
|
||||||
import glob
|
|
||||||
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 ..data 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():
|
|
||||||
"""月份/修改时间最新的团购收益明细(金色湖畔前缀的文件天然不匹配)。"""
|
|
||||||
paths = glob.glob(os.path.join(config.WORK_DIR, config.DETAIL_GLOB))
|
|
||||||
paths = [p for p in paths if '_备份' not in p and not os.path.basename(p).startswith('~$')]
|
|
||||||
if not paths:
|
|
||||||
return ''
|
|
||||||
paths.sort(key=os.path.getmtime, reverse=True)
|
|
||||||
return paths[0]
|
|
||||||
|
|
||||||
|
|
||||||
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.WORK_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):
|
|
||||||
path = os.path.join(config.WORK_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.HEADER_ROW, max_row=config.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}(表头第 {config.HEADER_ROW} 行)')
|
|
||||||
rows = []
|
|
||||||
for row in ws.iter_rows(min_row=config.DATA_START_ROW, 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.WORK_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}
|
|
||||||
|
|
||||||
_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": "xq0041",
|
"id": "xq0041",
|
||||||
"name": "新美大平台核对",
|
"name": "新美大平台核对",
|
||||||
"version": "1.3.13",
|
"version": "1.3.17",
|
||||||
"description": "美团数据导出与到账统计核对,两个独立动作:download=只导表(下载打款记录/团购/预订收益明细);check_settlement=到账统计核对(新美大到账统计:并入台账 → 门店归属 → 更新核对统计)。美团核对与抖音核对已迁到 XQ0085 团购数据核对插件。界面可配经营宝账号密码自动填好,登录/验证码/选商家由人工完成;金色印象与金色湖畔各自独立浏览器档案与调试端口(xq0041 / xq0041_b、9222 / 9333),登录态互不干扰,金色湖畔报表文件名带「金色湖畔_」前缀。",
|
"description": "美团数据导出与到账统计核对,两个独立动作:download=只导表(下载打款记录/团购/预订收益明细);check_settlement=到账统计核对(新美大到账统计:并入台账 → 更新核对统计)。美团核对/抖音核对/门店归属(CRM 券号)已迁到 XQ0085 团购数据核对插件,本插件只做导表与到账统计表维护。界面可配经营宝账号密码自动填好,登录/验证码/选商家由人工完成;金色印象与金色湖畔各自独立浏览器档案与调试端口(xq0041 / xq0041_b、9222 / 9333),登录态互不干扰,金色湖畔报表文件名带「金色湖畔_」前缀。导表支持断点续传:每张表最多等 5 分钟(团购+预订合计 10 分钟,出齐提前结束),没出就跳过并记待续,继续下一张;下次运行接着查、出表即下载(不重复提交生成任务)。界面可切「断点续传 / 全新下载」与「每表 5 分钟跳过 / 一次等到底」。",
|
||||||
"category": "财务",
|
"category": "财务",
|
||||||
"icon": "",
|
"icon": "",
|
||||||
"platform": "",
|
"platform": "",
|
||||||
@@ -12,13 +12,7 @@
|
|||||||
"capabilities": [
|
"capabilities": [
|
||||||
"xq0041"
|
"xq0041"
|
||||||
],
|
],
|
||||||
"requires": {
|
"requires": {},
|
||||||
"sdks": {
|
|
||||||
"crm_sdk": {
|
|
||||||
"compat": "^0.3"
|
|
||||||
}
|
|
||||||
}
|
|
||||||
},
|
|
||||||
"permissions": {
|
"permissions": {
|
||||||
"platforms": []
|
"platforms": []
|
||||||
},
|
},
|
||||||
@@ -61,6 +55,26 @@
|
|||||||
],
|
],
|
||||||
"description": "full=只导金色印象 + 并台账 + 更新核对统计;export_only=按「导出范围」勾选的公司各导一份,不写任何表"
|
"description": "full=只导金色印象 + 并台账 + 更新核对统计;export_only=按「导出范围」勾选的公司各导一份,不写任何表"
|
||||||
},
|
},
|
||||||
|
"download_mode": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "下载方式",
|
||||||
|
"default": "resume",
|
||||||
|
"enum": [
|
||||||
|
"resume",
|
||||||
|
"fresh"
|
||||||
|
],
|
||||||
|
"description": "resume=断点续传(默认,先认领上次没出表的账单,出表就下载);fresh=全新下载(不复用已有账单,一律重新提交生成任务)。两种方式都是每张表最多等 5 分钟(团购+预订合计 10 分钟,出齐提前结束),没出就跳过记待续,下次运行接着下"
|
||||||
|
},
|
||||||
|
"wait_mode": {
|
||||||
|
"type": "string",
|
||||||
|
"title": "等待策略",
|
||||||
|
"default": "skip",
|
||||||
|
"enum": [
|
||||||
|
"skip",
|
||||||
|
"until_done"
|
||||||
|
],
|
||||||
|
"description": "skip=每张表最多等 5 分钟,没出就跳过记待续(收益按张数累计,团购+预订 10 分钟);until_done=一次等到底,不限时直到所选表全部出齐(想一次跑完时用,受执行机单次执行超时与强停约束,被中断也会留待续状态)"
|
||||||
|
},
|
||||||
"export_companies": {
|
"export_companies": {
|
||||||
"type": "array",
|
"type": "array",
|
||||||
"title": "导出范围(仅导出模式生效)",
|
"title": "导出范围(仅导出模式生效)",
|
||||||
@@ -149,12 +163,6 @@
|
|||||||
"default": true,
|
"default": true,
|
||||||
"description": "把收益明细里晚于台账最新一笔的记录追加到台账(需勾选团购收益明细)"
|
"description": "把收益明细里晚于台账最新一笔的记录追加到台账(需勾选团购收益明细)"
|
||||||
},
|
},
|
||||||
"run_store_map": {
|
|
||||||
"type": "boolean",
|
|
||||||
"title": "门店归属(CRM 券号)",
|
|
||||||
"default": true,
|
|
||||||
"description": "用 CRM 团购核销的券号把美团「消费门店」翻译成内部门店 + 品牌,输出「门店核对_起_止.xlsx」(门店映射 / 门店汇总 / 未匹配)与累积映射表;不改动台账。CRM 未登录时只告警跳过"
|
|
||||||
},
|
|
||||||
"run_links": {
|
"run_links": {
|
||||||
"type": "boolean",
|
"type": "boolean",
|
||||||
"title": "更新核对统计",
|
"title": "更新核对统计",
|
||||||
|
|||||||
@@ -108,6 +108,26 @@
|
|||||||
</div>
|
</div>
|
||||||
<div class="sec-body">
|
<div class="sec-body">
|
||||||
<el-form label-position="top">
|
<el-form label-position="top">
|
||||||
|
<el-form-item label="下载方式">
|
||||||
|
<el-radio-group v-model="form.download_mode" :disabled="running">
|
||||||
|
<el-radio value="resume">断点续传(推荐)</el-radio>
|
||||||
|
<el-radio value="fresh">全新下载</el-radio>
|
||||||
|
</el-radio-group>
|
||||||
|
</el-form-item>
|
||||||
|
<el-form-item label="等待策略">
|
||||||
|
<el-radio-group v-model="form.wait_mode" :disabled="running">
|
||||||
|
<el-radio value="skip">每张表最多 5 分钟,没出就跳过(推荐)</el-radio>
|
||||||
|
<el-radio value="until_done">一次等到底(不限时)</el-radio>
|
||||||
|
</el-radio-group>
|
||||||
|
</el-form-item>
|
||||||
|
<div class="tip">
|
||||||
|
{{ form.download_mode === 'fresh'
|
||||||
|
? '每次都重新提交生成任务,不复用平台已有账单(数据最新,但平台排队慢时要从头等)。'
|
||||||
|
: '先用平台上已提交的账单:出表就下载。' }}
|
||||||
|
{{ form.wait_mode === 'until_done'
|
||||||
|
? '等待策略:不限时直到所选表全部出齐(想一次跑完时用,受执行机单次执行超时/强停约束,被中断也留待续状态)。'
|
||||||
|
: '等待策略:每张表最多等 5 分钟(收益按张数累计,团购+预订共 10 分钟,出齐提前结束),没出就跳过记待续,下次运行接着查。' }}
|
||||||
|
</div>
|
||||||
<div class="grid grid-mix">
|
<div class="grid grid-mix">
|
||||||
<el-form-item label="打款记录">
|
<el-form-item label="打款记录">
|
||||||
<el-switch v-model="form.pay_enabled" :disabled="running" />
|
<el-switch v-model="form.pay_enabled" :disabled="running" />
|
||||||
@@ -327,6 +347,8 @@ const DEFAULTS = () => {
|
|||||||
mt2_password: '',
|
mt2_password: '',
|
||||||
run_mode: 'full',
|
run_mode: 'full',
|
||||||
export_companies: ['a', 'b'],
|
export_companies: ['a', 'b'],
|
||||||
|
download_mode: 'resume',
|
||||||
|
wait_mode: 'skip',
|
||||||
do_download: true,
|
do_download: true,
|
||||||
do_reconcile: true,
|
do_reconcile: true,
|
||||||
pay_enabled: true,
|
pay_enabled: true,
|
||||||
@@ -414,6 +436,8 @@ const {
|
|||||||
mt2_password: t(f.mt2_password),
|
mt2_password: t(f.mt2_password),
|
||||||
run_mode: exportOnly ? 'export_only' : 'full',
|
run_mode: exportOnly ? 'export_only' : 'full',
|
||||||
export_companies: exportOnly ? (f.export_companies || []) : [],
|
export_companies: exportOnly ? (f.export_companies || []) : [],
|
||||||
|
download_mode: f.download_mode === 'fresh' ? 'fresh' : 'resume',
|
||||||
|
wait_mode: f.wait_mode === 'until_done' ? 'until_done' : 'skip',
|
||||||
action,
|
action,
|
||||||
pay_enabled: !!f.pay_enabled,
|
pay_enabled: !!f.pay_enabled,
|
||||||
pay_date_from: t(f.pay_date_from),
|
pay_date_from: t(f.pay_date_from),
|
||||||
|
|||||||
+14
-14
File diff suppressed because one or more lines are too long
+1
-1
File diff suppressed because one or more lines are too long
@@ -4,8 +4,8 @@
|
|||||||
<meta charset="UTF-8" />
|
<meta charset="UTF-8" />
|
||||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||||
<title>新美大平台核对</title>
|
<title>新美大平台核对</title>
|
||||||
<script type="module" crossorigin src="/pui/xq0041/assets/index-DELRgOsV.js"></script>
|
<script type="module" crossorigin src="/pui/xq0041/assets/index-BY3zG_5m.js"></script>
|
||||||
<link rel="stylesheet" crossorigin href="/pui/xq0041/assets/index-Xqpz4Bby.css">
|
<link rel="stylesheet" crossorigin href="/pui/xq0041/assets/index-DjCvalnn.css">
|
||||||
</head>
|
</head>
|
||||||
<body>
|
<body>
|
||||||
<div id="app"></div>
|
<div id="app"></div>
|
||||||
|
|||||||
Reference in New Issue
Block a user