diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/README.md b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/README.md index 742156f..e1f8a54 100644 --- a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/README.md +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/README.md @@ -1,82 +1,118 @@ -# XQ0013 社保费用申报导出并汇总(插件版) - -迁移自影刀工程(16 个流程,见 `docs/需求单/XQ0001-0100/XQ0013 社保费用申报导出并汇总/`)。 -目标:按月批量登录重庆社保客户端(`EPEvenue_SB.exe`),完成日常/特殊申报、申报记录导出,并合并汇总。 - -## 当前进度(v0.1.0) - -| 能力 | 影刀来源 | 状态 | -|---|---|---| -| 图像模板库(45 个) | `imagesV2.xml` + `resources/images/*.png` | ✅ 已导入 `images/`(含 `manifest.json`:threshold/gray/scales) | -| Win32 元素库(22 个) | `selectorsV2.xml` | ✅ 已导入 `selectors/selectors.xml`,`data/selectors.py` 用 FindWindowEx 逐层定位 | -| 账户列表读取/回写 | 自定义指令 `mjqywawyv` / `m8k8hi9j8` | ✅ `data/accounts.py` | -| 客户端启动 | process1 | ✅ `logic/client.start_client`(重试 3 次 + 等窗口) | -| 登录 | process2 | ✅ `logic/client.login`(元素填税号 → 滑块 → 图像点登录 → 输密码 → 等菜单栏) | -| 弹窗清理 | process3 | ✅ `logic/client.clean_popups` | -| 添加单位 | process6 | ⏳ 未迁移(新账户首次登录会明确报错提示) | -| 日常申报导出 | process4 / 9 / 10 | ⏳ 未迁移 | -| 特殊申报导出 | process5 / 13 | ⏳ 未迁移 | -| 申报记录识别 | process8 | ⏳ 未迁移 | -| 征集信息导出 | process12 | ⏳ 未迁移 | -| 明细合并(19 列去重) | merge | ⏳ 未迁移 | -| PDF 金额汇总 | process14 | ⏳ 未迁移(依赖 camelot + pymupdf,影刀版也缺依赖) | - -## 运行方式 - -插件界面选择 **执行模式 = check**:启动客户端 → 登录账户列表里第一家待执行门店 → 清弹窗 → 关闭。 -用于验证「客户端路径 / 元素库 / 模板」在当前机器是否可用,不会做任何申报动作。 - -`full` 模式目前会明确抛出「尚未迁移完成」,避免半成品误操作生产数据。 - -## 账户列表约定 - -`账户列表.xlsx`(默认 `输出目录/账户列表.xlsx`): - -| 列 | 含义 | -|---|---| -| A | 门店 | -| B | 税号 | -| C | 密码 | -| E | 执行标记:`0`=待执行,`1`=跳过;其他值(含空)跳过 | - -## 目录结构 - -``` -XQ0013 社保费用申报导出并汇总/ -├── __init__.py ScenePlugin 入口(mode=check/full) -├── plugin.json 元数据与参数表单 -├── config/__init__.py 路径常量、模板名/元素名、manifest 参数读取、日志钩子 -├── data/ -│ ├── accounts.py 账户列表读/写(A门店 B税号 C密码 E标记) -│ └── selectors.py 影刀 Win32 元素库解析与操作(查找/赋值/点击/截图/拖动) -├── logic/ -│ └── client.py 启动 / 登录 / 弹窗清理 / 关闭 -├── report/__init__.py 编排与汇总(待补) -├── images/ 45 个影刀模板 + manifest.json -├── selectors/selectors.xml 22 个 Win32 元素选择器 -├── _pack.py 打包到 dist-plugin/xq0013_v<版本>.zip -└── requirements.txt -``` - -## 依赖 - -执行机需预装(`requirements.txt` 声明): - -``` -pandas openpyxl pywin32 ddddocr -``` - -以及仓库内桌面自动化库 `desktopauto`(**SDK 下发**,不从 PyPI 装): - -`plugin.json` 已声明 `"requires": {"sdks": {"desktopauto": {"compat": "^0.4"}}}`, -执行机启动 / 登录 / 每 30 分钟按账号已授权插件的依赖自动下载并挂载。 - -> 不要再 `pip install -e <仓库>\libs\desktopauto` 预装进环境包,也不要复制进插件包: -> 环境包里若有同名包,SDK 挂载会因「SDK 包被环境包遮蔽」直接失败。 - -## 迁移注意 - -- 影刀登录用的是 **Win32 元素**(税号框 / 滑动栏)而不是图像——老 Delphi 客户端没有 UIA 树, - 但 Win32 控件层次完整,`FindWindowEx` 逐层找比图像稳,优先走 `data/selectors.py`。 -- 图像只用于「视觉判断」的位置:登录按钮、菜单栏、错误弹窗、申报页签等。 -- 影刀 `process14`(PDF 汇总)在影刀里就缺 `camelot`/`pymupdf` 依赖,迁移时一并补。 +# XQ0013 社保费用申报导出并汇总(插件版) + +迁移自生产验证过的 Python 实现(`D:\SBKHD\py`,四川/湖南实测 115~212 秒/户), +纯 Win32 消息驱动 + 影刀图像模板 + OCR。需求:按月批量登录重庆社保费管理客户端 +(`EPEvenue_SB.exe`),完成日常申报、特殊申报、申报记录导出 PDF,并合并职工未申报明细、 +汇总上下半月金额回写账户表副本。 + +> 重庆只有「日常申报 + 特殊申报」两步,**没有缴费工资申报**(那是成都/长沙的业务)。 + +## 当前进度(v0.3.0,全流程已迁移) + +| 能力 | 对应模块 | 状态 | +|---|---|---| +| 图像模板库(45 个) | `images/` + `manifest.json` | ✅ `logic/sbimg.py` | +| Win32 UI 驱动(ctypes) | `logic/sbui.py` | ✅ 管理员自检 / 消息 / 坐标 / 剪贴板 | +| OCR(desktopauto RapidOCR) | `logic/sbocr.py` | ✅ 菜单/页面按文字定位 | +| PrintWindow 位图 OCR | `logic/winprint.py` | ✅ 表格/弹窗正文(被遮挡也能抓) | +| 账户列表读写(按表头名) | `data/accounts.py` | ✅ 执行状态≠1 待跑,逐户回写 | +| 启动 / 添加单位 / 登录 / 清弹窗 | `logic/login.py` | ✅ | +| 日常申报(导出/提交) | `logic/daily_declare.py` | ✅ 汇总 xls + 职工明细 xlsx | +| 特殊缴费申报(判定/导出/提交) | `logic/special_declare.py` | ✅ | +| 申报记录 → PDF | `logic/records_export.py` | ✅ | +| 职工未申报明细合并(19 列去重) | `report/merge_detail.py` | ✅ | +| PDF 上下半月金额汇总 | `report/summarize_declare.py` | ✅ camelot + pymupdf | +| 批量循环 + 状态回写 | `logic/batch.py` | ✅(run_one / status_of / mark) | + +## 运行方式 + +插件界面选择 **执行模式**: + +- `check`:只对第一家跑 启动 → 添加单位(幂等)→ 登录 → 清弹窗 → 关闭,验证环境;不做任何申报动作。 +- `full`:逐户完整跑日常/特殊/申报记录,整批结束后合并明细 + 汇总金额。 + +**真实提交申报** 开关(`submit`)默认关闭:默认只导出不提交;开启后日常/特殊申报会真正向税局提交,不可撤销。 + +前提:执行机必须**以管理员身份运行**——客户端是 High 完整性进程,普通权限发消息会被 UIPI 拒绝 +(插件不做 runas 自提权重启,否则会脱离执行机,非管理员直接报错)。 + +## 账户列表约定 + +`账户列表.xlsx`(默认 `输出目录/账户列表.xlsx`),**按表头名定位**,表头缺失时回退 A/B/C: + +| 列名 | 含义 | +|---|---| +| 门店 | 用于产物子目录与汇总匹配 | +| 税号 | 登录用统一社会信用代码/纳税人识别号 | +| 密码 | 登录密码(密码只来自账户表,不走命令行) | +| 执行状态 | `1`=已完成(跳过);`0`/空=待执行 | +| 日常申报状态 | 回写:已导出 / 已提交 / 无数据 / 失败 | +| 特殊申报状态 | 回写:无需申报 / 已导出 / 失败 | +| 申报记录 | 回写:已导出 / 无成功记录 / 失败 | + +每户跑完立刻保存;三步都无异常才把「执行状态」置 `1`,中断可续跑。 + +## 输出目录 + +统一在 `save_dir` 下: + +``` +save_dir/ +├── 账户列表.xlsx 账户表(可被 account_file 覆盖) +├── 申报结果/<门店>/*.pdf 申报记录导出 PDF +├── 申报结果/<门店>/*.xls 日常/特殊申报汇总 xls +├── 职工未申报明细/<门店>/*.xlsx 职工未申报明细 +├── 职工未申报明细合并结果.xlsx 19 列合并去重 +├── 汇总结果/社保申报汇总_YYYY-MM_时间戳.xlsx +├── 截图/ 调试截图 +└── _run/ state.json 与 xq0013-*.log +``` + +## 目录结构 + +``` +XQ0013 社保费用申报导出并汇总/ +├── __init__.py ScenePlugin 入口(check/full 编排) +├── plugin.json 元数据与参数表单(mode/submit/client_exe/save_dir/account_file) +├── config/__init__.py 目录/客户端路径/日志钩子/账户列名/模板 manifest +├── data/accounts.py 账户表按表头名读写 +├── logic/ +│ ├── sbui.py Win32 UI 驱动(ctypes) +│ ├── sbocr.py OCR 看字/点字 +│ ├── sbimg.py 影刀模板点击 +│ ├── winprint.py PrintWindow 位图 OCR +│ ├── login.py 启动/添加单位/登录/清弹窗 +│ ├── daily_declare.py 日常申报 +│ ├── special_declare.py 特殊缴费申报 +│ ├── records_export.py 申报记录 → PDF +│ └── batch.py 多户循环与状态回写 +├── report/ +│ ├── summarize_declare.py PDF → 上下半月金额 +│ └── merge_detail.py 职工未申报明细 19 列合并 +├── images/ 45 个影刀模板 + manifest.json +├── selectors/selectors.xml 旧影刀元素库(保留资源,代码已不再使用) +├── _pack.py 打包到 dist-plugin/xq0013_v<版本>.zip +└── requirements.txt +``` + +## 依赖 + +`requirements.txt`:`pandas openpyxl pywin32 Pillow numpy pymupdf camelot-py`。 + +> **camelot / Ghostscript**:旧版 camelot(<2.0)解析 PDF 表格依赖系统安装 **Ghostscript**(`gs` 在 PATH); +> camelot 2.x 改用 pypdfium2 后端(本仓库 .venv 实测 2.0.0,无需 Ghostscript)。 +> 执行机环境包若装的是旧版 camelot,请一并安装 Ghostscript,否则汇总步骤会失败。 + +`desktopauto`(OCR / 图像匹配)**SDK 下发**,不从 PyPI 装: +`plugin.json` 已声明 `"requires": {"sdks": {"desktopauto": {"compat": "^0.5"}}}`。 +不要再 `pip install -e` 预装或复制进插件包,否则 SDK 挂载会因同名包 fail-fast。 + +## 迁移注意(关键坑位) + +- 登录用 **Win32 控件**(税号框 `TITSEdit`、列表 `TVirtualStringTree`、密码框 `TXPFamerEditEx`), + 密码窗里的「纳税人识别号/名称」是自绘文字只能 OCR;密码要全角转半角。 +- 左侧菜单是自绘无句柄,**坐标点击 + hover tooltip** 会互相打架:点完必须把鼠标挪到 (927,489)。 +- 窗口刚被拉到前台时,**第一次点击常被"激活窗口"吃掉**,所以点菜单前先 `warm_up` 点顶栏空白。 +- `PrintWindow` 在部分机器上失效(返回 ok 但位图全黑),因此页面/表格状态统一走屏幕 OCR。 +- 申报记录 PDF 写入不是原子的(先 17 字节再补全),必须等文件大小稳定才算保存完成。 +- 申报记录页「查看」按钮是最后一列,需先把表格横向滚到最右(`WM_HSCROLL, SB_RIGHT`)再 OCR。 diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/__init__.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/__init__.py index 0e946d7..ddfc49b 100644 --- a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/__init__.py +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/__init__.py @@ -1,110 +1,219 @@ -# -*- coding: utf-8 -*- -"""XQ0013 社保费用申报导出并汇总 插件入口(迁移自影刀工程 16 个流程)。 - -当前进度(v0.1.0,分阶段迁移): - ✅ 影刀 45 个图像模板 + 22 个 Win32 元素库已导入插件包(images/、selectors/) - ✅ 账户列表读取/回写(对应自定义指令 mjqywawyv / m8k8hi9j8) - ✅ 客户端启动、登录(元素填税号 + 滑块 + 图像点登录 + OCR 判账户)、弹窗清理 - ⏳ 待迁移:日常申报导出(process4/9/10)、特殊申报导出(process5/13)、申报记录识别(process8)、 - 征集信息导出(process12)、添加单位(process6)、明细合并(merge)、PDF 金额汇总(process14) - -因此 run() 目前只提供 `check` 模式(启动 → 登录第一家有账户 → 清弹窗 → 关闭), -用于验证客户端路径、元素库、模板在当前机器上是否可用;`full` 模式会明确提示未完成。 -""" -from webhost.backend.plugins.base import ScenePlugin, PLUGINS - -from . import config -from .data import accounts -from .logic import client - - -class SocialDeclarePlugin(ScenePlugin): - """社保费用申报导出并汇总(需求 XQ0013)。""" - - id = "xq0013" - name = "社保费用申报导出并汇总" - version = "0.1.1" - description = ("按月批量登录重庆社保客户端完成日常/特殊申报与记录导出并汇总。" - "当前版本已迁移:账户列表读写、客户端启动、登录(Win32 元素+图像+OCR)、弹窗清理;" - "申报导出与汇总流程待迁移,run 请使用 check 模式验证环境。") - platform = "" # 客户端本地登录,不依赖底座平台登录态 - uses_month = False - capabilities = ["xq0013"] - permissions = {"platforms": []} - fields = { - "mode": { - "type": "string", "title": "执行模式", "default": "check", - "enum": ["check", "full"], - "description": "check=只验证环境(启动→登录第一家有账户→清弹窗→关闭);" - "full=完整批量申报(申报导出流程尚未迁移,会提示未完成)", - }, - "client_exe": { - "type": "string", "title": "社保客户端程序", - "default": r"D:\Program Files (x86)\EPPortal_SB1.0\EPEvenue_SB.exe", - "description": "EPEvenue_SB.exe 的完整路径", - }, - "save_dir": { - "type": "string", "title": "输出目录", - "default": r"D:\资料\人资\社保费用申报导出汇总", - "description": "账户列表、申报结果、职工未申报明细、截图等统一根目录", - }, - "account_file": { - "type": "string", "title": "账户列表文件", "default": "", - "description": "留空 = 输出目录/账户列表.xlsx(A门店 B税号 C密码 E执行标记:0待执行/1跳过)", - }, - } - - def run(self, fields: dict, ctx): - config.set_log(ctx.log) - config.configure( - client_exe=fields.get("client_exe") or "", - save_dir=fields.get("save_dir") or "", - account_file=fields.get("account_file") or "", - ) - mode = (fields.get("mode") or "check").strip().lower() - dirs = config.ensure_dirs() - ctx.progress(2) - ctx.log(f"===== 社保费用申报({mode}):输出目录 {dirs['base']} =====", "INFO") - - acct_file = config.account_file() - accts = accounts.load_accounts(acct_file) - ctx.progress(8) - - if mode == "full": - raise RuntimeError( - "完整申报流程尚未迁移完成(日常/特殊申报导出、申报记录识别、合并与汇总)。\n" - "请先用「执行模式 = check」验证客户端路径、元素库与模板可用性。") - - # ---- check 模式:启动 → 登录第一个账户 → 清弹窗 → 关闭 ---- - acct = accts[0] - ctx.log(f"待执行账户 {len(accts)} 家,本次验证门店:{acct['store']}", "INFO") - win = None - try: - win, sel = client.start_client(config.client_exe()) - ctx.progress(35) - ok = client.login(acct["tax_no"], acct["password"], sel, store=acct["store"]) - ctx.progress(75) - client.clean_popups() - ctx.progress(90) - summary = (f"环境验证通过:门店「{acct['store']}」登录成功" - f"(窗口 {win.title},元素库 {len(sel.names())} 个元素," - f"模板 {len(config.manifest())} 个)" if ok else "登录未成功") - finally: - client.close_client() - ctx.progress(100) - - return { - "summary": summary, - "detail": { - "模式": mode, - "验证门店": acct["store"], - "待执行账户数": len(accts), - "账户列表": acct_file, - "元素库元素数": 22, - "模板数": len(config.manifest()), - }, - "path": dirs["base"], - } - - -PLUGINS.append(SocialDeclarePlugin()) +# -*- coding: utf-8 -*- +"""XQ0013 社保费用申报导出并汇总 插件入口(已迁移全流程)。 + +需求:重庆社保费管理客户端(EPPortal/EPEvenue_SB.exe)按账户列表批量 + 登录 → 日常申报导出 → 特殊申报导出 → 申报记录导出 PDF + → 职工未申报明细合并 → PDF 上下半月金额汇总回写账户表副本。 + +重庆只有「日常申报 + 特殊申报」两步,**没有缴费工资申报**(那是成都/长沙的业务)。 + +执行模式: + check 只对第一家跑 启动 → add_unit(幂等)→ 登录 → settle → 关闭,验证环境 + full 逐户完整跑,最后合并明细 + 汇总金额 + +前提:执行机必须**以管理员身份运行**(客户端是 High 完整性进程,普通权限发消息被 UIPI 拒绝)。 +本插件不做 runas 自提权重启(会脱离执行机),非管理员直接报错。 +""" +import time +import traceback + +from webhost.backend.plugins.base import ScenePlugin, PLUGINS + +from . import config +from .data import accounts +from .logic import batch, login, sbui +from .report import merge_detail, summarize_declare + + +def _as_bool(v): + if isinstance(v, str): + return v.strip().lower() in ("1", "true", "yes", "on", "是") + return bool(v) + + +class SocialDeclarePlugin(ScenePlugin): + """社保费用申报导出并汇总(需求 XQ0013)。""" + + id = "xq0013" + name = "社保费用申报导出并汇总" + version = "0.3.0" + description = ("按月批量登录重庆社保客户端,完成日常申报/特殊申报导出、" + "申报记录导出 PDF,并合并职工未申报明细、汇总上下半月金额。") + platform = "" # 客户端本地登录,不依赖底座平台登录态 + uses_month = False + capabilities = ["xq0013"] + permissions = {"platforms": []} + fields = { + "mode": { + "type": "string", "title": "执行模式", "default": "check", + "enum": ["check", "full"], + "description": "check=只验证环境(启动→登录第一家→清弹窗→关闭);" + "full=逐户完整申报导出 + 合并明细 + 金额汇总", + }, + "submit": { + "type": "boolean", "title": "真实提交申报", "default": False, + "description": "默认只导出不提交(演练);开启后日常/特殊申报会真正向税局提交,不可撤销", + }, + "client_exe": { + "type": "string", "title": "社保客户端程序", + "default": r"D:\Program Files (x86)\EPPortal_SB1.0\EPEvenue_SB.exe", + "description": "EPEvenue_SB.exe 的完整路径(其所在目录即客户端安装目录)", + }, + "save_dir": { + "type": "string", "title": "输出目录", + "default": r"D:\资料\人资\社保费用申报导出汇总", + "description": "账户列表、申报结果、职工未申报明细、汇总结果、截图等统一根目录", + }, + "account_file": { + "type": "string", "title": "账户列表文件", "default": "", + "description": "留空 = 输出目录/账户列表.xlsx(按表头名读:门店/税号/密码/执行状态/日常申报状态/特殊申报状态/申报记录)", + }, + } + + # ---------------------------------------------------------------- 入口 + def run(self, fields: dict, ctx): + config.set_log(ctx.log) + config.configure( + client_exe=fields.get("client_exe") or "", + save_dir=fields.get("save_dir") or "", + account_file=fields.get("account_file") or "", + ) + mode = (fields.get("mode") or "check").strip().lower() + if mode not in ("check", "full"): + raise RuntimeError("未知执行模式:%r(只支持 check / full)" % mode) + submit = _as_bool(fields.get("submit")) + dirs = config.ensure_dirs() + ctx.progress(2) + ctx.log("===== 社保费用申报(%s,提交=%s):输出目录 %s =====" + % (mode, submit, dirs["base"]), "INFO") + + # 环境前置:管理员 / 安全警告看门狗 / 不休眠 / 未锁屏 + sbui.require_admin() + sbui.start_security_watchdog() + sbui.keep_awake(True) + try: + sbui.assert_unlocked() + ctx.progress(6) + + acct_file = config.account_file() + sheet = accounts.AccountSheet(acct_file) + todo = sheet.accounts(redo=False) + if not todo: + raise RuntimeError("账户列表没有待执行门店(执行状态≠1):%s" % acct_file) + ctx.log("待执行 %d 家门店,账户列表:%s" % (len(todo), acct_file), "INFO") + + if mode == "check": + return self._run_check(todo[0], acct_file, dirs, ctx) + return self._run_full(todo, sheet, acct_file, submit, dirs, ctx) + finally: + sbui.keep_awake(False) + + # ---------------------------------------------------------------- check + def _run_check(self, acct, acct_file, dirs, ctx): + store = acct["store"] + ctx.log("验证门店:%s(税号 %s)" % (store, acct["tax_no"]), "INFO") + detail = {"模式": "check", "账户列表": acct_file, "验证门店": store} + try: + login.restart_client() + ctx.progress(35) + try: + login.add_unit(acct["tax_no"], acct["password"]) + detail["添加单位"] = "已完成/已存在" + except Exception as e: # noqa: BLE001 单位通常在列表里,添加失败不阻断 + ctx.log("添加单位没走通(继续尝试直接登录):%r" % e, "WARN") + detail["添加单位"] = "告警:%r" % (e,) + r = login.login(acct["tax_no"], acct["password"]) + ctx.progress(75) + login.settle() + detail["登录"] = r.get("result") + detail["模板数"] = len(config.manifest()) + summary = "环境验证通过:门店「%s」登录成功(结果=%s)" % (store, r.get("result")) + finally: + login.kill_client() + ctx.progress(100) + return {"summary": summary, "detail": detail, "path": dirs["base"]} + + # ---------------------------------------------------------------- full + def _run_full(self, todo, sheet, acct_file, submit, dirs, ctx): + total = len(todo) + per = [] + t_start = time.time() + for i, acc in enumerate(todo, 1): + ctx.progress(int(8 + 80 * (i - 1) / max(1, total))) + ctx.log("===== [%d/%d] %s =====" % (i, total, acc["store"]), "INFO") + t0 = time.time() + try: + res = batch.run_one(acc, submit=submit) + ok, daily_s, special_s, record_s = batch.mark(sheet, acc, res) + per.append({"门店": acc["store"], "税号": acc["tax_no"], + "完成": ok, "日常申报": daily_s, + "特殊申报": special_s, "申报记录": record_s, + "耗时秒": round(time.time() - t0, 1)}) + ctx.log("%s 完成(日常=%s 特殊=%s 记录=%s),%.1f 秒" + % (acc["store"], daily_s, special_s, record_s, time.time() - t0), "INFO") + except Exception as e: # noqa: BLE001 单户失败不中断整批 + ctx.log("%s 失败:%r" % (acc["store"], e), "ERROR") + for line in traceback.format_exc().splitlines(): + ctx.log(" " + line, "ERROR") + try: + sheet.set(acc["row"], config.COL_DAILY, "失败") + sheet.set(acc["row"], config.COL_SPECIAL, "失败") + sheet.set(acc["row"], config.COL_RECORD, "失败") + sheet.save() + except Exception as e2: # noqa: BLE001 + ctx.log("回写失败状态失败:%r" % e2, "WARN") + per.append({"门店": acc["store"], "税号": acc["tax_no"], + "完成": False, "错误": repr(e)[:300], + "耗时秒": round(time.time() - t0, 1)}) + finally: + login.kill_client() + + ctx.progress(90) + + # 合并职工未申报明细(失败不影响已完成的申报) + ctx.log("合并职工未申报明细 …", "INFO") + try: + files, rows = merge_detail.merge_excel(config.dirs()["detail"], config.merged_file()) + merge_info = {"文件数": files, "行数": rows, "输出": config.merged_file()} + ctx.log("合并完成:%d 个文件,%d 行 → %s" % (files, rows, config.merged_file()), "INFO") + except Exception as e: # noqa: BLE001 + merge_info = {"错误": repr(e)[:300]} + ctx.log("合并失败(不影响已完成的申报):%r" % e, "WARN") + + # 上下半月金额汇总 → 账户表副本 + ctx.log("汇总上下半月金额 → 账户表副本 …", "INFO") + try: + code, payload = summarize_declare.run_summary( + root=config.dirs()["declare"], + xlsx=acct_file, + out_dir=config.summary_dir(), + region=None, + ) + summary_info = {"code": code, + "门店数": len(payload.get("stores") or {}), + "写入户数": len(payload.get("written") or []), + "失败PDF": len(payload.get("failed") or []), + "文件": payload.get("file")} + ctx.log("金额汇总:code=%s 门店=%d 写入=%d 文件=%s" + % (code, summary_info["门店数"], summary_info["写入户数"], + summary_info["文件"]), "INFO") + except Exception as e: # noqa: BLE001 + summary_info = {"错误": repr(e)[:300]} + ctx.log("金额汇总失败(不影响已完成的申报):%r" % e, "WARN") + + ctx.progress(100) + done = sum(1 for p in per if p.get("完成")) + if summary_info.get("code") == 2 and not summary_info.get("门店数"): + summary_tail = "无当月申报" + else: + summary_tail = summary_info.get("文件") or "失败" + summary = ("批量完成:%d/%d 户成功,用时 %.0f 秒;合并明细 %s 行;金额汇总 %s" + % (done, total, time.time() - t_start, + merge_info.get("行数", "失败"), summary_tail)) + detail = {"模式": "full", "提交": submit, "账户列表": acct_file, + "待执行户数": total, "每户结果": per, + "合并明细": merge_info, "金额汇总": summary_info} + return {"summary": summary, "detail": detail, "path": dirs["base"]} + + +PLUGINS.append(SocialDeclarePlugin()) diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/_selftest.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/_selftest.py index 1901197..5eaae55 100644 --- a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/_selftest.py +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/_selftest.py @@ -2,11 +2,10 @@ """XQ0013 插件离线自测(不启动客户端、不点鼠标、不碰真实账户)。 覆盖: - 1. 配置默认值与路径推导(输出目录/账户列表/子目录) + 1. 配置默认值与路径推导(client_dir/run_dir/各输出子目录) 2. 图像模板清单(images/manifest.json)与文件存在性 - 3. Win32 元素库(selectors/selectors.xml)可解析、元素数正确 - 4. 账户列表读取规则(E 列 0 待执行 / 1 跳过 / 空跳过;缺列与空值报错) - 5. 插件入口注册(需要 webhost 运行时;缺失时 skip 不误报) + 3. 账户列表按表头名读写(执行状态≠1 待跑;表头缺失回退 A/B/C;回写落盘) + 4. 插件入口注册(需要 webhost 运行时;缺失时 skip 不误报) 由 SDK 兼容预检调用(会挂上 webhost 与各 SDK 路径);也可手工: set PYTHONPATH=desktop\\electron-shell\\python;libs\\desktopauto @@ -37,12 +36,13 @@ def skip(msg: str) -> None: SKIPS.append(msg) -def _write_accounts_xlsx(path: str, rows: list[list]) -> None: +def _write_accounts_xlsx(path: str, rows: list[list], header=None) -> None: from openpyxl import Workbook # noqa: PLC0415 wb = Workbook() ws = wb.active - ws.append(["门店", "税号", "密码", "备注", "执行标记"]) + ws.append(header or ["门店", "税号", "密码", "执行状态", + "日常申报状态", "特殊申报状态", "申报记录"]) for r in rows: ws.append(r) wb.save(path) @@ -84,6 +84,12 @@ def main() -> int: config.configure(client_exe=r"C:\tmp\EPEvenue_SB.exe", save_dir=r"C:\tmp\out", account_file=r"C:\tmp\accts.xlsx") ok(config.account_file() == r"C:\tmp\accts.xlsx", "显式账户列表路径生效") + ok(config.client_dir() == r"C:\tmp", "client_dir = 客户端 exe 所在目录") + ok(config.run_dir().endswith(os.path.join("out", config.RUN_DIR_NAME)), + "run_dir = 输出目录/_run") + ok(config.declare_dir().endswith(config.DIR_DECLARE), "申报结果目录") + ok(config.detail_dir().endswith(config.DIR_DETAIL), "职工未申报明细目录") + ok(config.summary_dir().endswith(config.DIR_SUMMARY), "汇总结果目录") ok(set(config.dirs()) >= {"base", "screenshots", "declare", "detail", "summary"}, "输出子目录齐全") config.configure("", "", "") @@ -92,66 +98,55 @@ def main() -> int: print("== 图像模板 ==") man = config.manifest() ok(len(man) >= 40, f"manifest 模板数 {len(man)}(≥40)") - missing = [k for k in config.TPL.values() if not os.path.isfile(config.template_path(k))] - ok(not missing, f"TPL 声明的模板文件都存在(缺失 {len(missing)})") - opt = config.image_opt("login_btn") - ok(bool(opt["path"]) and 0.5 <= float(opt["threshold"]) <= 1.0, - f"登录按钮匹配参数 threshold={opt['threshold']}") + missing = [k for k, v in man.items() + if not os.path.isfile(os.path.join(config.IMAGES_DIR, v.get("file") or ""))] + ok(not missing, f"manifest 声明的模板文件都存在(缺失 {len(missing)})") if pkg is None: print(f"\n失败 {len(FAILS)} 项,跳过 {len(SKIPS)} 项") return 0 if not FAILS else 1 - # ---------- 3. Win32 元素库 ---------- - print("== Win32 元素库 ==") - selectors = sub("data.selectors") - xml = HERE / "selectors" / "selectors.xml" - ok(xml.is_file(), "selectors.xml 存在") - lib = selectors.Selectors(str(xml)) - ok(len(lib.names()) >= 10, f"元素数量 {len(lib.names())}(≥10)") - - # ---------- 4. 账户列表 ---------- - print("== 账户列表读取 ==") + # ---------- 3. 账户列表 ---------- + print("== 账户列表按表头名读写 ==") accounts = sub("data.accounts") with tempfile.TemporaryDirectory() as tmp: f = os.path.join(tmp, "账户列表.xlsx") _write_accounts_xlsx(f, [ - ["A店", "91500A", "pwdA", "", "0"], - ["B店", "91500B", "pwdB", "", "1"], - ["C店", "91500C", "pwdC", "", ""], + ["A店", "91500A", "pwdA", "0", "", "", ""], + ["B店", "91500B", "pwdB", "1", "已导出", "无需申报", "已导出"], + ["C店", "91500C", "pwdC", "", "", "", ""], ]) - rows = accounts.load_accounts(f) - ok(len(rows) == 1 and rows[0]["store"] == "A店" and rows[0]["row"] == 2, - "只返回 E=0 的账户(A店,Excel 第 2 行)") + sheet = accounts.AccountSheet(f) + rows = sheet.accounts() + ok(len(rows) == 2 and {r["store"] for r in rows} == {"A店", "C店"}, + "执行状态≠1 的户待跑(A店 0 / C店 空)") + ok(all(r["row"] in (2, 4) for r in rows), "Excel 行号正确(2/4)") - f2 = os.path.join(tmp, "空.xlsx") - _write_accounts_xlsx(f2, [["D店", "91500D", "pwdD", "", "1"]]) - try: - accounts.load_accounts(f2) - ok(False, "无待执行账户应报错") - except RuntimeError as e: - ok("没有待执行账户" in str(e), "无待执行账户 → 明确报错") + sheet.set(2, "日常申报状态", "已导出") + sheet.set(2, "执行状态", config.STATE_DONE) + sheet.save() + sheet2 = accounts.AccountSheet(f) + rows2 = sheet2.accounts() + ok(len(rows2) == 1 and rows2[0]["store"] == "C店", "回写后 A店 不再待跑") + ok(sheet2.ws.cell(row=2, column=5).value == "已导出", "回写落盘成功") - f3 = os.path.join(tmp, "缺列.xlsx") - from openpyxl import Workbook # noqa: PLC0415 - wb = Workbook() - wb.active.append(["门店", "税号"]) - wb.save(f3) - try: - accounts.load_accounts(f3) - ok(False, "列数不足应报错") - except RuntimeError as e: - ok("列数不完整" in str(e), "列数不足 → 明确报错") + # 表头缺失 → 回退 A/B/C + f2 = os.path.join(tmp, "无表头.xlsx") + _write_accounts_xlsx(f2, [["D店", "91500D", "pwdD"]], header=["x", "y", "z"]) + rows3 = accounts.AccountSheet(f2).accounts() + ok(len(rows3) == 1 and rows3[0]["store"] == "D店" and rows3[0]["tax_no"] == "91500D", + "表头缺失时回退 A门店/B税号/C密码") - # ---------- 5. 插件入口 ---------- + # ---------- 4. 插件入口 ---------- print("== 插件入口 ==") plugin = getattr(pkg, "SocialDeclarePlugin", None) ok(plugin is not None, "插件类存在") if plugin is not None: ok(plugin.id == "xq0013", "插件 id = xq0013") + ok(plugin.version == "0.3.0", "插件 version = 0.3.0") fields = plugin.fields or {} - ok(set(fields) >= {"mode", "client_exe", "save_dir", "account_file"}, - "fields 声明完整(mode/client_exe/save_dir/account_file)") + ok(set(fields) >= {"mode", "submit", "client_exe", "save_dir", "account_file"}, + "fields 声明完整(mode/submit/client_exe/save_dir/account_file)") ok(callable(getattr(plugin, "run", None)), "run 可调用") print(f"\n失败 {len(FAILS)} 项" + (f",跳过 {len(SKIPS)} 项" if SKIPS else "")) diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/config/__init__.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/config/__init__.py index 510122e..e5b2e1b 100644 --- a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/config/__init__.py +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/config/__init__.py @@ -1,216 +1,227 @@ -# -*- coding: utf-8 -*- -"""XQ0013 社保费用申报导出并汇总 插件 - 配置常量与全局钩子。 - -插件自包含:只依赖 标准库 / pandas / openpyxl / pywin32 / ddddocr / desktopauto(SDK 下发,见 plugin.json.requires.sdks)。 -模板图与 Win32 元素库随插件包发布: - images/*.png + images/manifest.json 影刀图像库导出(45 个) - selectors/selectors.xml 影刀 Win32 元素库(22 个) - -运行期参数(客户端路径、账户列表路径、输出目录)由 plugin.json.fields 注入, -经 configure() 覆盖默认值;未注入时用下面的默认常量(与影刀版一致)。 -""" -import json -import os - -# ==================== 插件内资源路径 ==================== -PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) -IMAGES_DIR = os.path.join(PLUGIN_ROOT, "images") -MANIFEST_FILE = os.path.join(IMAGES_DIR, "manifest.json") -SELECTORS_XML = os.path.join(PLUGIN_ROOT, "selectors", "selectors.xml") - -# ==================== 默认业务配置(与影刀版全局变量一致) ==================== -DEFAULT_CLIENT_EXE = r"D:\Program Files (x86)\EPPortal_SB1.0\EPEvenue_SB.exe" -CLIENT_TITLE = "社保费管理客户端" -CLIENT_CLASS = "TfrmCompMgrMerge" -CLIENT_PROCESS = "EPPortalSB.exe" # 实际进程名(启动后) -CLIENT_PROCESS_ALT = "EPEvenue_SB.exe" # 可执行文件名 -DEFAULT_SAVE_DIR = r"D:\资料\人资\社保费用申报导出汇总" -ACCOUNT_FILE_NAME = "账户列表.xlsx" - -# 账户列表列约定(影刀版:A=门店 B=税号 C=密码 E=执行标记) -COL_STORE = 0 -COL_TAX_NO = 1 -COL_PASSWORD = 2 -COL_FLAG = 4 -FLAG_PENDING = "0" # E 列 = 0 → 待执行 -FLAG_DONE = "1" # E 列 = 1 → 已完成/跳过 - -# ==================== 模板名(images/manifest.json 的 key) ==================== -TPL = { - "image": "图像", - "login_btn": "登录按钮", - "login_confirm": "确定登录按钮", - "menu_bar": "菜单栏", - "error_msg": "错误信息", - "error_confirm": "错误处理确认", - "social_declare": "社保费申报", - "daily_declare": "日常申报", - "special_declare": "特殊缴费申报", - "view_detail": "查看职工未申报明细", - "detail_query_area": "职工未申报明细导出查询区域", - "detail_export": "职工未申报明细导出按钮", - "export_ok_confirm": "导出成功确定按钮", - "detail_close": "职工未申报明细关闭按钮", - "select_all": "全选复选框", - "submit_declare": "提交申报按钮", - "tip_msg": "提示信息", - "tip_confirm": "提示信息确定按钮", - "server_error": "服务器连接异常", - "server_error_confirm": "服务器连接异常确定按钮", - "refresh_btn": "刷新按钮", - "big_data": "明细数据量大", - "submit_confirm": "提交申报确认", - "submit": "提交申报", - "declare_ok": "申报成功", - "record_query": "申报结果查询", - "add_unit": "添加单位", - "next_step": "下一步", - "confirm_unit": "确认单位", - "security_auth": "安全认证", - "cancel_btn": "取消按钮", - "add_btn": "添加按钮", - "multi_source": "多数据来源", - "data_source": "数据来源", - "tax_generated": "税务生成", - "collect_info": "征集信息", - "query_btn": "查询按钮", - "declare_record": "申报记录", - "latest_status": "申报数据最新状态", - "record_query_btn": "申报结果查询按钮", - "view_btn": "查看按钮", - "export_btn": "导出按钮", - "collect_serial": "征集通知流水号", - "tax_selected": "税务生成选中", - "reset_btn": "重置按钮", -} - -# ==================== Win32 元素名(selectors/selectors.xml) ==================== -ELE = { - "tax_no_input": "税号输入框", - "password_input": "密码框", - "slider_bar": "滑动栏", - "slider_pos": "位置", - "pending_account": "待选账户", -} - -# ==================== 运行期配置(configure 注入) ==================== -_client_exe = DEFAULT_CLIENT_EXE -_save_dir = DEFAULT_SAVE_DIR -_account_file = "" - - -def configure(client_exe: str = "", save_dir: str = "", account_file: str = "") -> None: - """由插件 run() 注入本次运行的业务配置(空值保持默认)。""" - global _client_exe, _save_dir, _account_file - if (client_exe or "").strip(): - _client_exe = client_exe.strip() - if (save_dir or "").strip(): - _save_dir = save_dir.strip() - _account_file = (account_file or "").strip() - - -def client_exe() -> str: - return _client_exe - - -def save_dir() -> str: - return _save_dir - - -def account_file() -> str: - """账户列表路径:未指定则取 输出目录/账户列表.xlsx。""" - return _account_file or os.path.join(_save_dir, ACCOUNT_FILE_NAME) - - -def dirs() -> dict: - """各输出子目录(按需创建)。""" - base = _save_dir - return { - "base": base, - "screenshots": os.path.join(base, "截图"), - "declare": os.path.join(base, "申报结果"), - "detail": os.path.join(base, "职工未申报明细"), - "summary": os.path.join(base, "汇总"), - } - - -def ensure_dirs() -> dict: - d = dirs() - for key, path in d.items(): - if key != "base": - os.makedirs(path, exist_ok=True) - os.makedirs(d["base"], exist_ok=True) - return d - - -def template_path(name_key: str) -> str: - """按 TPL 的 key 取模板图绝对路径(配合 manifest 里的阈值使用)。""" - name = TPL.get(name_key, name_key) - return os.path.join(IMAGES_DIR, f"{name}.png") - - -# ==================== 图像模板参数(manifest 里的 threshold/gray/scales) ==================== -_manifest = None - - -def manifest() -> dict: - """读取 images/manifest.json(影刀 similarity/graying/adaptive 转换结果),失败返回空。""" - global _manifest - if _manifest is None: - try: - with open(MANIFEST_FILE, encoding="utf-8") as f: - _manifest = json.load(f) - except Exception: # noqa: BLE001 - _manifest = {} - return _manifest - - -def image_opt(name_key: str) -> dict: - """取某模板的匹配参数:{path, threshold, gray, scales}。""" - name = TPL.get(name_key, name_key) - meta = manifest().get(name, {}) - return { - "path": os.path.join(IMAGES_DIR, meta.get("file") or f"{name}.png"), - "threshold": float(meta.get("threshold", 0.8)), - "gray": bool(meta.get("gray", False)), - "scales": tuple(meta.get("scales") or (1.0,)), - } - - -# ==================== 日志钩子(run 时注入 ctx.log) ==================== -_log = None - - -def set_log(fn) -> None: - global _log - _log = fn - - -def log(msg, level="INFO") -> None: - if _log: - _log(str(msg), level) - else: - print(f"[{level}] {msg}") - - -class _ModuleLogger: - """模块级 logger 适配:保留 logger.info(...) 调用点,统一转发到 ctx.log。""" - - @staticmethod - def debug(msg, *args): - log(msg % args if args else msg, "DEBUG") - - @staticmethod - def info(msg, *args): - log(msg % args if args else msg, "INFO") - - @staticmethod - def warning(msg, *args): - log(msg % args if args else msg, "WARN") - - @staticmethod - def error(msg, *args): - log(msg % args if args else msg, "ERROR") - - -logger = _ModuleLogger() +# -*- coding: utf-8 -*- +"""XQ0013 社保费用申报导出并汇总 插件 - 配置常量与全局钩子。 + +插件自包含:只依赖 标准库 / 第三方(pandas、openpyxl、pywin32、Pillow、numpy、pymupdf、camelot) +/ desktopauto(SDK 下发,见 plugin.json.requires.sdks)/ webhost.backend.plugins.base。 +模板图随插件包发布:images/*.png + images/manifest.json(影刀图像库导出,供 logic/sbimg.py 用)。 + +运行期参数(客户端路径、账户列表路径、输出目录)由 plugin.json.fields 注入, +经 configure() 覆盖默认值;未注入时用下面的默认常量。 + +目录约定(全部在 save_dir 下,重庆只有一个区域,不按区域分层): + save_dir/申报结果/<门店>/*.pdf 申报记录导出 PDF + save_dir/申报结果/<门店>/*.xls 日常/特殊申报的汇总 xls + save_dir/职工未申报明细/<门店>/*.xlsx 职工未申报明细 + save_dir/汇总结果/社保申报汇总_YYYY-MM_时间戳.xlsx + save_dir/截图 调试截图 + save_dir/职工未申报明细合并结果.xlsx 合并去重后的 19 列明细 + save_dir/_run/ 运行状态(state.json)与本次日志 +""" +import json +import os +import time + +# ==================== 插件内资源路径 ==================== +PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +IMAGES_DIR = os.path.join(PLUGIN_ROOT, "images") +MANIFEST_FILE = os.path.join(IMAGES_DIR, "manifest.json") + +# ==================== 默认业务配置 ==================== +DEFAULT_CLIENT_EXE = r"D:\Program Files (x86)\EPPortal_SB1.0\EPEvenue_SB.exe" +DEFAULT_SAVE_DIR = r"D:\资料\人资\社保费用申报导出汇总" +ACCOUNT_FILE_NAME = "账户列表.xlsx" + +# 输出子目录名 +DIR_DECLARE = "申报结果" +DIR_DETAIL = "职工未申报明细" +DIR_SUMMARY = "汇总结果" +DIR_SHOTS = "截图" +RUN_DIR_NAME = "_run" +MERGED_NAME = "职工未申报明细合并结果.xlsx" + +# ==================== 账户列表列名(按表头名读写;缺失时回退 A/B/C) ==================== +COL_STORE = "门店" +COL_TAX_NO = "税号" +COL_PASSWORD = "密码" +COL_STATE = "执行状态" +COL_DAILY = "日常申报状态" +COL_SPECIAL = "特殊申报状态" +COL_RECORD = "申报记录" +STATE_DONE = "1" # 执行状态 = 1 → 已完成,默认跳过 +STATE_PENDING = "0" # 执行状态 = 0(或空)→ 待执行 + +# ==================== 运行期配置(configure 注入) ==================== +_client_exe = DEFAULT_CLIENT_EXE +_save_dir = DEFAULT_SAVE_DIR +_account_file = "" + + +def configure(client_exe="", save_dir="", account_file="") -> None: + """由插件 run() 注入本次运行的业务配置(空值保持默认)。""" + global _client_exe, _save_dir, _account_file + if (client_exe or "").strip(): + _client_exe = client_exe.strip() + if (save_dir or "").strip(): + _save_dir = save_dir.strip() + _account_file = (account_file or "").strip() + + +def client_exe() -> str: + return _client_exe + + +def client_dir() -> str: + """客户端安装目录(EPEvenue_SB.exe 所在),由客户端程序路径推导,不写死区域目录。""" + return os.path.dirname(os.path.abspath(_client_exe)) + + +def save_dir() -> str: + return _save_dir + + +def account_file() -> str: + """账户列表路径:未指定则取 输出目录/账户列表.xlsx。""" + return _account_file or os.path.join(_save_dir, ACCOUNT_FILE_NAME) + + +# ==================== 输出目录 ==================== +def safe_name(s) -> str: + """文件名/目录名净化(门店名里可能有 : / * 等非法字符)。""" + s = "".join("_" if c in '\\/:*?"<>|' else c for c in str(s or "")).strip() + return s or "未命名" + + +def dirs() -> dict: + """各输出子目录(尚未创建)。""" + base = _save_dir + return { + "base": base, + "screenshots": os.path.join(base, DIR_SHOTS), + "declare": os.path.join(base, DIR_DECLARE), + "detail": os.path.join(base, DIR_DETAIL), + "summary": os.path.join(base, DIR_SUMMARY), + } + + +def ensure_dirs() -> dict: + d = dirs() + os.makedirs(d["base"], exist_ok=True) + for key, path in d.items(): + if key != "base": + os.makedirs(path, exist_ok=True) + os.makedirs(run_dir(), exist_ok=True) + return d + + +def run_dir() -> str: + """运行状态/日志目录 = save_dir/_run(自动创建)。""" + p = os.path.join(_save_dir, RUN_DIR_NAME) + os.makedirs(p, exist_ok=True) + return p + + +def declare_dir(store="") -> str: + """申报结果目录;给门店则再下一层 <门店>(自动创建)。""" + p = dirs()["declare"] + if store: + p = os.path.join(p, safe_name(store)) + os.makedirs(p, exist_ok=True) + return p + + +def detail_dir(store="") -> str: + """职工未申报明细目录;给门店则再下一层 <门店>(自动创建)。""" + p = dirs()["detail"] + if store: + p = os.path.join(p, safe_name(store)) + os.makedirs(p, exist_ok=True) + return p + + +def summary_dir() -> str: + p = dirs()["summary"] + os.makedirs(p, exist_ok=True) + return p + + +def shots_dir() -> str: + p = dirs()["screenshots"] + os.makedirs(p, exist_ok=True) + return p + + +def merged_file() -> str: + """合并明细的固定输出路径。""" + return os.path.join(_save_dir, MERGED_NAME) + + +# ==================== 图像模板参数(manifest 里的 threshold/gray/scales) ==================== +_manifest = None + + +def manifest() -> dict: + """读取 images/manifest.json(影刀 similarity/graying/adaptive 转换结果),失败返回空。""" + global _manifest + if _manifest is None: + try: + with open(MANIFEST_FILE, encoding="utf-8") as f: + _manifest = json.load(f) + except Exception: # noqa: BLE001 + _manifest = {} + return _manifest + + +# ==================== 日志钩子(run 时注入 ctx.log) ==================== +_log = None +_log_file = None + + +def set_log(fn) -> None: + global _log + _log = fn + + +def _write_log_file(msg, level) -> None: + global _log_file + try: + if _log_file is None: + _log_file = os.path.join(run_dir(), "xq0013-%s.log" % time.strftime("%Y%m%d-%H%M%S")) + with open(_log_file, "a", encoding="utf-8") as f: + f.write("[%s][%s] %s\n" % (time.strftime("%H:%M:%S"), level, msg)) + except OSError: + pass + + +def log(msg, level="INFO") -> None: + """统一日志出口:转发 ctx.log(run 时注入),同时落一份文件到 run_dir()。""" + if _log: + try: + _log(str(msg), level) + except TypeError: + _log(str(msg)) + else: + print("[%s] %s" % (level, msg)) + _write_log_file(msg, level) + + +class _ModuleLogger: + """模块级 logger 适配:保留 logger.info(...) 调用点,统一转发到 ctx.log。""" + + @staticmethod + def debug(msg, *args): + log(msg % args if args else msg, "DEBUG") + + @staticmethod + def info(msg, *args): + log(msg % args if args else msg, "INFO") + + @staticmethod + def warning(msg, *args): + log(msg % args if args else msg, "WARN") + + @staticmethod + def error(msg, *args): + log(msg % args if args else msg, "ERROR") + + +logger = _ModuleLogger() diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/data/accounts.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/data/accounts.py index 8584373..8fdc59d 100644 --- a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/data/accounts.py +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/data/accounts.py @@ -1,123 +1,135 @@ -# -*- coding: utf-8 -*- -"""账户列表读写(对应影刀自定义指令 mjqywawyv「读取账户列表」与 m8k8hi9j8「按门店+列名写单元格」)。 - -账户列表.xlsx 约定(与影刀版一致): - A列=门店 B列=税号 C列=密码 E列=执行标记(0=待执行,1=已完成/跳过) - 只处理 E 列为 "0" 的行;E 列既非 0 也非 1(含空)→ 跳过。 -""" -from __future__ import annotations - -import os -from typing import List - -import pandas as pd - -from ..config import ( - COL_FLAG, COL_PASSWORD, COL_STORE, COL_TAX_NO, FLAG_DONE, FLAG_PENDING, logger, -) - - -def _is_empty(val) -> bool: - if pd.isna(val): - return True - return str(val).strip() == "" - - -def load_accounts(file_path: str) -> List[dict]: - """读取账户列表,返回待执行账户 [{"store","tax_no","password","row"}]。 - - 数据不一致(E列=0 但门店/税号/密码为空)直接报错,避免跑错账户。 - """ - if not os.path.isfile(file_path): - raise RuntimeError(f"未找到账户列表:{file_path}") - try: - df = pd.read_excel(file_path, engine="openpyxl", dtype=str) - except PermissionError as e: - raise RuntimeError(f"账户列表被占用,请先关闭 Excel:{file_path}") from e - except Exception as e: # noqa: BLE001 - raise RuntimeError(f"读取账户列表失败:{file_path}({e})") from e - - if len(df.columns) <= COL_FLAG: - raise RuntimeError( - f"账户列表列数不完整:需要至少 {COL_FLAG + 1} 列(A门店/B税号/C密码/E执行标记)," - f"当前 {len(df.columns)} 列") - - out: List[dict] = [] - for idx, row in df.iterrows(): - flag = "" if pd.isna(row.iloc[COL_FLAG]) else str(row.iloc[COL_FLAG]).strip() - if flag == FLAG_DONE: - continue - if flag != FLAG_PENDING: - continue # 非 0/1 一律跳过(含空值与历史脏数据) - store = str(row.iloc[COL_STORE]).strip() if not _is_empty(row.iloc[COL_STORE]) else "" - tax_no = str(row.iloc[COL_TAX_NO]).strip() if not _is_empty(row.iloc[COL_TAX_NO]) else "" - password = str(row.iloc[COL_PASSWORD]).strip() if not _is_empty(row.iloc[COL_PASSWORD]) else "" - excel_row = idx + 2 # 表头占 1 行 - if not (store and tax_no and password): - raise RuntimeError( - f"账户列表第 {excel_row} 行 E 列标记为待执行,但门店/税号/密码存在空值") - out.append({"store": store, "tax_no": tax_no, "password": password, "row": excel_row}) - - if not out: - raise RuntimeError(f"账户列表筛选后没有待执行账户(E 列没有值为 {FLAG_PENDING} 的行):{file_path}") - logger.info("账户列表读取完成:待执行 %d 家门店", len(out)) - return out - - -def update_cell(file_path: str, store: str, column_name: str, content) -> None: - """按门店(A列)与列名(表头)写入单元格;列或行不存在则自动新增(影刀同款行为)。""" - from openpyxl import Workbook, load_workbook # 延迟导入,减少不用时的开销 - - if not column_name or not store: - raise ValueError("门店名称与列名不能为空") - if not str(file_path).lower().endswith(".xlsx"): - raise ValueError(f"账户列表必须是 .xlsx:{file_path}") - - parent = os.path.dirname(os.path.abspath(file_path)) - if parent: - os.makedirs(parent, exist_ok=True) - - if os.path.exists(file_path): - wb = load_workbook(file_path) - ws = wb.active - else: - wb = Workbook() - ws = wb.active - ws.cell(row=1, column=1).value = "门店" - - # 定位列 - target_col = None - for col in range(1, ws.max_column + 1): - if ws.cell(row=1, column=col).value == column_name: - target_col = col - break - if target_col is None: - target_col = ws.max_column + 1 - ws.cell(row=1, column=target_col).value = column_name - - # 定位行 - target_row = None - for row in range(2, ws.max_row + 1): - if str(ws.cell(row=row, column=1).value) == str(store): - target_row = row - break - if target_row is None: - target_row = ws.max_row + 1 - ws.cell(row=target_row, column=1).value = store - - ws.cell(row=target_row, column=target_col).value = content - try: - wb.save(file_path) - except PermissionError as e: - raise RuntimeError(f"账户列表被占用,无法写入,请先关闭 Excel:{file_path}") from e - logger.info("已回写账户列表:%s | %s = %s", store, column_name, content) - - -def mark_done(file_path: str, store: str, column_name: str = "执行状态") -> None: - """标记门店执行完成(默认写「执行状态」列=1)。""" - update_cell(file_path, store, column_name, FLAG_DONE) - - -def mark_failed(file_path: str, store: str, reason: str, column_name: str = "失败原因") -> None: - """记录失败原因(不写执行状态,便于人工重跑)。""" - update_cell(file_path, store, column_name, reason) +# -*- coding: utf-8 -*- +"""账户列表读写(**按表头名**定位,不再写死 A/B/C/E 列)。 + +账户列表.xlsx 约定(列按表头名找;表头缺失时回退 A/B/C): + 门店 | 税号 | 密码 | 执行状态 | 日常申报状态 | 特殊申报状态 | 申报记录 | ... + - 执行状态 = "1" → 已完成,默认跳过;= "0"(或空)→ 待执行 + - 每户跑完立刻回写并保存(中断可续跑) + +对外: + sheet = AccountSheet(path) + accounts = sheet.accounts(redo=False) # 待执行门店 + sheet.set(row, "日常申报状态", "已导出") + sheet.save() + +用 openpyxl 直接读写(不用 pandas),这样"写一列不改格式"更可控,也少一个读表依赖。 +""" +from __future__ import annotations + +import os + +import openpyxl + +from ..config import ( + COL_DAILY, COL_PASSWORD, COL_RECORD, COL_SPECIAL, COL_STATE, COL_STORE, COL_TAX_NO, + STATE_DONE, log, +) + + +def _text(v) -> str: + """单元格值转干净文本:整数型 float 去掉 .0,其余 strip。""" + if v is None: + return "" + if isinstance(v, bool): + return str(v) + if isinstance(v, float) and v.is_integer(): + v = int(v) + return str(v).strip() + + +class AccountSheet(object): + """账户表封装:按表头名读写单元格。""" + + def __init__(self, path): + if not os.path.isfile(path): + raise RuntimeError("未找到账户列表:%s" % path) + try: + self.wb = openpyxl.load_workbook(path) + except PermissionError as e: + raise RuntimeError("账户列表被占用,请先关闭 Excel:%s" % path) from e + except Exception as e: # noqa: BLE001 + raise RuntimeError("读取账户列表失败:%s(%s)" % (path, e)) from e + self.path = path + self.ws = self.wb.worksheets[0] + self.header = [(_text(c.value)) for c in self.ws[1]] + self._cols = self._resolve_columns() + + # ---------------------------------------------------------------- 列定位 + def _resolve_columns(self): + """按表头名定位;门店/税号/密码缺失时回退 A/B/C。""" + def find(name, fallback=None): + for i, h in enumerate(self.header): + if h == name: + return i + 1 + return fallback + + return { + "store": find(COL_STORE, 1), + "tax_no": find(COL_TAX_NO, 2), + "password": find(COL_PASSWORD, 3), + "state": find(COL_STATE), + "daily": find(COL_DAILY), + "special": find(COL_SPECIAL), + "record": find(COL_RECORD), + } + + def _cell(self, row, key): + col = self._cols.get(key) + if not col: + return "" + return _text(self.ws.cell(row=row, column=col).value) + + # ---------------------------------------------------------------- 读 + def accounts(self, redo=False): + """返回待执行门店:执行状态 != "1"(redo=True 时全部返回)。 + + 每项:{'store', 'tax_no', 'password', 'row', 'state', 'daily', 'special', 'record'} + """ + out = [] + for row in range(2, self.ws.max_row + 1): + tax_no = self._cell(row, "tax_no") + if not tax_no: + continue + state = self._cell(row, "state") + if state == STATE_DONE and not redo: + continue + store = self._cell(row, "store") or tax_no + out.append({ + "store": store, + "tax_no": tax_no, + "password": self._cell(row, "password"), + "row": row, + "state": state, + "daily": self._cell(row, "daily"), + "special": self._cell(row, "special"), + "record": self._cell(row, "record"), + }) + log("账户列表读取完成:待执行 %d 家门店(共 %d 行)" + % (len(out), max(0, self.ws.max_row - 1))) + return out + + # ---------------------------------------------------------------- 写 + def _col_of(self, column_name): + """取列号;表头没有该列就追加一列。""" + for i, h in enumerate(self.header): + if h == column_name: + return i + 1 + col = len(self.header) + 1 + self.header.append(column_name) + self.ws.cell(row=1, column=col, value=column_name) + return col + + def set(self, row, column_name, value): + """写一个单元格(列不存在则自动新增表头列)。""" + self.ws.cell(row=row, column=self._col_of(column_name), value=value) + + def save(self): + try: + self.wb.save(self.path) + except PermissionError as e: + raise RuntimeError("账户列表被占用,无法写入,请先关闭 Excel:%s" % self.path) from e + + +def open_sheet(path): + """便捷入口:返回 AccountSheet(语义同构造)。""" + return AccountSheet(path) diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/data/selectors.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/data/selectors.py deleted file mode 100644 index ea6669b..0000000 --- a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/data/selectors.py +++ /dev/null @@ -1,254 +0,0 @@ -# -*- coding: utf-8 -*- -"""Win32 元素定位:解析影刀 selectors.xml,按「类名 + 同类序号」逐层查找控件。 - -影刀 Win32 选择器本质就是控件树路径(用 Inspect 抓的),例如: - Window(cls=TfrmCompMgrMerge, title=社保费管理客户端) - > Pane(cls=TJdlsPanel, index=2) - > ... > Edit(cls=TITSEdit, index=0) - -用 FindWindow / FindWindowEx 逐层下钻即可定位,**不需要 UIA**(老 Delphi/VB 客户端 -根本没有 UIA 树,但 Win32 控件层次是完整的),稳定性和速度都优于图像识别。 - -接口: - lib = Selectors(xml_path) - lib.names() # 全部元素名 - lib.find("税号输入框") # → hwnd(找不到抛 RuntimeError) - lib.exists("滑动栏") # → bool - lib.set_value("税号输入框", "91500...") # WM_SETTEXT,失败自动回退 点击+粘贴 - lib.get_value("密码框") # → str - lib.click("确认单位") # 鼠标点控件中心 - lib.screenshot("待选账户", path) # 控件截图(给 OCR 用) - lib.drag("滑动栏", dx=280) # 滑块拖动(验证码) -""" -from __future__ import annotations - -import ctypes -import os -import time -import xml.etree.ElementTree as ET -from typing import Dict, List, Optional, Union - -try: - import win32con - import win32gui -except ImportError as _e: # pragma: no cover - raise RuntimeError("缺少依赖 pywin32,请安装:pip install pywin32") from _e - -from ..config import logger - -WM_SETTEXT = win32con.WM_SETTEXT -WM_GETTEXT = win32con.WM_GETTEXT -WM_GETTEXTLENGTH = win32con.WM_GETTEXTLENGTH - - -class Selectors: - """影刀元素库(selectors.xml)的 Win32 实现。""" - - def __init__(self, xml_path: str): - self.xml_path = xml_path - self._items: Dict[str, dict] = self._parse(xml_path) - - # ---------- 解析 ---------- - @staticmethod - def _parse(xml_path: str) -> Dict[str, dict]: - if not os.path.isfile(xml_path): - raise RuntimeError(f"元素库文件不存在:{xml_path}") - tree = ET.parse(xml_path) - items: Dict[str, dict] = {} - for el in tree.getroot().iter("selector"): - name = (el.get("name") or "").strip() - if not name: - continue - steps: List[dict] = [] - for wnd in el.findall("wnd"): - opt = wnd.find("{*}optional") - index = None - raw_index = wnd.get("index") - if raw_index is not None: - try: - index = int(raw_index) - except ValueError: - index = None - if opt is not None and opt.get("index") is not None: - try: - index = int(opt.get("index")) - except ValueError: - pass - steps.append({ - "cls": (wnd.get("cls") or "").strip(), - "title": (wnd.get("title") or "").strip(), - "index": index, - "optional": opt is not None, - }) - items[name] = { - "name": name, - "win_title": (el.get("winTitle") or "").strip(), - "process": (el.get("processName") or "").strip(), - "steps": steps, - } - logger.info("元素库加载完成:%d 个元素(%s)", len(items), os.path.basename(xml_path)) - return items - - def names(self) -> List[str]: - return list(self._items.keys()) - - def describe(self, name: str) -> dict: - return dict(self._items.get(name) or {}) - - def _get(self, name: str) -> dict: - item = self._items.get(name) - if not item: - raise KeyError(f"元素库里没有「{name}」,可用元素:{', '.join(self.names())}") - return item - - # ---------- 定位 ---------- - @staticmethod - def _find_child(parent: int, cls: str, index: Optional[int]) -> int: - """在 parent 下找第 index 个类名为 cls 的子窗口。""" - want = 0 if index is None else int(index) - seen = 0 - after = 0 - while True: - child = win32gui.FindWindowEx(parent, after, cls or None, None) - if not child: - return 0 - if seen == want: - return child - seen += 1 - after = child - - def _resolve(self, item: dict, top_window: Optional[int] = None) -> int: - steps = item["steps"] - if not steps: - return 0 - first = steps[0] - parent = int(top_window or 0) - if not parent: - parent = win32gui.FindWindow(first["cls"] or None, first["title"] or None) - if not parent and (first["title"] or item["win_title"]): - title = first["title"] or item["win_title"] - try: - from desktopauto import find_windows # SDK 下发(requires.sdks) - cands = find_windows(title=title) - if not cands and item["process"]: - cands = find_windows(process=item["process"]) - parent = int(cands[0]["hwnd"]) if cands else 0 - except Exception: # noqa: BLE001 - parent = 0 - if not parent: - return 0 - - for step in steps[1:]: - child = self._find_child(parent, step["cls"], step["index"]) - if not child: - if step["optional"]: - continue # 影刀语义:该层可选,找不到就跳过这一层继续下钻 - return 0 - parent = child - return parent - - def find(self, name: str, top_window: Optional[int] = None, - timeout: float = 0.0, interval: float = 0.2) -> int: - """定位元素,返回 hwnd;timeout>0 时轮询等待,超时抛错。""" - item = self._get(name) - deadline = time.time() + max(0.0, float(timeout)) - while True: - hwnd = self._resolve(item, top_window) - if hwnd: - return hwnd - if time.time() >= deadline: - raise RuntimeError( - f"未定位到元素「{name}」(客户端是否已启动/界面是否已切到目标页?)") - time.sleep(max(0.05, interval)) - - def exists(self, name: str, top_window: Optional[int] = None) -> bool: - try: - return bool(self._resolve(self._get(name), top_window)) - except KeyError: - return False - - # ---------- 操作 ---------- - @staticmethod - def _rect(hwnd: int): - left, top, right, bottom = win32gui.GetWindowRect(hwnd) - return left, top, right, bottom - - def center(self, name: str, top_window: Optional[int] = None) -> tuple: - left, top, right, bottom = self._rect(self.find(name, top_window)) - return (left + right) // 2, (top + bottom) // 2 - - def get_value(self, name: str, top_window: Optional[int] = None) -> str: - """读控件文本(WM_GETTEXT)。""" - hwnd = self.find(name, top_window) - length = int(win32gui.SendMessage(hwnd, WM_GETTEXTLENGTH, 0, 0) or 0) - buf = ctypes.create_unicode_buffer(max(1, length + 1)) - win32gui.SendMessage(hwnd, WM_GETTEXT, max(1, length + 1), buf) - return buf.value - - def set_value(self, name: str, text: str, top_window: Optional[int] = None, - timeout: float = 5.0, verify: bool = True) -> bool: - """给输入框赋值:优先 WM_SETTEXT(快、不受焦点影响),无效时回退 点击+粘贴。 - - Returns: - True=WM_SETTEXT 成功;False=走了回退路径(点击+粘贴)。 - """ - hwnd = self.find(name, top_window, timeout=timeout) - text = "" if text is None else str(text) - try: - win32gui.SendMessage(hwnd, WM_SETTEXT, 0, text) - except Exception as e: # noqa: BLE001 - logger.warning("WM_SETTEXT 失败(%s),改用点击+粘贴", e) - self._type_into(hwnd, text) - return False - if verify: - got = self.get_value(name, top_window) - if got.strip() != text.strip(): - logger.warning("WM_SETTEXT 未生效(读到「%s」),改用点击+粘贴", got) - self._type_into(hwnd, text) - return False - return True - - @staticmethod - def _type_into(hwnd: int, text: str) -> None: - """回退方案:点控件中心 → Ctrl+A → 粘贴(中文/长文本安全)。""" - from desktopauto import click_at, hotkey, paste - left, top, right, bottom = Selectors._rect(hwnd) - cx, cy = (left + right) // 2, (top + bottom) // 2 - try: - win32gui.SetForegroundWindow(hwnd) - except Exception: # noqa: BLE001 - pass - click_at(cx, cy) - time.sleep(0.15) - hotkey("ctrl", "a") - paste(text) - - def click(self, name: str, top_window: Optional[int] = None, - timeout: float = 5.0, delay_after: float = 0.3) -> None: - """点击控件中心(鼠标真实点击,兼容自绘控件)。""" - from desktopauto import click_at - hwnd = self.find(name, top_window, timeout=timeout) - left, top, right, bottom = self._rect(hwnd) - cx, cy = (left + right) // 2, (top + bottom) // 2 - click_at(cx, cy) - if delay_after: - time.sleep(float(delay_after)) - logger.debug("点击元素「%s」→ (%d, %d)", name, cx, cy) - - def screenshot(self, name: str, path: str = "", - top_window: Optional[int] = None) -> str: - """截控件区域(给 OCR / 元素识别留档用),返回图片路径。""" - from desktopauto import screenshot as _shot - hwnd = self.find(name, top_window) - left, top, right, bottom = self._rect(hwnd) - return _shot(path, region=(left, top, right, bottom)) - - def drag(self, name: str, dx: int = 0, dy: int = 0, duration: float = 0.8, - top_window: Optional[int] = None) -> None: - """拖动控件(滑块验证码:对「滑动栏」向右拖 dx 像素)。""" - from desktopauto import drag as _drag - hwnd = self.find(name, top_window) - left, top, right, bottom = self._rect(hwnd) - sx, sy = (left + right) // 2, (top + bottom) // 2 - _drag((sx, sy), (sx + int(dx), sy + int(dy)), duration=duration) - logger.debug("拖动元素「%s」→ 偏移 (%d, %d)", name, dx, dy) diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/batch.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/batch.py new file mode 100644 index 0000000..5be94f4 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/batch.py @@ -0,0 +1,141 @@ +# -*- coding: utf-8 -*- +"""batch.py —— 多户批量:逐户 重启 → 添加单位(幂等)→ 登录 → 日常 → 特殊 → 申报记录 + +重庆只有这三步:日常申报 / 特殊缴费申报 / 申报记录导出(**没有缴费工资申报**, +那是成都/长沙的业务,本插件不需要)。 + +每户: + 重启客户端 → 添加单位(失败仅告警继续)→ 登录 + → 日常申报(导出 / 提交) + → 特殊缴费申报(判定 / 有数据导出提交) + → 申报记录导出 PDF + +整批的「合并职工未申报明细」「上下半月汇总」不在这里做,由插件 __init__.py 编排。 +账户表读写交给 data.accounts.AccountSheet(按表头名),本模块只保留 run_one/status_of/mark。 +""" + +import os +import time +import traceback + +from .. import config +from . import daily_declare as dd +from . import login as lg +from . import records_export as rx +from . import sbui as ui +from . import special_declare as sp + + +def run_one(acc, submit=False, refresh=True): + """跑一户的完整流程(不含合并/汇总)。任何一步失败只记录,不影响后面的户。 + + acc 来自 data.accounts.AccountSheet.accounts(): + {'store', 'tax_no', 'password', 'row', ...} + """ + name = acc['store'] + nsrsbh = acc['tax_no'] + pw = str(acc.get('password') or '') + res = {'store': name, 'tax_no': nsrsbh, 'steps': {}} + ui.log('=' * 60) + ui.log('户: %s 税号: %s' % (name, nsrsbh)) + + ui.log(' 重启客户端 + 登录') + lg.restart_client() + try: + lg.add_unit(nsrsbh, pw) # 已存在时幂等 + except Exception as e: # noqa: BLE001 + ui.log(' 添加单位没走通(继续尝试直接登录): %r' % e) + lg.login(nsrsbh, pw) + + # ① 日常申报 + t0 = time.time() + try: + dly = dd.run_daily(store=name, submit=submit, refresh=refresh) + res['steps']['daily'] = {'rows': dly.get('rows'), + 'submitted': sum(1 for s in (dly.get('sources') or []) + if s.get('submitted')), + 'files': [os.path.basename(s[k]['file']) + for s in dly.get('sources') or [] + for k in ('summary', 'detail') + if s.get(k) and s[k].get('file')], + 'note': (dly.get('note') or '')[:60]} + except Exception as e: # noqa: BLE001 + ui.log(' ! 日常申报失败: %r' % e) + res['steps']['daily'] = {'error': repr(e)[:200]} + ui.log(' ① 日常申报 %.1fs' % (time.time() - t0)) + + # ② 特殊缴费申报 + t0 = time.time() + try: + s = sp.run(store=name, submit=submit) + res['steps']['special'] = {'state': s.get('state'), + 'note': (s.get('note') or '')[:60]} + except Exception as e: # noqa: BLE001 + ui.log(' ! 特殊缴费失败: %r' % e) + res['steps']['special'] = {'error': repr(e)[:200]} + ui.log(' ② 特殊缴费 %.1fs' % (time.time() - t0)) + + # ③ 申报记录 → PDF + t0 = time.time() + try: + r = rx.run(store=name) + res['steps']['records'] = {'rows': r.get('rows'), + 'exported': [os.path.basename(x.get('file') or '') + for x in (r.get('exported') or [])], + 'note': (r.get('note') or '')[:60]} + except Exception as e: # noqa: BLE001 + ui.log(' ! 申报记录导出失败: %r' % e) + res['steps']['records'] = {'error': repr(e)[:200]} + ui.log(' ③ 申报记录 %.1fs' % (time.time() - t0)) + return res + + +def status_of(res): + """把结果压成账户表里那几个状态词。""" + steps = res['steps'] + daily = steps.get('daily') or {} + special = steps.get('special') or {} + records = steps.get('records') or {} + + if daily.get('error'): + daily_s = '失败' + elif not daily.get('rows'): + daily_s = '无数据' + elif daily.get('submitted'): + daily_s = '已提交' + else: + daily_s = '已导出' + + if special.get('error'): + special_s = '失败' + elif special.get('state') == 'none': + special_s = '无需申报' + elif special.get('state') == 'data': + special_s = '已导出' + else: + special_s = '未判定' + + if records.get('error'): + record_s = '失败' + elif records.get('exported'): + record_s = '已导出' + else: + record_s = '无成功记录' + + ok = not any((steps.get(k) or {}).get('error') + for k in ('daily', 'special', 'records')) + return ok, daily_s, special_s, record_s + + +def mark(sheet, acc, res): + """把一户的状态写回账户表并落盘(每户跑完就保存,中断可续跑)。 + + 执行状态=1 仅当三步都没有异常;步骤状态词见 status_of。 + """ + ok, daily_s, special_s, record_s = status_of(res) + sheet.set(acc['row'], config.COL_STATE, config.STATE_DONE if ok else '0') + sheet.set(acc['row'], config.COL_DAILY, daily_s) + sheet.set(acc['row'], config.COL_SPECIAL, special_s) + sheet.set(acc['row'], config.COL_RECORD, record_s) + sheet.save() + return ok, daily_s, special_s, record_s diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/client.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/client.py deleted file mode 100644 index 73a556b..0000000 --- a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/client.py +++ /dev/null @@ -1,236 +0,0 @@ -# -*- coding: utf-8 -*- -"""客户端生命周期:启动 → 登录(元素填税号 + 滑块 + 图像点登录)→ 弹窗清理 → 关闭。 - -对应影刀 process1(社保客户端启动流程)、process2(社保账户登录流程)、process3(弹窗清理)。 -定位策略:能用 Win32 元素就走元素(税号框、滑动栏),拿不到元素/需要视觉判断的(登录按钮、 -菜单栏、错误弹窗)走图像 + OCR,与影刀版一致。 - -阶段说明:首个账户首次登录需要「添加单位」流程(影刀 process6),当前版本在 -OCR 判断"账户列表为空"时会明确报错并提示,待补 process6 迁移。 -""" -from __future__ import annotations - -import os -import time - -from desktopauto import Screen, find_windows, get_window, hotkey, sleep - -from ..config import ( - CLIENT_PROCESS, CLIENT_PROCESS_ALT, CLIENT_TITLE, ELE, client_exe, - image_opt, logger, -) -from ..data.selectors import Selectors - -# 登录后判定成功的锚点图与错误弹窗 -_LOGIN_OK_TPL = "menu_bar" -_ERROR_TPL = "error_msg" -_ERROR_CONFIRM_TPL = "error_confirm" - - -def _wait_tpl(screen: Screen, key: str, timeout: float = 5.0): - """按模板名等待出现(自动带 manifest 里的阈值/灰度/多尺度)。""" - opt = image_opt(key) - return screen.wait(opt["path"], timeout=timeout, interval=0.5, - threshold=opt["threshold"], gray=opt["gray"], scales=opt["scales"]) - - -def _shot_click(screen: Screen, key: str, timeout: float = 5.0, - delay_after: float = 1.0) -> bool: - """按模板名点击(自动带 manifest 里的阈值/灰度/多尺度)。""" - opt = image_opt(key) - return screen.click(opt["path"], threshold=opt["threshold"], gray=opt["gray"], - scales=opt["scales"], timeout=timeout, delay_after=delay_after) - - -def _shot_exists(screen: Screen, key: str) -> bool: - opt = image_opt(key) - return screen.exists(opt["path"], threshold=opt["threshold"], - gray=opt["gray"], scales=opt["scales"]) - - -# ==================== 启动 / 关闭 ==================== -def start_client(exe_path: str = "", retries: int = 3, ready_timeout: float = 30.0): - """启动社保客户端并等窗口就绪(影刀「运行或打开」+「等待图像」)。 - - Returns: - (Window, Selectors):窗口对象 + 元素库。 - - Raises: - RuntimeError:启动失败或超时(已重试)。 - """ - exe_path = (exe_path or client_exe()).strip() - if not os.path.isfile(exe_path): - raise RuntimeError(f"社保客户端程序不存在:{exe_path}(请在插件配置里修正路径)") - - sel = Selectors(os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), - "selectors", "selectors.xml")) - last_err = None - for attempt in range(1, max(1, retries) + 1): - logger.info("第 %d/%d 次启动社保客户端:%s", attempt, retries, exe_path) - try: - _launch(exe_path) - win = _wait_client_window(ready_timeout) - if win is not None: - win.activate() - logger.info("社保客户端启动成功:%s", win.title) - return win, sel - last_err = RuntimeError("等待窗口超时") - except Exception as e: # noqa: BLE001 - last_err = e - logger.warning("第 %d 次启动失败:%s", attempt, e) - _kill_client() - time.sleep(1.5) - raise RuntimeError(f"社保客户端连续 {retries} 次启动失败:{last_err}") - - -def _launch(exe_path: str) -> None: - """启动客户端(已在运行则跳过)。""" - if find_windows(process=CLIENT_PROCESS) or find_windows(process=CLIENT_PROCESS_ALT): - logger.info("社保客户端已在运行,跳过启动") - return - from desktopauto import run_or_open - run_or_open(exe_path, wait=1.0) - - -def _wait_client_window(timeout: float): - """等主窗口出现(按标题,元素库里的 cls 也参与匹配)。""" - deadline = time.time() + max(1.0, float(timeout)) - while time.time() < deadline: - cands = find_windows(title=CLIENT_TITLE) - if cands: - return get_window(cands[0]["hwnd"]) - time.sleep(0.5) - return None - - -def _kill_client() -> None: - """结束客户端进程(影刀每轮结束都会强杀,避免状态残留)。""" - from desktopauto import kill_process - for proc in (CLIENT_PROCESS, CLIENT_PROCESS_ALT): - try: - if find_windows(process=proc): - kill_process(proc, wait=0.5) - logger.info("已结束进程:%s", proc) - except Exception as e: # noqa: BLE001 - logger.warning("结束进程 %s 失败:%s", proc, e) - - -def close_client() -> None: - """关闭窗口(软关闭),失败再强杀。""" - wins = find_windows(title=CLIENT_TITLE) - if wins: - try: - w = get_window(wins[0]["hwnd"]) - w.close(wait=0.5) - if w.wait_closed(timeout=5): - logger.info("社保客户端已关闭") - return - except Exception as e: # noqa: BLE001 - logger.warning("软关闭失败:%s", e) - _kill_client() - - -# ==================== 登录 ==================== -def login(tax_no: str, password: str, sel: Selectors, store: str = "", - login_timeout: float = 60.0) -> bool: - """登录单个社保账户(影刀 process2)。 - - 流程:激活窗口 → 元素填税号 + Enter → 滑块验证 → 点击「登录按钮」→ 输入密码 - → 点击「确定登录按钮」→ 循环等「菜单栏」出现(期间处理错误弹窗)。 - - Raises: - RuntimeError:登录失败或超时(调用方据此回写失败原因)。 - """ - win = _wait_client_window(10.0) - if win is None: - raise RuntimeError("未找到社保费管理客户端窗口") - win.activate() - - screen = Screen(window=win.hwnd, threshold=0.8, debug_dir="") - - # 1. 填税号(元素通道,比图像稳) - logger.info("填入税号:%s(门店:%s)", tax_no, store or "-") - sel.set_value(ELE["tax_no_input"], tax_no, timeout=15.0) - sleep(0.5) - hotkey("enter") - sleep(1.0) - - # 2. 判断是否已有可选账户:对「待选账户」元素截图后 OCR 数文字行 - account_count = _count_pending_accounts(sel) - logger.info("可选账户文字行数:%d", account_count) - if account_count < 3: - raise RuntimeError( - "该税号在客户端里没有可登录账户(首次使用需先「添加单位」," - "影刀 process6 尚未迁移;请先在客户端手动添加一次该账户后重跑)") - - # 3. 拖动滑块(验证码)——滑块条元素拖动,位移取控件宽度的一半以上 - _drag_slider(sel) - - # 4. 点击「登录按钮」→ 输密码 → 点击「确定登录按钮」 - _shot_click(screen, "login_btn", timeout=5.0) - sleep(1.0) - screen.paste(password) - sleep(0.5) - _shot_click(screen, "login_confirm", timeout=5.0) - - # 5. 循环等菜单栏出现(期间处理错误提示) - deadline = time.time() + max(5.0, float(login_timeout)) - while time.time() < deadline: - if _shot_exists(screen, _ERROR_TPL): - logger.warning("检测到登录错误提示,点确认后继续等待") - _shot_click(screen, _ERROR_CONFIRM_TPL, timeout=3.0) - if _wait_tpl(screen, _LOGIN_OK_TPL, timeout=2.0) is not None: - logger.info("门店 %s 登录成功(已见菜单栏)", store or tax_no) - return True - sleep(1.0) - raise RuntimeError(f"登录超时:{store or tax_no}({login_timeout:.0f}s 内未出现主菜单)") - - -def _count_pending_accounts(sel: Selectors) -> int: - """对「待选账户」元素截图后 OCR,返回识别到的文字段数(影刀 process2 同款判断)。""" - try: - from desktopauto import ocr - shot = sel.screenshot(ELE["pending_account"]) - items = ocr.recognize(shot, min_score=0.5) - return len(items) - except Exception as e: # noqa: BLE001 - logger.warning("账户列表识别失败(按无账户处理):%s", e) - return 0 - - -def _drag_slider(sel: Selectors) -> None: - """拖滑块(验证码):拖动「滑动栏」控件,距离取控件宽度(拖到最右)。""" - try: - hwnd = sel.find(ELE["slider_bar"], timeout=5.0) - import win32gui - left, top, right, bottom = win32gui.GetWindowRect(hwnd) - distance = max(60, right - left) - sel.drag(ELE["slider_bar"], dx=distance, duration=0.8) - sleep(0.8) - logger.info("滑块拖动完成(距离 %d px)", distance) - except Exception as e: # noqa: BLE001 - logger.warning("滑块拖动失败(继续尝试登录):%s", e) - - -# ==================== 弹窗清理 ==================== -_POPUP_TITLES = ("确认单位", "待办事项提醒") - - -def clean_popups(max_rounds: int = 3) -> None: - """关闭「确认单位」「待办事项提醒」等弹窗(影刀 process3:最多 3 轮,两个都清掉即退出)。""" - for round_no in range(1, max(1, max_rounds) + 1): - cleaned = False - for title in _POPUP_TITLES: - wins = find_windows(title=title) - if not wins: - continue - try: - w = get_window(wins[0]["hwnd"]) - w.close(wait=0.3) - cleaned = True - logger.info("已关闭弹窗:%s", title) - except Exception as e: # noqa: BLE001 - logger.warning("关闭弹窗「%s」失败:%s", title, e) - if not cleaned: - return - sleep(1.0) diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/daily_declare.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/daily_declare.py new file mode 100644 index 0000000..53cbcd1 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/daily_declare.py @@ -0,0 +1,1007 @@ +# -*- coding: utf-8 -*- +""" +daily_declare.py —— 日常申报全流程(Python 生产版) + +覆盖页面上的完整动作链: + + 进页面 → 设查询参数(社保经办机构 / 费款所属期 / 数据来源) + → 刷新(联网取核定数据) + → 全选未申报记录 + → 导出汇总(社保费未申报汇总信息.xls)→ 申报结果/<门店>/ + → 查看职工未申报明细 → 导出明细(职工未申报明细.xlsx)→ 职工未申报明细/<门店>/ + → [可选] 提交申报(默认不做,见 submit_flow 的说明) + +用法(插件里): + from . import daily_declare as dd + r = dd.run_daily(store='某单位') + +产物目录由 config 统一决定(save_dir 下分 申报结果 / 职工未申报明细 / 截图 / 汇总结果), +重庆只有一个区域,不再按区域分层。 + +前提:客户端已启动并登录;本进程必须是管理员(由插件入口 sbui.require_admin() 保证)。 +""" + +import os +import re +import time + +from .. import config +from . import sbui as ui + +# ---------------------------------------------------------------- 界面常量(1920x1032 / 100%) +CONFIG = { + 'home_xy': (240, 106), # 面包屑「首页」两个字 + 'card_xy': (390, 255), # 首页卡片「社保费日常申报」 + 'menu_parent_y': 230, # 左侧「社保费申报」 + 'menu_child_x': 95, + 'detail_view_w': (130, 145), # 「查看职工未申报明细」按钮宽度 → 页面特征 + 'grid_check_dx': 22, # 表头全选框:相对表格左上角 + 'grid_check_dy': 20, +} + + +LAST_DIALOGS = [] # 最近处理过的弹窗正文(判服务器异常/无数据用) + + +class ClientError(RuntimeError): + def __init__(self, code, msg): + super().__init__(msg) + self.code = code + + +# ---------------------------------------------------------------- 定位与判断 +def get_main(): + # 注意 visible=False:客户端可能被最小化,此时 IsWindowVisible 也是 False, + # 但窗口仍然存在,foreground() 会把它还原出来。 + w = ui.find_window('Tfrm_MainFrame', visible=False) + if not w: + raise ClientError(11, '找不到主界面 Tfrm_MainFrame,请先启动并登录客户端') + ui.foreground(w) + return w + + +def buttons(page): + out = [] + for b in ui.children(page, visible_only=True): + if b.cls != 'TITSSpeedButton': + continue + l, t, w, h = b.rect + out.append({'win': b, 'x': l, 'y': t, 'w': w, 'h': h, 'enabled': b.enabled}) + return out + + +def find_daily_page(main): + page = ui.find_child(main, 'TfrmHdsbbbtx') + if not page: + return None + lo, hi = CONFIG['detail_view_w'] + return page if any(lo <= b['w'] <= hi for b in buttons(page)) else None + + +def _dialog_text(m, tries=3): + """读弹窗正文。PrintWindow 本机失效,实际走屏幕 OCR;**空结果要重试**。 + + 实测(2026-11-19 20:56):刚弹出的「未查询到未申报信息」被 OCR 读成空串 + (日志只有「提示信息 × 确定」),于是被判成"普通弹窗"静默点掉,白等 8 轮。 + 原因是弹窗还在淡入/重绘。这里空串就等 0.4 秒重读,最多 3 次。 + """ + for i in range(max(1, tries)): + try: + from . import sbocr + l, t, w, h = m.rect + txt = ' '.join(x.text for x in sbocr.texts( + (l + 8, t + 26, l + w - 8, t + h - 8), min_score=0.2)).strip() + if txt: + return txt + except Exception: # noqa: BLE001 + pass + if i + 1 < tries: + time.sleep(0.4) + return '' + + +def confirm_dialog(d, timeout=3.0): + """点掉一个 Tfrm_MsgDlgRich 弹窗:**先切前台再真实点击**,最后兜底 WM_CLOSE。 + + 实测(2026-11-19 19:00):弹窗在后面被挡住时,post_click / 屏幕坐标点击都点不掉, + 必须先 foreground(dlg) 再 real_click 按钮中心,否则弹窗一直挂着、主窗一直 disabled。 + """ + for _ in range(3): + btns = sorted([b for b in ui.children(d, visible_only=True) + if b.cls == 'TITSSpeedButton'], key=lambda b: b.rect[0]) + if not btns: + break + b = btns[0] + ui.foreground(d) + time.sleep(0.25) + ui.real_click(b.rect[0] + b.rect[2] // 2, b.rect[1] + b.rect[3] // 2) + time.sleep(0.8) + if not ui.find_window('Tfrm_MsgDlgRich', timeout=0): + return True + b = ui.find_window('Tfrm_MsgDlgRich', timeout=0) + if b: + ui.u32.PostMessageW(b.hwnd, ui.WM_CLOSE, 0, None) + time.sleep(0.5) + return not bool(ui.find_window('Tfrm_MsgDlgRich', timeout=0)) + + +def clear_msg_dialogs(): + n = 0 + for _ in range(10): + m = ui.find_window('Tfrm_MsgDlgRich') + if not m: + break + body = _dialog_text(m) + if body: + LAST_DIALOGS.append(body) + ui.log(' 弹窗[%s]:%s' % (m.title, body[:100])) + if '清空原有数据' in body or '还未提交申报' in body: + # 「您添加的数据还未提交申报,此操作将清空原有数据,是否继续?[确定][取消]」 + # 这是离开缴费工资调整页的确认框;日常申报要往下走 → 点「确定」放行 + btns = sorted([b for b in ui.children(m, visible_only=True) + if b.cls == 'TITSSpeedButton'], key=lambda b: b.rect[0]) + if btns: + b = btns[0] + ui.log(' → 未提交就离开的确认框,点「确定」放行') + ui.foreground(m) + time.sleep(0.2) + ui.real_click(b.rect[0] + b.rect[2] // 2, b.rect[1] + b.rect[3] // 2) + time.sleep(0.8) + n += 1 + continue + if not confirm_dialog(m): + break + n += 1 + time.sleep(0.7) + return n + + +def wait_idle(timeout=30.0): + """等加载框(SplashWindow)消失、提示框清完。""" + t0 = time.time() + while time.time() - t0 < timeout: + clear_msg_dialogs() + if not ui.find_window('SplashWindow'): + time.sleep(0.4) + if not ui.find_window('SplashWindow'): + return True + time.sleep(0.3) + return False + + +# ---------------------------------------------------------------- 进页面 +def open_daily_page(main, cfg, timeout=25.0): + page = find_daily_page(main) + if page: + return page + + # ① 左侧菜单(OCR 定位):社保费申报 → 日常申报 + # 2026-11-19 用户明确:**不要从首页卡片进**,按菜单顺序走(先缴费工资申报,再日常申报) + # ⚠ 点完必须**校验进的是不是日常页**:实测 21:50 在「社保费申报」子菜单上点「日常申报」, + # 客户端却落到了「申报记录」(TFrmHdsbsbjl)——只按"点过了"判断会一路跑错页。 + try: + from . import sbocr + for attempt in range(1, 4): + ui.log('不在日常申报页 → 左侧菜单(OCR):社保费申报 → 日常申报(第 %d 次)' % attempt) + sbocr.expand_menu(main, '社保费申报', '日常申报') + if not sbocr.click_text(main, '日常申报', region=sbocr.menu_region(main)): + continue + t_click = time.time() + deadline = t_click + timeout + while time.time() < deadline: + time.sleep(0.4) + clear_msg_dialogs() + page = find_daily_page(main) + if page: + ui.log(' 已进入(左侧菜单)') + return page + # 3 秒还没进日常页 → 看看是不是落到了别的页(申报记录 / 特殊缴费申报) + if time.time() - t_click > 3.0: + other = ui.find_child(main, 'TFrmHdsbsbjl') or ui.find_child(main, 'TfrmHdsbbbtx') + if other: + ui.log(' ⚠ 点「日常申报」后落在了 %s(%r)→ 重新点' % (other.cls, other.title)) + break + ui.log(' 菜单没进去 → 退回首页卡片') + except Exception as e: # OCR 不可用时不影响老路径 + ui.log(' OCR 菜单失败(%s),退回首页卡片' % type(e).__name__) + + l0, t0, _, _ = main.rect + ui.click_at(l0 + cfg['home_xy'][0], t0 + cfg['home_xy'][1], ancestor=main) + time.sleep(1.5) + ui.click_at(l0 + cfg['card_xy'][0], t0 + cfg['card_xy'][1], ancestor=main) + deadline = time.time() + timeout + while time.time() < deadline: + time.sleep(0.3) + clear_msg_dialogs() + page = find_daily_page(main) + if page: + ui.log(' 已进入(首页卡片)') + return page + + ui.log(' 卡片没进去 → 左侧菜单(像素兜底)') + parent_y = t0 + cfg['menu_parent_y'] + kids = ui.menu_children(parent_y=parent_y) + if not kids: + ui.log(' 菜单折叠,点父项展开') + ui.click_at(l0 + 63, parent_y, ancestor=main) + time.sleep(1.2) + kids = ui.menu_children(parent_y=parent_y) + else: + ui.log(' 菜单已展开(%d 子项),直接点子项' % len(kids)) + if kids: + ui.click_at(l0 + cfg['menu_child_x'], kids[0]['cy'], ancestor=main) + deadline = time.time() + 12 + while time.time() < deadline: + time.sleep(0.3) + page = find_daily_page(main) + if page: + ui.log(' 已进入(左侧菜单)') + return page + raise ClientError(12, '菜单和首页卡片都没能进入日常申报页') + + +# ---------------------------------------------------------------- 参数 +def pick_combos(page): + """识别页面上的三个下拉框,**不依赖坐标**(只用一个相对位置关系)。 + + 坑:`费款所属期` 在"本户没有核定数据"时只有「请选择」,按选项内容根本认不出来, + 所以改成:先按内容认出「社保经办机构」,再取**同一行里它右边那个**下拉框当「费款所属期」。 + """ + combos = [] + for c in ui.children(page, visible_only=True): + if c.cls == 'TITSComboBox': + combos.append((c, ui.combo_items(c))) + found = {} + + org = None + for c, items in combos: + if any(('社保局' in i) or ('医保局' in i) or ('经办' in i) for i in items[1:]): + found['org'] = (c, items) + org = c + break + + for c, items in combos: + if any('生成' in i for i in items[1:]): + found['source'] = (c, items) + break + + if org: + oy = org.rect[1] + same_row = [(c, items) for c, items in combos + if abs(c.rect[1] - oy) <= 8 and c.rect[0] > org.rect[0]] + if same_row: + found['period'] = sorted(same_row, key=lambda t: t[0].rect[0])[0] + if 'period' not in found: + for c, items in combos: + if any(re.match(r'^\d{4}-\d{2}$', i) for i in items[1:]): + found['period'] = (c, items) + break + return found + +def select_option(combo_pair, wanted=None, index=None): + """在 (控件, 选项列表) 里选中某一项;wanted 按名字,index 按序号(1 起,0 是"请选择")。""" + combo, items = combo_pair + if wanted: + if wanted not in items: + raise ClientError(13, '选项不存在: %s(可选 %s)' % (wanted, items[1:])) + idx = items.index(wanted) + else: + idx = index if index is not None else 1 + if not ui.combo_set(combo, idx): + raise ClientError(13, '下拉框设置失败: %s' % items[idx]) + ui.log(' 选中 %s' % items[idx]) + return items[idx] + + +# ---------------------------------------------------------------- 模板点击(影刀模板库) +def _img(): + """懒加载 sbimg(影刀模板库);不可用时返回 None,调用方退回坐标/控件通道。""" + try: + from . import sbimg + return sbimg + except Exception as e: # noqa: BLE001 + ui.log(' (模板库不可用:%s)' % type(e).__name__) + return None + + +def _main(): + return ui.find_window('Tfrm_MainFrame', visible=False) + + +def img_click(key, timeout=2.0, delay=0.8): + b = _img() + if not b: + return False + m = _main() + if not m: + return False + try: + return b.click(m, key, timeout=timeout, delay=delay) + except Exception as e: # noqa: BLE001 + ui.log(' (模板 %s 点击失败:%s)' % (key, e)) + return False + + +def img_find(key): + b = _img() + m = _main() + if not b or not m: + return None + try: + return b.find(m, key) + except Exception: # noqa: BLE001 + return None + + +# ---------------------------------------------------------------- 刷新 / 勾选 +def click_toolbar(page, which): + """工具栏按钮按 x 排序:0 刷新 / 1 提交申报 / 2 导出 / 3 明细 / 4 可抵缴。 + + 注意只取**第一排**:按「最上面那一排的 y」动态分组,不再写死 y<170 + (日常页第一排 y≈142,特殊缴费申报页因为顶部多一条温馨提示,整排下移到 y≈171)。 + 第二排的查询/重置(y≈198/227)不要混进来。 + """ + cands = [b for b in buttons(page) if b['w'] >= 50 and b['w'] > 0] + if len(cands) < 3: + raise ClientError(12, '工具栏按钮少于 3 个,页面状态不对') + y0 = min(b['y'] for b in cands) + toolbar = sorted([b for b in cands if abs(b['y'] - y0) <= 6], key=lambda b: b['x']) + idx = {'refresh': 0, 'submit': 1, 'export': 2, 'detail': 3}[which] + if idx >= len(toolbar): + raise ClientError(12, '工具栏没有第 %d 个按钮(%s)' % (idx, which)) + return toolbar[idx] + + +def refresh_data(page, timeout=40.0): + btn = click_toolbar(page, 'refresh') + if not btn['enabled']: + raise ClientError(12, '「刷新」按钮不可用') + ui.log(' 点「刷新」(联网取核定数据)') + ui.post_click(btn['win']) + ok = wait_idle(timeout) + ui.log(' 刷新%s(用时 %.1f 秒)' % ('完成' if ok else '超时仍未结束', 0)) + return ok + + +def select_all_rows(page, cfg): + """保证"全部勾选"。幂等:已经勾上(导出可用)就不再点,避免把勾选toggle掉。 + + 返回 True 表示有数据且已勾选。 + """ + if click_toolbar(page, 'export')['enabled']: + ui.log(' 已处于勾选状态') + return True + grid = None + for c in ui.children(page, visible_only=True): + if c.cls == 'TAdvStringGrid': + grid = c + break + if not grid: + raise ClientError(14, '找不到表格 TAdvStringGrid') + gx, gy, gw, gh = grid.rect + ui.click_at(gx + cfg['grid_check_dx'], gy + cfg['grid_check_dy'], + ancestor=ui.find_window('Tfrm_MainFrame')) + time.sleep(1.0) + exp = click_toolbar(page, 'export') + sub = click_toolbar(page, 'submit') + ui.log(' 全选后:导出=%s 提交申报=%s' % (exp['enabled'], sub['enabled'])) + return exp['enabled'] + + +# ---------------------------------------------------------------- 提交申报(实测 6 步) +# 实测顺序(2026-11-19 17:31 本户真实提交): +# ① 提交申报 +# ② 提示信息「请核对缴费人数…」 → 确定 +# ③ TFrmHdsbfsqr 「提交申报确认」(列出条数/税额)→ 立即提交 +# ④ 提示信息「提交成功」 → 确定 +# ⑤ TFrmCountDown「7 秒后自动获取申报结果,或立即获取」→ 立即获取(或等自动) +# ⑥ 提示信息「社保费申报成功…」 → 确定 +# 注意:②是条件出现的;④/⑤/⑥ 可能合并或顺序变化,所以用「按窗口类名驱动的循环」而不是死记顺序。 +def _click_leftmost(dlg): + """Tfrm_MsgDlgRich 的按钮是自绘的:最左 = 主操作(是/确定/立即提交)。""" + btns = sorted([b for b in ui.children(dlg, visible_only=True) if b.cls == 'TITSSpeedButton'], + key=lambda b: b.rect[0]) + if not btns: + return False + # 消息点击会被模态窗屏蔽(实测点不动)→ 一律切前台 + 真实点击,再校验窗口是否消失 + b = btns[0] + ui.foreground(dlg) + time.sleep(0.25) + ui.real_click(b.rect[0] + b.rect[2] // 2, b.rect[1] + b.rect[3] // 2) + time.sleep(0.6) + return True + + +def _click_rightmost(dlg): + """TFrmCountDown:左边取消、右边立即获取。""" + btns = sorted([b for b in ui.children(dlg, visible_only=True) if b.cls == 'TITSSpeedButton'], + key=lambda b: b.rect[0]) + if not btns: + return False + ui.post_click(btns[-1]) + return True + + +def submit_declaration(page, timeout=150.0): + """完成整条提交流程。返回处理过的步骤列表。 + + ⚠️ 会真正向税局提交申报,不可撤销。调用前必须确认申报期与数据。 + """ + if not page: + raise ClientError(17, '不在「日常申报」页(可能已跳到申报记录),无法提交') + btn = click_toolbar(page, 'submit') + if not btn['enabled']: + raise ClientError(17, '「提交申报」不可用(没勾选数据?)') + ui.log(' 点「提交申报」') + ui.post_click(btn['win']) + + deadline = time.time() + timeout + steps = [] + idle = 0 + while time.time() < deadline: + time.sleep(0.25) + err = ui.find_window('Tfrm_MsgDlgRich', title='错误信息') + if err: + _click_leftmost(err) + raise ClientError(17, '提交被拒绝:出现「错误信息」弹窗(多为未选数据/参数不全)') + + d = ui.find_window('Tfrm_MsgDlgRich') + if d: + _click_leftmost(d) + steps.append('提示信息') + ui.log(' 提示信息 → 确定') + idle = 0 + time.sleep(0.9) + continue + + w = ui.find_window('TFrmHdsbfsqr') + if w: + _click_leftmost(w) + steps.append('提交申报确认→立即提交') + ui.log(' 提交申报确认 → 立即提交') + idle = 0 + time.sleep(1.2) + continue + + w = ui.find_countdown() + if w: + # 业务口径:确认后**点取消**,不等自动、不点「立即获取」 + # 注意:cls/title 要在点之前读 —— 点完窗口就销毁了,读出来会是空串 + ui.log(' 倒计时窗[cls=%r title=%r] → 取消(不取申报结果)' % (w.cls, w.title)) + _click_leftmost(w) + steps.append('倒计时窗→取消') + idle = 0 + time.sleep(1.2) + continue + + idle += 1 + if steps and idle >= 8: # 连续 2 秒没有新窗口 → 认为流程结束 + break + if not steps: + raise ClientError(17, '点提交后没有任何弹窗,流程未启动') + return steps + +# ---------------------------------------------------------------- 导出 +def save_dialog_save(sav, target_path, timeout=60.0): + """在「另存为」里写完整路径 → 点保存 → 等落盘。返回 (size, 毫秒)。""" + edit = ui.find_child(sav, 'Edit') + if not edit: + raise ClientError(15, '另存为里没有文件名框') + if not ui.set_text(edit, target_path): + raise ClientError(15, '文件名写入失败:%r' % ui.get_text(edit)) + ui.log(' 保存到: %s' % target_path) + save_btn = next((b for b in ui.children(sav, visible_only=True) + if b.cls == 'Button' and '保存' in b.title), None) + if not save_btn: + raise ClientError(15, '另存为里没有「保存」按钮') + ui.foreground(sav) + time.sleep(0.4) + t0 = time.time() + ui.bm_click_wait(save_btn, 15000) + file_at = None + last_size, stable_since = -1, None + while time.time() - t0 < timeout: + time.sleep(0.2) + if not os.path.exists(target_path): + continue + size = os.path.getsize(target_path) + if file_at is None: + file_at = time.time() - t0 + # 文件"出现"≠"写完":FastReport 先建 0/17 字节的空壳,再往里写(2026-11-23 实测 + # 申报表 PDF 出现时只有 17 字节,实际 16,942 字节)→ 必须等大小稳定才返回。 + if size > 0 and size == last_size: + if stable_since is None: + stable_since = time.time() + elif time.time() - stable_since >= 0.6: + clear_msg_dialogs() + return size, int(file_at * 1000) + else: + stable_since = None + last_size = size + clear_msg_dialogs() + if file_at is None: + raise ClientError(16, '保存后 %.0f 秒内没生成 %s' % (timeout, target_path)) + size = os.path.getsize(target_path) + if size <= 0: + raise ClientError(16, '保存后文件是空的:%s' % target_path) + return size, int(file_at * 1000) + + +def export_summary(page, out_dir, source_label=''): + btn = click_toolbar(page, 'export') + if not btn['enabled']: + raise ClientError(15, '「导出」按钮不可用(没勾选数据?)') + ui.log(' 点「导出」(汇总)') + ui.post_click(btn['win']) + sav = ui.find_window('#32770', title='另存为', timeout=20.0) + if not sav: + raise ClientError(15, '点导出后 20 秒内没出现「另存为」') + safe = ''.join('_' if c in '\\/:*?"<>|' else c for c in (source_label or '汇总')) + name = '社保费未申报汇总信息_%s_%s.xls' % (safe, time.strftime('%H%M%S')) + target = os.path.join(out_dir, name) + size, ms = save_dialog_save(sav, target) + ui.log(' ✅ 汇总导出: %s %d 字节 %dms' % (name, size, ms)) + return {'file': target, 'size': size, 'save_ms': ms} + + +def open_detail(page, cfg, timeout=90.0): + detail = ui.find_window('TFrmAllYclZgmx') + if detail: + ui.log(' 明细页已开着,复用') + return detail + btn = click_toolbar(page, 'detail') + ui.log(' 点「查看职工未申报明细」(%d,%d)' % (btn['x'], btn['y'])) + ui.post_click(btn['win']) + t0 = time.time() + while time.time() - t0 < timeout: + time.sleep(0.3) + clear_msg_dialogs() + detail = ui.find_window('TFrmAllYclZgmx') + if detail: + ui.log(' 明细页出现,用时 %.1f 秒' % (time.time() - t0)) + return detail + raise ClientError(14, '明细页 %.0f 秒内没出现' % timeout) + + +def export_detail(detail, out_dir, source_label): + cands = [b for b in buttons(detail) if 55 <= b['w'] <= 70 and b['y'] < 320] + if not cands: + raise ClientError(15, '明细页上找不到导出按钮') + btn = min(cands, key=lambda b: b['y']) + ui.log(' 点明细页「导出」(%d,%d)' % (btn['x'], btn['y'])) + ui.post_click(btn['win']) + sav = ui.find_window('#32770', title='另存为', timeout=20.0) + if not sav: + raise ClientError(15, '点导出后 20 秒内没出现「另存为」') + safe = ''.join('_' if c in '\\/:*?"<>|' else c for c in source_label) + name = '职工未申报明细_%s_%s.xlsx' % (safe, time.strftime('%H%M%S')) + target = os.path.join(out_dir, name) + size, ms = save_dialog_save(sav, target) + ui.log(' ✅ 明细导出: %s %d 字节 %dms' % (name, size, ms)) + return {'file': target, 'size': size, 'save_ms': ms} + + +# ---------------------------------------------------------------- 收尾 +def close_all(): + clear_msg_dialogs() + d = ui.find_window('TFrmAllYclZgmx') + if d: + ui.u32.PostMessageW(d.hwnd, ui.WM_CLOSE, 0, None) + time.sleep(0.8) + main = ui.find_window('Tfrm_MainFrame') + if main: + ui.foreground(main) + + +# ---------------------------------------------------------------- 提交(含提交后核验) +def submit_flow(page, cfg): + """提交当前勾选的申报,并在提交后核验「本批数据是否已从列表消失」。""" + ui.log('--- 提交申报 ---') + if not select_all_rows(page, cfg): + ui.log(' 没有可提交的数据') + return False + steps = submit_declaration(page) + wait_idle(20) + + # 提交成功后客户端会**自动跳到「申报记录」页**(TFrmHdsbsbjl,是主窗口的子窗体不是顶层) + main = ui.find_window('Tfrm_MainFrame', visible=False) + got_record = False + deadline = time.time() + 30 + while time.time() < deadline: + clear_msg_dialogs() + if ui.find_child(main, 'TFrmHdsbsbjl'): + got_record = True + break + time.sleep(0.3) + ui.log(' 自动跳到申报记录页: %s' % got_record) + + # 复核:**不回日常申报页再进一次**(那一步纯属多余:慢,还会再触发一次查询)。 + # 提交成功后客户端已经自动停在「申报记录」,就在这一页读记录当证据。 + rec_text = '' + rec = ui.find_child(main, 'TFrmHdsbsbjl') if main else None + if rec: + try: + from . import sbocr + l, t, w, h = rec.rect + items = sbocr.texts((l + 10, t + 90, l + w - 10, t + min(h - 10, 340)), main=main) + rec_text = ' | '.join(i.text for i in items)[:220] + ui.log(' 申报记录页:%s' % (rec_text or '<没读到>')) + except Exception as e: # noqa: BLE001 + ui.log(' 读申报记录页失败:%r' % e) + ok = bool(got_record) + if not ok: + ui.log(' ⚠ 没跳到「申报记录」页 —— 提交结果不确定,需要人工核对') + return {'ok': ok, 'steps': steps, 'record_page': got_record, 'record_text': rec_text} + + +def ensure_main_ready(main, timeout=30.0): + """主窗可能被登录后的模态弹窗禁用(确认单位/待办/安全提示)。 + 主窗 disabled 时坐标点击会**静默无效**,所以进页面之前必须先把它清干净。""" + classes = ('TfrmSwjgSwitch', 'Tfrm_dbsxMessage', 'TfrmAqts', 'Tfrm_MsgDlgRich') + t0 = time.time() + while time.time() - t0 < timeout: + if main.enabled and not any(ui.find_window(c, timeout=0) for c in classes): + return True + for cls in classes: + w = ui.find_window(cls, timeout=0) + if not w: + continue + btns = sorted([b for b in ui.children(w, visible_only=True) + if b.cls == 'TITSSpeedButton'], key=lambda b: b.rect[0]) + if btns: + ui.log(' 清弹窗 %s(点按钮)' % cls) + ui.post_click(btns[0]) + else: + ui.u32.PostMessageW(w.hwnd, ui.WM_CLOSE, 0, None) + time.sleep(0.8) + time.sleep(0.3) + return False + +# ---------------------------------------------------------------- 主流程 +SOURCE_DETAIL = '税务生成' # 只有这个来源有「职工未申报明细」页 +NO_DATA_HINTS = ('未查询到', '没有查询到', '无未申报', '不存在未申报') +ERROR_HINTS = ('失败', '繁忙', '系统忙', '连接', '超时', '异常', '-10008', '网络') + + +def refresh_with_retry(page, tries=6, wait=12.0, timeout=40.0): + """点「刷新」联网取核定数据;服务器繁忙/连接失败/超时 一律重试刷新。 + + 用户口径(2026-11-19):异常弹窗不用去点别的,就再点刷新。 + 返回最后一批弹窗正文(用来判「未查询到未申报信息」= 真没数据)。 + """ + body = '' + for i in range(1, tries + 1): + del LAST_DIALOGS[:] + ok = refresh_data(page, timeout=timeout) + body = ' '.join(LAST_DIALOGS) + if any(h in body for h in ERROR_HINTS): + ui.log(' 刷新失败「%s%s」→ %d 秒后重试刷新(%d/%d)' + % (body[:50], '' if ok else ' 超时', wait, i, tries)) + time.sleep(wait) + continue + if i > 1: + ui.log(' 第 %d 次刷新成功' % i) + return body + raise ClientError(18, '刷新连续 %d 次都被服务端拒绝:%s' % (tries, body)) + + +def click_query(page): + """点第二排的「查询」(本地 SQL,按当前查询条件过滤)。""" + row = sorted([b for b in buttons(page) if 180 <= b['y'] <= 215], key=lambda b: b['x']) + if not row: + raise ClientError(13, '找不到「查询」按钮') + btn = row[0] + del LAST_DIALOGS[:] + ui.log(' 点「查询」(%d,%d)' % (btn['x'], btn['y'])) + ui.post_click(btn['win']) + wait_idle(30) + return ' '.join(LAST_DIALOGS) + + +def sources_of(page): + """「数据来源」下拉里所有真实来源(去掉「请选择」)。""" + combos = pick_combos(page) + pair = combos.get('source') + if not pair: + return [] + items = pair[1] + return [i for i in items[1:] if i and i not in ('请选择', '')] + + +def select_source(page, src): + combos = pick_combos(page) + if 'source' not in combos: + raise ClientError(13, '找不到「数据来源」下拉框') + return select_option(combos['source'], wanted=src) + + +def close_detail(): + d = ui.find_window('TFrmAllYclZgmx') + if d: + ui.u32.PostMessageW(d.hwnd, ui.WM_CLOSE, 0, None) + time.sleep(1.2) + return not bool(ui.find_window('TFrmAllYclZgmx')) + + +def verify_files(files): + """导出完必须校验文件真的在盘上(>0 字节),否则不允许提交。""" + bad = [] + for f in files: + if not f: + bad.append('<无记录>') + elif not os.path.exists(f['file']) or os.path.getsize(f['file']) <= 0: + bad.append(f['file']) + if bad: + raise ClientError(19, '导出文件缺失或为空:%s' % bad) + for f in files: + ui.log(' ✔ 文件已落盘:%s(%d 字节)' % (os.path.basename(f['file']), os.path.getsize(f['file']))) + return True + + +def process_source(page, main, cfg, src, declare_dir, detail_dir, submit, want_detail, want_summary): + """处理一个数据来源:选中 → 查询 → 勾选 → 明细(仅税务生成) → 汇总 → 校验 → 提交。 + + 用户口径(2026-11-19): + - 只有「税务生成」有职工未申报明细,先导明细再导汇总,两个文件都落盘才提交; + - 其他来源(征集信息)只有汇总,单独导出、单独提交。 + 汇总 xls 落 申报结果/<门店>/,职工明细 xlsx 落 职工未申报明细/<门店>/。 + """ + res = {'source': src, 'rows': False, 'detail': None, 'summary': None, + 'submitted': None, 'note': ''} + ui.log('--- 数据来源:%s ---' % src) + select_source(page, src) + body = click_query(page) + if any(h in body for h in NO_DATA_HINTS): + res['note'] = body + ui.log(' 无数据:%s' % body[:60]) + return res + + page = find_daily_page(main) or page + res['rows'] = select_all_rows(page, cfg) + if not res['rows']: + res['note'] = '查询后没有可勾选数据' + ui.log(' 查询后没有可勾选数据') + return res + + files = [] + if want_detail and src == SOURCE_DETAIL: + detail = open_detail(page, cfg) + ui.foreground(detail) + time.sleep(0.4) + res['detail'] = export_detail(detail, detail_dir, src) + files.append(res['detail']) + close_detail() + ui.foreground(main) + time.sleep(0.5) + # 明细页关掉后勾选可能被重置,重新全选一次 + page = find_daily_page(main) or page + select_all_rows(page, cfg) + + if want_summary: + res['summary'] = export_summary(page, declare_dir, src) + files.append(res['summary']) + + verify_files(files) + + if submit: + res['submitted'] = submit_flow(page, cfg) + return res + + +def grid_has_rows(page): + """表格正文有没有数据行。 + + 优先读底部「共 N 条记录」(空表也有表格线,像素墨迹会误判);读不到才退回墨迹, + 且必须在客户端前台时取(否则量到的是别的窗口)。 + """ + try: + from . import sbocr + it = sbocr.find('条记录', (200, 930, 900, 1000)) + if it is not None: + m = re.search(r'共\s*(\d+)\s*条', it.text) + n = int(m.group(1)) if m else None + if n is None: + nums = re.findall(r'\d+', it.text) + n = int(nums[-1]) if nums else None + if n is not None: + ui.log(' 底部记录数:%d' % n) + return n > 0 + except Exception: # noqa: BLE001 + pass + for c in ui.children(page, visible_only=True): + if c.cls == 'TAdvStringGrid': + l, t, w, h = c.rect + ink = ui.region_ink(l + 60, t + 45, l + w - 30, t + min(h - 10, 45 + 40 * 6)) + ui.log(' 表格正文墨迹=%d' % ink) + return ink > 200 + return False + + +def wait_entry_state(main, page, timeout=90.0): + """进页面后**不等弹窗**,直接抓页面/表单位图 OCR 判状态(影刀 process4 的做法)。 + + - 位图 OCR 出现「未生成未申报信息 / 未申报信息已申报」→ 无需申报 + - 出现「共 N 条记录」且 N>0 → 有数据 + - 中途弹窗(服务器连接异常等)→ PrintWindow 读正文、切前台点确定,异常则重按刷新 + 全程 PrintWindow 抓控件位图,不截屏、不量墨迹、不依赖前台。 + """ + from . import winprint + t0 = time.time() + rounds = 0 + last = '' + while time.time() - t0 < timeout and rounds < 40: + rounds += 1 + d = ui.find_window('Tfrm_MsgDlgRich') + if d: + body = _dialog_text(d) # 内部已重试 3 次(防淡入时读到空串) + last = body or last + if not body: + # 读不到正文时**先别点**:盲点会把「未查询到未申报信息」这种关键结论一起点掉 + ui.log(' ⚠ 弹窗「%s」正文没读到 → 稍等重读,先不点' % (d.title or '?')) + time.sleep(0.6) + continue + confirm_dialog(d) + if any(h in body for h in ERROR_HINTS): + ui.log(' 弹窗「%s」→ 点确定并重新刷新' % body[:50]) + refresh_data(page) + t0 = time.time() + continue + if any(h in body for h in NO_DATA_HINTS): + ui.log(' 弹窗「%s」→ 无需申报' % body[:60]) + return 'none', body + continue + + try: + grid = next((c for c in ui.children(page, visible_only=True) + if c.cls == 'TAdvStringGrid'), page) + text, _ok = winprint.ocr(grid) + except Exception as e: # noqa: BLE001 + ui.log(' 位图 OCR 失败:%s' % e) + text = [] + joined = ' '.join(text) + if joined: + last = joined + if any(h in joined for h in NO_DATA_HINTS): + ui.log(' 表单位图:「%s」→ 无需申报' % joined[:60]) + return 'none', joined + m = re.search(r'共\s*(\d+)\s*条', joined) + if m and int(m.group(1)) > 0: + ui.log(' 表单位图:共 %s 条记录 → 有数据' % m.group(1)) + return 'data', joined + if len(text) > 20: # 空表只识别出表头(实测 15 段),有数据行会明显变多 + ui.log(' 表单位图:%d 段文字 → 有数据' % len(text)) + return 'data', joined + if rounds >= 8: + ui.log(' 连续 %d 轮表单位图都没有数据/无数据关键字 → 按无数据处理' % rounds) + return 'none', joined or last + if rounds in (3, 6, 9): + ui.log(' 第 %d 轮:表单位图仍未见数据(%s)' % (rounds, joined[:40])) + time.sleep(1.0) + raise ClientError(21, '40 轮内判不出状态(末尾识别:%s)' % last[:80]) + + +def ordered_sources(page): + """"数据来源"下拉里的真实来源,按业务顺序:征集信息 → 税务生成 → 其他。 + + 直接读下拉选项(CB_GETLBTEXT),**不点开下拉框看**。 + """ + names = sources_of(page) + if not names: + return [SOURCE_DETAIL] + head = [s for s in ('征集信息', SOURCE_DETAIL) if s in names] + tail = [s for s in names if s not in head] + return head + tail + + +def safe_name(s): + return ''.join('_' if c in '\\/:*?"<>|' else c for c in str(s or '')).strip() or '未命名' + + +def run_daily(store='', org=None, period=None, cfg=None, refresh=True, + export_summary_xls=True, export_detail_xlsx=True, submit=False, + refresh_timeout=40.0, detail_timeout=90.0, + refresh_tries=6, retry_wait=12.0): + """日常申报完整流程(2026-11-19,按业务口径)。 + + 1. 进页面 → **等**:等弹窗(未生成未申报信息 = 无需申报 / 服务器连接异常 = 确定后重刷新), + 或等到表格有数据;两头都等不到再点刷新 + 2. 读「数据来源」下拉选项(不点开看):有征集信息 → 先做;没有就跳过 + 3. 每个来源分开:选中 → 查询 → 全选 → 导出(税务生成多一步职工未申报明细)→ 校验文件 + 4. 需要提交时**按来源分开提交**(确认后点取消,不取申报结果) + 返回 {'sources': [...], 'period':..., 'org':..., 'rows': bool} + + 产物目录: + 汇总 xls → save_dir/申报结果/<门店>/ + 明细 xlsx → save_dir/职工未申报明细/<门店>/ + """ + cfg = cfg or CONFIG + declare_dir = config.declare_dir(store) + detail_dir = config.detail_dir(store) + result = {'sources': [], 'period': None, 'org': None, 'rows': False, 'note': '', + 'declare_dir': declare_dir, 'detail_dir': detail_dir} + main = get_main() + ui.foreground(main) + time.sleep(0.5) + try: + ensure_main_ready(main) + page = open_daily_page(main, cfg) + + # 进页面先点一次刷新:弹窗(未查询到/服务器异常)会随刷新出现, + # 弹窗正文由 PrintWindow 读出并记录在 LAST_DIALOGS,命中「未查询到」就直接收工。 + # ⚠ 必须走 refresh_with_retry:首次刷新常遇 [-10008]系统忙,紧接着客户端可能再弹 + # 「未查询到未申报信息」;两批弹窗混在一起会被误判成"无需申报"(实测 21:49 踩到)。 + body = refresh_with_retry(page, tries=refresh_tries, wait=retry_wait, timeout=refresh_timeout) + if any(h in body for h in NO_DATA_HINTS): + ui.log(' 刷新弹窗:「%s」→ 无需申报(点确定即可)' % body[:60]) + result['note'] = body + return result + + # 页面控件分批创建,必须轮询。**这里不清弹窗**——「未查询到未申报信息」要留给 + # wait_entry_state 读正文判"无需申报",先清掉就会白等 90 秒然后误判成有数据。 + combos = {} + deadline = time.time() + 25 + while time.time() < deadline: + combos = pick_combos(page) + if 'org' in combos and 'period' in combos and 'source' in combos: + break + time.sleep(0.3) + if ui.find_window('Tfrm_MsgDlgRich'): + break # 有弹窗就直接交给 wait_entry_state 处理 + if 'org' not in combos or 'period' not in combos: + raise ClientError(13, '等了 25 秒仍没识别出「社保经办机构」/「费款所属期」(找到 %s)' + % list(combos)) + + # 经办机构:业务口径保持「请选择」不动 + c_org, items_org = combos['org'] + if org: + result['org'] = select_option(combos['org'], wanted=org) + else: + sel = ui.combo_sel(c_org) + result['org'] = items_org[sel] if sel >= 0 else None + ui.log(' 社保经办机构保持不动: %s' % result['org']) + + # ① 进页面先等:弹窗(无需申报/服务器连接异常)或表格数据,二选一 + state, body = wait_entry_state(main, page, timeout=90.0) + if state == 'none': + result['note'] = body + ui.log(' 结论:无需申报(%s)' % body[:60]) + return result + + # 期次:有就选最新一期,没有就按页面默认条件 + combos = pick_combos(page) + periods = [i for i in combos['period'][1][1:] if re.match(r'^\d{4}-\d{2}$', i)] \ + if 'period' in combos else [] + if periods: + result['period'] = select_option(combos['period'], wanted=period or periods[-1]) + else: + ui.log(' 「费款所属期」只有请选择(按默认条件查询)') + + # ② 数据来源:直接读下拉选项;没有征集信息就跳过,只做税务生成 + srcs = ordered_sources(page) + ui.log(' 数据来源 %d 个:%s' % (len(srcs), '、'.join(srcs))) + if '征集信息' not in srcs: + ui.log(' 没有「征集信息」→ 跳过,直接做「%s」' % SOURCE_DETAIL) + + for i, src in enumerate(srcs): + res = process_source(page, main, cfg, src, declare_dir, detail_dir, submit, + want_detail=export_detail_xlsx, + want_summary=export_summary_xls) + result['sources'].append(res) + if i == len(srcs) - 1: + # 最后一个来源做完就收工:提交后客户端停在「申报记录」, + # **不要再回日常申报页**(多进一次既慢又会再触发一次查询) + ui.log(' 最后一个数据来源已处理完,不再回日常申报页') + break + main = ui.find_window('Tfrm_MainFrame', visible=False) or main + page = find_daily_page(main) + if page is None: + page = open_daily_page(main, cfg) + + result['rows'] = any(s['rows'] for s in result['sources']) + if not result['rows']: + last = next((s['note'] for s in result['sources'] if s['note']), '') + result['note'] = last or '各数据来源都没有可申报数据' + ui.log(' 各数据来源都没有可申报数据') + return result + finally: + close_all() diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/login.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/login.py new file mode 100644 index 0000000..31068be --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/login.py @@ -0,0 +1,658 @@ +# -*- coding: utf-8 -*- +""" +login.py —— 登录 / 切换单位(生产版移植) + +用法(插件里): + from . import login + if not login.is_logged_in(): + r = login.login(nsrsbh='92510107MA66TYBN2M', password='***') + +流程(实测): + 1. 客户端没起 → 起 EPEvenue_SB.exe,等 40~90 秒出登录窗(TfrmCompMgrMerge) + 2. 税号填进搜索框(TITSEdit)→ 列表过滤 → 双击第一行 + 3. 若弹密码窗(TfrmRegister / TXPFamerEditEx)→ 填密码 → 点确定 + 4. 等主界面 Tfrm_MainFrame(登录后要 10 秒以上)+ 清掉确认单位/待办/安全提示 + +注意: + - 进程必须管理员(客户端是 High 完整性);由插件入口 sbui.require_admin() 保证 + - 双击「当前已登录的单位」是空操作,只有别的单位才弹密码框 + - 密码要全角转半角(to_halfwidth) + - 客户端安装目录(EPEvenue_SB.exe 所在)= config.client_dir(),运行状态 = config.run_dir() +""" + +import json +import os +import re +import subprocess +import time + +from .. import config +from . import sbui as ui + +POPUP_CLASSES = ('TfrmSwjgSwitch', 'Tfrm_dbsxMessage', 'TfrmAqts') + + +class LoginError(RuntimeError): + def __init__(self, code, msg): + super().__init__(msg) + self.code = code + + +# ---------------------------------------------------------------- 状态 +def state_file(): + return os.path.join(config.run_dir(), 'state.json') + + +def current_unit(): + """当前登录单位 —— **权威来源是客户端自己写的 UserConfig.ini**。 + + AppComs\\Main\\UserConfig.ini 只有一行 Nsrsbh=xxxx,客户端每次登录/切户都会重写它 + (实测 2026-11-19 15:11 切户后该文件时间戳同步变化)。比我们自己记的 state 文件可靠。 + """ + ini = os.path.join(config.client_dir(), 'AppComs', 'Main', 'UserConfig.ini') + if os.path.exists(ini): + try: + with open(ini, encoding='utf-8', errors='ignore') as f: + for line in f: + line = line.strip() + if line.upper().startswith('NSRSBH='): + v = line.split('=', 1)[1].strip() + if v: + return v + except OSError: + pass + # 兜底:脚本自己记录的 state 文件(可能过期) + p = state_file() + if not os.path.exists(p): + return None + try: + with open(p, encoding='utf-8-sig') as f: # PS 写的文件带 BOM + return json.load(f).get('current') + except Exception: + return None + + +def save_unit(nsrsbh): + os.makedirs(config.run_dir(), exist_ok=True) + with open(state_file(), 'w', encoding='utf-8') as f: + json.dump({'current': nsrsbh, 'at': time.strftime('%Y-%m-%d %H:%M:%S')}, f, ensure_ascii=False) + + +def main_window(): + return ui.find_window('Tfrm_MainFrame', visible=False) + + +def is_logged_in(): + w = main_window() + return bool(w) and w.visible + + +def running(): + """客户端进程在不在。 + + 进程名不固定(EPPortalSB / EPPortalSB1),安装目录由 config.client_dir() 决定。 + 优先看客户端窗口的进程 exe 是否落在 client_dir 下(避免误判别的区域副本); + 没有窗口时退回归一化 tasklist(仍按固定进程名)。 + """ + client_dir = os.path.normcase(config.client_dir()) + for cls in ('Tfrm_MainFrame', 'TfrmCompMgrMerge'): + w = ui.find_window(cls, visible=False) + if w: + exe = ui.process_path_of(w.hwnd) + if exe and os.path.normcase(os.path.dirname(exe)) == client_dir: + return True + for name in ('EPPortalSB.exe', 'EPPortalSB1.exe'): + try: + out = subprocess.run(['tasklist', '/FI', 'IMAGENAME eq %s' % name, '/NH'], + capture_output=True, text=True, timeout=10).stdout + if name.split('.')[0] in out: + return True + except Exception: + pass + return False + + +# ---------------------------------------------------------------- 启动 +def launch_client(wait=180.0): + """启动客户端(EPEvenue_SB.exe),等登录窗出现。""" + region_dir = config.client_dir() + exe = config.client_exe() + if not os.path.exists(exe): + exe = os.path.join(region_dir, 'EPEvenue_SB.exe') + if not os.path.exists(exe): + raise LoginError(2, '找不到启动器: %s' % exe) + ui.log('启动客户端: %s(首次约 40~90 秒,别重复启动)' % region_dir) + subprocess.Popen([exe], cwd=region_dir) + return wait_login_window(timeout=wait) + + +def wait_login_window(timeout=180.0): + """等登录窗出现。前 6 秒只有登录器、没有主进程,不能据此判失败。 + + 期间会顺手关掉 Windows 的「打开文件 - 安全警告」(区域副本的 exe 带 Internet 标记时, + 每次启动子进程都弹一次,不点就永远等不到登录窗)。 + """ + t0 = time.time() + last = 0 + while time.time() - t0 < timeout: + if ui.dismiss_security_warning(): + continue + w = ui.find_window('TfrmCompMgrMerge', timeout=0) + if w: + ui.log('登录窗出现(%.0f 秒)' % (time.time() - t0)) + return w + if time.time() - t0 - last >= 30: + last = time.time() - t0 + ui.log(' 已等 %.0f 秒,仍在启动中…' % last) + time.sleep(0.5) + raise LoginError(3, '等了 %.0f 秒仍未出现登录窗 TfrmCompMgrMerge' % timeout) + + +# ---------------------------------------------------------------- 登录窗操作 +def fill_nsrsbh(login_win, nsrsbh): + edit = None + for k in ui.children(login_win, visible_only=True): + if k.cls == 'TITSEdit' and k.rect[2] >= 300: + edit = k + break + if not edit: + raise LoginError(4, '登录窗里找不到税号搜索框(TITSEdit,宽>=300)') + l, t, w, h = edit.rect + ui.click_at(l + w // 2, t + h // 2, ancestor=login_win) + ui.ctrl(0x41) # Ctrl+A + time.sleep(0.15) + ui.key(ui.VK_DELETE) + time.sleep(0.25) + n = ui.type_unicode(nsrsbh) + ui.log('已输入税号(%d 个字符事件)' % (n // 2)) + time.sleep(0.8) + # ★ 结构化校验:搜索框读回必须等于目标税号(残留字符会让列表过滤成空/错行, + # 坑 29 踩过)。不一致就清空重输一次,仍不一致直接失败,不往下点。 + got = (ui.get_text(edit) or '').strip() + if got != nsrsbh: + ui.log(' 搜索框读回不一致(%r)→ WM_SETTEXT 清空重输' % got) + ui.set_text(edit, '') + time.sleep(0.3) + ui.click_at(l + w // 2, t + h // 2, ancestor=login_win) + ui.type_unicode(nsrsbh) + time.sleep(1.0) + got = (ui.get_text(edit) or '').strip() + ui.log(' 搜索框读回: %r' % got) + if got != nsrsbh: + raise LoginError(14, '税号搜索框读回不一致:期望 %s,实际 %r' % (nsrsbh, got)) + time.sleep(2.0) + + +def pick_first_row(login_win, timeout=20.0): + """双击列表第一行。返回 'register'(弹了密码窗)/ 'same'(当前已登录单位)/ None。 + + 注意:输入税号后列表要重新过滤,`TVirtualStringTree` 会**短暂消失再出现**。 + 这里必须轮询等它回来,不能一找不到就报错(实测 2026-11-19 19:42 就是这样误判的)。 + """ + tree = None + t0 = time.time() + while time.time() - t0 < timeout: + for k in ui.children(login_win, visible_only=True): + if k.cls == 'TVirtualStringTree': + tree = k + break + if tree: + break + time.sleep(0.3) + if not tree: + raise LoginError(5, '登录窗里等了 %.0f 秒仍没有账户列表 TVirtualStringTree' % timeout) + l, t, w, h = tree.rect + x, y = l + 258, t + 57 + ui.click_at(x, y, ancestor=login_win) + time.sleep(0.5) + ui.double_click(x, y) + ui.log('已双击第一行 (%d,%d)' % (x, y)) + + for attempt in (1, 2): + t0 = time.time() + while time.time() - t0 < 10: + time.sleep(0.3) + if ui.find_window('TfrmRegister', timeout=0): + return 'register' + if is_logged_in(): + return 'same' + if attempt == 1: + ui.log(' 双击没反应,列表可能还没过滤完,再双击一次') + ui.click_at(x, y, ancestor=login_win) + time.sleep(0.4) + ui.double_click(x, y) + return None + + +def parse_register_texts(texts): + """从 OCR 文本行里抽「纳税人识别号 / 纳税人名称」(纯函数,方便自测)。""" + out = {'nsrsbh': '', 'name': ''} + for s in texts or []: + flat = (s or '').replace(' ', '').replace(':', ':') + if '纳税人识别号' in flat and not out['nsrsbh']: + m = re.search(r'纳税人识别号[:]?([0-9A-Za-z]{15,20})', flat) + if m: + out['nsrsbh'] = m.group(1).upper() + elif '纳税人名称' in flat and not out['name']: + m = re.search(r'纳税人名称[:]?(.+)$', flat) + if m: + out['name'] = m.group(1).strip() + return out + + +def read_register_unit(reg_win): + """从「安全认证」密码窗 OCR 出纳税人识别号 / 名称。 + + 这个窗里的税号是**画在面板上的文字**(TLabel 没有 HWND、VCL 也没实现 UIA, + 实测 UIA 只暴露 Pane),只能 OCR。 + 实测原文(2026-11-23): + 纳税人识别号:91430103MACQR4C07Y + 纳税人名称:长沙市天心区康荣足浴有限公司 + """ + from . import sbocr + + l, t, w, h = reg_win.rect + items = sbocr.texts((l, t, l + w, t + h), min_score=0.3) + texts = [i.text or '' for i in items] + out = parse_register_texts(texts) + out['text'] = ' | '.join(texts)[:300] + return out + + +def verify_register_unit(reg_win, nsrsbh, strict=True): + """核对密码窗显示的单位是不是目标单位;不一致就关窗并报错(不输密码)。""" + got = read_register_unit(reg_win) + target = ui.to_halfwidth(str(nsrsbh or '')).strip().upper() + ok = bool(got['nsrsbh']) and got['nsrsbh'] == target + ui.log(' 密码窗:税号=%s 名称=%s(目标 %s)→ %s' + % (got['nsrsbh'] or '<没读到>', got['name'] or '-', target or '-', + '一致' if ok else '不一致')) + if not ok and strict: + close_register(reg_win) + raise LoginError(13, '密码窗里的单位与目标不一致:显示 %r / %r,目标 %s' + % (got['nsrsbh'], got['name'], target)) + return got + + +def close_register(reg_win=None): + """关掉密码窗(点右上角 ×,不吃 WM_CLOSE 时再按 ESC)。""" + reg_win = reg_win or ui.find_window('TfrmRegister', timeout=0) + if not reg_win: + return True + l, t, w, h = reg_win.rect + try: + ui.foreground(reg_win) + ui.real_click(l + w - 22, t + 18) + time.sleep(1.0) + except Exception: # noqa: BLE001 + pass + if ui.find_window('TfrmRegister', timeout=0): + ui.key(0x1B) + time.sleep(0.8) + return not bool(ui.find_window('TfrmRegister', timeout=0)) + + +def verify_logged_unit(nsrsbh, strict=True): + """登录后从主界面底部状态栏再核对一次「当前操作单位 …[税号]」。 + + 这是**客户端自己显示的**结论,比我们记录的 state 文件可信。 + OCR 读不到(空串)只告警;读到了但税号对不上 → 抛错(可能登错单位)。 + """ + from . import sbocr + + main = ui.find_window('Tfrm_MainFrame', visible=False) + if not main: + return '' + try: + l, t, w, h = main.rect + items = sbocr.texts((l, t + h - 48, l + w, t + h), min_score=0.25) + text = ' '.join(i.text or '' for i in items).strip() + except Exception as e: # noqa: BLE001 + ui.log(' ⚠ 状态栏 OCR 失败:%r' % e) + return '' + ui.log(' 状态栏:%s' % (text[:120] or '<空>')) + if not text: + ui.log(' ⚠ 状态栏没读到文字,跳过单位核对(不影响登录)') + return text + target = ui.to_halfwidth(str(nsrsbh)).upper() + if target not in text.replace(' ', '').upper(): + if strict: + raise LoginError(15, '登录后状态栏没看到目标税号 %s,可能登错单位:%r' + % (target, text[:120])) + ui.log(' ⚠ 状态栏没看到目标税号(strict=False,继续)') + return text + + +def fill_password(reg_win, password, submit=True): + pw = None + for k in ui.children(reg_win, visible_only=True): + if k.cls == 'TXPFamerEditEx': + pw = k + break + if not pw: + raise LoginError(6, '密码窗里找不到输入框 TXPFamerEditEx') + l, t, w, h = pw.rect + cx, cy = l + w // 2, t + h // 2 + ui.click_at(cx, cy, ancestor=reg_win) + time.sleep(0.4) + ui.ctrl(0x41) + time.sleep(0.15) + ui.key(ui.VK_DELETE) + time.sleep(0.2) + + # 先试直接写控件(快、稳);读回不一致就逐字符输入 + ok = ui.set_text(pw, password) + ui.log('WM_SETTEXT 读回一致: %s' % ok) + if not ok: + ui.click_at(cx, cy, ancestor=reg_win) + time.sleep(0.3) + ui.ctrl(0x41) + ui.key(ui.VK_DELETE) + ui.type_unicode(password) + time.sleep(0.4) + ui.log('逐字符输入后读回长度=%d' % len(ui.get_text(pw))) + if not submit: + ui.log('按 -NoSubmit:未提交') + return True + + time.sleep(0.9) # 去抖,只提交一次 + btns = sorted([b for b in ui.children(reg_win, visible_only=True) if b.cls == 'TITSSpeedButton'], + key=lambda b: b.rect[0]) + if btns: + ui.log('点「确定」(%d,%d)' % btns[-1].rect[0:2]) + ui.post_click(btns[-1]) + else: + # 兜底:按窗口比例点(实测 0.815 / 0.929) + bx = int(l + (reg_win.rect[2]) * 0.815) + by = int(t + (reg_win.rect[3]) * 0.929) + ui.log('没有按钮句柄,按比例点「确定」(%d,%d)' % (bx, by)) + ui.click_at(bx, by, ancestor=reg_win) + return True + + +# ---------------------------------------------------------------- 重启(批量每户的入口) +def kill_client(): + """强杀客户端相关进程。进程名不固定:EPPortalSB / EPPortalSB1 都可能。""" + for name in ('EPPortalSB.exe', 'EPPortalSB1.exe', 'ProcDataDeal.exe', 'EPEvenue_SB.exe'): + try: + subprocess.run(['taskkill', '/F', '/IM', name], + capture_output=True, timeout=15) + except Exception: + pass + + +def restart_client(wait=200.0, grace=2.0): + """直接强杀再启动。 + + 实测:客户端的 WM_CLOSE 从来关不掉(15 秒等下来还是要强杀), + 所以不再做优雅关闭,省掉每户 15 秒。杀完等 2 秒让文件句柄释放。 + """ + ui.log('关闭客户端(直接强杀)…') + kill_client() + time.sleep(grace) + return launch_client(wait=wait) + +# ---------------------------------------------------------------- 添加单位(登录列表里没有时才需要) +def _bottom_btns(win): + """对话框底部那排按钮(上一步/下一步/完成),按 x 排序。""" + x, y, w, h = win.rect + out = [b for b in ui.children(win, visible_only=True) + if b.cls == 'TITSSpeedButton' and b.rect[1] > y + h - 140] + return sorted(out, key=lambda b: b.rect[0]) + + +def _click_next(win, label=''): + btns = _bottom_btns(win) + if not btns: + raise LoginError(12, '「%s」没有底部按钮' % label) + ui.log(' %s → 点最右底部按钮 %r' % (label, btns[-1].rect[:2])) + ui.post_click(btns[-1]) + + +def add_unit(nsrsbh, password, timeout=90.0): + """把单位加进登录列表(登录窗「添加」按钮)。 + + 实测 3 步: + ① 添加单位:填「纳税人识别号」→ 下一步 + ② 确认单位:列出该税号下的单位(名称/税务机关/状态)→ 下一步 + ③ 输密码验证身份 → 完成(最右底部按钮) + 返回 True 表示添加完成(注册窗关闭);失败抛 LoginError。 + 幂等:单位已在列表里时,仍走一遍流程;真正的"是否已存在"由上层决定是否调用。 + """ + nsrsbh = ui.to_halfwidth(nsrsbh.strip()) + pw = ui.to_halfwidth(password or '') + + login_win = ui.find_window('TfrmCompMgrMerge', timeout=10.0) + if not login_win: + raise LoginError(12, '不在登录窗,无法添加单位') + ui.foreground(login_win) + time.sleep(0.5) + # 窗口刚被拉到前台时,**第一次点击常被"激活窗口"吃掉**(2026-11-19 17:58 实测)。 + # 先点一下自己的标题栏空白处热身。 + ui.click_at(login_win.rect[0] + 60, login_win.rect[1] + 60, ancestor=login_win) + time.sleep(0.4) + + # 登录窗工具条:添加 / 删除 / 重置(按 x 排序,添加最左) + row = sorted([b for b in ui.children(login_win, visible_only=True) + if b.cls == 'TITSSpeedButton' and 430 <= b.rect[1] <= 480], + key=lambda b: b.rect[0]) + if not row: + raise LoginError(12, '登录窗上找不到「添加」按钮') + reg = None + for attempt in (1, 2): + ui.log('点「添加」%r(第 %d 次)' % (row[0].rect[:2], attempt)) + ui.post_click(row[0]) + reg = ui.find_window('TfrmRegister', timeout=8.0) + if reg: + break + ui.foreground(login_win) + time.sleep(0.6) + if not reg: + raise LoginError(13, '点添加后没出现「添加单位」窗') + ui.foreground(reg) + time.sleep(0.6) + + # ① 填税号 → 下一步 + edit = None + for k in ui.children(reg, visible_only=True): + if k.cls == 'TXPFamerEditEx': + edit = k + break + if not edit: + raise LoginError(13, '「添加单位」里没有税号输入框') + if not ui.set_text(edit, nsrsbh): + raise LoginError(13, '税号写入失败') + ui.log(' 税号: %s' % nsrsbh) + _click_next(reg, '添加单位') + + # ② 确认单位(会查服务端,带 SplashWindow)→ 下一步 + t0 = time.time() + while time.time() - t0 < timeout: + time.sleep(0.5) + if ui.find_window('SplashWindow', timeout=0): + continue + reg = ui.find_window('TfrmRegister', timeout=0) + if not reg: + break + btns = _bottom_btns(reg) + if len(btns) >= 2: # 出现「上一步/下一步」= 已到确认单位 + break + reg = ui.find_window('TfrmRegister', timeout=0) + if not reg: + raise LoginError(14, '添加流程中途窗口消失') + _click_next(reg, '确认单位') + time.sleep(2.0) + + # ③ 输密码验证身份 → 完成 + reg = ui.find_window('TfrmRegister', timeout=15.0) + if not reg: + raise LoginError(15, '没到「输密码验证身份」这一步') + pw_edit = None + for k in ui.children(reg, visible_only=True): + if k.cls == 'TXPFamerEditEx': + pw_edit = k + break + if not pw_edit: + raise LoginError(15, '找不到密码输入框') + if not ui.set_text(pw_edit, pw): + raise LoginError(15, '密码写入失败') + _click_next(reg, '验证身份') + + # 等注册窗关闭 + t0 = time.time() + while time.time() - t0 < timeout: + time.sleep(0.5) + if not ui.find_window('TfrmRegister', timeout=0): + ui.log(' ✅ 单位已添加') + return True + m = ui.find_window('Tfrm_MsgDlgRich', timeout=0) + if m: + ui.log(' 提示: %s' % m.title) + close_msg(m) + time.sleep(0.5) + raise LoginError(16, '添加单位超时(注册窗仍在)') + +# ---------------------------------------------------------------- 等主界面 +def wait_main(timeout=180.0): + t0 = time.time() + while time.time() - t0 < timeout: + time.sleep(1) + if ui.dismiss_security_warning(): + continue + m = ui.find_window('Tfrm_MsgDlgRich', timeout=0) + if m: + ui.log('出现提示框: %s' % m.title) + close_msg(m) + time.sleep(1) + continue + if is_logged_in() and not ui.find_window('TfrmRegister', timeout=0): + ui.log('主界面已出现(%.0f 秒)' % (time.time() - t0)) + return True + if int(time.time() - t0) % 30 == 0: + ui.log(' 等待主界面… %.0f 秒' % (time.time() - t0)) + return False + + +def close_msg(win): + btns = sorted([b for b in ui.children(win, visible_only=True) if b.cls == 'TITSSpeedButton'], + key=lambda b: b.rect[0]) + if btns: + ui.post_click(btns[0]) + else: + ui.u32.PostMessageW(win.hwnd, ui.WM_CLOSE, 0, None) + + +def close_popups(timeout=40.0): + """关掉登录后必现的弹窗,直到**主窗口变可用**为止。 + + 实测(2026-11-19 17:40): + - `TfrmSwjgSwitch`「确认单位」不吃 WM_CLOSE,只能点它自己的「确定」; + - 它关掉后可能还有「待办事项提醒」等第二个模态窗; + - 判据不是"关了几个",而是 `IsWindowEnabled(Tfrm_MainFrame) == True`。 + 模态窗没清干净时主窗是 disabled,后面点首页卡片会**静默无效**。 + """ + t0 = time.time() + while time.time() - t0 < timeout: + main = main_window() + if main and main.enabled and not any(ui.find_window(c, timeout=0) for c in POPUP_CLASSES): + return True + acted = False + for cls in POPUP_CLASSES + ('Tfrm_MsgDlgRich',): + w = ui.find_window(cls, timeout=0) + if not w: + continue + btns = sorted([b for b in ui.children(w, visible_only=True) + if b.cls == 'TITSSpeedButton'], key=lambda b: b.rect[0]) + if btns: + ui.log(' 关闭 %s:点按钮 %r' % (cls, btns[0].rect[:2])) + ui.post_click(btns[0]) + else: + ui.u32.PostMessageW(w.hwnd, ui.WM_CLOSE, 0, None) + acted = True + time.sleep(0.9) + if not acted: + time.sleep(0.5) + main = main_window() + ui.log(' ! 弹窗清理超时(主窗可用=%s)' % (main.enabled if main else None)) + return False + +def settle(timeout=45.0, quiet=2.0): + """登录后"落地":一直清弹窗,直到主窗可用并且连续 quiet 秒没有新弹窗。 + + 为什么需要:`确认单位`(TfrmSwjgSwitch) 是**延迟弹出**的——主窗先出现, + 1~3 秒后弹窗才盖上来。只在主窗出现那一刻清一次,必然漏掉。 + """ + t0 = time.time() + last = time.time() + while time.time() - t0 < timeout: + main = main_window() + pending = any(ui.find_window(c, timeout=0) + for c in POPUP_CLASSES + ('Tfrm_MsgDlgRich',)) + if pending or (main and not main.enabled): + close_popups(timeout=6) + last = time.time() + elif main and main.enabled and (time.time() - last) >= quiet: + return True + time.sleep(0.4) + main = main_window() + ui.log(' ! settle 超时(主窗可用=%s)' % (main.enabled if main else None)) + return False + +# ---------------------------------------------------------------- 主流程 +def login(nsrsbh, password=None, timeout=200.0, no_submit=False): + """登录或在登录窗里选单位。返回 dict:{'result': 'ok'|'already'|'submitted', ...}""" + nsrsbh = ui.to_halfwidth(nsrsbh.strip()) + if password is not None: + pw, converted = ui.to_halfwidth(password), True + else: + pw, converted = None, False + + if is_logged_in(): + cur = current_unit() + ui.log('已在主界面(记录的单位: %s)' % cur) + if cur and cur == nsrsbh: + return {'result': 'already', 'nsrsbh': nsrsbh} + # 已登录但不是目标单位 → 需要先点「切换单位」回到登录窗(由调用方决定是否切) + raise LoginError(7, '当前已登录 %s,切换单位请先在界面上点「切换单位」' % cur) + + if not running(): + launch_client(wait=timeout) + login_win = ui.find_window('TfrmCompMgrMerge', timeout=60.0) + if not login_win: + raise LoginError(3, '找不到登录窗 TfrmCompMgrMerge') + ui.foreground(login_win) + time.sleep(0.6) + + fill_nsrsbh(login_win, nsrsbh) + who = pick_first_row(login_win) + if who is None: + raise LoginError(8, '双击第一行后既没弹密码框也没进主界面') + if who == 'same': + ui.log('双击的是当前已登录单位 → 不弹密码框') + save_unit(nsrsbh) + close_popups() + return {'result': 'already', 'nsrsbh': nsrsbh} + + reg = ui.find_window('TfrmRegister', timeout=10.0) + if not reg: + raise LoginError(9, '没等到密码窗 TfrmRegister') + if not pw: + raise LoginError(10, '需要密码:账户表「密码」列不能为空') + ui.foreground(reg) + time.sleep(0.5) + # ★ 密码窗里会显示「纳税人识别号 / 纳税人名称」,先在**输密码之前**核对, + # 免得把密码打到别人头上(双击列表第一行的风险就在这里)。 + verify_register_unit(reg, nsrsbh) + ui.log('密码长度=%d(含全角转换=%s)' % (len(pw), converted)) + fill_password(reg, pw, submit=not no_submit) + + if no_submit: + return {'result': 'no-submit', 'nsrsbh': nsrsbh} + + if not wait_main(timeout): + raise LoginError(11, '等主界面超时') + settle() + verify_logged_unit(nsrsbh) + save_unit(nsrsbh) + ui.log('登录完成: %s' % nsrsbh) + return {'result': 'ok', 'nsrsbh': nsrsbh} diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/records_export.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/records_export.py new file mode 100644 index 0000000..ce55a56 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/records_export.py @@ -0,0 +1,351 @@ +# -*- coding: utf-8 -*- +"""records_export.py —— 申报记录导出(移植自影刀 process11 申报结果导出) + +影刀原流程: + 1. 激活窗口 → 建 <账户> 目录 + 2. 等「查看按钮」模板出现 + 3. view_coordinates:OCR 全窗,取所有以「查」开头且不是「查询」的文本 → 这些是每行的「查看」按钮; + 横坐标用固定列 1797(屏幕),y 用 OCR 的 y+高/2 + 4. 逐个点「查看」→ 等「导出按钮」→ 点导出 → 文件名框填 + `社会保险费缴费申报表_{i}.pdf` → 回车 → 有「导出成功确定按钮」就点 → 双击关闭详情 + 5. 回写账户表「申报记录」列 = 已导出申报记录 / 无需导出申报记录 + +本模块只做第 1~4 步(导出 PDF 到 申报结果/<门店>/),不碰账户表。 +""" +import os +import re +import time + +from .. import config +from . import daily_declare as dd +from . import sbocr +from . import sbui as ui + +VIEW_BTN_X = 1797 # 影刀里写死的「查看」列屏幕横坐标 +RECORDS_CLASS = 'TFrmHdsbsbjl' +WM_HSCROLL = 0x0114 +SB_RIGHT = 7 + + +class RecordsError(RuntimeError): + pass + + +def records_page(main=None): + main = main or ui.find_window('Tfrm_MainFrame', visible=False) + if not main: + raise RecordsError('主界面不在') + return ui.find_child(main, RECORDS_CLASS) + + +def open_records_page(main=None, timeout=25.0): + """左侧菜单:社保费申报 → 申报记录(进错页就重点)。""" + main = main or ui.find_window('Tfrm_MainFrame', visible=False) + if not main: + raise RecordsError('主界面不在') + page = records_page(main) + if page: + return page + + ui.foreground(main) + ui.dismiss_dialogs(main) + for attempt in range(1, 4): + ui.log(' 进「申报记录」(第 %d 次)' % attempt) + sbocr.expand_menu(main, '社保费申报', '申报记录') + if not sbocr.click_text(main, '申报记录', region=sbocr.menu_region(main)): + continue + t0 = time.time() + while time.time() - t0 < timeout: + time.sleep(0.4) + page = records_page(main) + if page: + ui.log(' 已进入申报记录页') + return page + raise RecordsError('3 次都没进入「申报记录」页') + + +def buttons(page): + out = [] + for b in ui.children(page, visible_only=True): + if b.cls != 'TITSSpeedButton': + continue + l, t, w, h = b.rect + out.append({'win': b, 'x': l, 'y': t, 'w': w, 'h': h, 'enabled': b.enabled}) + return out + + +def dismiss_popups(rounds=8, wait=0.6): + """把进页/查询后的提示框清干净(返回清掉的数量)。 + + 用户 2026-11-23 说明的实操顺序: + 进「申报记录」→ **先关掉弹窗** → 点「申报结果查询」 → 才能点「查看」导出。 + 这个提示框("若要获取已申报数据最新状态…")在进页和点查询后都会弹,而且是延迟弹的。 + """ + total = 0 + for _ in range(rounds): + total += dd.clear_msg_dialogs() + time.sleep(wait) + if total and not ui.find_window('Tfrm_MsgDlgRich', timeout=0): + time.sleep(0.8) # 再等一轮,防"延迟弹" + if not ui.find_window('Tfrm_MsgDlgRich', timeout=0): + break + return total + + +def click_result_query(page): + """点左上角「申报结果查询」。 + + 必须先点它,表格每行的「查看」才可用(用户 2026-11-23 指出)。 + 按钮是自绘 TITSSpeedButton(没标题),按 OCR 文字点最稳,找不到再按几何兜底。 + """ + l, t, w, h = page.rect + hit = None + for _ in range(3): # 刚关完弹窗时页面可能还没重绘,OCR 读不到 → 重试 + hit = sbocr.find('申报结果查询', (l, t, l + w, t + 110), min_score=0.3) + if hit: + break + time.sleep(0.5) + if hit: + ui.log(' 点「申报结果查询」%r' % (hit.center,)) + ui.real_click(*hit.center) + return True + row = sorted([b for b in buttons(page) if b['w'] <= 130], key=lambda b: b['x']) + btn = next((b for b in row if b['enabled']), None) + if not btn: + raise RecordsError('找不到「申报结果查询」按钮') + ui.log(' 点「申报结果查询」(几何兜底)(%d,%d)' % (btn['x'], btn['y'])) + ui.post_click(btn['win']) + return False + + +def wait_rows(page, timeout=40.0): + """轮询到表格出行为止(期间不断清弹窗 + 滚到最右)。""" + t0 = time.time() + while time.time() - t0 < timeout: + dismiss_popups(rounds=2, wait=0.4) + scroll_right(page) + rows = read_rows(page) + if rows: + return rows + time.sleep(1.0) + return [] + + +def click_query(page): + """兼容旧调用:等价于「清弹窗 → 点申报结果查询」。""" + dismiss_popups(rounds=3) + return click_result_query(page) + + +def grid_of(page): + return next((c for c in ui.children(page, visible_only=True) + if c.cls == 'TAdvStringGrid'), None) + + +def scroll_right(page, times=3): + """把表格横向滚到最右。 + + ⚠ 「查看」是最后一列,默认贴着窗口右边缘,经常只露出半个「查」甚至完全看不见 + (用户 2026-11-23 指出:得拖横向滚动条才行)。 + TAdvStringGrid 自带滚动条,直接 PostMessage(WM_HSCROLL, SB_RIGHT) 滚到底最省事; + 滚完再 OCR,坐标才是当前可视位置。 + """ + g = grid_of(page) + if not g: + return False + for _ in range(max(1, times)): + ui.u32.PostMessageW(g.hwnd, WM_HSCROLL, SB_RIGHT, 0) + time.sleep(0.25) + time.sleep(0.4) + return True + + +def find_view_buttons(page): + """OCR 找每行的「查看」按钮,返回屏幕坐标列表(y 升序)。 + + 判据沿用影刀:文本以「查」开头、但不是「查询」。 + ⚠ 影刀里把横坐标写死成 1797,实测 43-湖南 是 **1677**(窗口/列宽不同), + 所以这里用 OCR 自己的 x,只把 1797 当兜底。 + """ + l, t, w, h = page.rect + items = sbocr.texts((l + 4, t + 40, l + w - 4, t + h - 4), min_score=0.25) + pts = [] + for it in items: + s = (it.text or '').strip() + if not s.startswith('查') or s.startswith('查询'): + continue + pts.append((it.center[0], it.center[1])) + pts.sort(key=lambda p: p[1]) + if not pts: + return [] + xs = sorted(p[0] for p in pts) + x = xs[len(xs) // 2] # 取中位数,避免个别 OCR 抖动 + if not (l < x < l + w): + x = VIEW_BTN_X + return [(x, y) for _x, y in pts] + + +def read_rows(page): + """OCR 出每一行:{y: {'status': 申报状态, 'view': (x,y)}}。 + + 「申报状态」列是彩色可点文字(申报成功/申报失败/处理中), + 「操作」列的「查看」是个链接 —— 两者都靠 OCR 拿。 + """ + l, t, w, h = page.rect + items = sbocr.texts((l + 4, t + 170, l + w - 4, t + h - 4), min_score=0.25) + status = {} + views = [] + for it in items: + s = re.sub(r'\s+', '', it.text or '') + if s in ('申报成功', '申报失败', '处理中', '已作废', '申报中'): + status[it.center[1]] = s + elif s.startswith('查') and not s.startswith('查询'): + # 最后一列被窗口边缘切掉时 OCR 只认到「查」,也认 + views.append((it.center[0], it.center[1])) + rows = [] + for y, s in sorted(status.items()): + near = min(views, key=lambda p: abs(p[1] - y), default=None) + rows.append({'y': y, 'status': s, 'view': near if near and abs(near[1] - y) < 20 else None}) + return rows + + +def _dump_windows(tag=''): + rows = [] + for w in ui.windows(visible_only=False): + rows.append(' %-26s %-18r %r vis=%s' % (w.cls, w.title, w.rect, w.visible)) + ui.log(' 窗口清单%s:\n%s' % (('(' + tag + ')') if tag else '', '\n'.join(rows))) + + +def _find_detail_window(before=None, timeout=15.0): + """等「查看」打开的明细窗(可见的 TFrmHdsbMx)。 + + ⚠ 两个坑(2026-11-23 实测): + 1. 类名是 `TFrmHdsbMx`(大写 TFrm),用 `startswith('Tfrm')` 会漏掉; + 2. **不能按"新出现的窗口"找**:上一次关掉的明细窗对象还留着(隐藏、rect 不变), + 按 (cls,title,rect) 去重会把这次真正打开的窗口当成旧的过滤掉 → + 改成"找当前可见的那一个"。 + """ + t0 = time.time() + while time.time() - t0 < timeout: + cands = [w for w in ui.windows(visible_only=False) + if 'hdsbmx' in (w.cls or '').lower()] + vis = [w for w in cands if w.visible and w.rect[2] > 300] + if vis: + return vis[0] + time.sleep(0.3) + return None + + +def export_one(view_xy, out_dir, index, timeout=30.0): + """点某行的「查看」→ 在明细窗里点「导出」→ 另存为 PDF。""" + os.makedirs(out_dir, exist_ok=True) + main = ui.find_window('Tfrm_MainFrame', visible=False) + before = {(x.cls, x.title, x.rect) for x in ui.windows(visible_only=False)} + + # ⚠ 点「查询」后那个「若要获取已申报数据最新状态…」的模态框是**延迟弹**的 + # (11:12:40 点查询、11:12:48 才盖上来),click_query 里那次 clear 没拦住, + # 结果点「查看」打在模态框上 → 明细窗永远不出来(2026-11-23 第二次踩到)。 + # 所以点击前清一次;没反应就清弹窗+重新置前,最多 3 次。 + wnd = None + for attempt in (1, 2, 3): + dd.clear_msg_dialogs() + ui.foreground(main) + ui.log(' 点「查看」%r(第 %d 次)' % (view_xy, attempt)) + ui.real_click(*view_xy) + wnd = _find_detail_window(before, timeout=6.0) + if wnd: + break + ui.log(' 没反应(可能有模态框挡着)→ 清弹窗重试') + time.sleep(1.0) + + if not wnd: + _dump_windows('点查看后') + raise RecordsError('点「查看」后没等到明细窗 TFrmHdsbMx') + ui.log(' 明细窗:%s %r %r' % (wnd.cls, wnd.title, wnd.rect)) + time.sleep(0.8) + + # 在窗口顶部工具条里找「导出」(OCR,因为这个窗口的按钮没有标题) + l, t, w, h = wnd.rect + hit = sbocr.find('导出', (l, t, l + w, t + 100), min_score=0.25) + if hit is None: + # 兜底:工具条按钮按几何找(最上面一排、宽度 >= 60 的自绘按钮) + btns = sorted([b for b in ui.children(wnd, visible_only=True) + if b.cls == 'TITSSpeedButton' and b.rect[2] >= 60], + key=lambda b: (b.rect[1], b.rect[0])) + ui.log(' OCR 没找到「导出」→ 明细窗按钮:%r' + % ([(b.rect, b.title) for b in btns],)) + try: + from PIL import ImageGrab + shot = os.path.join(config.shots_dir(), + 'records-detail-%s.png' % time.strftime('%H%M%S')) + ImageGrab.grab(bbox=(l, t, l + w, t + min(h, 140))).save(shot) + ui.log(' 明细窗顶部截图:%s' % shot) + except Exception: # noqa: BLE001 + pass + close_window(wnd) + raise RecordsError('明细窗口里没找到「导出」') + ui.log(' 点明细窗「导出」%r' % (hit.center,)) + ui.real_click(*hit.center) + + sav = ui.find_window('#32770', title='另存为', timeout=25.0) + if not sav: + close_window(wnd) + raise RecordsError('点「导出」后没出现「另存为」') + + target = os.path.join(out_dir, '社会保险费缴费申报表_%d.pdf' % index) # 与影刀同名 + if os.path.exists(target): + # 同名旧文件先删:否则「另存为」会弹"是否替换",脚本没点它 → 卡在对话框 + try: + os.remove(target) + ui.log(' 删掉同名旧文件:%s' % os.path.basename(target)) + except OSError as e: + ui.log(' ⚠ 删旧文件失败(%r),保存时可能弹覆盖确认' % e) + size, ms = dd.save_dialog_save(sav, target, timeout=timeout) + dd.clear_msg_dialogs() + close_window(wnd) + ui.log(' ✅ 申报表导出: %s %d 字节 %dms' % (os.path.basename(target), size, ms)) + return {'file': target, 'size': size, 'save_ms': ms} + + +def close_window(wnd): + try: + ui.u32.PostMessageW(wnd.hwnd, ui.WM_CLOSE, 0, None) + except Exception: # noqa: BLE001 + pass + time.sleep(0.8) + + +def run(store=''): + """申报记录导出:只导「申报成功」的记录(失败/处理中的没有导出,用户 2026-11-20 确认)。 + + PDF 落 save_dir/申报结果/<门店>/,文件名「社会保险费缴费申报表_<序号>.pdf」。 + """ + main = ui.find_window('Tfrm_MainFrame', visible=False) + page = open_records_page(main) + # 用户 2026-11-23 给的实操顺序:进页先关弹窗 → 点「申报结果查询」→ 才能点「查看」 + dismiss_popups() + click_result_query(page) + rows = wait_rows(page) + if not rows: + raise RecordsError('点「申报结果查询」后 40 秒仍没有申报记录行') + ok = [r for r in rows if r['status'] == '申报成功' and r['view']] + failed = [r for r in rows if r['status'] == '申报失败'] + ui.log(' 申报记录 %d 条:成功 %d,失败 %d,其他 %d' + % (len(rows), len(ok), len(failed), len(rows) - len(ok) - len(failed))) + if failed: + ui.log(' ⚠ 申报失败的记录没有导出(失败原因多为「系统忙」,可重报)') + + if not ok: + ui.log(' 没有「申报成功」的记录 → 无需导出') + return {'rows': len(rows), 'exported': [], 'failed': len(failed), + 'note': '无需导出申报记录'} + + out_dir = config.declare_dir(store) + exported = [] + for i, r in enumerate(ok, 1): + try: + exported.append(export_one(r['view'], out_dir, i)) + except RecordsError as e: + ui.log(' ✗ 第 %d 条导出失败:%s' % (i, e)) + return {'rows': len(rows), 'exported': exported, 'failed': len(failed), + 'note': '已导出申报记录' if exported else '导出未成功'} diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/sbimg.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/sbimg.py new file mode 100644 index 0000000..1db33b2 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/sbimg.py @@ -0,0 +1,129 @@ +# -*- coding: utf-8 -*- +"""sbimg.py —— 用「影刀模板库」点客户端界面(图像匹配,替代写死坐标)。 + +模板来源:本插件自带的 images/(影刀工程导出的 45 张图 + manifest.json), + 目录取自 config.IMAGES_DIR,随插件包发布,不再写死仓库绝对路径。 + +为什么要它: + 客户端按钮是自绘的,按坐标点(218,142)这种写法一换分辨率/版本就废; + 影刀模板实测在本机 score=1.0 命中(刷新/查询/查看明细/导出/提交申报/税务生成), + 模板 + OCR + 原生控件的组合比纯坐标稳得多。 + +用法: + from . import sbimg + sbimg.click(main, '刷新按钮') + sbimg.wait(main, '提示信息确定按钮', timeout=10) + if sbimg.exists(main, '服务器连接异常'): + sbimg.click(main, '服务器连接异常确定按钮') +""" + +import json +import os +import time + +from desktopauto import Screen # noqa: E402 + +from .. import config +from . import sbui as ui + +IMG_DIR = config.IMAGES_DIR + +_MANIFEST = None + + +def manifest(): + global _MANIFEST + if _MANIFEST is None: + with open(os.path.join(IMG_DIR, 'manifest.json'), encoding='utf-8') as f: + _MANIFEST = json.load(f) + return _MANIFEST + + +def template(key): + """模板名 → 绝对路径;不存在抛 KeyError。""" + m = manifest() + if key not in m: + raise KeyError('没有这个模板:%s(可用:%s)' % (key, '、'.join(sorted(m)[:20]))) + return os.path.join(IMG_DIR, m[key]['file']), m[key] + + +def _screen(main): + return Screen(window=main.hwnd, threshold=0.8) + + +def _ensure(main): + try: + from . import sbocr + sbocr.ensure_foreground(main) + except Exception: # noqa: BLE001 + ui.foreground(main) + time.sleep(0.3) + + +def find(main, key, region=None): + path, opt = template(key) + m = _screen(main).find(path, threshold=opt.get('threshold', 0.8), + gray=opt.get('gray', True), + scales=tuple(opt.get('scales') or (1.0,)), + region=region) + return m + + +def exists(main, key): + return find(main, key) is not None + + +def wait(main, key, timeout=10.0, interval=0.4): + """等模板出现;返回 Match 或 None。""" + t0 = time.time() + while time.time() - t0 < timeout: + m = find(main, key) + if m is not None: + return m + time.sleep(interval) + return None + + +def click(main, key, timeout=0.0, delay=0.9, dx=0, dy=0): + """点模板中心。timeout>0 时先等出现。返回是否点到。""" + _ensure(main) + m = wait(main, key, timeout=timeout) if timeout > 0 else find(main, key) + if m is None: + ui.log(' ✗ 模板未命中:%s' % key) + return False + cx, cy = m.center + ui.real_click(cx + dx, cy + dy) + ui.log(' 点「%s」→ (%d,%d) score=%.2f' % (key, cx + dx, cy + dy, m.score)) + if delay: + time.sleep(delay) + return True + + +def click_dialog_button(main, dialog='提示信息确定按钮', timeout=12.0): + """等弹窗按钮模板并点击(提示信息/导出成功/服务器连接异常的「确定」长得一样)。""" + return click(main, dialog, timeout=timeout, delay=0.8) + + +def catch_common_dialogs(main, log=True): + """清掉常见弹窗:服务器连接异常 / 提示信息 / 导出成功 / 明细数据量大(正在上传)。 + + 返回最后处理过的模板名列表(用来判断"刚才是不是连接异常"→ 调用方重试刷新)。 + """ + handled = [] + for _ in range(6): + hit = None + for key, btn in (('服务器连接异常', '服务器连接异常确定按钮'), + ('明细数据量大', '提示信息确定按钮'), + ('提示信息', '提示信息确定按钮'), + ('导出成功确定按钮', '导出成功确定按钮')): + if find(main, key) is not None: + hit = (key, btn) + break + if not hit: + break + key, btn = hit + handled.append(key) + if log: + ui.log(' 弹窗:%s → 点确定' % key) + click(main, btn, timeout=3.0, delay=0.8) + return handled diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/sbocr.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/sbocr.py new file mode 100644 index 0000000..74f6741 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/sbocr.py @@ -0,0 +1,228 @@ +# -*- coding: utf-8 -*- +"""sbocr.py —— 用 desktopauto 的 RapidOCR 给社保客户端做「看字 / 点字」。 + +为什么要有这层: + 客户端左侧菜单是**自绘、无控件句柄**,只能坐标点击。原来靠"像素墨迹推断行位置" + (sbui.menu_rows / expand_menu),hover tooltip、展开状态、行距变化都会让它判错, + 实测经常"点不到菜单"。OCR 直接读文字 + 坐标,稳得多。 + +依赖: + desktopauto(执行机按 plugin.json requires.sdks 挂载,含 rapidocr/onnxruntime/ + opencv/pillow)。本模块只 `from desktopauto import ...`,不再往 sys.path 塞仓库路径。 + +用法: + from . import sbocr + items = sbocr.menu_texts(main) # 菜单区所有文字(带坐标) + sbocr.click_text(main, '缴费工资申报', exact=True) + sbocr.open_page(main, '缴费工资申报', '月度缴费工资申报') + +注意:OCR 是"看屏幕",窗口必须在前台且不被遮挡;限定 region 后单次约 0.3~1s。 +""" + +import time + +from desktopauto import Screen # noqa: E402 +from desktopauto import ocr as _docr # noqa: E402 + +from . import sbui as ui + +MIN_SCORE = 0.3 +PARK = (927, 489) # 鼠标"停靠点":页面中间空白处,避开菜单 hover 区(影刀同款坐标) + + +def available(): + try: + import desktopauto.ocr as o + return o.available() + except Exception: + return False + + +def _screen(): + return Screen() # region 每次单独传,坐标 = 屏幕绝对坐标 + + +# ---------------------------------------------------------------- 区域 +def menu_region(main): + """左侧菜单区(屏幕绝对坐标)。按主窗位置推算,覆盖「功能菜单」到最底一项。""" + l, t, w, h = main.rect + return (l + 2, t + 80, l + 215, t + min(h - 40, 730)) + + +def page_region(main): + """右侧页面区(工具栏 + 表格上方),用于找按钮/标题。""" + l, t, w, h = main.rect + return (l + 215, t + 80, l + w - 5, t + h - 40) + + +def ensure_foreground(main, tries=3): + """确保主窗真的在最前面(OCR 截的是屏幕,被挡住就会把别的窗口当客户端)。 + + 实测:`SetForegroundWindow` 会被前台锁定挡掉,此时 OCR 读到的是 DSH/浏览器窗口, + 于是"表格里全是聊天记录"。所以每次截图前都要验一次 GetForegroundWindow。 + """ + for _ in range(max(1, tries)): + if ui.foreground(main, tries=1) and ui.u32.GetForegroundWindow() == main.hwnd: + time.sleep(0.25) + return True + time.sleep(0.35) + try: # 未公开 API:绕过前台锁定 + ui.u32.SwitchToThisWindow.argtypes = [ui.wt.HWND, ui.wt.BOOL] + ui.u32.SwitchToThisWindow(main.hwnd, True) + except Exception: + pass + time.sleep(0.6) + return ui.u32.GetForegroundWindow() == main.hwnd + + +def _main(main=None): + return main or ui.find_window('Tfrm_MainFrame', visible=False) + + +# ---------------------------------------------------------------- 识别 +def texts(region, min_score=MIN_SCORE, main=None): + """识别一个区域,返回 TextItem 列表(屏幕绝对坐标)。""" + main = _main(main) + if main is not None: + ensure_foreground(main) + return _screen().read_text(region=region, min_score=min_score) + + +def find(text, region, exact=False, regex=False, min_score=MIN_SCORE, main=None): + """在区域内找一段文字,返回最可信的 TextItem 或 None。""" + hits = _screen().find_all_text(text, exact=exact, regex=regex, + region=region, min_score=min_score) + return _docr.best_text(hits) + + +def find_all(text, region, exact=False, regex=False, min_score=MIN_SCORE): + return _screen().find_all_text(text, exact=exact, regex=regex, + region=region, min_score=min_score) + + +def menu_texts(main, min_score=MIN_SCORE): + return texts(menu_region(main), min_score=min_score, main=main) + + +def dump(items, tag=''): + """把识别结果写日志(一行一条,带中心坐标)。""" + ui.log(' [OCR%s] %d 段' % ((' ' + tag) if tag else '', len(items))) + for it in items: + cx, cy = it.center + ui.log(' %-28s (%4d,%4d) %.2f' % (it.text[:28], cx, cy, it.score)) + + +# ---------------------------------------------------------------- 点击 +def click_item(item, dx=0, dy=0, park=True): + """真实鼠标点击某段文字的中心(相对偏移可选)。 + + **点完必须把鼠标挪走**:左侧菜单父项 hover 会弹深色 tooltip,正好盖住刚展开的 + 二级菜单,OCR 就只看到 tooltip 文字,判成"没展开"(用户 2026-11-19 指出, + 影刀里每步点完 move_mouse(927,489) 就是这个原因)。 + """ + cx, cy = item.center + ui.real_click(cx + dx, cy + dy) + if park: + ui.move_to(*PARK) + time.sleep(0.45) + return (cx + dx, cy + dy) + + +def click_text(main, text, region=None, exact=False, regex=False, + dx=0, dy=0, timeout=0.0, min_score=MIN_SCORE): + """在前台主窗的指定区域里找文字并点它。返回点到的屏幕坐标或 None。""" + region = region or page_region(main) + ui.foreground(main) + time.sleep(0.25) + item = find(text, region, exact=exact, regex=regex, min_score=min_score) + if item is None and timeout > 0: + t0 = time.time() + while time.time() - t0 < timeout: + time.sleep(0.8) + item = find(text, region, exact=exact, regex=regex, min_score=min_score) + if item is not None: + break + if item is None: + ui.log(' ✗ OCR 没找到「%s」' % text) + return None + pos = click_item(item, dx, dy) + ui.log(' OCR 点「%s」→ %r(识别=%r %.2f)' % (text, pos, item.text, item.score)) + time.sleep(0.5) + return pos + + +def warm_up(main): + """点一下窗口顶栏空白处热身。 + + 实测:窗口刚被拉到前台时,**第一次点击会被"激活窗口"吃掉**,直接点菜单毫无反应。 + """ + l, t, w, h = main.rect + ui.real_click(l + w // 2, t + 75) + time.sleep(0.45) + + +def expand_menu(main, parent_text, child_text, exact_parent=True, tries=2): + """展开左侧菜单的某个父项(OCR 版)。 + + 坑(2026-11-19 18:20 踩到): + - 窗口刚激活时第一次点击被吃掉 → 先 warm_up; + - 点开后菜单有动画,**1 秒内 OCR 可能还没看到子项**,此时若再点父项会把刚展开的 + 收起来(手风琴),于是"怎么点都不展开" → 点完至少等 2 秒再判。 + - 子项已可见时绝不点父项。 + """ + mr = menu_region(main) + ui.dismiss_dialogs(main) + ui.foreground(main) + time.sleep(0.4) + warm_up(main) + + if find(child_text, mr) is not None: + ui.log(' 子项「%s」已可见,不用展开' % child_text) + return True + + for i in range(tries): + # ★ 每轮都重新 OCR:菜单展开/收起会让整列菜单上下移动 ~90px, + # 沿用上一轮坐标再点父项会点到**别的条目**(实测 22:05 就这么点进了「申报记录」) + mr = menu_region(main) + ui.foreground(main) + parent = find(parent_text, mr, exact=exact_parent) + if parent is None: + ui.log(' ✗ 菜单里没识别到「%s」' % parent_text) + dump(texts(mr), 'menu') + time.sleep(1.0) + continue + click_item(parent) + ui.log(' 点父项「%s」→ (%d,%d),等展开' % (parent_text, *parent.center)) + time.sleep(2.4) + mr = menu_region(main) + if find(child_text, mr) is not None: + ui.log(' 展开成功') + return True + ui.log(' 第 %d 次点开后仍看不到子项' % (i + 1)) + time.sleep(0.6) + return find(child_text, menu_region(main)) is not None + + +def open_page(main, parent_text, child_text, wait_page=None, timeout=25.0): + """OCR 走到二级菜单页面:展开父项 → 点子项 → 等页面类出现。 + + wait_page: 页面类名(如 'TfrmNjfgz_rc_ary'),给了就等到它出现才返回。 + """ + if not expand_menu(main, parent_text, child_text): + raise RuntimeError('菜单「%s → %s」展开失败' % (parent_text, child_text)) + mr = menu_region(main) + child = find(child_text, mr, exact=False) + if child is None: + raise RuntimeError('子项「%s」没找到' % child_text) + click_item(child) + ui.log(' 点子项「%s」→ (%d,%d)' % (child_text, *child.center)) + time.sleep(1.0) + if not wait_page: + return True + t0 = time.time() + while time.time() - t0 < timeout: + if ui.find_child(main, wait_page): + ui.log(' 页面已出现:%s(%.1f 秒)' % (wait_page, time.time() - t0)) + return True + time.sleep(0.5) + raise RuntimeError('%.0f 秒内没出现页面 %s' % (timeout, wait_page)) diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/sbui.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/sbui.py new file mode 100644 index 0000000..b916adb --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/sbui.py @@ -0,0 +1,1053 @@ +# -*- coding: utf-8 -*- +""" +sbui.py —— 社保费管理客户端 UI 驱动层(纯 ctypes,零第三方依赖) + +与 PowerShell 版 tools/ui.ps1 能力一一对应,可直接被本插件内部模块 import: + + from . import sbui as ui + ui.is_admin, ui.require_admin, ui.find_window, ui.find_child, ui.children, + ui.set_text, ui.get_text, ui.post_click, ui.bm_click_wait, ui.foreground, + ui.combo_items, ui.combo_set, ui.combo_sel, ui.click_at, ui.is_under, + ui.menu_rows, ui.menu_children, ui.log + +硬前提(比代码更重要): + 调用方进程必须是**管理员**。客户端是 High 完整性进程,普通权限发消息会被 + UIPI 直接拒绝:SendMessage 返回 0、GetLastError()==5。 + 由插件入口调用 require_admin() 自检;**不做 runas 自提权重启**——那会把插件 + 进程换掉、脱离执行机,所以非管理员直接报错让用户以管理员身份运行执行机。 + +设计原则: + 1) 定位只用「窗口类名 + 标题/尺寸」,绝不写死 HWND(重启就变) + 2) 点按钮用 PostMessage(不阻塞);需要等结果的用后台线程 + join 超时 + 3) 所有等待都有超时,绝不无限循环 +""" + +import ctypes +import re +import threading +import time +from ctypes import wintypes as wt + +from .. import config + +u32 = ctypes.WinDLL('user32', use_last_error=True) +g32 = ctypes.WinDLL('gdi32', use_last_error=True) +k32 = ctypes.WinDLL('kernel32', use_last_error=True) + + +# ---------------------------------------------------------------- DPI 感知 +# 不做 DPI 感知时:125%/150% 缩放下 GetWindowRect 给的是"逻辑坐标"(被系统缩放), +# 而截屏/OCR 拿到的是物理像素 → 坐标点击会偏 20%~50%,表现为"点不到/点错行"。 +# 必须在**任何窗口操作之前**声明,所以放在模块导入时执行。 +_DPI_MODE = 'none' + + +def enable_dpi_awareness(): + """尽量声明 Per-Monitor V2 / Per-Monitor / System 感知;返回模式名。""" + global _DPI_MODE + try: # Win10 1703+ + ctx = ctypes.c_void_p(-4) # DPI_AWARENESS_CONTEXT_PER_MONITOR_AWARE_V2 + if u32.SetProcessDpiAwarenessContext(ctx): + _DPI_MODE = 'permonitorv2' + return _DPI_MODE + except Exception: # noqa: BLE001 + pass + try: # Win8.1+ + ctypes.WinDLL('shcore').SetProcessDpiAwareness(2) # PER_MONITOR + _DPI_MODE = 'permonitor' + return _DPI_MODE + except Exception: # noqa: BLE001 + pass + try: # Vista+ + if u32.SetProcessDPIAware(): + _DPI_MODE = 'system' + return _DPI_MODE + except Exception: # noqa: BLE001 + pass + _DPI_MODE = 'none' + return _DPI_MODE + + +def dpi_info(): + """当前 DPI / 屏幕 / 感知模式(排障用)。""" + info = {'mode': _DPI_MODE} + try: + info['dpi'] = u32.GetDpiForSystem() if hasattr(u32, 'GetDpiForSystem') else 96 + except Exception: # noqa: BLE001 + info['dpi'] = 96 + try: + hdc = u32.GetDC(0) + info['log_pixels_x'] = g32.GetDeviceCaps(hdc, 88) # LOGPIXELSX + u32.ReleaseDC(0, hdc) + except Exception: # noqa: BLE001 + info['log_pixels_x'] = 96 + info['screen'] = (u32.GetSystemMetrics(0), u32.GetSystemMetrics(1)) + try: + info['scale'] = round(float(info['log_pixels_x']) / 96.0, 2) + except Exception: # noqa: BLE001 + info['scale'] = 1.0 + return info + + +enable_dpi_awareness() + + +# ---------------------------------------------------------------- 锁屏 / 休眠 +ES_CONTINUOUS = 0x80000000 +ES_SYSTEM_REQUIRED = 0x00000001 +ES_DISPLAY_REQUIRED = 0x00000002 + + +def keep_awake(on=True): + """跑批期间阻止系统休眠/关屏(长流程 45~55 分钟,中途黑屏会让点击/截屏全废)。""" + try: + flags = (ES_CONTINUOUS | ES_SYSTEM_REQUIRED | ES_DISPLAY_REQUIRED) if on else ES_CONTINUOUS + k32.SetThreadExecutionState(ctypes.c_uint(flags)) + return True + except Exception: # noqa: BLE001 + return False + + +def is_locked(): + """当前是不是锁屏/登录界面(锁屏时所有 UI 自动化都会失效)。 + + 判据(任一成立即算锁定): + 1) 前台窗口是 Windows 锁屏界面(CoreWindow + 标题含"锁屏/Lock"); + 2) 输入桌面不叫 "Default"(锁屏时是 Winlogon 桌面)。 + """ + try: + fg = u32.GetForegroundWindow() + if fg: + cls = _cls(fg) or '' + title = _title(fg) or '' + if cls == 'Windows.UI.Core.CoreWindow' and ('锁屏' in title or 'Lock' in title): + return True + except Exception: # noqa: BLE001 + pass + try: + h = u32.OpenInputDesktop(0, False, 0x0001) # DESKTOP_READOBJECTS + if not h: + return True + try: + UOI_NAME = 2 + need = ctypes.c_uint(0) + u32.GetUserObjectInformationW(h, UOI_NAME, None, 0, ctypes.byref(need)) + buf = ctypes.create_unicode_buffer(max(16, need.value // 2 + 2)) + if not u32.GetUserObjectInformationW(h, UOI_NAME, buf, need.value or 64, + ctypes.byref(need)): + return False + return (buf.value or '').lower() != 'default' + finally: + u32.CloseDesktop(h) + except Exception: # noqa: BLE001 + return False + + +def assert_unlocked(where=''): + """锁屏时直接抛错,别让后面几十轮点击白跑。""" + if is_locked(): + raise RuntimeError('当前屏幕已锁定%s:UI 自动化无法工作,请解锁后重跑' + % (('(' + where + ')') if where else '')) + +# ---------------------------------------------------------------- 消息常量 +WM_SETTEXT = 0x000C +WM_GETTEXT = 0x000D +WM_CLOSE = 0x0010 +WM_COMMAND = 0x0111 +WM_LBUTTONDOWN = 0x0201 +WM_LBUTTONUP = 0x0202 +BM_CLICK = 0x00F5 +CB_GETCOUNT = 0x0146 +CB_GETCURSEL = 0x0147 +CB_GETLBTEXT = 0x0148 +CB_SETCURSEL = 0x014E + +ERROR_ACCESS_DENIED = 5 + +# ---------------------------------------------------------------- 原型声明 +ENUMPROC = ctypes.WINFUNCTYPE(wt.BOOL, wt.HWND, wt.LPARAM) + +u32.EnumWindows.argtypes = [ENUMPROC, wt.LPARAM] +u32.EnumChildWindows.argtypes = [wt.HWND, ENUMPROC, wt.LPARAM] +u32.GetClassNameW.argtypes = [wt.HWND, wt.LPWSTR, ctypes.c_int] +u32.GetWindowTextW.argtypes = [wt.HWND, wt.LPWSTR, ctypes.c_int] +u32.GetWindowTextLengthW.argtypes = [wt.HWND] +u32.GetWindowRect.argtypes = [wt.HWND, ctypes.POINTER(wt.RECT)] +u32.GetWindowThreadProcessId.argtypes = [wt.HWND, ctypes.POINTER(wt.DWORD)] +u32.IsWindowVisible.argtypes = [wt.HWND] +u32.IsWindowEnabled.argtypes = [wt.HWND] +u32.IsWindow.argtypes = [wt.HWND] +u32.GetParent.argtypes = [wt.HWND] +u32.GetDlgCtrlID.argtypes = [wt.HWND] +u32.SendMessageW.restype = ctypes.c_ssize_t +u32.SendMessageW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, ctypes.c_void_p] +u32.PostMessageW.restype = wt.BOOL +u32.PostMessageW.argtypes = [wt.HWND, wt.UINT, wt.WPARAM, ctypes.c_void_p] +u32.SetForegroundWindow.argtypes = [wt.HWND] +u32.BringWindowToTop.argtypes = [wt.HWND] +u32.ShowWindow.argtypes = [wt.HWND, ctypes.c_int] +u32.IsIconic.argtypes = [wt.HWND] +u32.GetForegroundWindow.restype = wt.HWND +u32.AttachThreadInput.argtypes = [wt.DWORD, wt.DWORD, wt.BOOL] +u32.SetCursorPos.argtypes = [ctypes.c_int, ctypes.c_int] +u32.WindowFromPoint.restype = wt.HWND +u32.WindowFromPoint.argtypes = [wt.POINT] +u32.GetDC.restype = wt.HDC +u32.GetDC.argtypes = [wt.HWND] +u32.ReleaseDC.argtypes = [wt.HWND, wt.HDC] +u32.GetSystemMetrics.argtypes = [ctypes.c_int] +g32.BitBlt.argtypes = [wt.HDC, ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_int, + wt.HDC, ctypes.c_int, ctypes.c_int, wt.DWORD] +k32.GetCurrentThreadId.restype = wt.DWORD +u32.mouse_event.argtypes = [wt.DWORD, wt.DWORD, wt.DWORD, wt.DWORD, ctypes.c_void_p] +u32.keybd_event.argtypes = [wt.BYTE, wt.BYTE, wt.DWORD, ctypes.c_void_p] + +# 剪贴板 / 全局内存(64 位下 HANDLE 必须显式 restype,否则被截断成 int) +u32.OpenClipboard.argtypes = [wt.HWND] +u32.OpenClipboard.restype = wt.BOOL +u32.CloseClipboard.restype = wt.BOOL +u32.EmptyClipboard.restype = wt.BOOL +u32.GetClipboardData.argtypes = [wt.UINT] +u32.GetClipboardData.restype = wt.HANDLE +u32.SetClipboardData.argtypes = [wt.UINT, wt.HANDLE] +u32.SetClipboardData.restype = wt.HANDLE +k32.GlobalAlloc.argtypes = [wt.UINT, ctypes.c_size_t] +k32.GlobalAlloc.restype = wt.HANDLE +k32.GlobalLock.argtypes = [wt.HANDLE] +k32.GlobalLock.restype = ctypes.c_void_p +k32.GlobalUnlock.argtypes = [wt.HANDLE] +k32.GlobalUnlock.restype = wt.BOOL + +# ---------------------------------------------------------------- 键盘 / 输入 +ULONG_PTR = ctypes.c_ulonglong if ctypes.sizeof(ctypes.c_void_p) == 8 else ctypes.c_ulong + + +class KEYBDINPUT(ctypes.Structure): + _fields_ = [('wVk', wt.WORD), ('wScan', wt.WORD), ('dwFlags', wt.DWORD), + ('time', wt.DWORD), ('dwExtraInfo', ULONG_PTR)] + + +class MOUSEINPUT(ctypes.Structure): + _fields_ = [('dx', wt.LONG), ('dy', wt.LONG), ('mouseData', wt.DWORD), ('dwFlags', wt.DWORD), + ('time', wt.DWORD), ('dwExtraInfo', ULONG_PTR)] + + +class HARDWAREINPUT(ctypes.Structure): + _fields_ = [('uMsg', wt.DWORD), ('wParamL', wt.WORD), ('wParamH', wt.WORD)] + + +class _INPUTUNION(ctypes.Union): + _fields_ = [('ki', KEYBDINPUT), ('mi', MOUSEINPUT), ('hi', HARDWAREINPUT)] + + +class INPUT(ctypes.Structure): + _fields_ = [('type', wt.DWORD), ('u', _INPUTUNION)] + + +u32.SendInput.argtypes = [wt.UINT, ctypes.POINTER(INPUT), ctypes.c_int] +u32.SendInput.restype = wt.UINT + +KEYEVENTF_KEYUP = 0x0002 +KEYEVENTF_UNICODE = 0x0004 + +VK_CTRL = 0x11 +VK_DELETE = 0x2E +VK_RETURN = 0x0D +VK_ESC = 0x1B + + +def _kb(vk=0, scan=0, flags=0): + e = INPUT(type=1) # INPUT_KEYBOARD + e.u.ki = KEYBDINPUT(wVk=vk, wScan=scan, dwFlags=flags, time=0, dwExtraInfo=0) + return e + + +def key(vk): + """按一次普通键(按下+抬起)。""" + u32.SendInput(1, ctypes.byref(_kb(vk)), ctypes.sizeof(INPUT)) + time.sleep(0.02) + u32.SendInput(1, ctypes.byref(_kb(vk, 0, KEYEVENTF_KEYUP)), ctypes.sizeof(INPUT)) + time.sleep(0.02) + + +def ctrl(vk): + u32.keybd_event(VK_CTRL, 0, 0, None) + time.sleep(0.03) + key(vk) + u32.keybd_event(VK_CTRL, 0, KEYEVENTF_KEYUP, None) + + +def type_unicode(text, delay=0.03): + """逐字符 Unicode 直投:不依赖键盘布局,中文/符号/全角都能进。返回发出事件数。""" + n = 0 + for ch in text: + code = ord(ch) + u32.SendInput(1, ctypes.byref(_kb(0, code, KEYEVENTF_UNICODE)), ctypes.sizeof(INPUT)) + time.sleep(0.012) + u32.SendInput(1, ctypes.byref(_kb(0, code, KEYEVENTF_UNICODE | KEYEVENTF_KEYUP)), + ctypes.sizeof(INPUT)) + time.sleep(delay) + n += 2 + return n + + +def double_click(x, y): + u32.SetCursorPos(x, y) + time.sleep(0.12) + for _ in range(2): + u32.mouse_event(0x0002, 0, 0, 0, 0) + time.sleep(0.04) + u32.mouse_event(0x0004, 0, 0, 0, 0) + time.sleep(0.09) + + +def to_halfwidth(s): + """全角→半角。表里录的 !@#(U+FF01..)与英文 !@# 不是同一个字符,客户端不认。""" + out = [] + for ch in s: + c = ord(ch) + if 0xFF01 <= c <= 0xFF5E: + out.append(chr(c - 0xFEE0)) + elif c == 0x3000: + out.append(' ') + else: + out.append(ch) + return ''.join(out) + +# GDI 句柄一律用 c_void_p,否则 64 位下会被截成 int 而崩 +HGDIOBJ = ctypes.c_void_p +g32.CreateCompatibleDC.restype = wt.HDC +g32.CreateCompatibleDC.argtypes = [wt.HDC] +g32.CreateCompatibleBitmap.restype = wt.HBITMAP +g32.CreateCompatibleBitmap.argtypes = [wt.HDC, ctypes.c_int, ctypes.c_int] +g32.SelectObject.restype = HGDIOBJ +g32.SelectObject.argtypes = [wt.HDC, HGDIOBJ] +g32.DeleteObject.argtypes = [HGDIOBJ] +g32.DeleteDC.argtypes = [wt.HDC] +g32.GetDIBits.restype = ctypes.c_int +g32.GetDIBits.argtypes = [wt.HDC, wt.HBITMAP, wt.UINT, wt.UINT, + ctypes.c_void_p, ctypes.c_void_p, wt.UINT] + +# ---------------------------------------------------------------- 日志 +# 统一转发插件 config.log:由插件入口 config.set_log(ctx.log) 注入。 +# config.log 同时落一份文件到 run_dir()/xq0013-*.log,这里不再自己写文件。 + + +def log(msg): + config.log(msg) + + +# ---------------------------------------------------------------- 权限 +def is_admin(): + try: + return ctypes.windll.shell32.IsUserAnAdmin() != 0 + except Exception: + return False + + +def require_admin(): + """要求调用方进程是管理员;非管理员直接报错。 + + **不**用 ShellExecuteW(runas) 自提权重启:那会把当前插件进程换掉、脱离执行机 + 的 stdout/日志通道,且执行机无法感知新进程。所以只做自检,让用户以管理员身份 + 重新运行执行机。 + """ + if not is_admin(): + raise RuntimeError( + '需要管理员权限:请以管理员身份运行执行机' + '(客户端是 High 完整性进程,普通权限发消息会被 UIPI 拒绝)') + return True + + +# ---------------------------------------------------------------- 基础查询 +def _cls(h): + buf = ctypes.create_unicode_buffer(256) + u32.GetClassNameW(h, buf, 256) + return buf.value + + +def _title(h): + n = u32.GetWindowTextLengthW(h) + 1 + buf = ctypes.create_unicode_buffer(n) + u32.GetWindowTextW(h, buf, n) + return buf.value + + +class Window(object): + """窗口句柄的轻量包装,打印时带类名和标题,方便排查。""" + __slots__ = ('hwnd',) + + def __init__(self, hwnd): + self.hwnd = hwnd + + def __int__(self): + return int(self.hwnd) if self.hwnd else 0 + + def __bool__(self): + return bool(self.hwnd) and bool(u32.IsWindow(self.hwnd)) + + def __eq__(self, other): + return int(self) == int(other) + + def __hash__(self): + return hash(int(self)) + + def __repr__(self): + if not self: + return '' + return '' % (int(self.hwnd), _cls(self.hwnd), _title(self.hwnd)) + + @property + def cls(self): + return _cls(self.hwnd) + + @property + def title(self): + return _title(self.hwnd) + + @property + def rect(self): + r = wt.RECT() + u32.GetWindowRect(self.hwnd, ctypes.byref(r)) + return (r.left, r.top, r.right - r.left, r.bottom - r.top) + + @property + def pid(self): + p = wt.DWORD() + u32.GetWindowThreadProcessId(self.hwnd, ctypes.byref(p)) + return p.value + + @property + def visible(self): + return bool(u32.IsWindowVisible(self.hwnd)) + + @property + def enabled(self): + return bool(u32.IsWindowEnabled(self.hwnd)) + + @property + def parent(self): + return Window(u32.GetParent(self.hwnd)) + + +def windows(visible_only=False): + out = [] + + def cb(h, l): + out.append(h) + return True + + u32.EnumWindows(ENUMPROC(cb), 0) + if visible_only: + out = [h for h in out if u32.IsWindowVisible(h)] + return [Window(h) for h in out] + + +def children(parent, visible_only=False): + out = [] + + def cb(h, l): + out.append(h) + return True + + u32.EnumChildWindows(parent.hwnd, ENUMPROC(cb), 0) + if visible_only: + out = [h for h in out if u32.IsWindowVisible(h)] + return [Window(h) for h in out] + + +def find_window(cls, title=None, timeout=0.0, visible=True): + """按「类名 + 标题正则」找顶层窗口;timeout>0 时轮询等待。找不到返回 None。""" + deadline = time.time() + (timeout or 0) + while True: + for w in windows(visible_only=visible): + if w.cls != cls: + continue + if title and not re.search(title, w.title): + continue + return w + if timeout <= 0 or time.time() >= deadline: + return None + time.sleep(0.1) + + +def find_child(parent, cls, title=None, min_width=0, visible=True): + """在子控件里找第一个匹配的(类名 + 可选标题 + 可选最小宽度);找不到返回 None。""" + for w in children(parent, visible_only=visible): + if w.cls != cls: + continue + if title and not re.search(title, w.title): + continue + if min_width and w.rect[2] < min_width: + continue + return w + return None + + +def wait_gone(cls, title=None, timeout=30.0): + deadline = time.time() + timeout + while time.time() < deadline: + if find_window(cls, title) is None: + return True + time.sleep(0.1) + return False + + +# ---------------------------------------------------------------- 消息发送 +def _send(h, msg, wparam=0, lparam=0): + return u32.SendMessageW(h.hwnd, msg, wparam, ctypes.c_void_p(lparam) if isinstance(lparam, int) else lparam) + + +def set_text(win, text): + """WM_SETTEXT,写完读回校验。返回 bool。""" + buf = ctypes.cast(ctypes.c_wchar_p(text), ctypes.c_void_p) + u32.SendMessageW(win.hwnd, WM_SETTEXT, 0, buf) + return get_text(win) == text + + +# ---------------------------------------------------------------- 剪贴板(读表格单元格) +def clipboard_text(): + """读剪贴板文本(CF_UNICODETEXT)。读不到返回 ''。""" + CF_UNICODETEXT = 13 + if not u32.OpenClipboard(None): + return '' + try: + h = u32.GetClipboardData(CF_UNICODETEXT) + if not h: + return '' + ptr = k32.GlobalLock(h) + if not ptr: + return '' + try: + return ctypes.wstring_at(ptr) + finally: + k32.GlobalUnlock(h) + finally: + u32.CloseClipboard() + + +def clipboard_set(text): + """写剪贴板文本。""" + CF_UNICODETEXT = 13 + GMEM_MOVEABLE = 0x0002 + data = str(text).encode('utf-16-le') + b'\x00\x00' + if not u32.OpenClipboard(None): + return False + try: + u32.EmptyClipboard() + h = k32.GlobalAlloc(GMEM_MOVEABLE, len(data)) + if not h: + return False + ptr = k32.GlobalLock(h) + ctypes.memmove(ptr, data, len(data)) + k32.GlobalUnlock(h) + u32.SetClipboardData(CF_UNICODETEXT, h) + return True + finally: + u32.CloseClipboard() + + +def grab_cell(x, y, settle=0.35): + """点一个表格单元格 → Ctrl+C → 读剪贴板(TAdvStringGrid 没有 cell 句柄)。""" + clipboard_set('<>') + time.sleep(0.08) + real_click(x, y) + time.sleep(0.28) + ctrl(0x43) + time.sleep(settle) + return clipboard_text().strip() + + +def get_text(win): + """WM_GETTEXT。""" + buf = ctypes.create_unicode_buffer(2048) + u32.SendMessageW(win.hwnd, WM_GETTEXT, 2048, ctypes.cast(buf, ctypes.c_void_p)) + return buf.value + + +def post_click(win): + """给自绘按钮(TITSSpeedButton)发鼠标消息。Post 立即返回,不会因模态窗口阻塞。""" + l, t, w, h = win.rect + lp = ((h // 2) << 16) | (w // 2) + u32.PostMessageW(win.hwnd, WM_LBUTTONDOWN, 1, ctypes.c_void_p(lp)) + time.sleep(0.08) + u32.PostMessageW(win.hwnd, WM_LBUTTONUP, 0, ctypes.c_void_p(lp)) + + +def _click_thread(fn, ms): + done = [] + + def run(): + try: + fn() + finally: + done.append(True) + + t = threading.Thread(target=run, daemon=True) + t.start() + t.join(ms / 1000.0) + return bool(done) + + +def send_click_wait(win, timeout_ms=1500): + """SendMessage 版鼠标点击(需要同步时用),带超时,避免被模态窗口永久卡住。""" + l, t, w, h = win.rect + lp = ((h // 2) << 16) | (w // 2) + + def run(): + u32.SendMessageW(win.hwnd, WM_LBUTTONDOWN, 1, ctypes.c_void_p(lp)) + time.sleep(0.08) + u32.SendMessageW(win.hwnd, WM_LBUTTONUP, 0, ctypes.c_void_p(lp)) + + return _click_thread(run, timeout_ms) + + +def bm_click_wait(win, timeout_ms=15000): + """标准按钮(#32770 里的保存/确定):BM_CLICK + 超时。""" + return _click_thread(lambda: u32.SendMessageW(win.hwnd, BM_CLICK, 0, None), timeout_ms) + + +def restore(win): + """最小化就还原。坐标点击前必须先做,否则窗口不可见、点击会打到别的程序上。""" + if u32.IsIconic(win.hwnd): + u32.ShowWindow(win.hwnd, 9) # SW_RESTORE + time.sleep(0.6) + return True + return False + + +def topmost(win, on=True): + """临时把窗口压到最上层 / 取消置顶。 + + 为什么需要(2026-11-19 实测):客户端跑在全屏 1920x1032,只要 DSH 的浏览器窗口 + 在前面,`WindowFromPoint` 命中的就是 Chrome —— 屏幕 OCR 读到别人的画面、坐标点击 + 全打在浏览器上(表现为"点了没反应")。SetForegroundWindow 不一定能把 z 序翻上来, + 所以用 HWND_TOPMOST 临时压一层,**用完必须立刻取消**(否则客户端会浮在所有窗口上)。 + """ + HWND_TOPMOST, HWND_NOTOPMOST = -1, -2 + flags = 0x0001 | 0x0002 | 0x0010 # NOSIZE | NOMOVE | NOACTIVATE + return bool(u32.SetWindowPos(win.hwnd, HWND_TOPMOST if on else HWND_NOTOPMOST, + 0, 0, 0, 0, flags)) + + +def under(win, x, y): + """(x,y) 这一点现在是不是真的落在 win 上(点之前用它自检,避免点空)。""" + return is_under(x, y, win) + + +def find_countdown(): + """找「N 秒后自动获取申报结果,或立即获取」的倒计时窗。 + + 类名在不同流程里大小写不一致(日常页是 `TFrmCountDown`,缴费工资那边出现过 + 别的写法),所以**按类名忽略大小写匹配**,不要写死一种。 + """ + for w in windows(visible_only=True): + if 'countdown' in (w.cls or '').lower(): + return w + return None + + +def process_path_of(hwnd): + """由窗口句柄反查进程可执行文件路径(高完整性下可用)。失败返回 ''。""" + pid = wt.DWORD() + u32.GetWindowThreadProcessId(hwnd, ctypes.byref(pid)) + if not pid.value: + return '' + PROCESS_QUERY_LIMITED_INFORMATION = 0x1000 + h = k32.OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, False, pid.value) + if not h: + return '' + try: + buf = ctypes.create_unicode_buffer(1024) + size = wt.DWORD(1024) + if k32.QueryFullProcessImageNameW(h, 0, buf, ctypes.byref(size)): + return buf.value + return '' + finally: + k32.CloseHandle(h) + + +_WATCHDOG = None + + +def start_security_watchdog(interval=0.5): + """后台线程:只要出现「打开文件 - 安全警告」就自动点「运行」。 + + 为什么必须有:区域副本里的 `ProcDataDeal.exe` 带 Internet 标记, + **客户端每拉起一次子进程就弹一次**,流程走到哪一步都可能弹; + 不点它,客户端就卡在那里(主界面永远不出现、菜单点不动)。 + 只针对这个对话框动作,别的窗口一律不碰。 + """ + global _WATCHDOG + if _WATCHDOG is not None and _WATCHDOG.is_alive(): + return _WATCHDOG + + def loop(): + while True: + try: + dismiss_security_warning() + except Exception: # noqa: BLE001 + pass + time.sleep(interval) + + _WATCHDOG = threading.Thread(target=loop, name='sec-warn-watchdog', daemon=True) + _WATCHDOG.start() + return _WATCHDOG + + +def dismiss_security_warning(): + """关掉 Windows 的「打开文件 - 安全警告」(客户端启动 ProcDataDeal.exe 时会弹)。 + + file:// 来源的 exe(从母版复制过来的区域副本)带 Internet 区标记时, + 每次拉起子进程都会弹一次「你想运行此文件吗?[运行(R)][取消]」, + 不点就会**卡住登录**(主界面永远不出现)。 + 返回 True 表示点掉了至少一个。 + """ + acted = False + for _ in range(4): + target = None + for w in windows(visible_only=True): + if w.cls == '#32770' and ('安全警告' in (w.title or '') or 'Open File' in (w.title or '')): + target = w + break + if not target: + break + btn = None + for c in children(target, visible_only=True): + if c.cls == 'Button' and ('运行' in (c.title or '') or 'Run' in (c.title or '')): + btn = c + break + if btn is None: + for c in children(target, visible_only=True): + if c.cls == 'Button': + btn = c + break + if btn is None: + u32.PostMessageW(target.hwnd, WM_CLOSE, 0, None) + acted = True + time.sleep(0.4) + continue + log(' 关掉「打开文件 - 安全警告」→ 点「%s」' % (btn.title or '运行')) + foreground(target) + time.sleep(0.2) + real_click(btn.rect[0] + btn.rect[2] // 2, btn.rect[1] + btn.rect[3] // 2) + acted = True + time.sleep(0.8) + return acted + + +def foreground(win, tries=4): + """先还原(如果最小化),再切前台;绝不设 TOPMOST(会浮在所有窗口上干扰用户)。 + + Windows 有"前台锁定":后台进程直接 SetForegroundWindow 可能被忽略,于是窗口看着在 + 最上面,实际焦点还在别的程序,坐标点击就打到别人身上。这里用 ALT 轻敲 + + AttachThreadInput 绕过,并回读确认;返回是否真的切过去了。 + """ + restore(win) + if u32.GetForegroundWindow() == win.hwnd: + return True + # ALT 轻按解除前台锁定 + u32.keybd_event(0x12, 0, 0, None) + u32.keybd_event(0x12, 0, 2, None) + for _ in range(tries): + fg = Window(u32.GetForegroundWindow()) + tgt = wt.DWORD() + if fg: + u32.GetWindowThreadProcessId(fg.hwnd, ctypes.byref(tgt)) + me = k32.GetCurrentThreadId() + if fg: + u32.AttachThreadInput(me, tgt.value, True) + u32.BringWindowToTop(win.hwnd) + u32.SetForegroundWindow(win.hwnd) + if fg: + u32.AttachThreadInput(me, tgt.value, False) + time.sleep(0.25) + if u32.GetForegroundWindow() == win.hwnd: + return True + return False + + +# ---------------------------------------------------------------- 真实鼠标 +def move_to(x, y): + """移动系统光标(真实位置,不是消息)。""" + u32.SetCursorPos(int(x), int(y)) + + +def real_click(x, y, hold=0.06): + """真实鼠标左键点击(SetCursorPos + mouse_event)。 + + 为什么需要:客户端的菜单、TAdvStringGrid 单元格只认**真实输入**, + WM_LBUTTONDOWN 消息点不进编辑态;菜单 hover 也依赖真实光标位置。 + 代价:会移动用户的光标。 + """ + move_to(x, y) + time.sleep(0.1) + u32.mouse_event(0x0002, 0, 0, 0, None) # MOUSEEVENTF_LEFTDOWN + time.sleep(hold) + u32.mouse_event(0x0004, 0, 0, 0, None) # MOUSEEVENTF_LEFTUP + + +# ---------------------------------------------------------------- 下拉框(原生/CB_* 兼容) +def combo_count(win): + return int(u32.SendMessageW(win.hwnd, CB_GETCOUNT, 0, None)) + + +def combo_text(win, index): + buf = ctypes.create_unicode_buffer(512) + u32.SendMessageW(win.hwnd, CB_GETLBTEXT, index, ctypes.cast(buf, ctypes.c_void_p)) + return buf.value + + +def combo_items(win): + return [combo_text(win, i) for i in range(combo_count(win))] + + +def combo_sel(win): + return u32.SendMessageW(win.hwnd, CB_GETCURSEL, 0, None) + + +def combo_set(win, index): + u32.SendMessageW(win.hwnd, CB_SETCURSEL, index, None) + time.sleep(0.2) + return combo_sel(win) == index + + +# ---------------------------------------------------------------- 坐标点击(自绘菜单唯一办法) +def is_under(x, y, ancestor): + pt = wt.POINT(x, y) + h = Window(u32.WindowFromPoint(pt)) + for _ in range(24): + if not h: + return False + if int(h) == int(ancestor): + return True + h = h.parent + return False + + +def click_at(x, y, ancestor=None, retries=3): + """合成鼠标点击。传 ancestor 时校验落点确实属于该窗口,不属于就先把窗口拉到前台重试。""" + if ancestor is not None: + ok = False + for _ in range(retries): + if is_under(x, y, ancestor): + ok = True + break + foreground(ancestor) + time.sleep(0.4) + if not ok: + raise RuntimeError('落点 (%d,%d) 不属于目标窗口,可能被其他窗口挡住(前台=%r)' + % (x, y, Window(u32.GetForegroundWindow()))) + u32.SetCursorPos(x, y) + time.sleep(0.12) + u32.mouse_event(0x0002, 0, 0, 0, 0) + time.sleep(0.04) + u32.mouse_event(0x0004, 0, 0, 0, 0) + + +# ---------------------------------------------------------------- 截屏 + 左侧菜单识别 +class _BMIH(ctypes.Structure): + _fields_ = [('biSize', wt.DWORD), ('biWidth', wt.LONG), ('biHeight', wt.LONG), + ('biPlanes', wt.WORD), ('biBitCount', wt.WORD), ('biCompression', wt.DWORD), + ('biSizeImage', wt.DWORD), ('biXPelsPerMeter', wt.LONG), ('biYPelsPerMeter', wt.LONG), + ('biClrUsed', wt.DWORD), ('biClrImportant', wt.DWORD)] + + +class _BMI(ctypes.Structure): + _fields_ = [('bmiHeader', _BMIH), ('bmiColors', wt.DWORD * 3)] + + +def grab_screen(): + """整屏抓成 BGRA 字节串,返回 (宽, 高, bytes)。纯 GDI,不依赖 Pillow。""" + w = u32.GetSystemMetrics(0) + h = u32.GetSystemMetrics(1) + hdc = u32.GetDC(None) + mem = g32.CreateCompatibleDC(hdc) + bmp = g32.CreateCompatibleBitmap(hdc, w, h) + old = g32.SelectObject(mem, bmp) + g32.BitBlt(mem, 0, 0, w, h, hdc, 0, 0, 0x00CC0020) # SRCCOPY + bi = _BMI() + bi.bmiHeader.biSize = ctypes.sizeof(_BMIH) + bi.bmiHeader.biWidth = w + bi.bmiHeader.biHeight = -h # 负数=自上而下 + bi.bmiHeader.biPlanes = 1 + bi.bmiHeader.biBitCount = 32 + buf = ctypes.create_string_buffer(w * h * 4) + g32.GetDIBits(mem, bmp, 0, h, ctypes.cast(buf, ctypes.c_void_p), + ctypes.cast(ctypes.byref(bi), ctypes.c_void_p), 0) + g32.SelectObject(mem, old) + g32.DeleteObject(bmp) + g32.DeleteDC(mem) + u32.ReleaseDC(None, hdc) + return w, h, buf.raw + + +def region_ink(x0, y0, x1, y1, ink=190): + """统计一个矩形区域里"有墨迹"的像素数(亮度 < ink)。 + + 用来判断"表格里到底有没有数据行"——比看按钮是否可用可靠: + 实测缴费工资申报的空表,点一下表头全选框也会把「提交申报」点亮。 + """ + sw, sh, raw = grab_screen() + x0 = max(0, x0); y0 = max(0, y0); x1 = min(sw - 1, x1); y1 = min(sh - 1, y1) + n = 0 + for y in range(y0, y1 + 1): + base = y * sw * 4 + for x in range(x0, x1 + 1): + i = base + x * 4 + b, g, r = raw[i], raw[i + 1], raw[i + 2] + if 0.299 * r + 0.587 * g + 0.114 * b < ink: + n += 1 + return n + +def menu_rows(top=130, bottom=540, left=45, right=190, ink=190): + """扫描左侧菜单区域,返回每一条(文字/图标)行。 + + 返回 [{'y0','y1','cy','minx','maxx','ink'}, ...] + 判据:亮度 < ink 视为"有墨迹";同一行墨迹 >2 像素、连续高度 >=6px 算一条。 + + 注意:扫之前先把鼠标挪开——菜单 hover 会弹出深色 tooltip 盖在菜单上 + (实测把「缴费工资申报」的子项判成"没展开"),墨迹范围也会被撑大。 + """ + move_to(u32.GetSystemMetrics(0) - 20, u32.GetSystemMetrics(1) - 80) + time.sleep(0.25) + sw, sh, raw = grab_screen() + rows = [] + for y in range(top, min(bottom, sh - 1) + 1): + base = y * sw * 4 + cnt = 0 + minx, maxx = 9999, -1 + for x in range(left, min(right, sw - 1) + 1): + i = base + x * 4 + b, g, r = raw[i], raw[i + 1], raw[i + 2] + if 0.299 * r + 0.587 * g + 0.114 * b < ink: + cnt += 1 + if x < minx: + minx = x + if x > maxx: + maxx = x + rows.append((y, cnt, minx if maxx >= 0 else 0, maxx)) + items = [] + cur = None + for y, cnt, minx, maxx in rows: + if cnt > 2: + if cur is None: + cur = {'y0': y, 'y1': y, 'cy': y, 'minx': minx, 'maxx': maxx, 'ink': 0} + else: + cur['y1'] = y + cur['cy'] = (cur['y0'] + cur['y1']) // 2 + cur['minx'] = min(cur['minx'], minx) + cur['maxx'] = max(cur['maxx'], maxx) + cur['ink'] += cnt + else: + if cur and cur['y1'] - cur['y0'] >= 6: + items.append(cur) + cur = None + if cur and cur['y1'] - cur['y0'] >= 6: + items.append(cur) + return items + + +def menu_children(parent_y, **kw): + """判断某个父菜单项是否已展开:已展开返回子项列表,未展开返回 []。 + + 判据(实测):折叠时下一行间距 40px 且右侧有 ▼(墨迹到 x≈184); + 展开时子项间距 30px、右侧没有 ▼(墨迹止于 x≈101~127)。 + """ + rows = menu_rows(**kw) + parent = next((r for r in rows if abs(r['cy'] - parent_y) <= 8), None) + if not parent: + return [] + after = sorted([r for r in rows if r['cy'] > parent['cy'] + 8], key=lambda r: r['cy']) + if not after: + return [] + first = after[0] + # 判据:子项是缩进的(文字从 x≈50 起,顶层从 45 起)+ 行距 36~38 变 30。 + # 不能只看墨迹右边界——长标签(月度缴费工资申报)会超过 140 被误判。 + if (first['cy'] - parent['cy']) >= 38 or first['minx'] < 48: + return [] + kids = [first] + for prev, cur in zip(after, after[1:]): + if (cur['cy'] - prev['cy']) <= 34 and cur['minx'] >= 48: + kids.append(cur) + else: + break + return kids + + +SAFE_DIALOGS = ('Tfrm_MsgDlgRich', 'TfrmSwjgSwitch', 'Tfrm_dbsxMessage', 'TfrmAqts') + + +def dismiss_dialogs(main, timeout=15.0, unsaved='ok'): + """关掉挡住主窗的信息类弹窗,直到 main.enabled。 + + 主窗 disabled 时,所有坐标点击都是**静默无效**的(不报错、也没反应), + 所以任何"点菜单/点按钮"之前都应先调用它。 + 只处理已知的信息类窗(确认单位/提示信息/待办/安全提示),不碰业务窗口。 + + 特例:`您添加的数据还未提交申报,此操作将清空原有数据,是否继续?[确定][取消]` + —— 这是「离开缴费工资调整页」时的确认框。 + unsaved='ok' → 点「确定」(允许离开,清空未提交的编辑) + unsaved='stay' → 点「取消」(留在本页,保留数据) + 默认 'ok':调用这个函数通常是为了**切到别的页面**,不让它卡住。 + """ + t0 = time.time() + while time.time() - t0 < timeout: + if main.enabled: + return True + acted = False + for cls in SAFE_DIALOGS: + w = find_window(cls, timeout=0) + if not w: + continue + btns = sorted([b for b in children(w, visible_only=True) if b.cls == 'TITSSpeedButton'], + key=lambda b: b.rect[0]) + if not btns: + u32.PostMessageW(w.hwnd, WM_CLOSE, 0, None) + acted = True + time.sleep(0.6) + continue + # 「未提交就离开」确认框:按调用方意图选按钮 + body = '' + try: + from . import sbocr + l, t, ww, hh = w.rect + body = ' '.join(i.text for i in sbocr.texts((l + 6, t + 28, l + ww - 6, t + hh - 6))) + except Exception: # noqa: BLE001 + pass + if '清空原有数据' in body or '还未提交申报' in body: + b = btns[0] if unsaved == 'ok' else btns[-1] + log(' 弹窗「未提交就离开」→ 点「%s」(%s)' + % ('确定' if unsaved == 'ok' else '取消', unsaved)) + foreground(w) + time.sleep(0.2) + real_click(b.rect[0] + b.rect[2] // 2, b.rect[1] + b.rect[3] // 2) + acted = True + time.sleep(0.8) + continue + post_click(btns[0]) + acted = True + time.sleep(0.6) + if not acted: + time.sleep(0.3) + return main.enabled + +def expand_menu(main, parent_y, child_x=95, tries=3): + """确保某个父菜单展开,返回子项列表(空=失败)。 + + 坑:菜单是"手风琴 + 可折叠",已展开时再点父项会把它收起来。 + 所以必须:先看 → 没展开才点 → 点完再看 → 还不行就再点一次(切回来)。 + """ + for i in range(tries): + kids = menu_children(parent_y=parent_y) + if kids: + return kids + foreground(main) + time.sleep(0.3) + # 空点一次:窗口刚被拉到前台时,**第一次点击常被"激活窗口"吃掉**, + # 直接点菜单项会毫无反应(实测 2026-11-19 17:54)。点顶栏空白处最安全。 + click_at(main.rect[0] + 960, main.rect[1] + 75, ancestor=main) + time.sleep(0.4) + click_at(main.rect[0] + 63, parent_y, ancestor=main) + time.sleep(1.2) + return menu_children(parent_y=parent_y) diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/special_declare.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/special_declare.py new file mode 100644 index 0000000..85a6bf0 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/special_declare.py @@ -0,0 +1,452 @@ +# -*- coding: utf-8 -*- +"""special_declare.py —— 特殊缴费申报(**按影刀 process5 / process13 原版逻辑移植**)。 + +影刀原版位置: + ...\\97e2e9b5-...\\xbot_robot\\process5.py 特殊缴费申报:进页 + 判有没有活 + ...\\97e2e9b5-...\\xbot_robot\\process13.py 有数据:全选 → 导出 → 提交 + selectorsV2.xml 「特殊缴费申报表单」= TfrmHdsbbbtx 里的 TAdvStringGrid + +process5 的真实流程(不是"点刷新等弹窗"): + 1. 等「社保费申报」图像(20s) + 2. 若「特殊缴费申报」已可见 → **单击**;否则先点「社保费申报」父项、挪鼠标、再点子项 + 3. 若看不到「征集通知流水号」→ **再点子项一次**(进页重试) + 4. 不点刷新(进页时客户端自己会查)。循环 ≤30 次: + OCR「特殊缴费申报表单」 + - 命中 "未申报信息还未生成" / "无需进行申报" → 点确定 → 状态=无需进行申报 → 结束 + - OCR 条数 > 30 → 有数据 → process13 + - 出现「服务器连接异常」→ 点确定 → 点刷新 → 超时清零 + 5. 超时 30 次仍无结论 → 结束 + +# 2026-11-19 实测补充(与影刀原版的差异,必须知道) +# · 日常页与特殊页**同类名** TfrmHdsbbbtx:旧版 page_win() 只按类名找,会把仍开着的日常页 +# 当成特殊页返回("已进入"是假的、菜单没点)。现在按结构指纹判: +# 按钮第一排 y≈171(日常 142)、无 136px 明细按钮、有可见「征集通知流水号」输入框、 +# 表格顶边 y≈352(日常 323)。面包屑**错写**成"日常申报",不能用它。 +# · **PrintWindow 在本机失效**:主窗/表格/弹窗 grab() 全部 ok=False、位图为空, +# 所以"元素截图再 OCR"这条路读到的永远是空串(旧版空转 30 轮的根因)。 +# 现在统一走屏幕 OCR(sbocr,要求主窗在前台)。 +# · 无数据弹窗原文(Tfrm_MsgDlgRich「提示信息」): +# 未查询到未申报信息,可能原因: +# 1.您未办理特殊缴费申请,无需进行申报; +# 2.您已办理特殊缴费申报,未申报信息还未生成,请稍后再试! +""" + +import os +import time + +from .. import config +from . import sbui as ui + +NO_DATA_WORDS = ('未申报信息还未生成', '无需进行申报', '未查询到未申报信息') +CONN_ERROR_WORDS = ('服务器连接异常', '连接异常', '连接失败', '网络') +PAGE_CLASS = 'TfrmHdsbbbtx' +DAILY_DETAIL_W = (130, 145) # 日常页「查看职工未申报明细」按钮宽度 +SPECIAL_TOOLBAR_Y = 160 # 特殊页工具栏第一排 y>=160(日常页 142) +DATA_LINES = 30 # 影刀口径:OCR 条数 > 30 → 有数据 +MAX_ROUNDS = 30 + + +class SpecialError(RuntimeError): + pass + + +# ---------------------------------------------------------------- 页面识别 +def main_win(): + m = ui.find_window('Tfrm_MainFrame', visible=False) + if not m: + raise SpecialError('主界面不在(没登录?)') + return m + + +def _pages(main): + return [c for c in ui.children(main, visible_only=False) if c.cls == PAGE_CLASS] + + +def _structural_special(page): + """四川口径的结构指纹:工具栏下移 29px、且没有 130~145 宽的「查看职工未申报明细」。""" + if not page or not page.visible: + return False + btns = [b for b in ui.children(page, visible_only=True) + if b.cls == 'TITSSpeedButton' and b.rect[2] >= 50] + if not btns: + return False + if any(DAILY_DETAIL_W[0] <= b.rect[2] <= DAILY_DETAIL_W[1] for b in btns): + return False + return min(b.rect[1] for b in btns) >= SPECIAL_TOOLBAR_Y + + +def _breadcrumb(main=None): + """读面包屑那行文字(首页 >> 社保费申报 >> xxx)。""" + main = main or main_win() + if not main: + return '' + from . import sbocr + l, t, _w, _h = main.rect + try: + items = sbocr.texts((l + 200, t + 88, l + 780, t + 132), min_score=0.4, main=main) + except Exception: # noqa: BLE001 + return '' + return ' '.join(i.text for i in items) + + +def _has_detail_btn(page): + return any(DAILY_DETAIL_W[0] <= b.rect[2] <= DAILY_DETAIL_W[1] + for b in ui.children(page, visible_only=True) if b.cls == 'TITSSpeedButton') + + +def is_special(page, main=None): + """是否在「特殊缴费申报」页。 + + 2026-11-19 实测(两省都逐页对照过): + · 四川:工具栏下移 29px(y=171)且无「查看职工未申报明细」→ 结构指纹直接判。 + · 湖南:两个页面按钮位置**完全一样**(y=142),唯一区别是 + **日常页有 136px 宽的「查看职工未申报明细」按钮,特殊页没有**。 + · 面包屑在湖南是**对的**(日常页写日常申报、特殊页写特殊缴费申报), + 但四川特殊页会错写成"日常申报",所以代码不依赖它。 + · 流水号输入框两页都有(日常在 x≈639,特殊在 x≈360),也不能当指纹。 + """ + if _structural_special(page): + return True + if not page or not page.visible: + return False + if _has_detail_btn(page): + return False # 有明细按钮 = 日常页 + btns = [b for b in ui.children(page, visible_only=True) + if b.cls == 'TITSSpeedButton' and b.rect[2] >= 50] + return len(btns) >= 3 # 工具栏完整(刷新/提交/导出…)= 特殊页 + + +def page_win(main): + for p in _pages(main): + if is_special(p, main): + return p + return None + + +def serial_edit(page): + """「征集通知流水号」输入框 —— 特殊页的**唯一可靠指纹**。 + + 实测坐标:四川 (360,266),湖南 (360,237);日常页上这个组合框是**隐藏**的。 + 宽度判据放宽到 >100,y 放宽到 200~320(两省位置差 29px)。 + """ + for c in ui.children(page, visible_only=True): + if c.cls in ('TInputCombobox', 'Edit') and 200 < c.rect[1] < 320 and c.rect[2] > 100: + return c + return None + + +def describe(page): + if not page: + return '<无页面>' + btns = ['%d,%d w%d%s' % (b.rect[0], b.rect[1], b.rect[2], '' if b.enabled else '(禁)') + for b in ui.children(page, visible_only=True) + if b.cls == 'TITSSpeedButton' and b.rect[2] >= 50] + return '按钮=[%s] 流水号框=%s 表格y=%s' % ( + ' '.join(sorted(btns)), '有' if serial_edit(page) else '无', + next((c.rect[1] for c in ui.children(page, visible_only=True) + if c.cls == 'TAdvStringGrid'), '?')) + + +# ---------------------------------------------------------------- 弹窗 +def dialog_body(d): + """读提示信息正文(PrintWindow 失效 → 屏幕 OCR)。""" + l, t, w, h = d.rect + from . import sbocr + items = sbocr.texts((l + 8, t + 34, l + w - 8, t + h - 8), min_score=0.3) + return ' '.join(i.text for i in items).strip() + + +def close_dialog(d=None): + """点掉一个提示信息(影刀用「错误处理确认」图像 = 最左按钮)。""" + from . import daily_declare as dd + d = d or ui.find_window('Tfrm_MsgDlgRich', timeout=0) + if not d: + return True + return dd.confirm_dialog(d) + + +# ---------------------------------------------------------------- 进页面(影刀 process5 第 1~3 步) +def goto_special(main, timeout=25.0): + """强制走左侧菜单进特殊页。返回 (page, navigated): + + navigated=True 表示这次真的切了页面(客户端进页会自动查一次,不必再点刷新); + navigated=False 表示本来就在这一页(数据可能是旧的,需要点刷新)。 + """ + p = page_win(main) + if p: + ui.log(' 已在特殊缴费申报页(%s)' % describe(p)) + return p, False + + from . import sbocr + sbocr.ensure_foreground(main) + menu = sbocr.menu_region(main) + + if sbocr.find('社保费申报', menu, min_score=0.6) is None: + # 截图可能被别的窗口挡了 → 再验一次前台/遮挡,别急着乱点 + ui.log(' 菜单 OCR 没读到「社保费申报」→ 重新置前再读一次') + sbocr.ensure_foreground(main) + ui.topmost(main, True) + time.sleep(0.5) + if sbocr.find('社保费申报', menu, min_score=0.6) is None: + raise SpecialError('左侧菜单读不到「社保费申报」(窗口可能被挡住/不在前台)') + + hit = sbocr.find('特殊缴费申报', menu, min_score=0.6) + if hit is None: + ui.log(' 子项没展开 → 点父项「社保费申报」') + parent = sbocr.find('社保费申报', menu, min_score=0.6) + if not parent: + raise SpecialError('左侧菜单找不到「社保费申报」') + sbocr.click_item(parent, park=False) + ui.move_to(927, 489) + time.sleep(1.2) + hit = sbocr.find('特殊缴费申报', menu, min_score=0.6) + if not hit: + raise SpecialError('左侧菜单找不到「特殊缴费申报」') + + # 窗口刚被拉到前台时,第一次点击会被"激活窗口"吃掉 → 先热身(影刀同款) + sbocr.warm_up(main) + ui.log(' 点「特殊缴费申报」(%d,%d)' % hit.center) + sbocr.click_item(hit) + ui.move_to(927, 489) # 影刀同款:点完把鼠标挪开,避免 tooltip 盖住菜单 + + def wait_page(sec): + t0 = time.time() + while time.time() - t0 < sec: + time.sleep(0.4) + p = page_win(main) + if p and serial_edit(p): + return p, time.time() - t0 + return None, sec + + p, used = wait_page(timeout / 2) + if p: + ui.log(' 已进入特殊缴费申报页(单击,%.1f 秒):%s' % (used, describe(p))) + return p, True + + # 单击没反应 → 双击(影刀在原版里子项已可见时用的就是 dbclick) + ui.log(' 单击后仍停在原页 → 双击「特殊缴费申报」再试') + cx, cy = hit.center + ui.double_click(cx, cy) + ui.move_to(927, 489) + p, used = wait_page(timeout / 2) + if p: + ui.log(' 已进入特殊缴费申报页(双击,%.1f 秒):%s' % (used, describe(p))) + return p, True + + # 影刀第 3 步:还是看不到「征集通知流水号」就再点一次子项 + ui.log(' 双击也没进 → 重新展开父项后再点一次') + hit2 = sbocr.find('特殊缴费申报', menu, min_score=0.6) + if hit2: + sbocr.expand_menu(main, '社保费申报', '特殊缴费申报') + sbocr.click_item(hit2) + ui.move_to(927, 489) + p, used = wait_page(timeout / 2) + if p: + ui.log(' 已进入特殊缴费申报页(第三次,%.1f 秒):%s' % (used, describe(p))) + return p, True + + raise SpecialError('点了菜单仍未进入特殊缴费申报页(现在:%s)' + % describe(_pages(main)[0] if _pages(main) else None)) + + +# ---------------------------------------------------------------- 判状态(影刀 process5 第 4 步) +def form_ocr(page, main): + """OCR「特殊缴费申报表单」= 表格 TAdvStringGrid(屏幕 OCR)。""" + from . import sbocr + grid = next((c for c in ui.children(page, visible_only=True) if c.cls == 'TAdvStringGrid'), None) + if not grid: + return [] + l, t, w, h = grid.rect + ml, mt, mw, mh = main.rect + rect = (l + 2, t + 30, min(l + w - 2, ml + mw - 6), min(t + h - 2, mt + mh - 46)) + return [i.text for i in sbocr.texts(rect, min_score=0.3, main=main)] + + +def wait_state(main, page, timeout=None): + """返回 ('none'|'data'|'unknown', 证据)。""" + from . import daily_declare as dd + t0 = time.time() + rounds = 0 + refreshes = 0 + last = '' + while rounds < MAX_ROUNDS: + rounds += 1 + + d = ui.find_window('Tfrm_MsgDlgRich', timeout=0) + if d: + body = dialog_body(d) + last = body or last + if body: + ui.log(' 弹窗[%s]:%s' % (d.title, body[:90])) + close_dialog(d) + if any(h in body for h in CONN_ERROR_WORDS): + refreshes += 1 + if refreshes > 3: + ui.log(' → 连续 %d 次服务器连接异常,放弃' % refreshes) + return 'unknown', body + ui.log(' → 服务器连接异常:点刷新后重来(轮次清零,第 %d 次)' % refreshes) + refresh(page) + rounds = 0 + t0 = time.time() + continue + if any(w in body for w in NO_DATA_WORDS): + ui.log(' → 判为「无需进行申报」') + return 'none', body + time.sleep(0.5) + continue + + lines = form_ocr(page, main) + text = ' '.join(lines) + if text: + last = text + if any(w in text for w in NO_DATA_WORDS): + ui.log(' 表单位图命中关键字 → 无需进行申报') + return 'none', text + ui.log(' 第 %d 轮:表单 OCR %d 段(%s)' % (rounds, len(lines), (text or '<空>')[:50])) + if len(lines) > DATA_LINES: + ui.log(' → OCR 条数 %d > %d,判为有数据' % (len(lines), DATA_LINES)) + return 'data', text + + if timeout and time.time() - t0 > timeout: + break + time.sleep(1.0) + ui.log(' %d 轮都没得出结论 → 按无数据处理' % rounds) + return 'none', last + + +def refresh(page): + """点「刷新」= 联网取核定数据。**点完立刻返回**,不要 wait_idle: + + dd.wait_idle() 会调 clear_msg_dialogs() 把「未查询到未申报信息」当成普通弹窗点掉, + 证据就没了(实测 2026-11-19:判定被吞,随后 30 轮空转)。弹窗一律交给 wait_state 处理。 + """ + from . import daily_declare as dd + btn = dd.click_toolbar(page, 'refresh') + if not btn['enabled']: + raise SpecialError('「刷新」按钮不可用') + ui.log(' 点「刷新」(%d,%d)' % (btn['x'], btn['y'])) + ui.post_click(btn['win']) + return True + + +# ---------------------------------------------------------------- 导出 + 提交(影刀 process13) +def _special_save(sav, target): + """另存为:影刀是"文件名框填完整路径 + ENTER"(不是点保存)。""" + from . import daily_declare as dd + edit = ui.find_child(sav, 'Edit') + if not edit: + raise SpecialError('另存为里没有文件名框') + if not ui.set_text(edit, target): + raise SpecialError('文件名写入失败:%r' % ui.get_text(edit)) + ui.log(' 存到:%s' % target) + ui.foreground(sav) + time.sleep(0.4) + ui.key(ui.VK_RETURN) + t0 = time.time() + while time.time() - t0 < 60: + time.sleep(0.25) + if os.path.exists(target) and os.path.getsize(target) > 0: + dd.clear_msg_dialogs() + return os.path.getsize(target) + # 兜底:点保存按钮 + save_btn = next((b for b in ui.children(sav, visible_only=True) + if b.cls == 'Button' and '保存' in b.title), None) + if save_btn: + ui.bm_click_wait(save_btn, 15000) + time.sleep(1.0) + dd.clear_msg_dialogs() + if os.path.exists(target) and os.path.getsize(target) > 0: + return os.path.getsize(target) + raise SpecialError('另存为后没生成文件:%s' % target) + + +def export_special(page, out_dir, store=''): + """全选 → 导出 → 另存为 → 导出成功确定。""" + from . import daily_declare as dd + ui.log(' 全选(点表头勾选框)') + if not dd.select_all_rows(page, dd.CONFIG): + raise SpecialError('全选后「导出」不可用') + btn = dd.click_toolbar(page, 'export') + if not btn['enabled']: + raise SpecialError('「导出」按钮不可用') + ui.log(' 点「导出」(%d,%d)' % (btn['x'], btn['y'])) + ui.post_click(btn['win']) + sav = ui.find_window('#32770', title='另存为', timeout=20.0) + if not sav: + raise SpecialError('点导出后 20 秒没出现「另存为」') + safe = ''.join('_' if c in '\\/:*?"<>|' else c for c in (store or '特殊申报')) + target = os.path.join(out_dir, '特殊申报_职工未申报明细_%s_%s.xls' + % (safe, time.strftime('%H%M%S'))) + size = _special_save(sav, target) + ui.log(' ✔ 导出落盘:%s(%d 字节)' % (os.path.basename(target), size)) + # 影刀:「导出成功确定按钮」 + for _ in range(6): + d = ui.find_window('Tfrm_MsgDlgRich', timeout=0) + if not d: + break + ui.log(' 导出后弹窗:%s' % dialog_body(d)[:60]) + close_dialog(d) + time.sleep(0.6) + return target + + +def run(store='', submit=False, timeout=None): + """返回 {'state','note','summary','submitted',...}。 + + 导出文件落 save_dir/申报结果/<门店>/(与申报记录 PDF 同目录)。 + """ + from . import daily_declare as dd + from . import sbocr + + out_dir = config.declare_dir(store) + main = main_win() + sbocr.ensure_foreground(main) + # 客户端全屏、又常被别的窗口压住:整个流程期间临时置顶,结束时立刻还原 + ui.topmost(main, True) + try: + return _run_body(main, out_dir, store, submit, timeout, dd) + finally: + ui.topmost(main, False) + ui.log(' 已取消临时置顶') + + +def _run_body(main, out_dir, store, submit, timeout, dd): + # 先把挡着的弹窗点掉(主窗 disabled 时坐标点击会静默失效) + for _ in range(4): + d = ui.find_window('Tfrm_MsgDlgRich', timeout=0) + if not d: + break + body = dialog_body(d) + ui.log(' 起始弹窗:%s' % body[:80]) + close_dialog(d) + time.sleep(0.6) + + page, navigated = goto_special(main) + res = {'store': store, 'state': 'unknown', 'note': '', 'summary': None, + 'submitted': None, 'page': describe(page), 'navigated': navigated} + + if navigated: + ui.log(' 刚切进本页:客户端进页时会自己查一次,不再点刷新(影刀 process5 同款)') + else: + ui.log(' 本来就在本页:旧数据不可信 → 点一次「刷新」取新数据') + refresh(page) + + state, body = wait_state(main, page, timeout=timeout) + res['state'] = state + res['note'] = body[:150] + if state != 'data': + ui.log(' 结论:%s' % ('无需进行申报' if state == 'none' else '状态未知')) + return res + + ui.log(' 结论:有数据 → 导出') + target = export_special(page, out_dir, store) + res['summary'] = target + + if not submit: + ui.log(' 已导出(未提交,submit=True 才提交)') + return res + ui.log(' 提交申报(影刀 process13)') + steps = dd.submit_declaration(page) + res['submitted'] = steps + ui.log(' ✔ 提交完成:%s' % ' → '.join(steps)) + return res diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/winprint.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/winprint.py new file mode 100644 index 0000000..2255da5 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/winprint.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +"""winprint.py —— 用 PrintWindow 抓窗口位图(被遮挡也能抓),再做 OCR。 + +背景:客户端弹窗正文是自绘的,控件树里读不到文字;屏幕截图又依赖窗口在前台 +(被别的窗口挡住就量到别人的画面)。PrintWindow + PW_RENDERFULLCONTENT 直接让 +窗口把自己画到位图上,跟前后台无关。 + +desktopauto 由执行机按 plugin.json requires.sdks 挂载,直接 import,不再塞 sys.path。 +""" + +import ctypes +from ctypes import wintypes as wt + +import numpy as np +from PIL import Image + +from desktopauto import ocr as d_ocr + +u32 = ctypes.windll.user32 +g32 = ctypes.windll.gdi32 + +u32.GetWindowDC.restype = wt.HDC +u32.PrintWindow.argtypes = [wt.HWND, wt.HDC, wt.UINT] +u32.GetWindowDC.argtypes = [wt.HWND] +u32.ReleaseDC.argtypes = [wt.HWND, wt.HDC] +g32.CreateCompatibleDC.argtypes = [wt.HDC] +g32.CreateCompatibleDC.restype = wt.HDC +g32.CreateCompatibleBitmap.argtypes = [wt.HDC, ctypes.c_int, ctypes.c_int] +g32.CreateCompatibleBitmap.restype = wt.HBITMAP +g32.SelectObject.argtypes = [wt.HDC, wt.HGDIOBJ] +g32.SelectObject.restype = wt.HGDIOBJ +g32.DeleteObject.argtypes = [wt.HGDIOBJ] +g32.DeleteDC.argtypes = [wt.HDC] +g32.GetDIBits.argtypes = [wt.HDC, wt.HBITMAP, wt.UINT, wt.UINT, + ctypes.c_void_p, ctypes.c_void_p, wt.UINT] +g32.GetDIBits.restype = ctypes.c_int + + +class _BMIH(ctypes.Structure): + _fields_ = [('biSize', wt.DWORD), ('biWidth', wt.LONG), ('biHeight', wt.LONG), + ('biPlanes', wt.WORD), ('biBitCount', wt.WORD), ('biCompression', wt.DWORD), + ('biSizeImage', wt.DWORD), ('biXPelsPerMeter', wt.LONG), + ('biYPelsPerMeter', wt.LONG), ('biClrUsed', wt.DWORD), ('biClrImportant', wt.DWORD)] + + +class _BMI(ctypes.Structure): + _fields_ = [('bmiHeader', _BMIH), ('bmiColors', wt.DWORD * 3)] + + +def grab(win): + """抓窗口位图,返回 PIL Image(BGR 转好 RGB)。PW_RENDERFULLCONTENT=2。""" + l, t, w, h = win.rect + w, h = max(1, w), max(1, h) + src = u32.GetWindowDC(win.hwnd) + mem = g32.CreateCompatibleDC(src) + bmp = g32.CreateCompatibleBitmap(src, w, h) + g32.SelectObject(mem, bmp) + ok = u32.PrintWindow(win.hwnd, mem, 2) + bi = _BMI() + bi.bmiHeader.biSize = ctypes.sizeof(_BMIH) + bi.bmiHeader.biWidth = w + bi.bmiHeader.biHeight = -h + bi.bmiHeader.biPlanes = 1 + bi.bmiHeader.biBitCount = 32 + buf = ctypes.create_string_buffer(w * h * 4) + g32.GetDIBits(mem, bmp, 0, h, buf, ctypes.byref(bi), 0) + g32.DeleteObject(bmp) + g32.DeleteDC(mem) + u32.ReleaseDC(win.hwnd, src) + return Image.frombytes('RGB', (w, h), buf.raw, 'raw', 'BGRX'), bool(ok) + + +def ocr(win, min_score=0.2): + """抓窗口 → OCR,返回文字段列表。""" + img, ok = grab(win) + arr = np.asarray(img)[:, :, ::-1] # RGB -> BGR + items = d_ocr.recognize(arr, min_score=min_score) + return [i.text for i in items], ok diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/plugin.json b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/plugin.json index 6e22f1e..dbce395 100644 --- a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/plugin.json +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/plugin.json @@ -1,54 +1,60 @@ -{ - "schema_version": 1, - "id": "xq0013", - "name": "社保费用申报导出并汇总", - "version": "0.1.2", - "description": "按月批量登录重庆社保客户端完成日常/特殊申报与申报记录导出并汇总。当前版本已迁移:账户列表读写、客户端启动、登录(Win32 元素+图像+OCR 验证)、弹窗清理;申报导出与汇总流程待迁移。", - "category": "社保公积金", - "icon": "", - "platform": "", - "uses_month": false, - "ui": true, - "capabilities": ["xq0013"], - "permissions": { - "platforms": [] - }, - "requires": { - "sdks": { - "desktopauto": { - "compat": "^0.5" - } - } - }, - "fields": { - "type": "object", - "properties": { - "mode": { - "type": "string", - "title": "执行模式", - "default": "check", - "enum": ["check", "full"], - "description": "check=只验证环境(启动→登录第一家有账户→清弹窗→关闭);full=完整批量申报(尚未迁移完成)" - }, - "client_exe": { - "type": "string", - "title": "社保客户端程序", - "default": "D:\\Program Files (x86)\\EPPortal_SB1.0\\EPEvenue_SB.exe", - "description": "EPEvenue_SB.exe 的完整路径" - }, - "save_dir": { - "type": "string", - "title": "输出目录", - "default": "D:\\资料\\人资\\社保费用申报导出汇总", - "description": "账户列表、申报结果、职工未申报明细、截图等统一根目录" - }, - "account_file": { - "type": "string", - "title": "账户列表文件", - "default": "", - "description": "留空 = 输出目录/账户列表.xlsx(A门店 B税号 C密码 E执行标记:0待执行/1跳过)" - } - }, - "required": [] - } -} +{ + "schema_version": 1, + "id": "xq0013", + "name": "社保费用申报导出并汇总", + "version": "0.3.0", + "description": "按月批量登录重庆社保客户端,完成日常申报/特殊申报导出、申报记录导出 PDF,并合并职工未申报明细、汇总上下半月金额回写账户表副本。已迁移全流程(Win32 消息驱动 + 影刀模板 + OCR,无缴费工资申报步骤)。", + "category": "社保公积金", + "icon": "", + "platform": "", + "uses_month": false, + "ui": true, + "capabilities": ["xq0013"], + "permissions": { + "platforms": [] + }, + "requires": { + "sdks": { + "desktopauto": { + "compat": "^0.5" + } + } + }, + "fields": { + "type": "object", + "properties": { + "mode": { + "type": "string", + "title": "执行模式", + "default": "check", + "enum": ["check", "full"], + "description": "check=只验证环境(启动→添加单位→登录第一家→清弹窗→关闭);full=逐户完整申报导出 + 合并明细 + 金额汇总" + }, + "submit": { + "type": "boolean", + "title": "真实提交申报", + "default": false, + "description": "默认只导出不提交(演练);开启后日常/特殊申报会真正向税局提交,不可撤销" + }, + "client_exe": { + "type": "string", + "title": "社保客户端程序", + "default": "D:\\Program Files (x86)\\EPPortal_SB1.0\\EPEvenue_SB.exe", + "description": "EPEvenue_SB.exe 的完整路径(其所在目录即客户端安装目录)" + }, + "save_dir": { + "type": "string", + "title": "输出目录", + "default": "D:\\资料\\人资\\社保费用申报导出汇总", + "description": "账户列表、申报结果、职工未申报明细、汇总结果、截图等统一根目录" + }, + "account_file": { + "type": "string", + "title": "账户列表文件", + "default": "", + "description": "留空 = 输出目录/账户列表.xlsx(按表头名读:门店/税号/密码/执行状态/日常申报状态/特殊申报状态/申报记录)" + } + }, + "required": [] + } +} diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/report/merge_detail.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/report/merge_detail.py new file mode 100644 index 0000000..13f2e6c --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/report/merge_detail.py @@ -0,0 +1,212 @@ +# -*- coding: utf-8 -*- +"""merge_detail.py —— 合并「职工未申报明细」 + +移植自影刀 `xbot_robot/merge.py`(用户 2026-11-20 指出),**逻辑照原样保留**: + - 明细文件表头在**第 2 行**(第 1 行是"基本医疗保险费/失业保险费"这类分组标题); + - 「参保单位」列不来自文件,而是**用文件所在的子文件夹名**填; + - 固定 19 列顺序(TARGET_COLS),各省缺的列留空; + - 证件类型/证件号码/费款所属期起止 按**文本**读写(防止身份证变科学计数法); + - 去重:按除「序号」外的所有目标列; + - 去重后重排序号 1..N;空串统一成真空值;文本列写出时设成 Excel 文本格式 "@"。 + +与原版的差别(适配本插件的产物命名/目录): + - 影刀导出的文件名是 `税务生成_职工未申报明细_xxx.xlsx`, + 本项目 `daily_declare.py` 导出的是 `职工未申报明细_税务生成_HHMMSS.xlsx` → **两种都认**; + - 目录不再有 <区域>/<日期> 层:输入根 = save_dir/职工未申报明细,每个门店一个子目录。 + +入口:merge_excel(root, output_path) / precheck(root)。 +""" +import os +import time + +import pandas as pd +from openpyxl.utils import get_column_letter + +from .. import config + +# 目标列(完整 19 列),稳定结构语义,不随运行变化 +TARGET_COLS = [ + "序号", + "参保单位", + "姓名", + "证件类型", + "证件号码", + "费款所属期起", + "费款所属期止", + "职工基本医疗保险(单位缴纳)应缴费额(元)", + "职工基本医疗保险(个人缴纳)应缴费额(元)", + "职工大额医疗互助保险(单位缴纳)应缴费额(元)", + "职工大额医疗互助保险(个人缴纳)应缴费额(元)", + "长期护理保险(单位缴纳)应缴费额(元)", + "长期护理保险(个人缴纳)应缴费额(元)", + "生育保险应缴费额(元)", + "职工基本养老保险(单位缴纳)应缴费额(元)", + "职工基本养老保险(个人缴纳)应缴费额(元)", + "失业保险(单位缴纳)应缴费额(元)", + "失业保险(个人缴纳)应缴费额(元)", + "工伤保险应缴费额(元)", +] + +# 按文本格式读写的列,防止身份证/期次变成数字或科学计数法 +TEXT_COLS = ["证件类型", "证件号码", "费款所属期起", "费款所属期止"] + +# 两种命名都认:影刀 `税务生成_职工未申报明细_…`,本项目 `职工未申报明细_税务生成_…` +NAME_PREFIXES = ("税务生成_职工未申报明细", "职工未申报明细_税务生成") + + +def log(msg): + config.log(msg) + + +def match_detail(filenames): + out = [] + for f in filenames: + low = f.lower() + if not low.endswith(".xlsx") or f.startswith("~$"): + continue + if any(f.startswith(p) for p in NAME_PREFIXES): + out.append(f) + return out + + +def precheck(root_dir): + """预检:哪些子文件夹下有多个明细文件(多数据来源/重复导出会这样)。""" + log("========== 预检开始 ==========") + for dirpath, dirnames, filenames in os.walk(root_dir): + dirnames[:] = [d for d in dirnames if not d.startswith("_")] + files = match_detail(filenames) + if len(files) > 1: + log("文件夹: {}".format(dirpath)) + log(" 包含 {} 个文件: {}".format(len(files), files)) + log("========== 预检结束 ==========") + + +def ensure_dir(file_path): + d = os.path.dirname(file_path) + if d and not os.path.exists(d): + os.makedirs(d) + log("已创建输出目录: {}".format(d)) + + +def _to_text(x): + """单元格值转干净文本,避免出现 123456789.0 这种尾巴。""" + if pd.isna(x): + return None + s = str(x).strip() + if s.endswith(".0"): + s = s[:-2] + return s + + +def _read_sub_table(file_path): + """读单个明细文件:第 2 行为表头,参保单位用子文件夹名填充。""" + header_df = pd.read_excel(file_path, engine="openpyxl", header=1, nrows=0) + header_df.columns = [str(c).strip() for c in header_df.columns] + + dtype_map = {col: str for col in TEXT_COLS if col in header_df.columns} + df = pd.read_excel(file_path, engine="openpyxl", header=1, dtype=dtype_map) + df.columns = [str(c).strip() for c in df.columns] + + unit_name = os.path.basename(os.path.dirname(file_path)) + + cols = [c for c in TARGET_COLS if c != "参保单位" and c in df.columns] + if not cols: + raise ValueError("文件 {} 不包含任何目标列(除参保单位外)".format(file_path)) + + sub = df[cols].copy() + sub["参保单位"] = unit_name + for col in TEXT_COLS: + if col in sub.columns: + sub[col] = sub[col].apply(_to_text) + return sub.reindex(columns=TARGET_COLS) + + +def _collect(root_dir, latest_per_unit=False): + """收集所有明细文件。返回 [(dirpath, filename), ...]。 + + latest_per_unit=True 时**每个门店目录只取最新一天**的文件: + 若产物再带上日期层,按区域合并时如果跨天全收,同一个人会在两天各出现一次 + (金额还不一样)——那不是"按区域合并"想要的结果。 + """ + found = [] + for dirpath, dirnames, filenames in os.walk(root_dir): + # 跳过 `_历史测试` / `_合并` 这类下划线目录(本项目自己的测试产物和输出目录) + dirnames[:] = [d for d in dirnames if not d.startswith("_")] + files = sorted(match_detail(filenames)) + if files: + found.append((dirpath, files)) + if not latest_per_unit: + return [(d, f) for d, names in found for f in names] + + def day_of(dirpath): + """从路径里取 YYYY-MM-DD(<区域>\\<日期>\\<门店>);取不到就用文件时间。""" + for part in reversed(os.path.normpath(dirpath).split(os.sep)): + if len(part) == 10 and part[4] == "-" and part[7] == "-": + return part + return "" + + # 同一门店可能出现在多个日期目录下 → 按"门店名"聚合,只留最新那天的 + best = {} # store_name -> (day, [(dirpath, file)...]) + for dirpath, names in found: + store = os.path.basename(dirpath) + day = day_of(dirpath) + if not day: + day = time.strftime("%Y-%m-%d", time.localtime( + max(os.path.getmtime(os.path.join(dirpath, n)) for n in names))) + cur = best.get(store) + if cur is None or day > cur[0]: + best[store] = (day, [(dirpath, f) for f in names]) + out = [] + for store in sorted(best): + out.extend(best[store][1]) + return out + + +def merge_excel(root_dir, output_path, latest_per_unit=False): + """合并 root_dir 下所有明细文件,去重后按目标列写出一份。返回 (文件数, 行数)。""" + ensure_dir(output_path) + all_dfs, file_count = [], 0 + + for dirpath, file in _collect(root_dir, latest_per_unit=latest_per_unit): + path = os.path.join(dirpath, file) + try: + sub = _read_sub_table(path) + except Exception as e: # noqa: BLE001 + log("读取文件 {} 失败,已跳过: {}".format(path, e)) + continue + all_dfs.append(sub) + file_count += 1 + log("已读取: {} (参保单位: {}, 行数: {})".format( + path, os.path.basename(dirpath), len(sub))) + + if not all_dfs: + raise RuntimeError("未找到任何有效数据,合并终止(目录 %s)" % root_dir) + + combined = pd.concat(all_dfs, ignore_index=True) + original = len(combined) + log("共读取 {} 个文件,合并后总行数(去重前): {}".format(file_count, original)) + + subset = [c for c in TARGET_COLS if c != "序号"] + combined.drop_duplicates(subset=subset, inplace=True) + after = len(combined) + log("去重后总行数: {} (去除了 {} 行重复)".format(after, original - after)) + + combined["序号"] = range(1, len(combined) + 1) + + # 空串 → 真空值(否则 Excel 里 COUNT/SUN 之类会别扭) + try: + combined = combined.map(lambda x: None if isinstance(x, str) and not x.strip() else x) + except AttributeError: # pandas < 2.1 + combined = combined.applymap(lambda x: None if isinstance(x, str) and not x.strip() else x) + + with pd.ExcelWriter(output_path, engine="openpyxl") as writer: + combined.to_excel(writer, index=False, sheet_name="Sheet1") + ws = writer.sheets["Sheet1"] + for col in TEXT_COLS: + if col in combined.columns: + letter = get_column_letter(combined.columns.get_loc(col) + 1) + for cell in ws[letter]: + cell.number_format = "@" + + log("合并结果已保存至: {}".format(output_path)) + return file_count, after diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/report/summarize_declare.py b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/report/summarize_declare.py new file mode 100644 index 0000000..b8e7b26 --- /dev/null +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/report/summarize_declare.py @@ -0,0 +1,512 @@ +# -*- coding: utf-8 -*- +"""summarize_declare.py —— 汇总社保申报(移植自影刀 process14「汇总社保申报」) + +影刀原流程(xbot_robot/process14.py): + 1. 遍历「申报结果」下每个门店子目录,找 `社会保险费缴费申报表*.pdf` + 2. 只处理**受理日期为当月**的 PDF + 3. 受理日期 1~15 号算上半月,16 号及以后算下半月 + 4. 每张 PDF 用 camelot(lattice) 提明细表,汇总 + 「本期应缴费额 / 抵缴费额 / 本期实际应缴纳费额」(含往月补缴行) + 5. 按子目录名匹配账户表的「门店」列,写 6 列金额 + 备注 + 6. 结果另存到汇总目录,文件名带时间戳(**不改账户表原文件**) + +本插件的落点(由 config 决定,不写死路径): + · 输入 root = save_dir/申报结果(PDF 在 <门店>/社会保险费缴费申报表_N.pdf); + 递归扫描,**父目录名 = 门店**; + · 输出 out_dir = save_dir/汇总结果,文件名「社保申报汇总_YYYY-MM_时间戳.xlsx」; + · 解析失败的 PDF 不"算 0 了事":每张 PDF 都报「解析行数」,0 行 = 打警告并计入 failed。 + +前置:camelot 2.x + pymupdf(camelot 还需系统装 Ghostscript)。 +""" +import contextlib +import glob +import io +import json +import os +import re +from datetime import datetime + +from .. import config + +PDF_KEYWORD = '社会保险费缴费申报表' +UPPER_HALF_DAY = 15 + +# 三个求和列(按"表头清洗后包含"匹配,留别名兼容各省模板的细微差异) +AMOUNT_ALIASES = [ + ('due', '本期应缴费额', ('本期应缴费额', '本期应缴金额', '应缴金额')), + ('offset', '抵缴费额', ('抵缴费额', '抵缴金额')), + ('actual', '本期实际应缴纳费额', ('本期实际应缴纳费额', '本期实际应缴纳', '实际应缴纳费额')), +] + +# 账户表里要写的 6 列(上半月/下半月 × 三个金额) +UPPER_COLS = ['上半月本期应缴费额', '上半月抵缴费额', '上半月本期实际应缴纳费额'] +LOWER_COLS = ['下半月本期应缴费额', '下半月抵缴费额', '下半月本期实际应缴纳费额'] +REMARK_COL = '备注' + + +def log(msg): + config.log(msg) + + +# ---------------------------------------------------------------- PDF 解析 +def clean_header(value): + """表头清洗:去空白(含换行)+ 去 * 标记。""" + s = str(value) + return re.sub(r'\s+', '', s).replace('*', '') + + +def to_number(value): + """文本型数字转数值(去千分号/内部空白);转不动返回 None,由调用方按 0 计并计数。""" + if value is None: + return None + s = str(value).strip() + if not s or s in ('—', '——', '-', '--'): + return 0.0 + t = re.sub(r'\s+', '', s).replace(',', '') + try: + return float(t) + except ValueError: + return None + + +def is_total_row(cells): + """合计行判定(影刀原逻辑):首列是"合/计/合计"、前两列含"合计"、或 ≥3 个破折号; + 首列是数字(序号)就一定不是合计行。""" + texts = [str(c).strip() if c is not None else '' for c in cells] + if not texts: + return False + if texts[0] in ('合', '计', '合计'): + return True + if '合计' in ''.join(texts[:2]): + return True + if texts[0].replace('*', '').replace(' ', '').isdigit(): + return False + dash = sum(1 for c in texts if c.replace(' ', '') in ('—', '——', '-', '--')) + return dash >= 3 + + +def align_columns(cells, n): + """把一行对齐到表头的列数(camelot 会把合并单元格拆出多余空列)。""" + m = len(cells) + if m == n: + return cells + if m > n: + if m == 20 and n == 17: # 影刀实测:征收子目/抵缴费额等空列 + drop = {4, 7, 9} + return [v for i, v in enumerate(cells) if i not in drop] + return cells[:n] + return list(cells) + [None] * (n - m) + + +def extract_accept_date(path): + """读受理日期,返回 'YYYYMMDD' 或 None。先看最后一页(影刀口径),没有再全文找。""" + import pymupdf + + doc = pymupdf.open(path) + try: + pages = [doc[doc.page_count - 1].get_text()] + if len(doc) > 1: + pages.append('\n'.join(doc[i].get_text() for i in range(doc.page_count - 1))) + finally: + doc.close() + + for text in pages: + text = text.translate(str.maketrans('0123456789', '0123456789')) + m = re.search(r'受理日期[::]?\s*(\d{4})\D*?(\d{1,2})\D*?(\d{1,2})', text) + if m: + y, mo, d = m.groups() + return '%s%02d%02d' % (y, int(mo), int(d)) + return None + + +def extract_tables(path): + """camelot 提取整份 PDF,返回 (header, rows)。 + + header: 清洗后的表头 list;rows: 已对齐/去合计/去全空的数据行。 + 与影刀一致:第一张表第一行当表头,后续表直接接数据;遇合计行截断该表。 + """ + import camelot + + tables = camelot.read_pdf(path, pages='all', flavor='lattice', + line_scale=40, split_text=True) + header, rows = None, [] + for t in tables: + df = t.df + if header is None: + header = [clean_header(c) for c in df.iloc[0].tolist()] + data = df.iloc[1:] + else: + data = df + for _, row in data.iterrows(): + cells = row.tolist() + if is_total_row(cells): + break + cells = align_columns(cells, len(header)) + if all(c is None or str(c).strip() == '' for c in cells): + continue + rows.append(cells) + return (header or []), rows + + +def col_index(header, aliases): + for i, h in enumerate(header): + if any(a in h for a in aliases): + return i + return None + + +def has_col(header, name): + return any(name in h for h in header) + + +def sum_amount(rows, idx): + """按列索引求和;非数字单元格计 0,返回 (合计, 非法单元格数)。""" + if idx is None: + return 0.0, 0 + total, bad = 0.0, 0 + for cells in rows: + v = to_number(cells[idx] if idx < len(cells) else None) + if v is None: + bad += 1 + continue + total += v + return total, bad + + +def parse_pdf(path): + """解析一张 PDF,返回 dict(不含月份过滤)。""" + header, rows = extract_tables(path) + cols = {key: col_index(header, aliases) for key, _name, aliases in AMOUNT_ALIASES} + amounts, bad = {}, 0 + for key, _name, _aliases in AMOUNT_ALIASES: + amounts[key], n_bad = sum_amount(rows, cols[key]) + bad += n_bad + return { + 'path': path, + 'header': header, + 'rows': len(rows), + 'cols': {k: v for k, v in cols.items()}, + 'amounts': amounts, + 'bad_cells': bad, + 'is_special': has_col(header, '特殊缴费类型'), + # 医保单独申报短表:没有抵缴/实缴两列,也不是特殊缴费表 + 'is_medical_only': (cols['offset'] is None and cols['actual'] is None + and not has_col(header, '特殊缴费类型')), + } + + +def is_blank_pdf_parse(info): + """0 行 = 解析没拿到数据(不是"金额为 0")。""" + return info['rows'] == 0 + + +# ---------------------------------------------------------------- 收集与汇总 +def discover(root, keyword=PDF_KEYWORD, date=None, region=None): + """递归找 PDF,返回 [(store, path)]。父目录名 = 门店;跳过 `_` 开头的目录。""" + pattern = os.path.join(root, '**', keyword + '*.pdf') + found = [] + for path in glob.glob(pattern, recursive=True): + parts = os.path.relpath(path, root).split(os.sep) + dirs = parts[:-1] + if any(d.startswith('_') for d in dirs): + continue + if date and date not in dirs: + continue + if region and region not in dirs: + continue + store = dirs[-1] if dirs else os.path.basename(os.path.abspath(root)) + found.append((store, path)) + return sorted(found) + + +def file_digest(path): + """sha256(判断"同一个 PDF 被导出了两次",避免金额重复累加)。""" + import hashlib + + h = hashlib.sha256() + with open(path, 'rb') as fh: + for chunk in iter(lambda: fh.read(1 << 20), b''): + h.update(chunk) + return h.hexdigest() + + +def collect(root, year, month, keyword=PDF_KEYWORD, date=None, region=None, + upper_day=UPPER_HALF_DAY): + """按门店汇总上下半月金额 + 标签。""" + results, failed, seen = {}, [], set() + for store, path in discover(root, keyword=keyword, date=date, region=region): + name = os.path.basename(path) + digest = file_digest(path) + if (store, digest) in seen: + log(' 跳过(同一份 PDF 重复导出):%s' % name) + continue + seen.add((store, digest)) + + accept = extract_accept_date(path) + if not accept: + log(' 跳过(没读到受理日期):%s' % name) + failed.append({'file': path, 'reason': 'no_accept_date'}) + continue + y, mo, d = int(accept[:4]), int(accept[4:6]), int(accept[6:8]) + if (y, mo) != (year, month): + log(' 跳过(受理 %s 非 %04d-%02d):%s' % (accept, year, month, name)) + continue + + log(' 处理 %s(受理 %s)' % (name, accept)) + try: + with contextlib.redirect_stdout(io.StringIO()): # camelot 刷屏 + info = parse_pdf(path) + except Exception as e: # noqa: BLE001 + log(' ✗ 解析失败:%s(%r)' % (name, e)) + failed.append({'file': path, 'reason': repr(e)}) + continue + if is_blank_pdf_parse(info): + log(' ⚠ 解析 0 行(表格没认出来 / 扫描件)→ 计入失败,别当 0 元') + failed.append({'file': path, 'reason': 'no_table_rows'}) + continue + if info['bad_cells']: + log(' ⚠ %s 有 %d 个单元格不是数字(已按 0 计)' % (name, info['bad_cells'])) + + item = results.setdefault(store, { + 'upper': [0.0, 0.0, 0.0], 'lower': [0.0, 0.0, 0.0], + 'upper_tags': set(), 'lower_tags': set(), 'files': [], 'rows': 0, + }) + tags = set() + if info['is_special']: + tags.add('特殊缴费') + if info['is_medical_only']: + tags.add('医保单独申报') + is_upper = d <= upper_day + bucket = item['upper'] if is_upper else item['lower'] + for i, key in enumerate(('due', 'offset', 'actual')): + bucket[i] += info['amounts'][key] + (item['upper_tags'] if is_upper else item['lower_tags']).update(tags) + item['files'].append(path) + item['rows'] += info['rows'] + return results, failed + + +def build_remark(upper_tags, lower_tags): + parts = [] + if upper_tags: + parts.append('上半月:' + '+'.join(sorted(upper_tags))) + if lower_tags: + parts.append('下半月:' + '+'.join(sorted(lower_tags))) + return ';'.join(parts) if parts else '日常申报' + + +def norm_store(s): + return re.sub(r'\s+', '', str(s or '')).replace('(', '(').replace(')', ')') + + +def read_stores(xlsx): + """读账户表的「门店」列(按表头定位,不假设一定是第一列)。""" + import openpyxl + + wb = openpyxl.load_workbook(xlsx, read_only=True) + try: + ws = wb.active + header = [str(c.value or '').strip() for c in next(ws.iter_rows(min_row=1, max_row=1))] + if '门店' not in header: + raise RuntimeError('账户表没有「门店」列:%s' % xlsx) + col = header.index('门店') + 1 + stores = [str(ws.cell(row=r, column=col).value or '').strip() + for r in range(2, ws.max_row + 1)] + finally: + wb.close() + return [s for s in stores if s] + + +def match_results(results, stores): + """门店名归一后匹配,返回 {store_in_xlsx: result}。""" + by_norm = {norm_store(k): v for k, v in results.items()} + out, unmatched = {}, [] + for s in stores: + r = by_norm.get(norm_store(s)) + if r: + out[s] = r + for k in results: + if norm_store(k) not in {norm_store(s) for s in stores}: + unmatched.append(k) + return out, unmatched + + +# ---------------------------------------------------------------- 写账户表 +def write_accounts(xlsx, matched, out_dir, year, month): + import openpyxl + + try: + wb = openpyxl.load_workbook(xlsx) + except PermissionError: + raise RuntimeError('账户表被占用(Excel 开着?):%s' % xlsx) + ws = wb.active + headers = [c.value if c.value is not None else '' for c in ws[1]] + + if '门店' not in headers: + raise RuntimeError('账户表没有「门店」列,无法写入:%s' % xlsx) + store_col = headers.index('门店') + 1 + + # 上半月三列:优先新列名,兼容旧列名(本期应缴费额…)就地改名,没有就追加 + upper_cols = {} + for old_name, new_name in zip([a[1] for a in AMOUNT_ALIASES], UPPER_COLS): + if new_name in headers: + upper_cols[new_name] = headers.index(new_name) + 1 + elif old_name in headers: + idx = headers.index(old_name) + 1 + ws.cell(row=1, column=idx, value=new_name) + headers[idx - 1] = new_name + upper_cols[new_name] = idx + else: + headers.append(new_name) + ws.cell(row=1, column=len(headers), value=new_name) + upper_cols[new_name] = len(headers) + lower_cols = {} + for name in LOWER_COLS: + if name not in headers: + headers.append(name) + ws.cell(row=1, column=len(headers), value=name) + lower_cols[name] = headers.index(name) + 1 + if REMARK_COL not in headers: + headers.append(REMARK_COL) + ws.cell(row=1, column=len(headers), value=REMARK_COL) + remark_col = headers.index(REMARK_COL) + 1 + + written = [] + for r in range(2, ws.max_row + 1): + store = ws.cell(row=r, column=store_col).value + key = str(store or '').strip() + res = matched.get(key) + if not res: + continue + for name, val in zip(UPPER_COLS, res['upper']): + ws.cell(row=r, column=upper_cols[name], value=round(val, 2)) + for name, val in zip(LOWER_COLS, res['lower']): + ws.cell(row=r, column=lower_cols[name], value=round(val, 2)) + ws.cell(row=r, column=remark_col, + value=build_remark(res['upper_tags'], res['lower_tags'])) + written.append(key) + + os.makedirs(out_dir, exist_ok=True) + stamp = datetime.now().strftime('%Y%m%d_%H%M%S') + save_path = os.path.join(out_dir, '社保申报汇总_%04d-%02d_%s.xlsx' % (year, month, stamp)) + wb.save(save_path) + return save_path, written + + +# ---------------------------------------------------------------- 报表 +def report(results, failed, matched_stores, unmatched, check_match=True): + log('') + log('%-42s %12s %12s %12s | %12s %12s %12s 备注' % + ('门店', '上·应缴', '上·抵缴', '上·实缴', '下·应缴', '下·抵缴', '下·实缴')) + totals = [0.0] * 6 + for store in sorted(results): + r = results[store] + row = r['upper'] + r['lower'] + totals = [a + b for a, b in zip(totals, row)] + flag = '' if (store in matched_stores or not check_match) else '!!未匹配' + log('%-42s %12.2f %12.2f %12.2f | %12.2f %12.2f %12.2f %s %s' % + (store, row[0], row[1], row[2], row[3], row[4], row[5], + build_remark(r['upper_tags'], r['lower_tags']), flag)) + log('%-42s %12.2f %12.2f %12.2f | %12.2f %12.2f %12.2f' % + ('合计(%d 户)' % len(results), *totals)) + if unmatched and check_match: + log('') + log('⚠ 以下门店在账户表里没找到,没写入:') + for s in sorted(unmatched): + log(' - %s' % s) + if failed: + log('') + log('⚠ %d 张 PDF 没算进汇总(见上):' % len(failed)) + for f in failed: + log(' - %s(%s)' % (os.path.basename(f['file']), f['reason'])) + + +def run_summary(root=None, xlsx=None, out_dir=None, month=None, date=None, region=None, + keyword=PDF_KEYWORD, upper_day=UPPER_HALF_DAY, dry_run=False, + json_path=None): + """汇总入口。返回 (exit_code, payload)。 + + exit_code: 0 正常 / 2 没有可汇总的 PDF(或参数不对) / 3 账户表读不了/写不了。 + 默认:root = save_dir/申报结果,out_dir = save_dir/汇总结果。 + """ + root = root or config.dirs()['declare'] + out_dir = out_dir or config.dirs()['summary'] + + if month: + try: + year, mo = [int(x) for x in month.split('-')[:2]] + except ValueError: + log('month 要 YYYY-MM 格式:%r' % month) + return 2, {} + else: + now = datetime.now() + year, mo = now.year, now.month + + if date and not re.match(r'^\d{4}-\d{2}-\d{2}$', date): + log('date 要 YYYY-MM-DD 格式:%r' % date) + return 2, {} + + log('目标月份 %04d-%02d,上半月截止 %d 号' % (year, mo, upper_day)) + log('扫描目录 %s%s' % (root, (' 日期=%s' % date) if date else '')) + if not os.path.isdir(root): + log('目录不存在:%s' % root) + return 2, {} + + results, failed = collect(root, year, mo, keyword=keyword, date=date, + region=region, upper_day=upper_day) + log('共 %d 个门店有当月申报,%d 张 PDF 没算进汇总' % (len(results), len(failed))) + + payload = { + 'month': '%04d-%02d' % (year, mo), + 'root': root, + 'stores': {k: {'upper': v['upper'], 'lower': v['lower'], + 'upper_tags': sorted(v['upper_tags']), + 'lower_tags': sorted(v['lower_tags']), + 'files': v['files'], 'rows': v['rows']} + for k, v in results.items()}, + 'failed': failed, + } + + matched, unmatched = {}, list(results) + if not results: + log('本月没有可汇总的申报 PDF(%04d-%02d),不生成汇总文件' % (year, mo)) + payload.update({'written': [], 'unmatched': [], 'file': None}) + report(results, failed, set(), [], check_match=False) + return 2, payload + + if xlsx: + try: + stores = read_stores(xlsx) + except Exception as e: # noqa: BLE001 + log('✗ 读账户表失败:%r' % e) + payload.update({'written': [], 'unmatched': unmatched, 'file': None}) + return 3, payload + matched, unmatched = match_results(results, stores) + + save_path, written = None, [] + if xlsx and not dry_run: + try: + save_path, written = write_accounts(xlsx, matched, out_dir, year, mo) + except RuntimeError as e: + log('✗ %s' % e) + payload.update({'written': [], 'unmatched': unmatched, 'file': None}) + return 3, payload + log('已写入 %d 户 → %s' % (len(written), save_path)) + + payload['written'] = written + payload['unmatched'] = unmatched + payload['file'] = save_path + if not xlsx: + matched_stores = set() # 没给账户表就不判"未匹配" + elif written: + matched_stores = set(written) + else: + matched_stores = set(matched) if dry_run else set() + report(results, failed, matched_stores, unmatched, check_match=bool(xlsx)) + + if json_path: + with io.open(json_path, 'w', encoding='utf-8') as fh: + json.dump(payload, fh, ensure_ascii=False, indent=1, default=str) + log('JSON → %s' % json_path) + + return (0 if results else 2), payload diff --git a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/requirements.txt b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/requirements.txt index 50a2792..7ab4027 100644 --- a/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/requirements.txt +++ b/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/requirements.txt @@ -1,7 +1,11 @@ -pandas>=2.0 -openpyxl>=3.1 -pywin32>=306 -# desktopauto 由 SDK 下发(plugin.json.requires.sdks 已声明 ^0.4),不从 PyPI 装、 -# 也不要再 pip install -e 预装进环境包:同名包会让 SDK 挂载失败。 -# 验证码识别(后续 process6/登录兜底用) -ddddocr>=1.5 +pandas>=2.0 +openpyxl>=3.1 +pywin32>=306 +Pillow>=10.0 +numpy>=1.24 +# 申报记录 PDF 解析(受理日期) +pymupdf>=1.23 +# PDF 表格提取(汇总上下半月金额;camelot 还需系统安装 Ghostscript) +camelot-py>=1.0 +# desktopauto 由 SDK 下发(plugin.json.requires.sdks 已声明 ^0.5),不从 PyPI 装、 +# 也不要 pip install -e 预装进环境包:同名包会让 SDK 挂载 fail-fast。