feat(xq0002): 新增钉钉群通知推送功能,优化雇主险增减操作流程

This commit is contained in:
2026-10-05 09:42:56 +08:00
parent 26d4125798
commit 41bcb44e34
83 changed files with 11419 additions and 180 deletions
+713
View File
@@ -0,0 +1,713 @@
# -*- coding: utf-8 -*-
"""重庆社保系统增减员办理(增员/减员系统导入)—— import_add.py / import_stop.py 移植。
统一引擎 ImportEngine(kind):
- kind='add':城保参保单位人员增加,消费《新参保-增员》目录《XX增员导入名单.xls》,
回写「办理状态」列(参保失败),审核结论回写「办理状态」
- kind='stop':城保参保单位人员减少,消费《停保-减员》目录《XX减员导入名单.xls》,
回写「办理停保」列(停保失败),审核结论回写「办理停保」
流程(每参保单位):
登录(web_login,法人用户+图形验证码)→ 进业务页 → 上传导入 → 校验未通过回写 →
预申报 → 去申报 → 全部提交 → 下一步 → 提交 → 去查看 → 明细审核结论回写 →
下个单位前清 cookies 关浏览器。回写 JSON 缓存防崩溃,运行结束统一写 Excel。
"""
import os
import re
import time
from datetime import datetime
from .. import config
from ..data import source_reader
from ..data.writeback import Writeback
from . import web_login
# ==================== 通用网页操作(增/减共用) ====================
WEB_TIMEOUT = 20 # 网页元素等待超时(秒)
def _shot(tab, name):
"""调试截图:仅调试模式开启时保存页面截图并打印当前 URL。"""
if not config.is_debug():
return
try:
from pathlib import Path
d = Path(config.CKPT_DIR) / "debug_shots"
d.mkdir(parents=True, exist_ok=True)
ts = datetime.now().strftime("%H%M%S")
tab.get_screenshot(path=str(d), name=f"{ts}_{name}.png")
config.log(f" [截图] {ts}_{name}.png url={str(tab.url)[:90]}")
except Exception as e:
config.log(f" [截图失败] {name}: {e}")
def _click_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
"""按候选选择器顺序定位并点击第一个命中元素,全部未命中抛异常。"""
last_err = None
for sel in selectors:
try:
ele = tab.ele(sel, timeout=timeout)
except Exception as e:
last_err = e
continue
if ele:
ele.click()
return ele
raise RuntimeError(f"网页操作失败:找不到{desc}({last_err})")
def _find_any(tab, selectors, desc, timeout=WEB_TIMEOUT):
"""按候选选择器顺序查找元素,全部未命中抛异常。"""
for sel in selectors:
ele = tab.ele(sel, timeout=timeout)
if ele:
return ele
raise RuntimeError(f"网页操作失败:找不到{desc}")
def _wait_modal(tab, keyword, timeout=60):
"""等待某 ant-modal 弹窗正文出现指定关键字,返回该弹窗元素;超时返回 None。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
for m in tab.eles('css:.ant-modal-body'):
if keyword in (m.text or ''):
return m
except Exception:
pass
time.sleep(0.5)
return None
def _dismiss_popups(tab, rounds=5):
"""循环关闭常见提示弹窗(我已知晓/我知道了/确定/同意),直到没有可关的。"""
texts = ["我已知晓", "我知道了", "知道了", "确 定", "确定", "同 意", "同意"]
for _ in range(rounds):
hit = False
for t in texts:
try:
btn = tab.ele(f'tag:button@@text()={t}', timeout=0.5)
except Exception:
btn = None
if btn:
try:
btn.click()
config.log(f" 关闭弹窗:{t}")
hit = True
time.sleep(1.2)
except Exception:
pass
if not hit:
break
def _open_business_page(page, work_tab, business_item):
"""工作台 → 单位办事 → 业务「在线办理」。返回承载业务页的 tab。"""
before = set(page.tab_ids)
_click_any(work_tab, ['tag:button@@text()=单位办事'], '「单位办事」菜单')
time.sleep(2.5)
h4 = _find_any(work_tab, [f'tag:h4@@text()={business_item}'], f'业务入口「{business_item}」')
li = h4
for _ in range(6):
li = li.parent()
if li is None:
break
if li.tag == 'li':
break
act = li.ele('text=在线办理', timeout=3) if li is not None else None
if act is None:
raise RuntimeError("网页操作失败:找不到「在线办理」按钮")
act.click()
deadline = time.time() + 30
while time.time() < deadline:
time.sleep(1)
cand_tids = [i for i in page.tab_ids if i not in before] + [work_tab.tab_id]
for tid in cand_tids:
try:
t = page.get_tab(tid)
if t.ele('#customized_form_controls_data', timeout=0.5):
return t
except Exception:
continue
raise RuntimeError("进入在线办理页失败(未出现文件上传控件)")
# ==================== 减员特有:提示信息弹窗 ====================
def _title_is_tip(m):
"""弹窗标题是否含「提示信息」。"""
try:
t = m.ele('css:.ant-modal-title', timeout=0.2)
return bool(t and '提示信息' in (t.text or ''))
except Exception:
return False
def _find_tip_modal_by_title(tab):
"""按标题「提示信息」定位弹窗:一次查询所有标题元素再上溯到 .ant-modal。"""
try:
for t in tab.eles('css:.ant-modal-title'):
if '提示信息' not in (t.text or ''):
continue
p = t
for _ in range(4):
p = p.parent()
if p is None:
break
cls = p.attr('class') or ''
if 'ant-modal' in cls and 'ant-modal-content' not in cls \
and 'ant-modal-header' not in cls:
return p
except Exception:
pass
return None
def _remove_tip_modals(tab):
"""把「提示信息」类弹窗残留节点连 wrap 一起从 DOM 移除。"""
try:
tab.run_js(
"document.querySelectorAll('.ant-modal').forEach(function(m){"
" var t = m.querySelector('.ant-modal-title');"
" var onlyX = m.querySelector('button.ant-modal-close') &&"
" m.querySelectorAll('button').length === 1;"
" if ((t && t.textContent.indexOf('提示信息') !== -1) || onlyX) {"
" var w = m.closest('.ant-modal-wrap') || m; w.remove();"
" }"
"});")
except Exception:
pass
def _close_tip_modal(tab):
"""关闭「提示信息」弹窗(减员流程特有)。未弹出返回 False。"""
m = _find_tip_modal_by_title(tab)
if m is None:
return False
x = m.ele('css:button.ant-modal-close', timeout=1)
if x:
try:
if x.states.has_rect:
x.click()
config.log(" 关闭「提示信息」弹窗")
time.sleep(0.8)
except Exception:
pass
_remove_tip_modals(tab)
return True
def _body_in_tip_modal(m):
"""modal-body 是否属于标题为「提示信息」的说明弹窗。"""
p = m
for _ in range(3):
try:
p = p.parent()
except Exception:
return False
if p is None:
return False
if _title_is_tip(p):
return True
return False
# ==================== 导入与申报(增/减共用,少量分支) ====================
def _wait_import_result(tab, timeout=90):
"""导入结果探针:等待「导入完成」成功弹窗,或捕获失败提示。
返回 ("ok", modal元素) / ("fail", 提示文本) / ("timeout", None)。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
bodies = tab.eles('css:.ant-modal-body')
# 第一遍只认「导入完成」成功标志(页面可能同时残留说明弹窗)
for m in bodies:
if '导入完成' in (m.text or ''):
return "ok", m
# 第二遍:其它任何非加载中、非「提示信息」说明弹窗的文本都视为失败提示
for m in bodies:
t = (m.text or '').strip()
if t and not any(k in t for k in ('提交中', '导入中', '加载中')) \
and not _body_in_tip_modal(m):
return "fail", t
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
return "fail", t
except Exception:
pass
time.sleep(0.4)
return "timeout", None
def _wait_unit_ready(tab, timeout=5):
"""等参保单位信息真正显示出来(导入请求 aab001 部件的就绪信号)。"""
deadline = time.time() + timeout
while time.time() < deadline:
try:
for sel in tab.eles('css:.ant-select-borderless'):
for kind in ('css:.ant-select-selection-placeholder',
'css:.ant-select-selection-item'):
ele = sel.ele(kind, timeout=1)
if ele and (ele.text or '').strip():
return True
except Exception:
pass
time.sleep(0.5)
return False
def _upload_import(tab, xls_path, close_tip, max_rounds=3):
"""上传名单 xls 并点「导入」,带失败探针与重试。返回 (导入成功人数, 导入失败人数)。"""
last_err = "导入超时无响应"
for rnd in range(1, max_rounds + 1):
inp = _find_any(tab, ['#customized_form_controls_data',
'css:input[type="file"]'], '文件上传控件')
inp.input(xls_path)
if not _wait_unit_ready(tab, timeout=40):
config.log(" 警告:40s 内单位信息未出现,本轮仍尝试导入")
time.sleep(1.0)
_shot(tab, "03_file_selected")
if close_tip:
_close_tip_modal(tab) # 点导入前再兜底清一次「提示信息」
_click_any(tab, ['tag:button@@text()=导 入', 'tag:button@@text():导入'], '「导 入」按钮')
state, payload = _wait_import_result(tab, timeout=90)
if state == "ok":
_shot(tab, "04_import_result")
text = payload.text or ''
m_ok = re.search(r'成功[::]\s*(\d+)\s*人', text)
m_fail = re.search(r'失败[::]\s*(\d+)\s*人', text)
total = int(m_ok.group(1)) if m_ok else 0
failed = int(m_fail.group(1)) if m_fail else 0
config.log(f" 导入完成:成功 {total} 人,失败 {failed} 人")
if total == 0:
raise RuntimeError(f"导入完成但成功人数为 0,提示:{text.strip()[:120]}")
for t in ('确 定', '确定'):
try:
btn = tab.ele(f'tag:button@@text()={t}', timeout=2)
except Exception:
btn = None
if btn:
btn.click()
break
time.sleep(1.5)
return total, failed
last_err = payload if state == "fail" else "导入后未出现结果弹窗(超时)"
config.log(f" 第 {rnd} 轮导入未成功:{str(last_err)[:120]}")
time.sleep(2 + rnd)
raise RuntimeError(f"导入重试 {max_rounds} 轮均失败,最后提示:{str(last_err)[:160]}")
def _read_failed_rows(tab):
"""切到「校验未通过人员」tab 读表格,返回 [(证件号码, 详细信息), ...]。"""
try:
tab_btn = tab.ele('tag:span@@text()=校验未通过人员', timeout=10)
except Exception:
tab_btn = None
if not tab_btn:
return []
tab_btn.click()
time.sleep(2)
rows = []
try:
for tb in tab.eles('tag:table'):
ths = [th.text.strip() for th in tb.eles('tag:th')]
if '证件号码' in ths and '详细信息' in ths:
i_id, i_detail = ths.index('证件号码'), ths.index('详细信息')
for tr in tb.eles('css:tbody tr'):
tds = [td.text.strip() for td in tr.eles('tag:td')]
if len(tds) > max(i_id, i_detail) and len(tds[i_id]) >= 15:
detail = tds[i_detail]
for sep in (':', ':'):
if sep in detail:
detail = detail.split(sep, 1)[1].strip()
break
rows.append((tds[i_id], detail))
break
except Exception as e:
config.log(f" 读取校验未通过表格异常:{e}")
_shot(tab, "05_check_failed_tab")
return rows
def _wait_pdf_ready(tab, timeout=60):
"""等 react-pdf canvas 出现且 2 秒不变,视为 PDF 绘制完成。超时仅告警不拦截。"""
last, stable_since = None, None
deadline = time.time() + timeout
while time.time() < deadline:
try:
canvases = tab.eles('css:.react-pdf__Page__canvas')
sig = (len(canvases), canvases[0].attr('width') if canvases else None)
except Exception:
sig = None
if sig and sig[0] > 0:
if sig == last:
if stable_since and time.time() - stable_since >= 2:
return True
else:
stable_since = time.time()
last = sig
time.sleep(1)
config.log(" 警告:等待 PDF 渲染超时,继续尝试提交", "WARN")
return False
def _goto_submit_page(tab, tries=3):
"""点「下一步」进入提交页,验证「提 交」按钮出现;未出现则重试。"""
for i in range(tries):
_click_any(tab, ['tag:button@@text()=下一步'], '「下一步」按钮')
deadline = time.time() + 12
while time.time() < deadline:
if tab.ele('tag:button@@text()=提 交', timeout=1):
return True
time.sleep(0.5)
config.log(f" 下一步后未出现「提 交」按钮(第 {i + 1} 次),重试")
time.sleep(1.5)
return False
def _click_submit_add(tab, tries=3):
"""增员:点「提 交」,验证「已知晓」确认弹窗出现。"""
for i in range(tries):
btn = tab.ele('tag:button@@text()=提 交', timeout=5)
if btn:
try:
btn.click()
except Exception:
pass
deadline = time.time() + 10
while time.time() < deadline:
if tab.ele('tag:button@@text()=已知晓', timeout=1):
return True
try:
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
config.log(f" 提交提示:{t[:100]}")
except Exception:
pass
time.sleep(0.5)
config.log(f" 第 {i + 1} 次提交未出现「已知晓」确认弹窗,重试")
time.sleep(1.5)
return False
def _confirm_submit_add(tab, tries=3):
"""增员:点「已知晓」→ 等「您已成功提交」弹窗。"""
for i in range(tries):
btn = tab.ele('tag:button@@text()=已知晓', timeout=5)
if btn:
try:
btn.click()
except Exception:
pass
if _wait_modal(tab, '您已成功提交', timeout=60):
return True
config.log(f" 第 {i + 1} 次点击已知晓后未见成功弹窗,重试")
return False
def _click_submit_stop(tab, tries=3):
"""减员:点「提 交」,成功弹窗自带「确 定/去查看」按钮(无「已知晓」确认环节)。"""
for i in range(tries):
btn = tab.ele('tag:button@@text()=提 交', timeout=5)
if btn:
try:
btn.click()
except Exception:
pass
if _wait_modal(tab, '您已成功提交', timeout=30):
return True
try:
for msg in tab.eles('css:.ant-message'):
t = (msg.text or '').strip()
if t:
config.log(f" 提交提示:{t[:100]}")
except Exception:
pass
config.log(f" 第 {i + 1} 次提交未出现「您已成功提交」弹窗,重试")
time.sleep(1.5)
return False
def _predeclare_and_submit(page, tab, kind):
"""预申报 → 去申报 → 关弹窗 → 全部提交 → 等 PDF → 下一步 → 提交 → 等成功。
kind='add' 走「已知晓」确认;kind='stop' 成功弹窗自带按钮。"""
_click_any(tab, ['tag:button@@text()=预申报'], '「预申报」按钮')
if _wait_modal(tab, '预申报成功', timeout=60) is None:
raise RuntimeError("预申报后未出现成功弹窗")
_click_any(tab, ['tag:button@@text()=去申报'], '「去申报」按钮')
deadline = time.time() + 15
while time.time() < deadline:
try:
if tab.ele('tag:button@@text()=我已知晓', timeout=0.5) or \
tab.ele('tag:button@@text()=我知道了', timeout=0.5) or \
tab.ele('tag:button@@text()=全部提交', timeout=0.5):
break
except Exception:
pass
time.sleep(0.3)
_dismiss_popups(tab)
_shot(tab, "06_declare_page")
_click_any(tab, ['tag:button@@text()=全部提交'], '「全部提交」按钮')
_wait_pdf_ready(tab)
_shot(tab, "07_pdf_ready")
if not _goto_submit_page(tab):
_shot(tab, "08_no_submit_btn")
raise RuntimeError("点击下一步后未出现「提 交」按钮")
_shot(tab, "08_submit_page")
if kind == 'add':
if not _click_submit_add(tab):
_shot(tab, "09_submit_no_confirm")
raise RuntimeError("点击提交后未出现「已知晓」确认弹窗")
if not _confirm_submit_add(tab):
_shot(tab, "10_confirm_no_success")
raise RuntimeError("点击已知晓后未出现「您已成功提交」弹窗(提交可能未完成)")
else:
if not _click_submit_stop(tab):
_shot(tab, "09_submit_no_success")
raise RuntimeError("点击提交后未出现「您已成功提交」弹窗(提交可能未完成)")
_shot(tab, "11_submit_success")
config.log(" 提交成功")
def _collect_review_rows(tab):
"""从明细表收集审核结论:{证件号码: (审核结论, 业务流水号)}。"""
results = {}
for tr in tab.eles('css:.ant-table-tbody tr.ant-table-row'):
try:
tds = [td.text.strip() for td in tr.eles('tag:td')]
except Exception:
continue
cid = tds[3] if len(tds) > 3 else ''
if len(cid) in (15, 18) and cid.rstrip('Xx').isdigit():
results[cid] = (tds[4], tds[0])
return results
def _open_query_page(page, tab, timeout=25):
"""点「去查看」进入申报查询列表(可能新开 tab),返回承载列表的 tab。"""
before = set(page.tab_ids)
_click_any(tab, ['tag:button@@text()=去查看'], '「去查看」按钮')
deadline = time.time() + timeout
while time.time() < deadline:
time.sleep(1)
tids = [i for i in page.tab_ids if i not in before] + [tab.tab_id]
for tid in tids:
try:
t = page.get_tab(tid)
row = t.ele('css:.ant-table-tbody tr.ant-table-row', timeout=0.5)
if row and row.ele('tag:a@@text()=查看', timeout=0.5):
_shot(t, "12_query_list")
return t
except Exception:
continue
raise RuntimeError("点击去查看后未找到申报查询列表(含「查看」按钮的记录表)")
def _query_review_results(page, tab, close_tip):
"""进入申报查询列表 → (减员先关提示信息)→ 打开序号1记录「查看」→ 读审核结论。
返回 {证件号码: (审核结论, 业务流水号)}。"""
qtab = _open_query_page(page, tab)
if close_tip:
_close_tip_modal(qtab) # 去查看后会再弹一次「提示信息」,需先关闭
for attempt in range(3):
row = qtab.ele('css:.ant-table-tbody tr.ant-table-row', timeout=10)
view = row.ele('tag:a@@text()=查看', timeout=3) if row else None
if view:
try:
view.click()
except Exception:
pass
deadline = time.time() + 12
while time.time() < deadline:
time.sleep(1)
results = _collect_review_rows(qtab)
if results:
_shot(qtab, "13_review_detail")
return results
config.log(f" 第 {attempt + 1} 次查看未读到审核结论明细,重试")
_shot(qtab, "13_review_detail_miss")
time.sleep(1.5)
raise RuntimeError("未读取到审核结论明细表")
# ==================== 统一导入引擎 ====================
class ImportEngine:
"""按 kind(add/stop)配置的增/减员系统办理引擎。"""
def __init__(self, kind):
self.kind = kind
if kind == 'add':
self.business_item = "城保参保单位人员增加"
self.import_dir_name = config.OUTPUT_DIR_ADD_NEW
self.file_suffix = "增员导入名单.xls"
self.fail_status = "参保失败"
self.close_tip = False
self.operation_type = config.WEB_ADD_TYPE
else:
self.business_item = "城保参保单位人员减少"
self.import_dir_name = config.OUTPUT_DIR_STOP
self.file_suffix = "减员导入名单.xls"
self.fail_status = "停保失败"
self.close_tip = True
self.operation_type = None
self.writeback = Writeback(kind)
# ---------------- 预检 ----------------
def precheck(self, units, accounts):
"""预检:核对每个单位的导入文件与账号。返回待办列表。"""
import_dir = config.roster_output_dir(self.import_dir_name)
tasks, errors = [], []
config.log("\n========== 预检 ==========")
for unit, count in units:
file_path = os.path.join(import_dir, f"{config._safe_name(unit)}{self.file_suffix}")
acc = accounts.get(unit)
problems = []
if not os.path.isfile(file_path):
problems.append(f"缺导入文件({self.import_dir_name}\\{os.path.basename(file_path)})")
if acc is None:
problems.append("台账未匹配(检查户头名/城市=重庆/是否在用=是)")
else:
if not acc["username"]:
problems.append("账号缺失(I列信用代码与K列平台用户名均为空)")
if not acc["password"]:
problems.append("密码缺失(L列平台密码为空)")
if problems:
errors.append(f"[{unit}] " + ";".join(problems))
config.log(f" ✗ {unit}({count}人):{';'.join(problems)}")
else:
tasks.append({"unit": unit, "count": count, "file": file_path,
"username": acc["username"], "password": acc["password"]})
config.log(f" ✓ {unit}({count}人)账号={acc['username']}"
f"({acc['username_src']})文件={os.path.basename(file_path)}")
if errors:
config.log(f"\n预检未通过,共 {len(errors)} 个问题,请先修正后重跑:")
for e in errors:
config.log(f" - {e}")
return None
config.log(f"预检通过:{len(tasks)} 个单位待办理\n")
return tasks
# ---------------- 单个单位网页办理 ----------------
def do_web_import(self, task):
"""登录后的完整业务流程:进业务页 → 上传导入 → 校验回写 → 预申报提交 → 查询回写。"""
page = web_login.LAST_SESSION.get('page')
work_tab = web_login.LAST_SESSION.get('tab')
if page is None or work_tab is None:
return {"success": False, "message": "无有效登录会话"}
res = {"success": False, "imported": 0, "failed": [], "review": {}}
try:
_shot(work_tab, "01_workbench")
biz_tab = _open_business_page(page, work_tab, self.business_item)
if self.close_tip:
_close_tip_modal(biz_tab) # 减员:进业务页先关「提示信息」弹窗
_shot(biz_tab, "02_biz_upload_page")
# 1) 上传导入
total, _failed_cnt = _upload_import(biz_tab, task['file'], self.close_tip)
res['imported'] = total
# 2) 校验未通过:回写 参保失败/停保失败 + 备注(详细信息)
fail_rows = _read_failed_rows(biz_tab)
res['failed'] = [{"id": cid, "detail": d} for cid, d in fail_rows]
expected = task.get('count', 0)
if expected and total + len(fail_rows) != expected:
raise RuntimeError(
f"人数不平账:导入成功{total} + 校验未通过{len(fail_rows)} ≠ 名单{expected}人,"
f"中止该单位(防漏人/重复申报),请人工核对")
if fail_rows:
self.writeback.writeback_source(
{cid: self.fail_status for cid, _ in fail_rows},
{cid: d for cid, d in fail_rows})
passed = total
# 3) 全员未通过 → 跳过申报
if passed <= 0:
config.log(" 校验通过人数为 0,跳过申报")
res.update(success=True,
message=f"导入{total}人,全部校验未通过,已回写未申报")
return res
# 4) 预申报 → 正式提交 → 查询审核结论回写
_predeclare_and_submit(page, biz_tab, self.kind)
review = _query_review_results(page, biz_tab, self.close_tip)
res['review'] = [{"id": cid, "conclusion": c, "sn": sn}
for cid, (c, sn) in review.items()]
if review:
self.writeback.writeback_source(
{cid: concl for cid, (concl, _) in review.items()}, {})
res.update(success=True,
message=f"导入{total}人,未通过{len(fail_rows)}人,提交{passed}人")
return res
except Exception as e:
res["message"] = f"网页操作异常:{e}"
return res
# ---------------- 逐单位登录 + 网页操作 ----------------
def process_units(self, tasks, accounts, progress_span=(0, 100)):
"""逐参保单位:登录 → 网页导入申报 → 回写。每账号办完清 cookies 关浏览器。"""
span_start, span_end = progress_span
results = []
for i, task in enumerate(tasks, 1):
config.log(f"\n========== [{i}/{len(tasks)}] {task['unit']}({task['count']}人)==========")
config.log(f"导入文件:{task['file']}")
if len(tasks) > 1:
config.progress(span_start + int((span_end - span_start) * (i - 1) / len(tasks)))
try:
login_res = web_login.ensure_login(task["username"], task["password"])
except Exception as e:
login_res = {"success": False, "message": f"登录调用异常:{e}"}
config.log(f"登录结果:{login_res.get('message')}")
try:
if login_res.get("success"):
web_res = self.do_web_import(task)
config.log(f"办理结果:{web_res.get('message')}")
results.append({**task, **web_res})
else:
results.append({**task, "success": False,
"message": login_res.get("message", "")})
finally:
web_login.close_session()
config.progress(span_end)
return results
# ---------------- 主流程 ----------------
def run(self, progress_span=(0, 100)):
"""主流程:恢复缓存 → 读名单(排除已回写人员)→ 取号 → 预检 → 逐单位登录(+导入)→ 统一回写。
返回 JSON 安全 dict。"""
recovered_ids = self.writeback.load_ckpt()
units, source_file, source_sheet = source_reader.load_units(
self.kind, operation_type=self.operation_type, status_filter="empty",
exclude_ids=recovered_ids)
self.writeback.bind_source(source_file, source_sheet)
if recovered_ids:
config.log("\n检测到上次未回写的内容,先统一回写:")
try:
self.writeback.flush()
except Exception as e:
config.log(f"恢复回写失败(缓存保留,下次启动重试):{e}")
if not units:
return {"success": True, "message": "无待办数据", "total": 0, "done": 0}
accounts = source_reader.load_accounts([u for u, _ in units])
tasks = self.precheck(units, accounts)
if tasks is None:
return {"success": False, "message": "预检未通过,详见日志",
"total": len(units), "done": 0}
limit = config.get_run_limit()
results = self.process_units(tasks[:limit], accounts, progress_span)
try:
self.writeback.flush()
except Exception as e:
config.log(f"回写失败:{e}")
ok = [r for r in results if r["success"]]
fail = [r for r in results if not r["success"]]
config.log(f"\n========== 汇总 ==========")
config.log(f"成功 {len(ok)} 家,失败 {len(fail)} 家")
for r in fail:
config.log(f" ✗ {r['unit']}:{r.get('message', '')}")
return {"success": not fail, "message": f"成功{len(ok)}/失败{len(fail)}",
"total": len(results), "done": len(ok)}