Files
37duAutomation/plugins/XQ0001-0100/XQ0013 社保费用申报导出并汇总/logic/client.py
T

237 lines
9.8 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- 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)