feat(xq0013): 社保申报全流程迁移完成(v0.3.0)

日常申报/特殊申报导出、申报记录 PDF 导出,合并职工未申报明细并汇总上下半月金额回写账户表副本;改为 Win32 消息驱动 + 图像/OCR 登录,移除旧 selectors/client 模块。
This commit is contained in:
2026-11-26 09:28:32 +08:00
parent 4047990d53
commit a2774aa3a1
20 changed files with 5633 additions and 1129 deletions
@@ -1,82 +1,118 @@
# XQ0013 社保费用申报导出并汇总(插件版) # XQ0013 社保费用申报导出并汇总(插件版)
迁移自影刀工程(16 个流程,见 `docs/需求单/XQ0001-0100/XQ0013 社保费用申报导出并汇总/`)。 迁移自生产验证过的 Python 实现(`D:\SBKHD\py`,四川/湖南实测 115~212 秒/户),
目标:按月批量登录重庆社保客户端(`EPEvenue_SB.exe`),完成日常/特殊申报、申报记录导出,并合并汇总。 纯 Win32 消息驱动 + 影刀图像模板 + OCR。需求:按月批量登录重庆社保费管理客户端
(`EPEvenue_SB.exe`),完成日常申报、特殊申报、申报记录导出 PDF,并合并职工未申报明细、
汇总上下半月金额回写账户表副本。
## 当前进度(v0.1.0) > 重庆只有「日常申报 + 特殊申报」两步,**没有缴费工资申报**(那是成都/长沙的业务)。
| 能力 | 影刀来源 | 状态 | ## 当前进度(v0.3.0,全流程已迁移)
| 能力 | 对应模块 | 状态 |
|---|---|---| |---|---|---|
| 图像模板库(45 个) | `imagesV2.xml` + `resources/images/*.png` | ✅ 已导入 `images/`(含 `manifest.json`:threshold/gray/scales) | | 图像模板库(45 个) | `images/` + `manifest.json` | ✅ `logic/sbimg.py` |
| Win32 元素库(22 个) | `selectorsV2.xml` | ✅ 已导入 `selectors/selectors.xml`,`data/selectors.py` 用 FindWindowEx 逐层定位 | | Win32 UI 驱动(ctypes) | `logic/sbui.py` | ✅ 管理员自检 / 消息 / 坐标 / 剪贴板 |
| 账户列表读取/回写 | 自定义指令 `mjqywawyv` / `m8k8hi9j8` | ✅ `data/accounts.py` | | OCR(desktopauto RapidOCR) | `logic/sbocr.py` | ✅ 菜单/页面按文字定位 |
| 客户端启动 | process1 | ✅ `logic/client.start_client`(重试 3 次 + 等窗口) | | PrintWindow 位图 OCR | `logic/winprint.py` | ✅ 表格/弹窗正文(被遮挡也能抓) |
| 登录 | process2 | ✅ `logic/client.login`(元素填税号 → 滑块 → 图像点登录 → 输密码 → 等菜单栏) | | 账户列表读写(按表头名) | `data/accounts.py` | ✅ 执行状态≠1 待跑,逐户回写 |
| 弹窗清理 | process3 | ✅ `logic/client.clean_popups` | | 启动 / 添加单位 / 登录 / 清弹窗 | `logic/login.py` | ✅ |
| 添加单位 | process6 | ⏳ 未迁移(新账户首次登录会明确报错提示) | | 日常申报(导出/提交) | `logic/daily_declare.py` | ✅ 汇总 xls + 职工明细 xlsx |
| 日常申报导出 | process4 / 9 / 10 | ⏳ 未迁移 | | 特殊缴费申报(判定/导出/提交) | `logic/special_declare.py` | ✅ |
| 特殊申报导出 | process5 / 13 | ⏳ 未迁移 | | 申报记录 → PDF | `logic/records_export.py` | ✅ |
| 申报记录识别 | process8 | ⏳ 未迁移 | | 职工未申报明细合并(19 列去重) | `report/merge_detail.py` | ✅ |
| 征集信息导出 | process12 | ⏳ 未迁移 | | PDF 上下半月金额汇总 | `report/summarize_declare.py` | ✅ camelot + pymupdf |
| 明细合并(19 列去重) | merge | ⏳ 未迁移 | | 批量循环 + 状态回写 | `logic/batch.py` | ✅(run_one / status_of / mark) |
| PDF 金额汇总 | process14 | ⏳ 未迁移(依赖 camelot + pymupdf,影刀版也缺依赖) |
## 运行方式 ## 运行方式
插件界面选择 **执行模式 = check**:启动客户端 → 登录账户列表里第一家待执行门店 → 清弹窗 → 关闭。 插件界面选择 **执行模式**:
用于验证「客户端路径 / 元素库 / 模板」在当前机器是否可用,不会做任何申报动作。
`full` 模式目前会明确抛出「尚未迁移完成」,避免半成品误操作生产数据。 - `check`:只对第一家跑 启动 → 添加单位(幂等)→ 登录 → 清弹窗 → 关闭,验证环境;不做任何申报动作。
- `full`:逐户完整跑日常/特殊/申报记录,整批结束后合并明细 + 汇总金额。
**真实提交申报** 开关(`submit`)默认关闭:默认只导出不提交;开启后日常/特殊申报会真正向税局提交,不可撤销。
前提:执行机必须**以管理员身份运行**——客户端是 High 完整性进程,普通权限发消息会被 UIPI 拒绝
(插件不做 runas 自提权重启,否则会脱离执行机,非管理员直接报错)。
## 账户列表约定 ## 账户列表约定
`账户列表.xlsx`(默认 `输出目录/账户列表.xlsx`): `账户列表.xlsx`(默认 `输出目录/账户列表.xlsx`),**按表头名定位**,表头缺失时回退 A/B/C:
| 列 | 含义 | | 列名 | 含义 |
|---|---| |---|---|
| A | 门店 | | 门店 | 用于产物子目录与汇总匹配 |
| B | 税号 | | 税号 | 登录用统一社会信用代码/纳税人识别号 |
| C | 密码 | | 密码 | 登录密码(密码只来自账户表,不走命令行) |
| E | 执行标记:`0`=待执行,`1`=跳过;其他值(含空)跳过 | | 执行状态 | `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 社保费用申报导出并汇总/ XQ0013 社保费用申报导出并汇总/
├── __init__.py ScenePlugin 入口(mode=check/full) ├── __init__.py ScenePlugin 入口(check/full 编排)
├── plugin.json 元数据与参数表单 ├── plugin.json 元数据与参数表单(mode/submit/client_exe/save_dir/account_file)
├── config/__init__.py 路径常量、模板名/元素名、manifest 参数读取、日志钩子 ├── config/__init__.py 目录/客户端路径/日志钩子/账户列名/模板 manifest
├── data/ ├── data/accounts.py 账户表按表头名读写
│ ├── accounts.py 账户列表读/写(A门店 B税号 C密码 E标记)
│ └── selectors.py 影刀 Win32 元素库解析与操作(查找/赋值/点击/截图/拖动)
├── logic/ ├── logic/
│ └── client.py 启动 / 登录 / 弹窗清理 / 关闭 │ ├── sbui.py Win32 UI 驱动(ctypes)
├── report/__init__.py 编排与汇总(待补) │ ├── 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 ├── images/ 45 个影刀模板 + manifest.json
├── selectors/selectors.xml 22 个 Win32 元素选择器 ├── selectors/selectors.xml 旧影刀元素库(保留资源,代码已不再使用)
├── _pack.py 打包到 dist-plugin/xq0013_v<版本>.zip ├── _pack.py 打包到 dist-plugin/xq0013_v<版本>.zip
└── requirements.txt └── requirements.txt
``` ```
## 依赖 ## 依赖
执行机需预装(`requirements.txt` 声明): `requirements.txt`:`pandas openpyxl pywin32 Pillow numpy pymupdf camelot-py`。
``` > **camelot / Ghostscript**:旧版 camelot(<2.0)解析 PDF 表格依赖系统安装 **Ghostscript**(`gs` 在 PATH);
pandas openpyxl pywin32 ddddocr > camelot 2.x 改用 pypdfium2 后端(本仓库 .venv 实测 2.0.0,无需 Ghostscript)。
``` > 执行机环境包若装的是旧版 camelot,请一并安装 Ghostscript,否则汇总步骤会失败。
以及仓库内桌面自动化库 `desktopauto`(**SDK 下发**,不从 PyPI 装): `desktopauto`(OCR / 图像匹配)**SDK 下发**,不从 PyPI 装:
`plugin.json` 已声明 `"requires": {"sdks": {"desktopauto": {"compat": "^0.5"}}}`。
不要再 `pip install -e` 预装或复制进插件包,否则 SDK 挂载会因同名包 fail-fast。
`plugin.json` 已声明 `"requires": {"sdks": {"desktopauto": {"compat": "^0.4"}}}`, ## 迁移注意(关键坑位)
执行机启动 / 登录 / 每 30 分钟按账号已授权插件的依赖自动下载并挂载。
> 不要再 `pip install -e <仓库>\libs\desktopauto` 预装进环境包,也不要复制进插件包: - 登录用 **Win32 控件**(税号框 `TITSEdit`、列表 `TVirtualStringTree`、密码框 `TXPFamerEditEx`),
> 环境包里若有同名包,SDK 挂载会因「SDK 包被环境包遮蔽」直接失败。 密码窗里的「纳税人识别号/名称」是自绘文字只能 OCR;密码要全角转半角。
- 左侧菜单是自绘无句柄,**坐标点击 + hover tooltip** 会互相打架:点完必须把鼠标挪到 (927,489)。
## 迁移注意 - 窗口刚被拉到前台时,**第一次点击常被"激活窗口"吃掉**,所以点菜单前先 `warm_up` 点顶栏空白。
- `PrintWindow` 在部分机器上失效(返回 ok 但位图全黑),因此页面/表格状态统一走屏幕 OCR。
- 影刀登录用的是 **Win32 元素**(税号框 / 滑动栏)而不是图像——老 Delphi 客户端没有 UIA 树, - 申报记录 PDF 写入不是原子的(先 17 字节再补全),必须等文件大小稳定才算保存完成。
但 Win32 控件层次完整,`FindWindowEx` 逐层找比图像稳,优先走 `data/selectors.py`。 - 申报记录页「查看」按钮是最后一列,需先把表格横向滚到最右(`WM_HSCROLL, SB_RIGHT`)再 OCR。
- 图像只用于「视觉判断」的位置:登录按钮、菜单栏、错误弹窗、申报页签等。
- 影刀 `process14`(PDF 汇总)在影刀里就缺 `camelot`/`pymupdf` 依赖,迁移时一并补。
@@ -1,21 +1,34 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""XQ0013 社保费用申报导出并汇总 插件入口(迁移自影刀工程 16 个流程)。 """XQ0013 社保费用申报导出并汇总 插件入口(已迁移全流程)。
当前进度(v0.1.0,分阶段迁移): 需求:重庆社保费管理客户端(EPPortal/EPEvenue_SB.exe)按账户列表批量
✅ 影刀 45 个图像模板 + 22 个 Win32 元素库已导入插件包(images/、selectors/) 登录 → 日常申报导出 → 特殊申报导出 → 申报记录导出 PDF
✅ 账户列表读取/回写(对应自定义指令 mjqywawyv / m8k8hi9j8) → 职工未申报明细合并 → PDF 上下半月金额汇总回写账户表副本。
✅ 客户端启动、登录(元素填税号 + 滑块 + 图像点登录 + OCR 判账户)、弹窗清理
⏳ 待迁移:日常申报导出(process4/9/10)、特殊申报导出(process5/13)、申报记录识别(process8)、
征集信息导出(process12)、添加单位(process6)、明细合并(merge)、PDF 金额汇总(process14)
因此 run() 目前只提供 `check` 模式(启动 → 登录第一家有账户 → 清弹窗 → 关闭), 重庆只有「日常申报 + 特殊申报」两步,**没有缴费工资申报**(那是成都/长沙的业务)。
用于验证客户端路径、元素库、模板在当前机器上是否可用;`full` 模式会明确提示未完成。
执行模式:
check 只对第一家跑 启动 → add_unit(幂等)→ 登录 → settle → 关闭,验证环境
full 逐户完整跑,最后合并明细 + 汇总金额
前提:执行机必须**以管理员身份运行**(客户端是 High 完整性进程,普通权限发消息被 UIPI 拒绝)。
本插件不做 runas 自提权重启(会脱离执行机),非管理员直接报错。
""" """
import time
import traceback
from webhost.backend.plugins.base import ScenePlugin, PLUGINS from webhost.backend.plugins.base import ScenePlugin, PLUGINS
from . import config from . import config
from .data import accounts from .data import accounts
from .logic import client 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): class SocialDeclarePlugin(ScenePlugin):
@@ -23,10 +36,9 @@ class SocialDeclarePlugin(ScenePlugin):
id = "xq0013" id = "xq0013"
name = "社保费用申报导出并汇总" name = "社保费用申报导出并汇总"
version = "0.1.1" version = "0.3.0"
description = ("按月批量登录重庆社保客户端完成日常/特殊申报与记录导出并汇总。" description = ("按月批量登录重庆社保客户端,完成日常申报/特殊申报导出、"
"当前版本已迁移:账户列表读写、客户端启动、登录(Win32 元素+图像+OCR)、弹窗清理;" "申报记录导出 PDF,并合并职工未申报明细、汇总上下半月金额。")
"申报导出与汇总流程待迁移,run 请使用 check 模式验证环境。")
platform = "" # 客户端本地登录,不依赖底座平台登录态 platform = "" # 客户端本地登录,不依赖底座平台登录态
uses_month = False uses_month = False
capabilities = ["xq0013"] capabilities = ["xq0013"]
@@ -35,25 +47,30 @@ class SocialDeclarePlugin(ScenePlugin):
"mode": { "mode": {
"type": "string", "title": "执行模式", "default": "check", "type": "string", "title": "执行模式", "default": "check",
"enum": ["check", "full"], "enum": ["check", "full"],
"description": "check=只验证环境(启动→登录第一家有账户→清弹窗→关闭);" "description": "check=只验证环境(启动→登录第一家→清弹窗→关闭);"
"full=完整批量申报(申报导出流程尚未迁移,会提示未完成)", "full=逐户完整申报导出 + 合并明细 + 金额汇总",
},
"submit": {
"type": "boolean", "title": "真实提交申报", "default": False,
"description": "默认只导出不提交(演练);开启后日常/特殊申报会真正向税局提交,不可撤销",
}, },
"client_exe": { "client_exe": {
"type": "string", "title": "社保客户端程序", "type": "string", "title": "社保客户端程序",
"default": r"D:\Program Files (x86)\EPPortal_SB1.0\EPEvenue_SB.exe", "default": r"D:\Program Files (x86)\EPPortal_SB1.0\EPEvenue_SB.exe",
"description": "EPEvenue_SB.exe 的完整路径", "description": "EPEvenue_SB.exe 的完整路径(其所在目录即客户端安装目录)",
}, },
"save_dir": { "save_dir": {
"type": "string", "title": "输出目录", "type": "string", "title": "输出目录",
"default": r"D:\资料\人资\社保费用申报导出汇总", "default": r"D:\资料\人资\社保费用申报导出汇总",
"description": "账户列表、申报结果、职工未申报明细、截图等统一根目录", "description": "账户列表、申报结果、职工未申报明细、汇总结果、截图等统一根目录",
}, },
"account_file": { "account_file": {
"type": "string", "title": "账户列表文件", "default": "", "type": "string", "title": "账户列表文件", "default": "",
"description": "留空 = 输出目录/账户列表.xlsx(A门店 B税号 C密码 E执行标记:0待执行/1跳过)", "description": "留空 = 输出目录/账户列表.xlsx(按表头名读:门店/税号/密码/执行状态/日常申报状态/特殊申报状态/申报记录)",
}, },
} }
# ---------------------------------------------------------------- 入口
def run(self, fields: dict, ctx): def run(self, fields: dict, ctx):
config.set_log(ctx.log) config.set_log(ctx.log)
config.configure( config.configure(
@@ -62,49 +79,141 @@ class SocialDeclarePlugin(ScenePlugin):
account_file=fields.get("account_file") or "", account_file=fields.get("account_file") or "",
) )
mode = (fields.get("mode") or "check").strip().lower() 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() dirs = config.ensure_dirs()
ctx.progress(2) ctx.progress(2)
ctx.log(f"===== 社保费用申报({mode}):输出目录 {dirs['base']} =====", "INFO") 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() acct_file = config.account_file()
accts = accounts.load_accounts(acct_file) sheet = accounts.AccountSheet(acct_file)
ctx.progress(8) 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 == "full": if mode == "check":
raise RuntimeError( return self._run_check(todo[0], acct_file, dirs, ctx)
"完整申报流程尚未迁移完成(日常/特殊申报导出、申报记录识别、合并与汇总)。\n" return self._run_full(todo, sheet, acct_file, submit, dirs, ctx)
"请先用「执行模式 = 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: finally:
client.close_client() sbui.keep_awake(False)
ctx.progress(100)
return { # ---------------------------------------------------------------- check
"summary": summary, def _run_check(self, acct, acct_file, dirs, ctx):
"detail": { store = acct["store"]
"模式": mode, ctx.log("验证门店:%s(税号 %s)" % (store, acct["tax_no"]), "INFO")
"验证门店": acct["store"], detail = {"模式": "check", "账户列表": acct_file, "验证门店": store}
"待执行账户数": len(accts), try:
"账户列表": acct_file, login.restart_client()
"元素库元素数": 22, ctx.progress(35)
"模板数": len(config.manifest()), try:
}, login.add_unit(acct["tax_no"], acct["password"])
"path": dirs["base"], 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()) PLUGINS.append(SocialDeclarePlugin())
@@ -2,11 +2,10 @@
"""XQ0013 插件离线自测(不启动客户端、不点鼠标、不碰真实账户)。 """XQ0013 插件离线自测(不启动客户端、不点鼠标、不碰真实账户)。
覆盖: 覆盖:
1. 配置默认值与路径推导(输出目录/账户列表/子目录) 1. 配置默认值与路径推导(client_dir/run_dir/各输出子目录)
2. 图像模板清单(images/manifest.json)与文件存在性 2. 图像模板清单(images/manifest.json)与文件存在性
3. Win32 元素库(selectors/selectors.xml)可解析、元素数正确 3. 账户列表按表头名读写(执行状态≠1 待跑;表头缺失回退 A/B/C;回写落盘)
4. 账户列表读取规则(E 列 0 待执行 / 1 跳过 / 空跳过;缺列与空值报错) 4. 插件入口注册(需要 webhost 运行时;缺失时 skip 不误报)
5. 插件入口注册(需要 webhost 运行时;缺失时 skip 不误报)
由 SDK 兼容预检调用(会挂上 webhost 与各 SDK 路径);也可手工: 由 SDK 兼容预检调用(会挂上 webhost 与各 SDK 路径);也可手工:
set PYTHONPATH=desktop\\electron-shell\\python;libs\\desktopauto set PYTHONPATH=desktop\\electron-shell\\python;libs\\desktopauto
@@ -37,12 +36,13 @@ def skip(msg: str) -> None:
SKIPS.append(msg) 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 from openpyxl import Workbook # noqa: PLC0415
wb = Workbook() wb = Workbook()
ws = wb.active ws = wb.active
ws.append(["门店", "税号", "密码", "备注", "执行标记"]) ws.append(header or ["门店", "税号", "密码", "执行状态",
"日常申报状态", "特殊申报状态", "申报记录"])
for r in rows: for r in rows:
ws.append(r) ws.append(r)
wb.save(path) 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", config.configure(client_exe=r"C:\tmp\EPEvenue_SB.exe", save_dir=r"C:\tmp\out",
account_file=r"C:\tmp\accts.xlsx") account_file=r"C:\tmp\accts.xlsx")
ok(config.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"}, ok(set(config.dirs()) >= {"base", "screenshots", "declare", "detail", "summary"},
"输出子目录齐全") "输出子目录齐全")
config.configure("", "", "") config.configure("", "", "")
@@ -92,66 +98,55 @@ def main() -> int:
print("== 图像模板 ==") print("== 图像模板 ==")
man = config.manifest() man = config.manifest()
ok(len(man) >= 40, f"manifest 模板数 {len(man)}(≥40)") 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))] missing = [k for k, v in man.items()
ok(not missing, f"TPL 声明的模板文件都存在(缺失 {len(missing)})") if not os.path.isfile(os.path.join(config.IMAGES_DIR, v.get("file") or ""))]
opt = config.image_opt("login_btn") ok(not missing, f"manifest 声明的模板文件都存在(缺失 {len(missing)})")
ok(bool(opt["path"]) and 0.5 <= float(opt["threshold"]) <= 1.0,
f"登录按钮匹配参数 threshold={opt['threshold']}")
if pkg is None: if pkg is None:
print(f"\n失败 {len(FAILS)} 项,跳过 {len(SKIPS)} 项") print(f"\n失败 {len(FAILS)} 项,跳过 {len(SKIPS)} 项")
return 0 if not FAILS else 1 return 0 if not FAILS else 1
# ---------- 3. Win32 元素库 ---------- # ---------- 3. 账户列表 ----------
print("== Win32 元素库 ==") print("== 账户列表按表头名读写 ==")
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("== 账户列表读取 ==")
accounts = sub("data.accounts") accounts = sub("data.accounts")
with tempfile.TemporaryDirectory() as tmp: with tempfile.TemporaryDirectory() as tmp:
f = os.path.join(tmp, "账户列表.xlsx") f = os.path.join(tmp, "账户列表.xlsx")
_write_accounts_xlsx(f, [ _write_accounts_xlsx(f, [
["A店", "91500A", "pwdA", "", "0"], ["A店", "91500A", "pwdA", "0", "", "", ""],
["B店", "91500B", "pwdB", "", "1"], ["B店", "91500B", "pwdB", "1", "已导出", "无需申报", "已导出"],
["C店", "91500C", "pwdC", "", ""], ["C店", "91500C", "pwdC", "", "", "", ""],
]) ])
rows = accounts.load_accounts(f) sheet = accounts.AccountSheet(f)
ok(len(rows) == 1 and rows[0]["store"] == "A店" and rows[0]["row"] == 2, rows = sheet.accounts()
"只返回 E=0 的账户(A店,Excel 第 2 行)") 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") sheet.set(2, "日常申报状态", "已导出")
_write_accounts_xlsx(f2, [["D店", "91500D", "pwdD", "", "1"]]) sheet.set(2, "执行状态", config.STATE_DONE)
try: sheet.save()
accounts.load_accounts(f2) sheet2 = accounts.AccountSheet(f)
ok(False, "无待执行账户应报错") rows2 = sheet2.accounts()
except RuntimeError as e: ok(len(rows2) == 1 and rows2[0]["store"] == "C店", "回写后 A店 不再待跑")
ok("没有待执行账户" in str(e), "无待执行账户 → 明确报错") ok(sheet2.ws.cell(row=2, column=5).value == "已导出", "回写落盘成功")
f3 = os.path.join(tmp, "缺列.xlsx") # 表头缺失 → 回退 A/B/C
from openpyxl import Workbook # noqa: PLC0415 f2 = os.path.join(tmp, "无表头.xlsx")
wb = Workbook() _write_accounts_xlsx(f2, [["D店", "91500D", "pwdD"]], header=["x", "y", "z"])
wb.active.append(["门店", "税号"]) rows3 = accounts.AccountSheet(f2).accounts()
wb.save(f3) ok(len(rows3) == 1 and rows3[0]["store"] == "D店" and rows3[0]["tax_no"] == "91500D",
try: "表头缺失时回退 A门店/B税号/C密码")
accounts.load_accounts(f3)
ok(False, "列数不足应报错")
except RuntimeError as e:
ok("列数不完整" in str(e), "列数不足 → 明确报错")
# ---------- 5. 插件入口 ---------- # ---------- 4. 插件入口 ----------
print("== 插件入口 ==") print("== 插件入口 ==")
plugin = getattr(pkg, "SocialDeclarePlugin", None) plugin = getattr(pkg, "SocialDeclarePlugin", None)
ok(plugin is not None, "插件类存在") ok(plugin is not None, "插件类存在")
if plugin is not None: if plugin is not None:
ok(plugin.id == "xq0013", "插件 id = xq0013") ok(plugin.id == "xq0013", "插件 id = xq0013")
ok(plugin.version == "0.3.0", "插件 version = 0.3.0")
fields = plugin.fields or {} fields = plugin.fields or {}
ok(set(fields) >= {"mode", "client_exe", "save_dir", "account_file"}, ok(set(fields) >= {"mode", "submit", "client_exe", "save_dir", "account_file"},
"fields 声明完整(mode/client_exe/save_dir/account_file)") "fields 声明完整(mode/submit/client_exe/save_dir/account_file)")
ok(callable(getattr(plugin, "run", None)), "run 可调用") ok(callable(getattr(plugin, "run", None)), "run 可调用")
print(f"\n失败 {len(FAILS)} 项" + (f",跳过 {len(SKIPS)} 项" if SKIPS else "")) print(f"\n失败 {len(FAILS)} 项" + (f",跳过 {len(SKIPS)} 项" if SKIPS else ""))
@@ -1,97 +1,54 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""XQ0013 社保费用申报导出并汇总 插件 - 配置常量与全局钩子。 """XQ0013 社保费用申报导出并汇总 插件 - 配置常量与全局钩子。
插件自包含:只依赖 标准库 / pandas / openpyxl / pywin32 / ddddocr / desktopauto(SDK 下发,见 plugin.json.requires.sdks)。 插件自包含:只依赖 标准库 / 第三方(pandas、openpyxl、pywin32、Pillow、numpy、pymupdf、camelot)
模板图与 Win32 元素库随插件包发布: / desktopauto(SDK 下发,见 plugin.json.requires.sdks)/ webhost.backend.plugins.base。
images/*.png + images/manifest.json 影刀图像库导出(45 个) 模板图随插件包发布:images/*.png + images/manifest.json(影刀图像库导出,供 logic/sbimg.py 用)。
selectors/selectors.xml 影刀 Win32 元素库(22 个)
运行期参数(客户端路径、账户列表路径、输出目录)由 plugin.json.fields 注入, 运行期参数(客户端路径、账户列表路径、输出目录)由 plugin.json.fields 注入,
经 configure() 覆盖默认值;未注入时用下面的默认常量(与影刀版一致)。 经 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 json
import os import os
import time
# ==================== 插件内资源路径 ==================== # ==================== 插件内资源路径 ====================
PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) PLUGIN_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
IMAGES_DIR = os.path.join(PLUGIN_ROOT, "images") IMAGES_DIR = os.path.join(PLUGIN_ROOT, "images")
MANIFEST_FILE = os.path.join(IMAGES_DIR, "manifest.json") 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" 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:\资料\人资\社保费用申报导出汇总" DEFAULT_SAVE_DIR = r"D:\资料\人资\社保费用申报导出汇总"
ACCOUNT_FILE_NAME = "账户列表.xlsx" ACCOUNT_FILE_NAME = "账户列表.xlsx"
# 账户列表列约定(影刀版:A=门店 B=税号 C=密码 E=执行标记) # 输出子目录名
COL_STORE = 0 DIR_DECLARE = "申报结果"
COL_TAX_NO = 1 DIR_DETAIL = "职工未申报明细"
COL_PASSWORD = 2 DIR_SUMMARY = "汇总结果"
COL_FLAG = 4 DIR_SHOTS = "截图"
FLAG_PENDING = "0" # E 列 = 0 → 待执行 RUN_DIR_NAME = "_run"
FLAG_DONE = "1" # E 列 = 1 → 已完成/跳过 MERGED_NAME = "职工未申报明细合并结果.xlsx"
# ==================== 模板名(images/manifest.json 的 key) ==================== # ==================== 账户列表列名(按表头名读写;缺失时回退 A/B/C) ====================
TPL = { COL_STORE = "门店"
"image": "图像", COL_TAX_NO = "税号"
"login_btn": "登录按钮", COL_PASSWORD = "密码"
"login_confirm": "确定登录按钮", COL_STATE = "执行状态"
"menu_bar": "菜单栏", COL_DAILY = "日常申报状态"
"error_msg": "错误信息", COL_SPECIAL = "特殊申报状态"
"error_confirm": "错误处理确认", COL_RECORD = "申报记录"
"social_declare": "社保费申报", STATE_DONE = "1" # 执行状态 = 1 → 已完成,默认跳过
"daily_declare": "日常申报", STATE_PENDING = "0" # 执行状态 = 0(或空)→ 待执行
"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 注入) ==================== # ==================== 运行期配置(configure 注入) ====================
_client_exe = DEFAULT_CLIENT_EXE _client_exe = DEFAULT_CLIENT_EXE
@@ -99,7 +56,7 @@ _save_dir = DEFAULT_SAVE_DIR
_account_file = "" _account_file = ""
def configure(client_exe: str = "", save_dir: str = "", account_file: str = "") -> None: def configure(client_exe="", save_dir="", account_file="") -> None:
"""由插件 run() 注入本次运行的业务配置(空值保持默认)。""" """由插件 run() 注入本次运行的业务配置(空值保持默认)。"""
global _client_exe, _save_dir, _account_file global _client_exe, _save_dir, _account_file
if (client_exe or "").strip(): if (client_exe or "").strip():
@@ -113,6 +70,11 @@ def client_exe() -> str:
return _client_exe return _client_exe
def client_dir() -> str:
"""客户端安装目录(EPEvenue_SB.exe 所在),由客户端程序路径推导,不写死区域目录。"""
return os.path.dirname(os.path.abspath(_client_exe))
def save_dir() -> str: def save_dir() -> str:
return _save_dir return _save_dir
@@ -122,31 +84,75 @@ def account_file() -> str:
return _account_file or os.path.join(_save_dir, ACCOUNT_FILE_NAME) 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: def dirs() -> dict:
"""各输出子目录(按需创建)。""" """各输出子目录(尚未创建)。"""
base = _save_dir base = _save_dir
return { return {
"base": base, "base": base,
"screenshots": os.path.join(base, "截图"), "screenshots": os.path.join(base, DIR_SHOTS),
"declare": os.path.join(base, "申报结果"), "declare": os.path.join(base, DIR_DECLARE),
"detail": os.path.join(base, "职工未申报明细"), "detail": os.path.join(base, DIR_DETAIL),
"summary": os.path.join(base, "汇总"), "summary": os.path.join(base, DIR_SUMMARY),
} }
def ensure_dirs() -> dict: def ensure_dirs() -> dict:
d = dirs() d = dirs()
os.makedirs(d["base"], exist_ok=True)
for key, path in d.items(): for key, path in d.items():
if key != "base": if key != "base":
os.makedirs(path, exist_ok=True) os.makedirs(path, exist_ok=True)
os.makedirs(d["base"], exist_ok=True) os.makedirs(run_dir(), exist_ok=True)
return d return d
def template_path(name_key: str) -> str: def run_dir() -> str:
"""按 TPL 的 key 取模板图绝对路径(配合 manifest 里的阈值使用)。""" """运行状态/日志目录 = save_dir/_run(自动创建)。"""
name = TPL.get(name_key, name_key) p = os.path.join(_save_dir, RUN_DIR_NAME)
return os.path.join(IMAGES_DIR, f"{name}.png") 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 里的 threshold/gray/scales) ====================
@@ -165,20 +171,9 @@ def manifest() -> dict:
return _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) ==================== # ==================== 日志钩子(run 时注入 ctx.log) ====================
_log = None _log = None
_log_file = None
def set_log(fn) -> None: def set_log(fn) -> None:
@@ -186,11 +181,27 @@ def set_log(fn) -> None:
_log = fn _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: def log(msg, level="INFO") -> None:
"""统一日志出口:转发 ctx.log(run 时注入),同时落一份文件到 run_dir()。"""
if _log: if _log:
try:
_log(str(msg), level) _log(str(msg), level)
except TypeError:
_log(str(msg))
else: else:
print(f"[{level}] {msg}") print("[%s] %s" % (level, msg))
_write_log_file(msg, level)
class _ModuleLogger: class _ModuleLogger:
@@ -1,123 +1,135 @@
# -*- coding: utf-8 -*- # -*- coding: utf-8 -*-
"""账户列表读写(对应影刀自定义指令 mjqywawyv「读取账户列表」与 m8k8hi9j8「按门店+列名写单元格」)。 """账户列表读写(**按表头名**定位,不再写死 A/B/C/E 列)。
账户列表.xlsx 约定(与影刀版一致): 账户列表.xlsx 约定(列按表头名找;表头缺失时回退 A/B/C):
A列=门店 B列=税号 C列=密码 E列=执行标记(0=待执行,1=已完成/跳过) 门店 | 税号 | 密码 | 执行状态 | 日常申报状态 | 特殊申报状态 | 申报记录 | ...
只处理 E 列为 "0" 的行;E 列既非 0 也非 1(含空)→ 跳过。 - 执行状态 = "1" → 已完成,默认跳过;= "0"(或空)→ 待执行
- 每户跑完立刻回写并保存(中断可续跑)
对外:
sheet = AccountSheet(path)
accounts = sheet.accounts(redo=False) # 待执行门店
sheet.set(row, "日常申报状态", "已导出")
sheet.save()
用 openpyxl 直接读写(不用 pandas),这样"写一列不改格式"更可控,也少一个读表依赖。
""" """
from __future__ import annotations from __future__ import annotations
import os import os
from typing import List
import pandas as pd import openpyxl
from ..config import ( from ..config import (
COL_FLAG, COL_PASSWORD, COL_STORE, COL_TAX_NO, FLAG_DONE, FLAG_PENDING, logger, COL_DAILY, COL_PASSWORD, COL_RECORD, COL_SPECIAL, COL_STATE, COL_STORE, COL_TAX_NO,
STATE_DONE, log,
) )
def _is_empty(val) -> bool: def _text(v) -> str:
if pd.isna(val): """单元格值转干净文本:整数型 float 去掉 .0,其余 strip。"""
return True if v is None:
return str(val).strip() == "" return ""
if isinstance(v, bool):
return str(v)
if isinstance(v, float) and v.is_integer():
v = int(v)
return str(v).strip()
def load_accounts(file_path: str) -> List[dict]: class AccountSheet(object):
"""读取账户列表,返回待执行账户 [{"store","tax_no","password","row"}]。 """账户表封装:按表头名读写单元格。"""
数据不一致(E列=0 但门店/税号/密码为空)直接报错,避免跑错账户。 def __init__(self, path):
""" if not os.path.isfile(path):
if not os.path.isfile(file_path): raise RuntimeError("未找到账户列表:%s" % path)
raise RuntimeError(f"未找到账户列表:{file_path}")
try: try:
df = pd.read_excel(file_path, engine="openpyxl", dtype=str) self.wb = openpyxl.load_workbook(path)
except PermissionError as e: except PermissionError as e:
raise RuntimeError(f"账户列表被占用,请先关闭 Excel:{file_path}") from e raise RuntimeError("账户列表被占用,请先关闭 Excel:%s" % path) from e
except Exception as e: # noqa: BLE001 except Exception as e: # noqa: BLE001
raise RuntimeError(f"读取账户列表失败:{file_path}({e})") from e 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()
if len(df.columns) <= COL_FLAG: # ---------------------------------------------------------------- 列定位
raise RuntimeError( def _resolve_columns(self):
f"账户列表列数不完整:需要至少 {COL_FLAG + 1} 列(A门店/B税号/C密码/E执行标记)," """按表头名定位;门店/税号/密码缺失时回退 A/B/C。"""
f"当前 {len(df.columns)} 列") def find(name, fallback=None):
for i, h in enumerate(self.header):
if h == name:
return i + 1
return fallback
out: List[dict] = [] return {
for idx, row in df.iterrows(): "store": find(COL_STORE, 1),
flag = "" if pd.isna(row.iloc[COL_FLAG]) else str(row.iloc[COL_FLAG]).strip() "tax_no": find(COL_TAX_NO, 2),
if flag == FLAG_DONE: "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 continue
if flag != FLAG_PENDING: state = self._cell(row, "state")
continue # 非 0/1 一律跳过(含空值与历史脏数据) if state == STATE_DONE and not redo:
store = str(row.iloc[COL_STORE]).strip() if not _is_empty(row.iloc[COL_STORE]) else "" continue
tax_no = str(row.iloc[COL_TAX_NO]).strip() if not _is_empty(row.iloc[COL_TAX_NO]) else "" store = self._cell(row, "store") or tax_no
password = str(row.iloc[COL_PASSWORD]).strip() if not _is_empty(row.iloc[COL_PASSWORD]) else "" out.append({
excel_row = idx + 2 # 表头占 1 行 "store": store,
if not (store and tax_no and password): "tax_no": tax_no,
raise RuntimeError( "password": self._cell(row, "password"),
f"账户列表第 {excel_row} 行 E 列标记为待执行,但门店/税号/密码存在空值") "row": row,
out.append({"store": store, "tax_no": tax_no, "password": password, "row": excel_row}) "state": state,
"daily": self._cell(row, "daily"),
if not out: "special": self._cell(row, "special"),
raise RuntimeError(f"账户列表筛选后没有待执行账户(E 列没有值为 {FLAG_PENDING} 的行):{file_path}") "record": self._cell(row, "record"),
logger.info("账户列表读取完成:待执行 %d 家门店", len(out)) })
log("账户列表读取完成:待执行 %d 家门店(共 %d 行)"
% (len(out), max(0, self.ws.max_row - 1)))
return out 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 update_cell(file_path: str, store: str, column_name: str, content) -> None: def set(self, row, column_name, value):
"""按门店(A列)与列名(表头)写入单元格;列或行不存在则自动新增(影刀同款行为)。""" """写一个单元格(列不存在则自动新增表头列)。"""
from openpyxl import Workbook, load_workbook # 延迟导入,减少不用时的开销 self.ws.cell(row=row, column=self._col_of(column_name), value=value)
if not column_name or not store: def save(self):
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: try:
wb.save(file_path) self.wb.save(self.path)
except PermissionError as e: except PermissionError as e:
raise RuntimeError(f"账户列表被占用,无法写入,请先关闭 Excel:{file_path}") from e raise RuntimeError("账户列表被占用,无法写入,请先关闭 Excel:%s" % self.path) from e
logger.info("已回写账户列表:%s | %s = %s", store, column_name, content)
def mark_done(file_path: str, store: str, column_name: str = "执行状态") -> None: def open_sheet(path):
"""标记门店执行完成(默认写「执行状态」列=1)。""" """便捷入口:返回 AccountSheet(语义同构造)。"""
update_cell(file_path, store, column_name, FLAG_DONE) return AccountSheet(path)
def mark_failed(file_path: str, store: str, reason: str, column_name: str = "失败原因") -> None:
"""记录失败原因(不写执行状态,便于人工重跑)。"""
update_cell(file_path, store, column_name, reason)
@@ -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)
@@ -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
@@ -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)
@@ -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}
@@ -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 '导出未成功'}
@@ -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
@@ -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))
File diff suppressed because it is too large Load Diff
@@ -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
@@ -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
@@ -2,8 +2,8 @@
"schema_version": 1, "schema_version": 1,
"id": "xq0013", "id": "xq0013",
"name": "社保费用申报导出并汇总", "name": "社保费用申报导出并汇总",
"version": "0.1.2", "version": "0.3.0",
"description": "按月批量登录重庆社保客户端完成日常/特殊申报与申报记录导出并汇总。当前版本已迁移:账户列表读写、客户端启动、登录(Win32 元素+图像+OCR 验证)、弹窗清理;申报导出与汇总流程待迁移。", "description": "按月批量登录重庆社保客户端,完成日常申报/特殊申报导出、申报记录导出 PDF,并合并职工未申报明细、汇总上下半月金额回写账户表副本。已迁移全流程(Win32 消息驱动 + 影刀模板 + OCR,无缴费工资申报步骤)。",
"category": "社保公积金", "category": "社保公积金",
"icon": "", "icon": "",
"platform": "", "platform": "",
@@ -28,25 +28,31 @@
"title": "执行模式", "title": "执行模式",
"default": "check", "default": "check",
"enum": ["check", "full"], "enum": ["check", "full"],
"description": "check=只验证环境(启动→登录第一家有账户→清弹窗→关闭);full=完整批量申报(尚未迁移完成)" "description": "check=只验证环境(启动→添加单位→登录第一家→清弹窗→关闭);full=逐户完整申报导出 + 合并明细 + 金额汇总"
},
"submit": {
"type": "boolean",
"title": "真实提交申报",
"default": false,
"description": "默认只导出不提交(演练);开启后日常/特殊申报会真正向税局提交,不可撤销"
}, },
"client_exe": { "client_exe": {
"type": "string", "type": "string",
"title": "社保客户端程序", "title": "社保客户端程序",
"default": "D:\\Program Files (x86)\\EPPortal_SB1.0\\EPEvenue_SB.exe", "default": "D:\\Program Files (x86)\\EPPortal_SB1.0\\EPEvenue_SB.exe",
"description": "EPEvenue_SB.exe 的完整路径" "description": "EPEvenue_SB.exe 的完整路径(其所在目录即客户端安装目录)"
}, },
"save_dir": { "save_dir": {
"type": "string", "type": "string",
"title": "输出目录", "title": "输出目录",
"default": "D:\\资料\\人资\\社保费用申报导出汇总", "default": "D:\\资料\\人资\\社保费用申报导出汇总",
"description": "账户列表、申报结果、职工未申报明细、截图等统一根目录" "description": "账户列表、申报结果、职工未申报明细、汇总结果、截图等统一根目录"
}, },
"account_file": { "account_file": {
"type": "string", "type": "string",
"title": "账户列表文件", "title": "账户列表文件",
"default": "", "default": "",
"description": "留空 = 输出目录/账户列表.xlsx(A门店 B税号 C密码 E执行标记:0待执行/1跳过)" "description": "留空 = 输出目录/账户列表.xlsx(按表头名读:门店/税号/密码/执行状态/日常申报状态/特殊申报状态/申报记录)"
} }
}, },
"required": [] "required": []
@@ -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
@@ -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
@@ -1,7 +1,11 @@
pandas>=2.0 pandas>=2.0
openpyxl>=3.1 openpyxl>=3.1
pywin32>=306 pywin32>=306
# desktopauto 由 SDK 下发(plugin.json.requires.sdks 已声明 ^0.4),不从 PyPI 装、 Pillow>=10.0
# 也不要再 pip install -e 预装进环境包:同名包会让 SDK 挂载失败。 numpy>=1.24
# 验证码识别(后续 process6/登录兜底用) # 申报记录 PDF 解析(受理日期)
ddddocr>=1.5 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。