From 5c7e44a9be17f01c1f9d4d7d1352a8916266ccd3 Mon Sep 17 00:00:00 2001 From: spudding <1115683088@qq.com> Date: Mon, 16 Nov 2026 11:27:43 +0800 Subject: [PATCH] =?UTF-8?q?feat(plugin):=20XQ0031=5FXQ0032=201.1.4=20?= =?UTF-8?q?=E6=94=B9=E4=B8=BA=20ERP=20WebAPI=20=E6=8E=A5=E5=8F=A3=E7=89=88?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit - 物料收发汇总表改走 StockReportQueryService.GetReportData 分页取数, 采购订单列表改走 ExecuteBillQuery;一次账密登录两张报表共用会话,不再起浏览器 - 新增 data/k3_report_api.py 适配层(组织内码、过滤方案、仓库条件),底层调 erpsdk - 导出格式与 K3 引出保持一致(说明行/表头行/合计行、新旧版列差异),前端产物重建 - 需求单开发文档同步 --- .../开发文档.md | 55 +- .../README.md | 122 +- .../__init__.py | 400 ++- .../config/__init__.py | 88 + .../data/k3_report_api.py | 59 + .../logic/material_summary.py | 111 + .../logic/purchase_order.py | 122 + .../plugin.json | 249 +- .../requirements.txt | 7 +- .../ui-src/index.html | 24 +- .../ui-src/package-lock.json | 3152 ++++++++--------- .../ui-src/package.json | 44 +- .../ui-src/src/App.vue | 685 ++-- .../ui-src/src/api.js | 1 - .../ui-src/src/main.js | 5 +- .../ui-src/src/style.css | 431 +++ .../ui-src/src/usePluginUI.js | 221 +- .../ui-src/vite.config.js | 41 +- ...{index-u2-ZnLC2.css => index-7jLxrewm.css} | 2 +- .../ui/assets/index-BAsvdLec.js | 80 - .../ui/assets/index-C_-S1JjW.js | 80 + .../ui/index.html | 26 +- 22 files changed, 3411 insertions(+), 2594 deletions(-) create mode 100644 plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/data/k3_report_api.py create mode 100644 plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/ui-src/src/style.css rename plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/ui/assets/{index-u2-ZnLC2.css => index-7jLxrewm.css} (97%) delete mode 100644 plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/ui/assets/index-BAsvdLec.js create mode 100644 plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/ui/assets/index-C_-S1JjW.js diff --git a/docs/需求单/XQ0001-0100/XQ0031 ERP物料收发汇总导出整合/开发文档.md b/docs/需求单/XQ0001-0100/XQ0031 ERP物料收发汇总导出整合/开发文档.md index e3caae8..e96ea8f 100644 --- a/docs/需求单/XQ0001-0100/XQ0031 ERP物料收发汇总导出整合/开发文档.md +++ b/docs/需求单/XQ0001-0100/XQ0031 ERP物料收发汇总导出整合/开发文档.md @@ -135,7 +135,60 @@ workflows/XQ0001-0100/XQ0032 ERP采购订单列表导出/ # 打包(仓库根执行) .venv\Scripts\python.exe "plugins\XQ0001-0100\XQ0031_XQ0032 物料收发与采购订单导出\_pack.py" # 发布(desktop/ 下执行,详见 docs/插件/发版规范.md) -.venv\Scripts\python.exe tools\agent_cli.py publish dist-plugin/xq0031_xq0032_v1.0.11.zip --id xq0031_xq0032 --version 1.0.11 +.venv\Scripts\python.exe tools\agent_cli.py publish dist-plugin/xq0031_xq0032_v1.1.0.zip --id xq0031_xq0032 --version 1.1.0 ``` 前端构建:`ui-src` 下 `npm install && npm run build`(产物输出到 `../ui/`,base=`/pui/xq0031_xq0032/`)。产物:`dist-plugin/xq0031_xq0032_v<版本>.zip`(排除 ui-src、__pycache__、_pack.py 等)。 + +## 九、v1.1.0 接口版改造(2026-11) + +把两张报表从「浏览器 UI 自动化」改为「WebAPI 取数」,通用 ERP 能力下沉到公共库 `libs/erpsdk`。 + +### 9.1 公共库 `libs/erpsdk`(SDK 下发) + +| 能力 | 说明 | +| --- | --- | +| `ErpClient(erp='new'/'old')` | 站点 + 账套内置(criterion `6877090c6dcab8` / erp `66eeb951ca7364`) | +| `login(user, pwd)` | `AuthService.ValidateUser` 账密登录,失败抛 `ErpError`;会话可跨调用复用 | +| `session_alive()` | 探活(权限报错也算有效,只认「会话信息已丢失」类失效) | +| `bill_query` / `bill_query_all` | `ExecuteBillQuery`,支持 FilterString、分页、`max_rows` 保护 | +| `report_query` | 分页报表取数 `StockReportQueryService.GetReportData`,内置日期/组织内码/仓库条件 | +| `query_metadata` | 表单元数据(生成 FieldKeys) | + +插件经 `plugin.json.requires.sdks.erpsdk` 声明,执行机自动挂载;自检 `python -m erpsdk._selftest`。 + +### 9.2 物料收发汇总表(31) + +- 接口:`StockReportQueryService.GetReportData`,参数整体序列化为**一个 JSON 字符串**塞入 `parameters[0]`; +- 条件:`QuicklyCondition` 传 `BeginDate`/`EndDate`/`StockOrgId`(组织**只认内码**), + 仓库走 `MoreCondition` 的 `FSTOCKNUMBER`(编码列,多条 `OR`); +- 过滤方案必须为**有元数据的方案**(系统默认方案返回 0 行); +- 输出:前 3 行说明 + 第 4 行表头 + 第 5 行起数据 + 末行合计,与 K3「引出」一致; + 新版 12 列 / 旧版 11 列(旧版仓库名在第 1 列、多「库存周转天数」); +- 各档导出后仍由 `report/merge_summary.py` 合并(逻辑未改)。 + +### 9.3 采购订单列表(32) + +- 接口:`ExecuteBillQuery`,`limit` 分页取全部明细; +- 列结构按历史导出样例逐列对齐:新版 22 列 / 旧版 17 列,表头在第 1 行,末行合计(仅汇总「采购数量」「价税合计」); +- 值转换:日期 `2026/11/14`、单据状态码→中文、富文本 CRLF→空行(还原 K3 引出渲染)、数值整数去 `.0`; +- 过滤口径(`config.PO_FILTER_STRING`,来自历史方案反推): + - 新版:`采购组织=重庆金七象供应链管理有限公司` + `单据类型=标准采购订单` + `FCancelStatus='A'` + - 旧版:`采购组织=金色湖畔事业部` +- 未启用方案条件时会拉全量(有 `PO_MAX_ROWS=50000` 上限并告警)。 + +### 9.4 验收结论(2026-11-14,与人工导出逐格比对) + +| 场景 | 结果 | +| --- | --- | +| 新版 31(单仓 508 行 / 5 仓 2528 行 / 全仓 2760 行) | 数值与合计完全一致 | +| 旧版 31(代管仓 614 行 / 全仓 3162 行) | 数值与合计完全一致 | +| 新版 32(22 列 20066 行) | 表头/行数/合计完全一致,仅 1 格「剩余入库数量」因导出后新增入库而变化 | +| 旧版 32(17 列) | 表头/逐格/合计完全一致 | + +### 9.5 已知限制 + +- 报表取数较慢(数千行约 10~30 秒),单页上限 10000 行,默认 5000 分页; +- 报表方案 ID 若为**个人方案**,换账号即失效,已改用**共享方案**(新旧各一个 `API专用(共享)`); +- 旧系统账号密码与新版不通用(旧系统用梁舫账号,密码需原样传入,勿做 strip 之外的加工); +- 浏览器兜底路径(`config.PO_USE_API=False`)保留,便于接口异常时回退。 diff --git a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/README.md b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/README.md index ceba42c..9abc152 100644 --- a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/README.md +++ b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/README.md @@ -1,41 +1,81 @@ -# ERP报表导出(xq0031_xq0032) - -金蝶 K3Cloud 报表自动导出插件:物料收发汇总表(需求31)+ 采购订单列表(需求32), -支持新旧系统切换、仓库编码多选(或关系)、日期多档(N天 / 自定义区间)逐档导出。 - -## 目录结构 - -- `*.py` — 插件后端(ScenePlugin 注册 + ERP 登录 + 两报表逻辑),自包含, - 只引用标准库 / 第三方依赖 / 底座注入接口(`webhost.backend.plugins.base`) -- `ui/` — 插件前端**构建产物**(壳子后端托管于 `/pui/xq0031_xq0032/`,勿手改) -- `ui-src/` — 插件前端源码(Vue 3 + Element Plus + Vite) -- `_pack.py` — 发布打包辅助(`_` 前缀,运行时不会被插件扫描加载) - -## 前端开发 / 构建 - -```bash -cd ui-src -npm install -npm run build # 产物输出到 ../ui/(vite.config.js 里 base=/pui/xq0031_xq0032/) -``` - -联调:先启动壳子(webhost),`npm run dev` 走 vite 代理(5180 → 127.0.0.1:8799)。 - -## 打包发布 - -1. 构建 ui(见上) -2. `desktop/` 下执行:`../.venv/Scripts/python.exe ../plugins/xq0031_xq0032/_pack.py` - → 产出 `dist-plugin/xq0031_xq0032_v<版本>.zip`(自动排除 ui-src 等) -3. `desktop/` 下发布: - `.venv\Scripts\python.exe tools\agent_cli.py publish dist-plugin\xq0031_xq0032_v<版本>.zip --id xq0031_xq0032 --version <版本> --admin puddy` - -## 个性化配置(自带界面) - -`plugin.json` 声明 `"ui": true`,壳子插件页展示「打开插件界面」入口(弹独立窗口, -同源自动携带登录会话)。账号密码 / 仓库编码 / 日期选项等在窗口内填写: - -- 配置经壳子 `GET/POST /api/plugin-config/xq0031_xq0032` 保存, - 落执行机本机 `%LOCALAPPDATA%\37duAutomation\plugin_configs\xq0031_xq0032.json`, - 下次打开自动回填(表单改动防抖自动保存); -- 执行经现有 `POST /api/runs`,日志/进度经 `WS /ws` 实时回显(另有 5 秒轮询兜底); -- 浏览器每次现场真登录(auto_port 独立实例),确保登录的就是本次配置的账号。 +# ERP报表导出(xq0031_xq0032) + +金蝶 K3Cloud 报表自动导出插件:物料收发汇总表(需求31)+ 采购订单列表(需求32), +支持新旧系统切换、仓库编码多选(或关系)、日期多档(N天 / 自定义区间)逐档导出。 + +**v1.1.0 起改为 WebAPI 接口版**:不启动浏览器,用插件里保存的 ERP 账号密码走 +WebAPI 账密登录,一次登录两张报表共用会话。通用 ERP 能力来自公共库 `erpsdk` +(`plugin.json` 的 `requires.sdks` 声明,执行机自动挂载)。 + +## 数据来源 + +| 报表 | 接口 | +|---|---| +| 物料收发汇总表(31) | `StockReportQueryService.GetReportData`(分页报表取数) | +| 采购订单列表(32) | `DynamicFormService.ExecuteBillQuery`(单据查询,分页) | + +## 导出格式(下游报表依赖,勿随意改动) + +**物料收发汇总表**(与 K3「引出」一致): + +- 第 1~3 行为说明行(货主/库存组织、起止日期/物料范围、仓库范围/参考价来源) +- **第 4 行为表头**;数据从第 5 行起;**末行为合计行** +- 新版 12 列(含规格型号、货主两列);旧版 11 列(仓库名称在第 1 列、多「库存周转天数」) +- 各档导出后用 `merge_summary` 合并:第 4 行表头首列插入「时间区间」,数据行首列填档位标签 + +**采购订单列表**(与 K3「按列表引出数据」一致): + +- **第 1 行为表头**;数据从第 2 行起;**末行为合计行**(仅汇总「采购数量」「价税合计」) +- 新版 22 列 / 旧版 17 列,列名与顺序见 `config.PO_COLUMNS` +- 日期格式 `2026/11/14`、单据状态显示中文(已审核/创建/暂存…)、 + 富文本换行按 K3 渲染规则转换(CRLF → 空行) + +## 过滤口径(config 可调) + +| 配置 | 说明 | +|---|---| +| `REPORT_SCHEME` | 报表过滤方案 ID(必须是有元数据的方案;系统默认方案接口取不到数据) | +| `REPORT_ORG_ID` | 组织编码 → 内码(快捷条件只认内码) | +| `PO_FILTER_STRING` | 采购订单过滤条件:新版=金七象组织+标准采购订单+排除作废;旧版=金色湖畔事业部 | +| `PO_USE_API` | `True` 走接口;置 `False` 回退浏览器导出(保留的兜底路径,需 DrissionPage) | + +## 目录结构 + +- `*.py` — 插件后端(ScenePlugin 注册 + 两报表逻辑),自包含, + 只引用标准库 / 第三方依赖 / 底座注入接口(`webhost.backend.plugins.base`)/ 下发的 SDK +- `data/k3_report_api.py` — 报表取数的插件内适配层(组织内码、方案、仓库条件),底层调 `erpsdk` +- `logic/material_summary.py` — 31:接口版 `run_api()` + 历史 UI 版 `run()`(兜底/参考) +- `logic/purchase_order.py` — 32:接口版 `run_api()` + 历史 UI 版 `run()`(兜底/参考) +- `report/merge_summary.py` — 各档合并汇总 +- `ui/` — 插件前端**构建产物**(壳子后端托管于 `/pui/xq0031_xq0032/`,勿手改) +- `ui-src/` — 插件前端源码(Vue 3 + Element Plus + Vite) +- `_pack.py` — 发布打包辅助(`_` 前缀,运行时不会被插件扫描加载) + +## 前端开发 / 构建 + +```bash +cd ui-src +npm install +npm run build # 产物输出到 ../ui/(vite.config.js 里 base=/pui/xq0031_xq0032/) +``` + +联调:先启动壳子(webhost),`npm run dev` 走 vite 代理(5180 → 127.0.0.1:8799)。 + +## 打包发布 + +1. 构建 ui(见上) +2. `desktop/` 下执行:`../.venv/Scripts/python.exe ../plugins/xq0031_xq0032/_pack.py` + → 产出 `dist-plugin/xq0031_xq0032_v<版本>.zip`(自动排除 ui-src 等) +3. `desktop/` 下发布: + `.venv\Scripts\python.exe tools\agent_cli.py publish dist-plugin\xq0031_xq0032_v<版本>.zip --id xq0031_xq0032 --version <版本> --admin puddy` + +## 个性化配置(自带界面) + +`plugin.json` 声明 `"ui": true`,壳子插件页展示「打开插件界面」入口(弹独立窗口, +同源自动携带登录会话)。账号密码 / 仓库编码 / 日期选项等在窗口内填写: + +- 配置经壳子 `GET/POST /api/plugin-config/xq0031_xq0032` 保存, + 落执行机本机 `%LOCALAPPDATA%\37duAutomation\plugin_configs\xq0031_xq0032.json`, + 下次打开自动回填(表单改动防抖自动保存); +- 执行经现有 `POST /api/runs`,日志/进度经 `WS /ws` 实时回显(另有 5 秒轮询兜底); +- 接口版使用配置里的**账号密码**直接登录 WebAPI(不再依赖浏览器登录态)。 diff --git a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/__init__.py b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/__init__.py index 355ad4e..579db10 100644 --- a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/__init__.py +++ b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/__init__.py @@ -1,185 +1,215 @@ -# -*- coding: utf-8 -*- -"""ERP报表导出 - webhost 场景插件(XQ0031 + XQ0032 合并版) - -金蝶 K3Cloud 报表自动导出,两种报表可单选或同次会话连导(登录一次): - 物料收发汇总表(XQ0031):组织/仓库编码(或关系多行)/日期多档(N天或自定义区间)逐档导出 - 采购订单列表(XQ0032):快捷方案 → 等查询 → 按列表引出数据 - -个性化设计(自带 Vue 界面,plugin.json 声明 "ui": true): - - ERP 新/旧系统、登录账号密码由用户在插件窗口内自行填写, - 经 /api/plugin-config 保存在执行机本机,下次打开自动回填; - - 仓库编码、日期选项均为多选(可自建条目,日期可混入自定义区间); - - 浏览器现场真登录(固定默认用户目录,保留登录态/配置),确保用的就是本次配置的账号。 -""" -import time -from datetime import datetime -from pathlib import Path - -from webhost.backend.plugins.base import PLUGINS, ScenePlugin - -from . import config -from .data import erp_login - -# 执行模式 -MODE_31 = '物料收发汇总表' -MODE_32 = '采购订单列表' -MODE_BOTH = '两个都导' - - -def _as_str_list(value): - """fields 里的多选值归一为去空去重的字符串列表(兼容逗号/空格分隔的字符串)。""" - if value is None: - return [] - if isinstance(value, str): - parts = value.replace(',', ',').replace(' ', ',').split(',') - elif isinstance(value, (list, tuple)): - parts = list(value) - else: - parts = [value] - out, seen = [], set() - for p in parts: - s = str(p).strip() - if s and s not in seen: - seen.add(s) - out.append(s) - return out - - -class ErpReportExportPlugin(ScenePlugin): - id = "xq0031_xq0032" - name = "ERP物料收发汇总-采购订单报表导出" - version = "1.0.13" - description = "金蝶K3Cloud报表导出:物料收发汇总表+ 采购订单列表,支持新旧系统与个性化配置" - platform = "" # ERP 自带登录页(无验证码),插件内现场真登录,不使用底座共享登录态 - uses_month = False - # 富字段声明(与 plugin.json 保持一致):ui=true 时壳子隐藏通用表单、展示打开插件窗口入口; - # 此处仅作为无 manifest 时的兜底与参数契约文档 - fields = [ - {"key": "mode", "label": "执行模式", "type": "select", - "options": [MODE_BOTH, MODE_31, MODE_32], "default": MODE_BOTH}, - {"key": "erp_system", "label": "ERP系统", "type": "select", - "options": ["新版", "旧版"], "default": "新版"}, - {"key": "erp_username", "label": "ERP登录账号", "type": "text", "default": ""}, - {"key": "erp_password", "label": "ERP登录密码", "type": "password", "default": ""}, - {"key": "org_name", "label": "查询组织", "type": "text", - "default": config.ORG_NAME}, - {"key": "stock_codes", "label": "仓库编码(多选,或关系)", "type": "multiselect", - "options": config.STOCK_CODES_DEFAULT + config.STOCK_CODES_DEFAULT_OLD, - "default": list(config.STOCK_CODES_DEFAULT)}, - {"key": "date_options", "label": "日期选项(多选,逐个导出)", "type": "multiselect", - "options": config.DATE_OPTIONS_DEFAULT, "default": list(config.DATE_OPTIONS_DEFAULT)}, - {"key": "scheme_name", "label": "采购订单快捷方案", "type": "text", - "default": config.SCHEME_NAME}, - {"key": "save_dir", "label": "保存目录(空=桌面/采购计划报表_日期)", "type": "text", "default": ""}, - ] - - def run(self, fields: dict, ctx) -> dict: - fields = fields or {} - # 注入日志钩子(插件内全部模块经 config.log 输出) - config.set_log(ctx.log) - - # ---------- 解析与校验 ---------- - mode = str(fields.get("mode") or MODE_BOTH).strip() - erp = 'old' if str(fields.get("erp_system") or "新版").strip() == "旧版" else 'new' - username = str(fields.get("erp_username") or "").strip() - password = str(fields.get("erp_password") or "") - org = str(fields.get("org_name") or "").strip() or ( - config.ORG_NAME_OLD if erp == 'old' else config.ORG_NAME) - scheme = str(fields.get("scheme_name") or "").strip() or config.SCHEME_NAME - codes = _as_str_list(fields.get("stock_codes")) # 空 = 全部仓库不筛选 - dates = _as_str_list(fields.get("date_options")) or list(config.DATE_OPTIONS_DEFAULT) - if not username or not password: - raise RuntimeError("ERP 登录账号/密码缺失:请在插件界面填写并保存配置后重试") - if mode not in (MODE_BOTH, MODE_31, MODE_32): - raise RuntimeError(f"未知执行模式:{mode}") - if mode in (MODE_BOTH, MODE_31) and not dates: - raise RuntimeError("物料收发汇总表需要日期选项(请在插件界面配置);仓库编码可留空=下载全部仓库") - - save_dir_raw = str(fields.get("save_dir") or "").strip().strip('"') - save_dir = Path(save_dir_raw) if save_dir_raw else Path( - _desktop()) / f"{config.FOLDER_NAME}_{datetime.now():%Y-%m-%d}" - save_dir.mkdir(parents=True, exist_ok=True) - ctx.log(f"保存目录: {save_dir}") - - # ---------- 登录(一次,两种报表共用会话) ---------- - ctx.progress(3) - ctx.log(f"ERP 系统:{'新版' if erp == 'new' else '旧版'}({erp_login.ERP_URLS[erp]}),查询组织:{org}") - ok, page = erp_login.erp_login(erp, username, password) - if not ok: - raise RuntimeError("ERP 登录失败(账号密码错误或网络异常),详见日志") - ctx.progress(8) - - # ---------- 执行计划与整体进度(进度 = 8 + 88*已完成单元/总单元) ---------- - do_31 = mode in (MODE_BOTH, MODE_31) - do_32 = mode in (MODE_BOTH, MODE_32) - units_31 = len(dates) if do_31 else 0 - total = units_31 + (1 if do_32 else 0) - - def _report(done_abs): - ctx.progress(8 + int(88 * done_abs / max(1, total))) - - saved, failed = [], [] - try: - try: - page.set.window.max() - except Exception: - pass - time.sleep(1) - from .logic import material_summary, purchase_order - from .report.merge_summary import merge_summary - - if do_31: - try: - ctx.log(f"开始导出物料收发汇总表:下载全部仓库,按所选 {len(codes)} 个仓库中文名筛选" if codes else "开始导出物料收发汇总表:下载全部仓库(未筛选)") - files31, failed31 = material_summary.run( - page, save_dir, org, codes, dates, - progress=lambda done_i, _total: _report(done_i), - set_org=True) # 新旧系统均显式设置查询组织(旧系统登录默认组织已不再默认) - saved += files31 - failed += [f"物料收发汇总表[{x}]" for x in failed31] - except RuntimeError as e: - failed.append(f"物料收发汇总表[{e}]") - files31 = [] - # 各档报表导出后合并为汇总文件(合并失败不阻断整体结果) - if files31: - try: - merged = merge_summary(save_dir) - if merged: - saved.append(str(merged)) - except Exception as e: - ctx.log(f"汇总文件生成失败: {e}") - if do_32: - try: - ctx.log(f"开始导出采购订单列表(方案:{scheme})") - f32 = purchase_order.run(page, save_dir, scheme, erp=erp, - progress=lambda _i, _t: _report(units_31 + 1)) - if f32: - saved.append(f32) - else: - failed.append("采购订单列表") - except RuntimeError as e: - failed.append(f"采购订单列表[{e}]") - finally: - try: - page.quit() - except Exception: - pass - ctx.progress(100) - - # ---------- 汇总 ---------- - notes = [f"已保存 {len(saved)} 个文件:"] + [f" {p}" for p in saved] - if failed: - notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}") - summary = f"导出完成(部分失败):成功 {len(saved)} 个,失败 {len(failed)} 项" - else: - summary = f"导出完成:共 {len(saved)} 个文件 → {save_dir}" - return {"summary": summary, "rows": [], "notes": notes} - - -# ================== 小工具 ================== -def _desktop(): - from .data.k3_common import get_desktop - return get_desktop() - - -PLUGINS.append(ErpReportExportPlugin()) +# -*- coding: utf-8 -*- +"""ERP报表导出 - webhost 场景插件(XQ0031 + XQ0032 合并版,WebAPI 接口版) + +金蝶 K3Cloud 报表自动导出,两种报表可单选或同次会话连导(登录一次): + 物料收发汇总表(XQ0031):WebAPI 分页报表取数 → 逐日期档落 xlsx → 合并汇总 + 采购订单列表(XQ0032):ExecuteBillQuery 取数 → 落 xlsx + +实现要点(2026-11 改造): + - 全程**不启动浏览器**:插件里保存的 ERP 账号密码走 WebAPI 账密登录 + (AuthService.ValidateUser,账套标识按新旧系统内置),一次登录两报表共用会话; + - 通用 ERP 能力来自公共库 erpsdk(SDK 下发,见 plugin.json requires.sdks); + - 原 UI 自动化代码(DrissionPage)保留在 data/erp_login.py、logic/*.py 的 run() 中作为历史参考, + 新流程不再调用。 +""" +import time +from datetime import datetime +from pathlib import Path + +from webhost.backend.plugins.base import PLUGINS, ScenePlugin + +from . import config + +# 执行模式 +MODE_31 = '物料收发汇总表' +MODE_32 = '采购订单列表' +MODE_BOTH = '两个都导' + + +def _as_str_list(value): + """fields 里的多选值归一为去空去重的字符串列表(兼容逗号/空格分隔的字符串)。""" + if value is None: + return [] + if isinstance(value, str): + parts = value.replace(',', ',').replace(' ', ',').split(',') + elif isinstance(value, (list, tuple)): + parts = list(value) + else: + parts = [value] + out, seen = [], set() + for p in parts: + s = str(p).strip() + if s and s not in seen: + seen.add(s) + out.append(s) + return out + + +class ErpReportExportPlugin(ScenePlugin): + id = "xq0031_xq0032" + name = "ERP物料收发汇总-采购订单报表导出" + version = "1.1.4" + description = "金蝶K3Cloud报表导出(WebAPI 接口版,无浏览器):物料收发汇总表+ 采购订单列表,支持新旧系统与个性化配置" + platform = "" # 走 WebAPI 账密登录,不使用底座共享登录态 + uses_month = False + # 富字段声明(与 plugin.json 保持一致):ui=true 时壳子隐藏通用表单、展示打开插件窗口入口; + # 此处仅作为无 manifest 时的兜底与参数契约文档 + fields = [ + {"key": "mode", "label": "执行模式", "type": "select", + "options": [MODE_BOTH, MODE_31, MODE_32], "default": MODE_BOTH}, + {"key": "erp_system", "label": "ERP系统", "type": "select", + "options": ["新版", "旧版"], "default": "新版"}, + {"key": "erp_username", "label": "ERP登录账号", "type": "text", "default": ""}, + {"key": "erp_password", "label": "ERP登录密码", "type": "password", "default": ""}, + {"key": "org_name", "label": "查询组织", "type": "text", + "default": config.ORG_NAME}, + {"key": "stock_codes", "label": "仓库编码(多选,或关系)", "type": "multiselect", + "options": config.STOCK_CODES_DEFAULT + config.STOCK_CODES_DEFAULT_OLD, + "default": list(config.STOCK_CODES_DEFAULT)}, + {"key": "date_options", "label": "日期选项(多选,逐个导出)", "type": "multiselect", + "options": config.DATE_OPTIONS_DEFAULT, "default": list(config.DATE_OPTIONS_DEFAULT)}, + {"key": "scheme_name", "label": "采购订单快捷方案", "type": "text", + "default": config.SCHEME_NAME}, + {"key": "save_dir", "label": "保存目录(空=桌面/采购计划报表_日期)", "type": "text", "default": ""}, + ] + + def run(self, fields: dict, ctx) -> dict: + fields = fields or {} + # 注入日志钩子(插件内全部模块经 config.log 输出) + config.set_log(ctx.log) + + # ---------- 解析与校验 ---------- + mode = str(fields.get("mode") or MODE_BOTH).strip() + erp = 'old' if str(fields.get("erp_system") or "新版").strip() == "旧版" else 'new' + username = str(fields.get("erp_username") or "").strip() + password = str(fields.get("erp_password") or "") + org = str(fields.get("org_name") or "").strip() or ( + config.ORG_NAME_OLD if erp == 'old' else config.ORG_NAME) + scheme = str(fields.get("scheme_name") or "").strip() or config.SCHEME_NAME + codes = _as_str_list(fields.get("stock_codes")) # 空 = 全部仓库不筛选 + dates = _as_str_list(fields.get("date_options")) or list(config.DATE_OPTIONS_DEFAULT) + if not username or not password: + raise RuntimeError("ERP 登录账号/密码缺失:请在插件界面填写并保存配置后重试") + if mode not in (MODE_BOTH, MODE_31, MODE_32): + raise RuntimeError(f"未知执行模式:{mode}") + if mode in (MODE_BOTH, MODE_31) and not dates: + raise RuntimeError("物料收发汇总表需要日期选项(请在插件界面配置);仓库编码可留空=下载全部仓库") + + save_dir_raw = str(fields.get("save_dir") or "").strip().strip('"') + save_dir = Path(save_dir_raw) if save_dir_raw else Path( + _desktop()) / f"{config.FOLDER_NAME}_{datetime.now():%Y-%m-%d}" + save_dir.mkdir(parents=True, exist_ok=True) + ctx.log(f"保存目录: {save_dir}") + + # ---------- 执行计划与整体进度(进度 = 8 + 88*已完成单元/总单元) ---------- + do_31 = mode in (MODE_BOTH, MODE_31) + do_32 = mode in (MODE_BOTH, MODE_32) + units_31 = len(dates) if do_31 else 0 + total = units_31 + (1 if do_32 else 0) + + def _report(done_abs): + ctx.progress(8 + int(88 * done_abs / max(1, total))) + + saved, failed = [], [] + need_api = do_31 or (do_32 and config.PO_USE_API) + need_browser = do_32 and not config.PO_USE_API + + from .logic import material_summary, purchase_order + from .report.merge_summary import merge_summary + from .data import k3_report_api + + # ---------- WebAPI 账密登录(报表接口需要时) ---------- + client = None + if need_api: + ctx.progress(8) + ctx.log(f"WebAPI 登录 ERP:{'新版' if erp == 'new' else '旧版'}" + f"({config.REPORT_HOST[erp]},账套 {config.REPORT_ACCT_ID[erp]})") + try: + client = k3_report_api.login(erp, username, password) + except Exception as e: + raise RuntimeError(f"ERP WebAPI 登录失败(账号密码错误或网络异常):{e}") + + # ---------- 采购订单列表仍走浏览器时,才打开页面 ---------- + page = None + if need_browser: + from .data import erp_login + ctx.log("采购订单列表使用浏览器导出(接口列格式待与历史文件核对后再启用)") + ok, page = erp_login.erp_login(erp, username, password) + if not ok: + raise RuntimeError("ERP 登录失败(账号密码错误或网络异常),详见日志") + try: + page.set.window.max() + except Exception: + pass + time.sleep(1) + + try: + files31 = [] + if do_31: + ctx.log(f"查询组织:{org};仓库:{'、'.join(codes) if codes else '全部'};" + f"日期档:{'、'.join(dates)}") + try: + files31, failed31 = material_summary.run_api( + erp, username, password, save_dir, org, codes, dates, + progress=lambda done_i, _t: _report(done_i), session=client) + saved += files31 + failed += [f"物料收发汇总表[{x}]" for x in failed31] + ctx.log(f"物料收发汇总表完成:成功 {len(files31)} 档,失败 {len(failed31)} 档") + except Exception as e: + failed.append(f"物料收发汇总表[{e}]") + files31 = [] + ctx.log(f"物料收发汇总表导出失败:{e}") + + # 各档报表导出后合并为汇总文件(合并失败不阻断整体结果) + if files31: + try: + merged = merge_summary(save_dir) + if merged: + saved.append(str(merged)) + except Exception as e: + ctx.log(f"汇总文件生成失败: {e}") + + if do_32: + try: + if config.PO_USE_API: + ctx.log(f"开始导出采购订单列表(WebAPI,{len(config.PO_COLUMNS[erp])} 列)") + f32 = purchase_order.run_api( + erp, username, password, save_dir, + progress=lambda _i, _t: _report(units_31 + 1), session=client) + else: + ctx.log(f"开始导出采购订单列表(浏览器模式,方案:{scheme})") + f32 = purchase_order.run(page, save_dir, scheme, erp=erp, + progress=lambda _i, _t: _report(units_31 + 1)) + if f32: + saved.append(f32) + else: + failed.append("采购订单列表") + except Exception as e: + failed.append(f"采购订单列表[{e}]") + ctx.log(f"采购订单列表导出失败:{e}") + finally: + if page is not None: + try: + page.quit() + except Exception: + pass + + ctx.progress(100) + + # ---------- 汇总 ---------- + notes = [f"已保存 {len(saved)} 个文件:"] + [f" {p}" for p in saved] + if failed: + notes.append(f"失败 {len(failed)} 项:{'、'.join(failed)}") + summary = f"导出完成(部分失败):成功 {len(saved)} 个,失败 {len(failed)} 项" + else: + summary = f"导出完成:共 {len(saved)} 个文件 → {save_dir}" + return {"summary": summary, "rows": [], "notes": notes} + + +# ================== 小工具 ================== +def _desktop(): + from .data.k3_common import get_desktop + return get_desktop() + + +PLUGINS.append(ErpReportExportPlugin()) diff --git a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/config/__init__.py b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/config/__init__.py index 0122566..53d0285 100644 --- a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/config/__init__.py +++ b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/config/__init__.py @@ -39,6 +39,94 @@ FILE_PREFIX_32 = '采购订单列表' # 32 导出文 RETRY_MAX = 3 TIMEOUT = 15 # 元素查找超时(秒) +# ==================== 2.5 接口版(WebAPI 报表取数)参数 ==================== +# 报表 WebAPI:Kingdee.K3.SCM.WebApi.ServicesStub.StockReportQueryService.GetReportData +# 实测(2026-11):与人工「引出」结果逐行一致;速度快且不受 UI 标签页/悬浮菜单影响 +REPORT_FORM_ID = 'STK_StockSummaryRpt' # 物料收发汇总表 +REPORT_HOST = {'new': 'criterion.erp.37du.co', 'old': 'erp.37du.co'} +REPORT_ACCT_ID = {'new': '6877090c6dcab8', 'old': '66eeb951ca7364'} # 数据中心(账套)标识 +# 过滤方案:必须是有元数据的方案(系统默认方案接口取不到数据) +# new 6af7c530351093 = API专用(共享);old 6af7c79a351208 = API专用(共享) +REPORT_SCHEME = {'new': '6af7c530351093', 'old': '6af7c79a351208'} +# 组织机构编码 → 内码(快捷条件 StockOrgId 只认内码;内码为账套级,不随账号变化) +REPORT_ORG_ID = { + 'new': {'99.01': '100084'}, + 'old': {'99.01.07.01.01': '100159'}, +} +REPORT_API_TIMEOUT = 240 # 报表取数较慢,单次最长 240 秒 +REPORT_API_PAGE = 5000 # 单次最多取 5000 行(接口上限 10000) +REPORT_LOGIN_ACCT = REPORT_ACCT_ID + +# ==================== 2.6 需求32 采购订单列表(接口版) ==================== +# 列结构按 2026-11-14 历史导出样例逐列对齐:新版 22 列 / 旧版 17 列,表头均在第 1 行,末行合计 +PO_USE_API = True +PO_FORM_ID = 'PUR_PurchaseOrder' +PO_PAGE_SIZE = 2000 +PO_ORDER_STRING = 'FID DESC' +PO_MAX_ROWS = 300000 # 安全上限(旧版石桥铺会馆含直拨单,实测约 11.7 万行) +# (中文列名, 接口字段, 值类型);类型决定落 Excel 前的转换:text/date/status/number +_PO_COLS_NEW = [ + ('采购日期', 'FDate', 'date'), + ('单据编号', 'FBillNo', 'text'), + ('单据状态', 'FDocumentStatus', 'status'), + ('采购组织', 'FPurchaseOrgId.FName', 'text'), + ('供应商', 'FSupplierId.FName', 'text'), + ('申请说明', 'F_VTUY_Remarks_tzk', 'text'), + ('反写付款供应商', 'F_VTUY_SupplierId_re5.FName', 'text'), + ('审批意见', 'F_ZFIU_ApprovalOpinion', 'text'), + ('整单价税合计', 'FBillAllAmount', 'number'), + ('需求组织', 'FRequireOrgId.FName', 'text'), + ('物料编码', 'FMaterialId.FNumber', 'text'), + ('物料名称', 'FMaterialId.FName', 'text'), + ('规格型号', 'FMaterialId.FSpecification', 'text'), + ('采购数量', 'FQty', 'number'), + ('采购单位', 'FUnitId.FName', 'text'), + ('变更前含税单价', 'F_VTUY_Price_qtr', 'number'), + ('剩余入库数量', 'FRemainStockINQty', 'number'), + ('当前含税单价', 'FTaxPrice', 'number'), + ('价税合计', 'FAllAmount', 'number'), + ('付款条件', 'FPayConditionId.FName', 'text'), + ('仓库', 'FStockId.FName', 'text'), + ('创建人', 'FCreatorId.FName', 'text'), +] +_PO_COLS_OLD = [ + ('采购日期', 'FDate', 'date'), + ('单据编号', 'FBillNo', 'text'), + ('采购组织', 'FPurchaseOrgId.FName', 'text'), + ('供应商', 'FSupplierId.FName', 'text'), + ('申请说明', 'F_VTUY_Remarks_tzk', 'text'), + ('反写付款供应商', 'F_VTUY_SupplierId_re5.FName', 'text'), + ('审批意见', 'F_ZFIU_ApprovalOpinion', 'text'), + ('整单价税合计', 'FBillAllAmount', 'number'), + ('需求组织', 'FRequireOrgId.FName', 'text'), + ('物料编码', 'FMaterialId.FNumber', 'text'), + ('物料名称', 'FMaterialId.FName', 'text'), + ('规格型号', 'FMaterialId.FSpecification', 'text'), + ('采购数量', 'FQty', 'number'), + ('采购单位', 'FUnitId.FName', 'text'), + ('变更前含税单价', 'F_VTUY_Price_qtr', 'number'), + ('当前含税单价', 'FTaxPrice', 'number'), + ('价税合计', 'FAllAmount', 'number'), +] +PO_COLUMNS = {'new': _PO_COLS_NEW, 'old': _PO_COLS_OLD} +PO_FIELD_KEYS = {k: ','.join(f for _n, f, _t in v) for k, v in PO_COLUMNS.items()} +# 单据状态码 → 中文(与人工导出显示一致) +PO_STATUS_MAP = {'A': '创建', 'B': '审核中', 'C': '已审核', 'D': '重新审核', 'Z': '暂存'} +# 合计行只汇总这两列(与 K3「按列表引出数据」产物一致) +PO_SUM_COLUMNS = ('采购数量', '价税合计') +# 过滤条件:历史样例只含「重庆金七象供应链管理有限公司」采购组织的单据, +# 接口不限组织会连其它组织一起拉(实测 5 万+ 行),故显式带上组织条件。 +PO_FILTER_STRING = { + # 历史样例口径:仅「金七象」采购组织、仅标准采购订单、排除已作废单据 + 'new': ("FPurchaseOrgId.FName='重庆金七象供应链管理有限公司'" + " and FBillTypeID.FName='标准采购订单'" + " and FCancelStatus='A'"), + # 旧系统:采购组织 = 99.01.07.01.01 石桥铺会馆(内码 100159),只排除已作废单据; + # 单据类型不限制(直拨/标准/直运都导出) + 'old': ("FPurchaseOrgId.FNumber='99.01.07.01.01'" + " and FCancelStatus='A'"), +} + # ==================== 3. 日志钩子(print → ctx.log) ==================== _log_fn = print diff --git a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/data/k3_report_api.py b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/data/k3_report_api.py new file mode 100644 index 0000000..4e1233f --- /dev/null +++ b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/data/k3_report_api.py @@ -0,0 +1,59 @@ +# -*- coding: utf-8 -*- +"""物料收发汇总表 —— 报表取数的插件内适配层(底层能力在 erpsdk)。 + +本模块只保留「插件口径」相关的部分(组织编码→内码、过滤方案、仓库条件、插件日志), +登录/会话/分页/接口协议全部交给 erpsdk(公共库,SDK 下发)。 + +实测口径(2026-11,与人工「引出」逐行一致): + - 时间范围:快捷条件 BeginDate / EndDate; + - 库存组织:快捷条件 StockOrgId,值必须是组织**内码**; + - 仓库:高级条件 FSTOCKNUMBER(编码列,多条 OR); + - 过滤方案必须是有元数据的方案(系统默认方案返回 0 行)。 +""" +from erpsdk import ErpClient, ErpError + +from .. import config + +# 内网 ERP 是自签/内部证书,requests 默认会因 verify=False 抛 InsecureRequestWarning, +# 写 stderr 被壳子记成 [ERROR]。这里统一压掉(erpsdk 0.1.1 起也内置了同样的处理)。 +import urllib3 +from urllib3.exceptions import InsecureRequestWarning + +urllib3.disable_warnings(InsecureRequestWarning) + +TAG = '[物料收发汇总表-接口]' + + +def org_id(erp, org_text): + """组织显示名(如「99.01 重庆金七象供应链管理有限公司」)→ 接口所需内码。""" + code = str(org_text or '').strip().split(' ')[0].split('\u3000')[0] + mapping = config.REPORT_ORG_ID.get(erp, {}) + if code in mapping: + return mapping[code] + raise ErpError(f'查询组织「{org_text}」没有配置内码({erp}),' + f'请在 config.REPORT_ORG_ID 补充:{code} → <组织内码>') + + +def login(erp, username, password): + """账密登录,返回可复用的 ErpClient。""" + client = ErpClient(erp, timeout=60, logger=config.log, retry=config.RETRY_MAX) + client.login(username, password) + return client + + +def session_alive(client, erp=None): + return bool(client and client.session_alive()) + + +def fetch(erp, username, password, begin, end, org_text, stock_codes, + progress=None, session=None): + """取一档日期的报表数据,返回 (rows, client);client 可在多档之间复用。""" + if session is None or not session.session_alive(): + session = login(erp, username, password) + rows = session.report_query( + config.REPORT_FORM_ID, config.REPORT_SCHEME[erp], begin, end, + org_id=org_id(erp, org_text), stock_codes=stock_codes, + limit=config.REPORT_API_PAGE, progress=progress) + if not rows: + config.log(f'{TAG} {begin}~{end} 无数据(组织/仓库/日期或方案口径可能不匹配)') + return rows, session diff --git a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/logic/material_summary.py b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/logic/material_summary.py index 1b3d310..7bb570a 100644 --- a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/logic/material_summary.py +++ b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/logic/material_summary.py @@ -1010,3 +1010,114 @@ def run(page, save_dir, org, codes, date_options, progress=None, set_org=True): pass time.sleep(1) return saved, failed + + +# ================== 接口版(WebAPI 取数,无浏览器) ================== +# 列结构按 ERP 系统区分:新版 12 列(含规格型号、货主两列);旧版 11 列(仓库在第一列、多库存周转天数) +_COLUMNS = { + 'new': ['物料编码', '物料名称', '规格型号', '仓库名称', '货主类型', '货主', + '库存单位', '期初', '收入', '发出', '结存', '库存周转次数'], + 'old': ['仓库名称', '物料编码', '物料名称', '规格型号', '库存单位', + '期初', '收入', '发出', '结存', '库存周转次数', '库存周转天数'], +} +# 字段映射:列名 → 接口字段 +_FIELD_MAP = { + '物料编码': 'FMATERIALNUMBER', '物料名称': 'FMATERIALNAME', '规格型号': 'FMATERIALMODEL', + '仓库名称': 'FSTOCKNAME', '货主类型': 'FOWNERTYPENAME', '货主': 'FOWNERNAME', + '库存单位': 'FSTOCKUNITNAME', + '期初': 'FSTOCKQCQTY', '收入': 'FSTOCKINQTY', '发出': 'FSTOCKOUTQTY', '结存': 'FSTOCKJCQTY', + '库存周转次数': 'finvturnovernum', '库存周转天数': 'finvturnoverdays', +} +_NUM_COLS = ('期初', '收入', '发出', '结存') + + +def _write_api_excel(erp, path, rows, begin, end, org, codes, label): + """把接口行写成与「引出」结构一致的 xlsx: + 前 3 行说明 + 第 4 行表头 + 数据行 + 末行合计(merge_summary 依赖第 4 行表头与末行汇总)。""" + import openpyxl + cols = _COLUMNS[erp] + # 排序:新版按物料编码;旧版按仓库名再物料编码(与人工导出顺序一致) + if erp == 'new': + rows = sorted(rows, key=lambda x: str(x.get('FMATERIALNUMBER') or '')) + else: + rows = sorted(rows, key=lambda x: (str(x.get('FSTOCKNAME') or ''), + str(x.get('FMATERIALNUMBER') or ''))) + + wb = openpyxl.Workbook() + ws = wb.active + ws.title = 'Sheet1' + # 前 3 行说明行:与 K3「引出」文件保持一致(下游报表只依赖第 4 行表头与数据列顺序) + owner = str((rows[0].get('FOWNERNAME') if rows else '') or '').strip() + ws.cell(1, 1, '货主类型:业务组织') + ws.cell(1, 2, f'货主:{owner}') + ws.cell(1, 3, f'库存组织:{org}') + ws.cell(2, 1, f'起始日期:{begin}') + ws.cell(2, 2, f'截止日期:{end}') + ws.cell(2, 3, '物料范围:全部') + ws.cell(3, 1, f'仓库范围:{"、".join(codes) if codes else "全部"}') + ws.cell(3, 2, '期初参考价来源:期初加权平均价') + ws.cell(3, 3, '收入发出参考价:平均成本') + for c, name in enumerate(cols, start=1): + ws.cell(4, c, name) + + r = 5 + totals = {k: 0.0 for k in _NUM_COLS} + for row in rows: + for c, name in enumerate(cols, start=1): + v = row.get(_FIELD_MAP[name]) + if name in _NUM_COLS: + v = float(v or 0) + totals[name] += v + ws.cell(r, c, v) + r += 1 + # 末行合计(merge_summary 合并时会跳过最后一行) + ws.cell(r, 1, '合计') + for c, name in enumerate(cols, start=1): + if name in _NUM_COLS: + ws.cell(r, c, round(totals[name], 4)) + + wb.save(str(path)) + wb.close() + config.log(f'{TAG} 已生成 {Path(path).name}:{len(rows)} 行({label})') + return len(rows) + + +def run_api(erp, username, password, save_dir, org, codes, date_options, + progress=None, session=None): + """接口版导出:WebAPI 登录一次,逐日期选项取数并落 xlsx(不打开浏览器)。 + + 参数与 UI 版 run() 对齐;session 可传入已登录的 ErpClient(两种报表共用)。 + 返回 (saved_files, failed_labels);失败时抛异常,由调用方决定是否回退 UI 版。 + """ + from ..data import k3_report_api + + session = session or k3_report_api.login(erp, username, password) + saved, failed = [], [] + total = max(1, len(date_options)) + for i, option in enumerate(date_options): + begin, end, label = resolve_dates(option) + config.log(f'{TAG} [{label}] 接口取数 {begin} ~ {end}') + try: + rows, session = k3_report_api.fetch( + erp, username, password, begin, end, org, codes, session=session) + except Exception as e: + if '会话信息已丢失' in str(e) or not k3_report_api.session_alive(session, erp): + # 会话中途失效:重登一次再取 + config.log(f'{TAG} 会话失效,重新登录后重取:{e}') + session = k3_report_api.login(erp, username, password) + rows, session = k3_report_api.fetch( + erp, username, password, begin, end, org, codes, session=session) + else: + raise + if not rows: + failed.append(label) + else: + fpath = Path(save_dir) / f'{config.FILE_PREFIX_31}_{label}.xlsx' + _write_api_excel(erp, fpath, rows, begin, end, org, codes, label) + saved.append(str(fpath)) + if progress: + try: + progress(i + 1, total) + except Exception: + pass + return saved, failed diff --git a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/logic/purchase_order.py b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/logic/purchase_order.py index b5ffddb..d2242c4 100644 --- a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/logic/purchase_order.py +++ b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/logic/purchase_order.py @@ -508,3 +508,125 @@ def run(page, save_dir, scheme, erp='new', progress=None): except Exception: pass return None + + +# ================== 接口版(WebAPI 取数,无浏览器) ================== +def _po_fmt_date(v): + """接口日期 "2026-11-14T00:00:00" → 人工导出显示的 "2026/11/14"。""" + s = str(v or '').strip() + if not s: + return None + part = s.split('T')[0].split(' ')[0] + try: + y, m, d = part.split('-') + return f'{int(y)}/{int(m)}/{int(d)}' + except Exception: + return part + + +def _po_fmt_num(v): + """"空白/None 留空;整数值去掉 .0,保持与人工导出一致。""" + if v is None or (isinstance(v, str) and not v.strip()): + return None + try: + f = float(v) + except Exception: + return v + return int(f) if abs(f - int(f)) < 1e-9 else f + + +def _po_fmt_text(v): + if v is None: + return None + s = str(v).strip() + if not s: + return None + # K3「按列表引出数据」把 CRLF 渲染成空行(与人工导出逐字对齐) + return s.replace('\r\n', '\n\n').replace('\r', '\n') + + +def _po_fmt_status(v): + code = str(v or '').strip() + return config.PO_STATUS_MAP.get(code, code or None) + + +def _po_fmt(v, kind): + if kind == 'date': + return _po_fmt_date(v) + if kind == 'number': + return _po_fmt_num(v) + if kind == 'status': + return _po_fmt_status(v) + return _po_fmt_text(v) + + +def run_api(erp, username, password, save_dir, progress=None, session=None): + """接口版:ExecuteBillQuery 取采购订单明细并落 xlsx(不打开浏览器)。 + + 列与过滤条件由 config.PO_COLUMNS / PO_FILTER_STRING / PO_ORDER_STRING 决定。 + 返回保存文件路径;失败抛异常(会话失效会自动重登一次)。 + """ + from erpsdk import ErpClient + import openpyxl + from datetime import datetime + from pathlib import Path + + client = session or ErpClient(erp, logger=config.log, retry=config.RETRY_MAX) + if session is None: + client.login(username, password) + + def _query(): + return client.bill_query_all( + config.PO_FORM_ID, config.PO_FIELD_KEYS[erp], + filter_string=config.PO_FILTER_STRING[erp], + order_string=config.PO_ORDER_STRING, + page_size=config.PO_PAGE_SIZE, + max_rows=config.PO_MAX_ROWS) + + try: + rows = _query() + except Exception as e: + if '会话' in str(e) or not client.session_alive(): + config.log(f'{TAG} 会话失效,重新登录后重取:{e}') + client.login(username, password) + rows = _query() + else: + raise + + if not rows: + config.log(f'{TAG} 接口返回 0 行(检查 PO_FILTER_STRING 或账号权限)') + return None + + path = Path(save_dir) / f'{config.FILE_PREFIX_32}_{datetime.now():%Y-%m-%d}.xlsx' + # 22 列、行数可能上万:用 write_only 流式写,避免逐单元格写爆内存/耗时 + cols = config.PO_COLUMNS[erp] + sum_idx = {i for i, (name, _k, _t) in enumerate(cols) if name in config.PO_SUM_COLUMNS} + totals = {i: 0.0 for i in sum_idx} + + wb = openpyxl.Workbook(write_only=True) + ws = wb.create_sheet('Sheet1') + ws.append([name for name, _k, _t in cols]) + for row in rows: + vals = [_po_fmt(row[i] if i < len(row) else None, t) + for i, (_name, _k, t) in enumerate(cols)] + for i in sum_idx: + try: + totals[i] += float(row[i] or 0) + except Exception: + pass + ws.append(vals) + total_row = [None] * len(cols) + total_row[0] = '合计' + for i, v in totals.items(): + total_row[i] = round(v, 4) + ws.append(total_row) + wb.save(str(path)) + config.log(f'{TAG} 已生成 {path.name}:{len(rows)} 行 + 合计({len(cols)} 列)') + wb.close() + config.log(f'{TAG} 已生成 {path.name}:{len(rows)} 行({len(config.PO_COLUMNS)} 列)') + if progress: + try: + progress(1, 1) + except Exception: + pass + return str(path) diff --git a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/plugin.json b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/plugin.json index 79041cc..fa16b5f 100644 --- a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/plugin.json +++ b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/plugin.json @@ -1,121 +1,128 @@ -{ - "schema_version": 1, - "id": "xq0031_xq0032", - "name": "ERP物料收发汇总-采购订单报表导出", - "version": "1.0.13", - "description": "金蝶K3Cloud报表自动导出:物料收发汇总表+ 采购订单列表,支持新旧系统、下载全部仓库后按所选仓库中文名自动筛选、日期多选(含自定义区间),个性化配置保存在本机", - "category": "报表", - "icon": "", - "platform": "", - "uses_month": false, - "ui": true, - "capabilities": [ - "xq0031_xq0032" - ], - "permissions": { - "platforms": [] - }, - "fields": { - "type": "object", - "properties": { - "mode": { - "type": "string", - "title": "执行模式", - "default": "两个都导", - "enum": [ - "两个都导", - "物料收发汇总表", - "采购订单列表" - ], - "description": "需求31=物料收发汇总表(按仓库/日期多档导出),需求32=采购订单列表(按方案导出)" - }, - "erp_system": { - "type": "string", - "title": "ERP系统", - "default": "新版", - "enum": [ - "新版", - "旧版" - ], - "description": "新版 criterion.erp.37du.co / 旧版 erp.37du.co" - }, - "erp_username": { - "type": "string", - "title": "ERP登录账号", - "default": "", - "description": "用户自己的ERP账号,保存在本机下次免填" - }, - "erp_password": { - "type": "string", - "title": "ERP登录密码", - "default": "", - "format": "password", - "description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填" - }, - "org_name": { - "type": "string", - "title": "查询组织", - "default": "99.01 重庆金七象供应链管理有限公司", - "description": "新版默认=金七象;旧版默认=99.01.07.01.01 石桥铺会馆,插件界面切换ERP系统自动带出" - }, - "stock_codes": { - "type": "array", - "title": "仓库编码(可多选)", - "items": { - "type": "string", - "enum": [ - "0101010101", - "0101010201", - "0101020201", - "0101030201", - "0101040201", - "03010127" - ] - }, - "default": [ - "0101010101", - "0101010201", - "0101020201", - "0101030201", - "0101040201" - ], - "description": "查询统一下载全部仓库,下载后按所选编码对应的中文仓库名自动筛选保存;留空=全部仓库不筛选。新版默认=五个三方仓;旧版默认=03010127(代管仓,切换ERP系统自动带出)" - }, - "date_options": { - "type": "array", - "title": "日期选项(多选,逐个导出)", - "items": { - "type": "string", - "enum": [ - "60D", - "30D", - "15D", - "7D", - "3D" - ] - }, - "default": [ - "60D", - "30D", - "15D", - "7D", - "3D" - ], - "description": "N天=今天往前推N天;可混入自定义区间如 2026-01-01~2026-09-15" - }, - "scheme_name": { - "type": "string", - "title": "采购订单快捷方案", - "default": "默认方案(个人)", - "description": "需求32使用的过滤方案名(精确匹配)" - }, - "save_dir": { - "type": "string", - "title": "保存目录", - "default": "", - "description": "留空=桌面/采购计划报表_日期" - } - }, - "required": [] - } -} +{ + "schema_version": 1, + "id": "xq0031_xq0032", + "name": "ERP物料收发汇总-采购订单报表导出", + "version": "1.1.4", + "description": "金蝶K3Cloud报表自动导出(WebAPI 接口版,无浏览器):物料收发汇总表 + 采购订单列表,一次账密登录连导两张报表,支持新旧系统、仓库多选、日期多档(含自定义区间),个性化配置保存在本机", + "category": "报表", + "icon": "", + "platform": "", + "uses_month": false, + "ui": true, + "requires": { + "sdks": { + "erpsdk": { + "compat": "^0.1" + } + } + }, + "capabilities": [ + "xq0031_xq0032" + ], + "permissions": { + "platforms": [] + }, + "fields": { + "type": "object", + "properties": { + "mode": { + "type": "string", + "title": "执行模式", + "default": "两个都导", + "enum": [ + "两个都导", + "物料收发汇总表", + "采购订单列表" + ], + "description": "需求31=物料收发汇总表(按仓库/日期多档导出),需求32=采购订单列表(按方案导出)" + }, + "erp_system": { + "type": "string", + "title": "ERP系统", + "default": "新版", + "enum": [ + "新版", + "旧版" + ], + "description": "新版 criterion.erp.37du.co / 旧版 erp.37du.co" + }, + "erp_username": { + "type": "string", + "title": "ERP登录账号", + "default": "", + "description": "用户自己的ERP账号,保存在本机下次免填" + }, + "erp_password": { + "type": "string", + "title": "ERP登录密码", + "default": "", + "format": "password", + "description": "仅保存在本机(%LOCALAPPDATA%\\37duAutomation\\plugin_configs),下次免填" + }, + "org_name": { + "type": "string", + "title": "查询组织", + "default": "99.01 重庆金七象供应链管理有限公司", + "description": "查询组织;界面候选按 ERP 系统切换:新版=99.01 重庆金七象供应链管理有限公司 / 旧版=99.01.07.01.01 石桥铺会馆" + }, + "stock_codes": { + "type": "array", + "title": "仓库编码(可多选)", + "items": { + "type": "string", + "enum": [ + "0101010101", + "0101010201", + "0101020201", + "0101030201", + "0101040201", + "03010127" + ] + }, + "default": [ + "0101010101", + "0101010201", + "0101020201", + "0101030201", + "0101040201" + ], + "description": "仓库编码(多选,或关系);界面候选按 ERP 系统切换:新版=五个三方仓 / 旧版=03010127 代管仓;留空=不限仓库" + }, + "date_options": { + "type": "array", + "title": "日期选项(多选,逐个导出)", + "items": { + "type": "string", + "enum": [ + "60D", + "30D", + "15D", + "7D", + "3D" + ] + }, + "default": [ + "60D", + "30D", + "15D", + "7D", + "3D" + ], + "description": "N天=今天往前推N天;可混入自定义区间如 2026-01-01~2026-09-15" + }, + "scheme_name": { + "type": "string", + "title": "采购订单快捷方案", + "default": "默认方案(个人)", + "description": "已弃用:接口版采购订单按固定列导出,不再使用列表快捷方案(仅浏览器兜底路径读取)" + }, + "save_dir": { + "type": "string", + "title": "保存目录", + "default": "", + "description": "留空=桌面/采购计划报表_日期" + } + }, + "required": [] + } +} diff --git a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/requirements.txt b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/requirements.txt index 4987144..8c4fb68 100644 --- a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/requirements.txt +++ b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/requirements.txt @@ -1 +1,6 @@ -DrissionPage>=4.0 +# 接口版(WebAPI)运行时依赖: +# erpsdk 由 SDK 下发机制挂载(plugin.json requires.sdks),自带 requests 依赖,无需在此声明 +# openpyxl 用于生成/合并 Excel +openpyxl>=3.0 +# 浏览器兜底路径(config.PO_USE_API=False 时)才需要: +DrissionPage>=4.0 diff --git a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/ui-src/index.html b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/ui-src/index.html index 3e4543a..5ac1389 100644 --- a/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/ui-src/index.html +++ b/plugins/XQ0001-0100/XQ0031_XQ0032 物料收发与采购订单导出/ui-src/index.html @@ -1,12 +1,12 @@ - - -
- - -((g=u.key)==null?void 0:g[h]))return 1}return 0};return e.map((i,u)=>({value:i,index:u,key:o?o(i,u):null})).sort((i,u)=>{let c=s(i,u);return c||(c=i.index-u.index),c*+n}).map(i=>i.value)},o2=function(e,t){let n=null;return e.columns.forEach(a=>{a.id===t&&(n=a)}),n},E7=function(e,t){let n=null;for(let a=0;a{n.canFocus=t,fv(n.childNodes,t)})};let QY=0;var pv=class hc{constructor(t){this.isLeafByUser=void 0,this.isLeaf=void 0,this.isEffectivelyChecked=!1,this.id=QY++,this.text=null,this.checked=!1,this.indeterminate=!1,this.data=null,this.expanded=!1,this.parent=null,this.visible=!0,this.isCurrent=!1,this.canFocus=!1;for(const n in t)Vt(t,n)&&(this[n]=t[n]);this.level=0,this.loaded=!1,this.childNodes=[],this.loading=!1,this.parent&&(this.level=this.parent.level+1)}initialize(){var o;const t=this.store;if(!t)throw new Error("[Node]store is required!");t.registerNode(this);const n=t.props;if(n&&typeof n.isLeaf<"u"){const s=zu(this,"isLeaf");qt(s)&&(this.isLeafByUser=s)}if(t.lazy!==!0&&this.data?(this.setData(this.data),t.defaultExpandAll&&(this.expanded=!0,this.canFocus=!0)):this.level>0&&t.lazy&&t.defaultExpandAll&&!this.isLeafByUser&&this.expand(),ye(this.data)||l0(this,this.data),!this.data)return;const a=t.defaultExpandedKeys,l=t.key;l&&!vn(this.key)&&a&&a.includes(this.key)&&this.expand(null,t.autoExpandParent),l&&t.currentNodeKey!==void 0&&this.key===t.currentNodeKey&&(t.currentNode&&(t.currentNode.isCurrent=!1),t.currentNode=this,t.currentNode.isCurrent=!0),t.lazy&&t._initDefaultCheckedNode(this),this.updateLeafState(),(this.level===1||((o=this.parent)==null?void 0:o.expanded)===!0)&&(this.canFocus=!0)}setData(t){ye(t)||l0(this,t),this.data=t,this.childNodes=[];let n;this.level===0&&ye(this.data)?n=this.data:n=zu(this,"children")||[];for(let a=0,l=n.length;ai&&(e.scrollTop=o-e.clientHeight)}function nR(e,t,n,a,l){const o=Date.now();let s;const i=()=>{const u=Date.now()-o,c=eR(u>a?a:u,t,n,a);tu(e)?e.scrollTo(window.pageXOffset,c):e.scrollTop=c,u{s&&al(s)}}const Qg=(e,t)=>tu(t)?e.ownerDocument.documentElement:t,eb=e=>tu(e)?window.scrollY:e.scrollTop,Ad=(e,t={})=>{Zt(e)||rn("[useLockscreen]","You need to pass a ref param to this function");const n=t.ns||me("popup"),a=S(()=>n.bm("parent","hidden"));let l=0,o=!1,s="0",i=!1;const u=()=>{i||(i=!0,setTimeout(()=>{typeof document>"u"||o&&document&&(document.body.style.width=s,aa(document.body,a.value))},200))};ce(e,c=>{if(!c){u();return}i=!1,o=!Fa(document.body,a.value),o&&(s=document.body.style.width,Va(document.body,a.value)),l=aS(n.namespace.value);const d=document.documentElement.clientHeight