feat: 新增多插件 UI 支持及运行日志集中回传功能
本次提交包含多项功能更新: 1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持 2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储 3. 新增插件分类字段支持,用于场景库分组管理 4. 优化 xq0034/0037/0048 等插件的功能及描述 5. 修复控制面响应兼容问题,支持新旧版本数据格式 6. 新增 xq0033 插件的状态存储模块,用于历史记录管理 7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
@@ -37,6 +37,23 @@ from .logic.workbook import (copy_today_to_prev, ensure_sheets, read_compare_res
|
||||
from .report.summary import build_summary
|
||||
|
||||
|
||||
def _gap_days(today, t2, covered_until):
|
||||
"""上轮已处理积分日期与 T-2 之间漏处理的日期(限本月、早于 T-2)。
|
||||
|
||||
跳天运行(如隔几天才跑一次)时,中间日期的考勤数据大多已在上轮快照里,
|
||||
按差值对比会因「差值=0」被漏掉,需按新增段口径全量补。
|
||||
"""
|
||||
if covered_until is None or covered_until >= t2 - timedelta(days=1):
|
||||
return []
|
||||
month_first = date(today.year, today.month, 1)
|
||||
d = max(covered_until + timedelta(days=1), month_first)
|
||||
days = []
|
||||
while d < t2 and d.month == today.month:
|
||||
days.append(d)
|
||||
d += timedelta(days=1)
|
||||
return days
|
||||
|
||||
|
||||
def _log_workbook_shape(ctx, path, wb):
|
||||
"""输出工作簿规模诊断:openpyxl 内存占用与「已存在单元格数」成正比。"""
|
||||
try:
|
||||
@@ -61,7 +78,7 @@ class Xq0033Plugin(ScenePlugin):
|
||||
|
||||
id = "xq0033"
|
||||
name = "门店管理及服务岗出勤积分更新"
|
||||
version = "1.0.4"
|
||||
version = "1.0.7"
|
||||
description = (
|
||||
"拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,"
|
||||
"自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,"
|
||||
@@ -189,11 +206,17 @@ class Xq0033Plugin(ScenePlugin):
|
||||
if stats["cleared"]:
|
||||
ctx.log(f"已踢除离职当月再入职人员无效积分段 {stats['cleared']} 个考勤状态", "INFO")
|
||||
|
||||
# 3. 选择目标批次文件
|
||||
target_path, is_new_batch = pick_target_file(today, save_dir, force_file)
|
||||
# 3. 选择目标批次文件(同时据来源文件名推断上轮已处理的积分日期)
|
||||
target_path, is_new_batch, covered_until = pick_target_file(today, save_dir, force_file)
|
||||
file_key = os.path.basename(target_path)
|
||||
gap_days = _gap_days(today, t2, covered_until)
|
||||
ctx.progress(30)
|
||||
ctx.log(f"目标文件:{target_path}({'新批文件' if is_new_batch else '续用追加'})", "INFO")
|
||||
ctx.log(f"目标文件:{target_path}({'新批文件' if is_new_batch else '续用追加'})"
|
||||
f",上轮积分日期:{covered_until or '未知'}", "INFO")
|
||||
if gap_days:
|
||||
ctx.log(f"检测到 {covered_until} 之后、T-2={t2} 之前漏处理日期:"
|
||||
f"{'、'.join(d.strftime('%m-%d') for d in gap_days)},"
|
||||
"本轮按新增段口径全量补齐", "WARN")
|
||||
|
||||
# 4. 全程只加载一次工作簿(大体积模板多次全量加载会触发 MemoryError),
|
||||
# 写操作复用同一 wb;需要公式缓存值时另开 read_only 轻量读取。
|
||||
@@ -235,18 +258,20 @@ class Xq0033Plugin(ScenePlugin):
|
||||
recalc_target(target_path)
|
||||
ctx.progress(56)
|
||||
|
||||
# 6. 读对比结果 → 新增段 / 修正补 / 修正删
|
||||
# 6. 读对比结果 → 新增段(含补漏日期)/ 修正补 / 修正删
|
||||
wv = openpyxl.load_workbook(target_path, data_only=True, read_only=True)
|
||||
try:
|
||||
new_rows, fix_rows, del_rows = read_compare_results(wv, today, t2)
|
||||
new_rows, fix_rows, del_rows = read_compare_results(wv, today, t2, gap_days)
|
||||
finally:
|
||||
wv.close()
|
||||
wv = None
|
||||
gc.collect()
|
||||
stats["new"], stats["fix"], stats["del"] = len(new_rows), len(fix_rows), len(del_rows)
|
||||
stats["gap"] = len(gap_days)
|
||||
ctx.progress(62)
|
||||
ctx.log(f"积分计算结果:新增段 {len(new_rows)} 行({t2}),修正补 {len(fix_rows)} 行,"
|
||||
f"修正删 {len(del_rows)} 行", "INFO")
|
||||
ctx.log(f"积分计算结果:新增段 {len(new_rows)} 行(T-2={t2}"
|
||||
f"{',含补漏 ' + '、'.join(d.strftime('%m-%d') for d in gap_days) if gap_days else ''})"
|
||||
f",修正补 {len(fix_rows)} 行,修正删 {len(del_rows)} 行", "INFO")
|
||||
|
||||
# 7. 写积分导入 / 积分删除(新增段保护 + 修正段全月刷新)→ COM 收尾重算
|
||||
state_file = config.state_path(os.path.dirname(target_path))
|
||||
@@ -294,12 +319,47 @@ class Xq0033Plugin(ScenePlugin):
|
||||
ctx.progress(min(96, base + 8))
|
||||
|
||||
for label, rows, kind in valid:
|
||||
url = client.import_url if kind == "import" else client.delete_url
|
||||
res = client.upload(url, build_kaoqin_bytes(rows), f"{label}.xlsx")
|
||||
results[label] = res
|
||||
if kind == "import":
|
||||
# 跳天补漏后单次可能上万行,OPM 逐行处理易超时 → 按积分日期分批(每批约单日量)
|
||||
groups = {}
|
||||
for r in rows:
|
||||
groups.setdefault(r[2].date(), []).append(r)
|
||||
if len(groups) > 1:
|
||||
ctx.log(f"{label} 共 {len(rows)} 行,按积分日期分 {len(groups)} 批上传", "INFO")
|
||||
parts, failed = [], []
|
||||
for d in sorted(groups):
|
||||
chunk = groups[d]
|
||||
res = self._upload_once(client, ctx, f"积分导入_{d:%m-%d}", chunk, kind)
|
||||
if res["success"]:
|
||||
parts.append(f"{d:%m-%d} {len(chunk)} 行")
|
||||
else:
|
||||
failed.append(f"{d:%m-%d}({res['message']})")
|
||||
results[label] = {
|
||||
"success": not failed,
|
||||
"message": ("分批成功:" + "、".join(parts)) if not failed
|
||||
else "失败批次:" + ";".join(failed),
|
||||
}
|
||||
else:
|
||||
results[label] = self._upload_once(client, ctx, label, rows, kind)
|
||||
res = results[label]
|
||||
ctx.log(f"{label} 推送:{'成功' if res['success'] else '失败'}({res['message']})",
|
||||
"INFO" if res["success"] else "ERROR")
|
||||
return results
|
||||
|
||||
@staticmethod
|
||||
def _upload_once(client, ctx, label, rows, kind):
|
||||
"""单批上传;失败时重登会话再试一次(大请求超时后 OPM 常会重置会话返回 HTML)。"""
|
||||
url = client.import_url if kind == "import" else client.delete_url
|
||||
res = client.upload(url, build_kaoqin_bytes(rows), f"{label}.xlsx")
|
||||
if res["success"]:
|
||||
return res
|
||||
ctx.log(f"{label} 上传失败,重登会话后重试一次:{res['message']}", "WARN")
|
||||
try:
|
||||
client.session = None
|
||||
client.ensure_session()
|
||||
except Exception as e:
|
||||
return {"success": False, "message": f"{res['message']};重登失败:{e}"}
|
||||
return client.upload(url, build_kaoqin_bytes(rows), f"{label}.xlsx")
|
||||
|
||||
|
||||
PLUGINS.append(Xq0033Plugin())
|
||||
|
||||
@@ -67,7 +67,7 @@ COM_PROG_IDS = ("Ket.Application", "et.Application", "Excel.Application")
|
||||
DEFAULT_OPM_URL = "https://opm.jsyxapp.com/login"
|
||||
OPM_IMPORT_PATH = "/operation/point/list/importAttendance"
|
||||
OPM_DELETE_PATH = "/operation/point/list/importAttendanceDel"
|
||||
OPM_TIMEOUT = 30
|
||||
OPM_TIMEOUT = 120
|
||||
# 服务端对「重复/无内容可删」的良性响应关键词:目标状态已达成,不算失败
|
||||
OPM_BENIGN_MSGS = ("不能重复添加", "未生成出勤积分", "已存在")
|
||||
|
||||
|
||||
@@ -59,11 +59,15 @@ def pick_latest_file(save_dir, force_file=None):
|
||||
|
||||
|
||||
def pick_target_file(today, save_dir, force_file=None):
|
||||
"""选择本轮写入的积分工作簿 → (绝对路径, 是否新建批次文件)。"""
|
||||
"""选择本轮写入的积分工作簿 → (绝对路径, 是否新建批次文件, 上轮已处理的积分日期)。
|
||||
|
||||
第三个返回值取「被复制批次文件名里的最大日期」,用于识别两次运行之间漏处理的日期;
|
||||
指定工作簿时来源不可信,返回 None(不做补漏推断)。
|
||||
"""
|
||||
if force_file:
|
||||
if not os.path.isfile(force_file):
|
||||
raise FileNotFoundError(f"指定的工作簿不存在:{force_file}")
|
||||
return os.path.abspath(force_file), False
|
||||
return os.path.abspath(force_file), False, None
|
||||
|
||||
if not os.path.isdir(save_dir):
|
||||
raise FileNotFoundError(f"工作簿目录不存在:{save_dir}")
|
||||
@@ -88,15 +92,18 @@ def pick_target_file(today, save_dir, force_file=None):
|
||||
path = os.path.join(save_dir, f)
|
||||
config.logger.info("命中文件名含 T-2(%s) 的数据文件:%s(续用追加模式)",
|
||||
t2.strftime("%m%d"), f)
|
||||
return path, False
|
||||
return path, False, t2
|
||||
|
||||
newest = max(files, key=lambda f: os.path.getmtime(os.path.join(save_dir, f)))
|
||||
src_dates = parse_name_dates(newest, today.year)
|
||||
covered_until = max(src_dates) if src_dates else None
|
||||
new_name = f"{config.FILE_PREFIX}{t2.strftime('%m%d')}.xlsx"
|
||||
new_path = os.path.join(save_dir, new_name)
|
||||
if os.path.exists(new_path):
|
||||
config.logger.warning("新批文件 %s 已存在但文件名未匹配 T-2,直接复用", new_name)
|
||||
return new_path, False
|
||||
return new_path, False, covered_until
|
||||
shutil.copy2(os.path.join(save_dir, newest), new_path)
|
||||
config.logger.info("未找到文件名含 T-2 的文件,已从最新文件 %s 复制新建批次文件:%s",
|
||||
newest, new_name)
|
||||
return new_path, True
|
||||
config.logger.info("未找到文件名含 T-2 的文件,已从最新文件 %s 复制新建批次文件:%s"
|
||||
"(上轮积分日期推断为 %s)",
|
||||
newest, new_name, covered_until or "未知")
|
||||
return new_path, True, covered_until
|
||||
|
||||
@@ -95,17 +95,26 @@ def write_compare_values(wb, sel_rows):
|
||||
return n
|
||||
|
||||
|
||||
def read_compare_results(wv, today, t2):
|
||||
"""读「对比结果」公式值 → (新增段行, 修正补行, 修正删行),每行为 (员工信息9列, date)。"""
|
||||
def read_compare_results(wv, today, t2, gap_days=()):
|
||||
"""读「对比结果」公式值 → (新增段行, 修正补行, 修正删行),每行为 (员工信息9列, date)。
|
||||
|
||||
新增段 = T-2 + gap_days(上轮积分日期到 T-2 之间漏处理的日期),两者均按镜像列=2
|
||||
全量取人;修正段 = 其余 [月首, T-3] 日期按差值 >0 补 / <0 删(gap_days 不参与差值,
|
||||
否则「上次快照已有值但从未推送」的日期会因差值=0 被漏掉)。
|
||||
"""
|
||||
ws = wv[config.SHEET_CMP]
|
||||
month_first = date(today.year, today.month, 1)
|
||||
mirror_idx = 40 + t2.day if t2 >= month_first else None
|
||||
if mirror_idx is None:
|
||||
gap_days = sorted(d for d in (gap_days or ()) if month_first <= d < t2)
|
||||
if t2 >= month_first:
|
||||
full_days = gap_days + [t2]
|
||||
else:
|
||||
config.logger.warning("T-2(%s) 不在本月报表范围,跳过新增段(月初边缘场景属正常)", t2)
|
||||
full_days = []
|
||||
fix_end = t2 - timedelta(days=1)
|
||||
gap_nums = {d.day for d in gap_days}
|
||||
fix_days = []
|
||||
if t2 >= month_first and fix_end >= month_first:
|
||||
fix_days = list(range(month_first.day, fix_end.day + 1))
|
||||
fix_days = [d for d in range(month_first.day, fix_end.day + 1) if d not in gap_nums]
|
||||
|
||||
new_rows, fix_rows, del_rows = [], [], []
|
||||
for row in ws.iter_rows(min_row=config.CMP_DATA_START, min_col=1, max_col=72,
|
||||
@@ -113,11 +122,14 @@ def read_compare_results(wv, today, t2):
|
||||
info = list(row[1:10])
|
||||
if clean(info[0]) == "":
|
||||
continue
|
||||
if mirror_idx is not None and mirror_idx < len(row):
|
||||
v = row[mirror_idx]
|
||||
for d in full_days:
|
||||
idx = 40 + d.day
|
||||
if idx >= len(row):
|
||||
continue
|
||||
v = row[idx]
|
||||
try:
|
||||
if v not in (None, "") and abs(float(v) - 2) < 1e-9:
|
||||
new_rows.append((info, t2))
|
||||
new_rows.append((info, d))
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
for d in fix_days:
|
||||
@@ -136,6 +148,7 @@ def read_compare_results(wv, today, t2):
|
||||
fix_rows.append((info, fix_date))
|
||||
elif diff < 0:
|
||||
del_rows.append((info, fix_date))
|
||||
new_rows.sort(key=lambda x: x[1])
|
||||
fix_rows.sort(key=lambda x: x[1])
|
||||
del_rows.sort(key=lambda x: x[1])
|
||||
return new_rows, fix_rows, del_rows
|
||||
@@ -190,13 +203,16 @@ def write_import_sheet(wb, today, t2, new_rows, fix_rows, state, file_key, is_ne
|
||||
ws.cell(row=r, column=11).number_format = "yyyy/m/d"
|
||||
|
||||
dates = set(state.setdefault(file_key, {}).setdefault("new_dates", []))
|
||||
for _info, d in new_rows: # 新增段含补漏日期,全部纳入历史保护
|
||||
dates.add(d.isoformat())
|
||||
if t2 >= date(today.year, today.month, 1):
|
||||
dates.add(t2.isoformat())
|
||||
state[file_key]["new_dates"] = sorted(dates)
|
||||
state[file_key]["new_dates"] = sorted(dates)
|
||||
new_dates_txt = "、".join(sorted({d.isoformat() for _info, d in new_rows})) or t2.isoformat()
|
||||
config.logger.info(
|
||||
"积分导入:删除旧行 %d(历史新增段保护日期 %s),追加新增段 %d 行(%s)+ 修正段 %d 行,现共 %d 行",
|
||||
removed, state[file_key].get("new_dates") or "无", len(new_rows), t2, len(fix_rows),
|
||||
scan_last_data_row(ws, 2, config.IMP_DATA_START) - config.IMP_DATA_START + 1)
|
||||
removed, state[file_key].get("new_dates") or "无", len(new_rows), new_dates_txt,
|
||||
len(fix_rows), scan_last_data_row(ws, 2, config.IMP_DATA_START) - config.IMP_DATA_START + 1)
|
||||
return len(out)
|
||||
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0033",
|
||||
"name": "门店管理及服务岗出勤积分更新",
|
||||
"version": "1.0.4",
|
||||
"version": "1.0.7",
|
||||
"description": "拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,COM 全量重算),可选将积分导入与删除表推送至 OPM 平台。",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -5,7 +5,7 @@
|
||||
def build_summary(today, t2, target_path, stats, push_result=None):
|
||||
"""按执行结果拼装 {summary, detail}。
|
||||
|
||||
stats: report_rows/selected/new/fix/del/rejoin_new/rejoin_total/cleared 计数;
|
||||
stats: report_rows/selected/new/fix/del/gap/rejoin_new/rejoin_total/cleared 计数;
|
||||
update=False 表示本轮仅推送(不展示更新计数)。
|
||||
push_result: {label: {success, message}} 或 None(未执行推送)。
|
||||
"""
|
||||
@@ -17,6 +17,7 @@ def build_summary(today, t2, target_path, stats, push_result=None):
|
||||
"报表人数": stats.get("report_rows", 0),
|
||||
"圈人命中": stats.get("selected", 0),
|
||||
"新增积分行": stats.get("new", 0),
|
||||
"补漏日期数": stats.get("gap", 0),
|
||||
"修正补积分行": stats.get("fix", 0),
|
||||
"修正删积分行": stats.get("del", 0),
|
||||
"再入职新增行": stats.get("rejoin_new", 0),
|
||||
@@ -32,6 +33,8 @@ def build_summary(today, t2, target_path, stats, push_result=None):
|
||||
]
|
||||
if stats.get("cleared"):
|
||||
lines.append(f"已踢除离职当月再入职人员无效积分段 {stats['cleared']} 个考勤状态。")
|
||||
if stats.get("gap"):
|
||||
lines.append(f"检测到漏处理日期 {stats['gap']} 天,已按新增段口径全量补齐。")
|
||||
else:
|
||||
detail = {"运行日": today.isoformat(), "工作簿": target_path}
|
||||
lines = [f"XQ0033 完成(运行日 {today},仅推送):工作簿 {target_path}"]
|
||||
|
||||
@@ -48,7 +48,7 @@ class _LogWriter:
|
||||
class Xq0034Plugin(ScenePlugin):
|
||||
id = "xq0034"
|
||||
name = "续签电子签"
|
||||
version = "1.0.17"
|
||||
version = "1.0.18"
|
||||
description = ("XQ0034 续签电子签:AI表格【续签名单到期跟进-月更新】驱动——否续签回填、"
|
||||
"是续签手机号校验后 HR 生效中合同属性页「续签合同」提交推送电子签并回填,"
|
||||
"HR 会话由壳子注入")
|
||||
|
||||
@@ -27,8 +27,9 @@ HR【劳动关系-合同台账-生效中合同】属性页「续签合同」提
|
||||
AI 表;补全后继续完整续签流程(不再跳过)。AI 信息不全的记录不提交
|
||||
(期限/开始/截止/类型缺失 -> 不提交,日志报出)。
|
||||
4. 通知(2026-10-16 精简,块格式与加班审批一致):只推送 续签推送成功数量 /
|
||||
核验完成数量 / 核验未完成数量 / 续签失败明细;防重、试算、跳过、异常、
|
||||
「是否续签=否」回填均只记日志不通知。
|
||||
核验完成数量 / 核验未完成数量 / 续签失败明细;防重、试算、跳过、「是否续签=否」
|
||||
回填均只记日志不通知。例外:合同到期日与生效中合同不一致的异常推送
|
||||
「合同到期日异常(未推送)」(2026-10-26 用户要求)。
|
||||
5. 核验流程(2026-10-16 口径修正):「是否续签=是」且「人资是否推送=是」且
|
||||
「完成签署」未填的记录逐条核验——【待生效合同】+【生效中合同】两 Tab 联合
|
||||
取该员工全部合同行,按合同开始日期取最新一条:
|
||||
@@ -57,7 +58,8 @@ HR【劳动关系-合同台账-生效中合同】属性页「续签合同」提
|
||||
无推送时间 -> 异常报出待人工核对。
|
||||
待生效无行 -> 查生效中合同:以 AI 表「合同/协议到期日」(旧合同到期日) 为界,
|
||||
生效中合同截止日期 > 旧合同到期日 = 续签新合同(可能已转生效,即使 AI 表续签期
|
||||
填错也视为已续签)-> 防重不回填发起;否则为旧合同 -> 正常发起续签。
|
||||
填错也视为已续签)-> 防重不回填发起;否则为旧合同 -> 核对 AI 表「合同/协议
|
||||
到期日」与生效中合同截止日期一致(不一致/未填 -> 异常,不发起续签)。
|
||||
4. 属性页 getPropPageData(businessKey=contract_id)-> 原样字段 + AI 表覆盖字段
|
||||
-> savePropPageData 提交(state=="1" 为成功);
|
||||
5. 复查:轮询【待生效合同】Tab 出现该员工行(HR 落库有秒级延迟);
|
||||
@@ -436,6 +438,17 @@ def renew_contract(session, ai, dry_run):
|
||||
return "防重", f"防重命中:{detail},回填推送时间={a_push}"
|
||||
return "防重", f"防重命中:{detail},行内无推送时间"
|
||||
# 生效中合同截止未超过旧合同到期日 -> 仍为旧合同 -> 正常走提交(发起续签)
|
||||
# 3.5) 旧合同到期日一致性闸门(2026-10-26 用户要求):发起续签前,AI 表
|
||||
# 「合同/协议到期日」须与【生效中合同】截止日期完全一致;不一致(含
|
||||
# AI 表未填)说明两边数据错位(旧合同已被替换/到期日填错),不发起
|
||||
# 续签,报异常转人工核对(该异常推送钉钉通知)。
|
||||
ai["_alert"] = True
|
||||
if old_expire is None:
|
||||
return "异常", ("AI表「合同/协议到期日」为空,无法核对生效中合同截止日期,"
|
||||
"不发起续签,请人工补充后重跑")
|
||||
if a_end != old_expire:
|
||||
return "异常", (f"AI表合同/协议到期日({old_expire})与生效中合同截止日期"
|
||||
f"({a_end or '?'})不一致,不发起续签,请人工核对")
|
||||
|
||||
# 4) 属性页连通性校验(businessKey=生效合同ID;提交体为固定构造,不用快照转发)
|
||||
resp = _request_retry("POST", GET_PROP_URL_RENEW, session,
|
||||
@@ -587,7 +600,7 @@ def process_renew(session, rec, dry_run):
|
||||
code = _norm_code(fields.get(F_CODE))
|
||||
r = {"record_id": rec.get("id"), "code": code,
|
||||
"name": _s(fields.get(F_NAME)), "status": "失败", "msg": "",
|
||||
"backfill": None, "prefill": None}
|
||||
"backfill": None, "prefill": None, "alert": False}
|
||||
if not code:
|
||||
r["msg"] = "工号为空"
|
||||
return r
|
||||
@@ -626,6 +639,7 @@ def process_renew(session, rec, dry_run):
|
||||
logger.info("【%s】电子签接收电话为空,默认取花名册联系方式回填", code)
|
||||
|
||||
status, msg = renew_contract(session, ai, dry_run)
|
||||
r["alert"] = bool(ai.pop("_alert", False)) # 合同到期日不一致类异常需推送钉钉
|
||||
fix_note = ai.pop("_phone_fixed", None)
|
||||
if fix_note:
|
||||
msg = f"{msg};🔧{fix_note}"
|
||||
@@ -803,10 +817,12 @@ def main(dry_run=False):
|
||||
v_done, v_wait, _ = run_verify(session, records, dry_run)
|
||||
|
||||
# 汇总消息(块格式与加班审批一致,2026-10-16 用户要求精简:
|
||||
# 只保留 推送成功明细 / 核验完成数量 / 核验未完成数量 / 失败明细)
|
||||
# 只保留 推送成功明细 / 核验完成数量 / 核验未完成数量 / 失败明细;
|
||||
# 合同到期日与生效中合同不一致的异常也推送,2026-10-26 用户要求)
|
||||
messages = []
|
||||
pushed = [r for r in results if r["status"] == "已推送"]
|
||||
fail = [r for r in results if r["status"] == "失败"]
|
||||
alerts = [r for r in results if r.get("alert")]
|
||||
|
||||
def _person_block(name, code, lines):
|
||||
"""单人 block(钉钉 Markdown 引用块内每行需空行分隔才会换行)。"""
|
||||
@@ -831,6 +847,11 @@ def main(dry_run=False):
|
||||
"blocks": [_person_block(
|
||||
r["name"], r["code"], [f"失败原因:{r['msg']}"])
|
||||
for r in fail]})
|
||||
if alerts:
|
||||
messages.append({"title": "【续签电子签】合同到期日异常(未推送)",
|
||||
"blocks": [_person_block(
|
||||
r["name"], r["code"], [f"异常原因:{r['msg']}"])
|
||||
for r in alerts]})
|
||||
if not messages:
|
||||
messages = ["续签电子签:无待处理名单"]
|
||||
for m in messages:
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0034",
|
||||
"name": "续签电子签",
|
||||
"version": "1.0.17",
|
||||
"description": "XQ0034 续签电子签:钉钉AI表格【续签名单到期跟进-月更新】驱动——「是否续签=否」回填人资是否推送=否;「是否续签=是」前置默认补全(电子签接收电话为空取花名册号码回填、期望推送日期为空默认当天回填)后完整发起续签:校验电话与花名册一致(不一致且合法自动修正HR联系方式),在 HR【合同台账-生效中合同】属性页「续签合同」提交推送电子签(新合同信息直接取AI表字段,电子签模板按员工+签署单位实时查询,为空不提交转人工),成功回填人资是否推送=是+推送时间;核验:待生效+生效中联合取最新合同,时间与AI表续签期一致且签署记录is_initiate_sign=2已完成签署才回填完成签署=是(1已发起/3已撤销均不算);通知块格式与加班审批一致,仅推送成功/核验完成数量/核验未完成数量/失败;HR 会话由壳子注入",
|
||||
"version": "1.0.18",
|
||||
"description": "XQ0034 续签电子签:钉钉AI表格【续签名单到期跟进-月更新】驱动——「是否续签=否」回填人资是否推送=否;「是否续签=是」前置默认补全(电子签接收电话为空取花名册号码回填、期望推送日期为空默认当天回填)后完整发起续签:校验电话与花名册一致(不一致且合法自动修正HR联系方式),发起前核对 AI 表「合同/协议到期日」与【生效中合同】截止日期,不一致或未填=异常不发起并推送钉钉通知,一致则在 HR【合同台账-生效中合同】属性页「续签合同」提交推送电子签(新合同信息直接取AI表字段,电子签模板按员工+签署单位实时查询,为空不提交转人工),成功回填人资是否推送=是+推送时间;核验:待生效+生效中联合取最新合同,时间与AI表续签期一致且签署记录is_initiate_sign=2已完成签署才回填完成签署=是(1已发起/3已撤销均不算);通知块格式与加班审批一致,推送成功/核验完成数量/核验未完成数量/失败/合同到期日异常;HR 会话由壳子注入",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
|
||||
@@ -9,6 +9,7 @@
|
||||
③ 待办完善信息提交 —— 完善信息环节自动保存+送审办结(合同期限/模板/签署单位计算)
|
||||
④ 发起离职电子签 —— 离职电子签办理环节发起(复用 XQ0035 initiate_resign_esign 内嵌副本)
|
||||
⑤ 回写AI表格跟进 —— HR 已发起者回写「改签离职电子签跟进-日更新」+ 回填发起日期
|
||||
(含「调动导出」已发人员补录,发起时间取操作时间)
|
||||
⑥ 签署完成核查回写 —— 离职/新合同签署完成核查 + checkbox 回写
|
||||
|
||||
会话:ctx.get_session("hr") 注入共享 HR 登录态(壳子运行前自动补登);
|
||||
@@ -64,10 +65,10 @@ class _LogWriter:
|
||||
class Xq0037Plugin(ScenePlugin):
|
||||
id = "xq0037"
|
||||
name = "调动改签离职电子签"
|
||||
version = "1.1.6"
|
||||
version = "1.1.7"
|
||||
description = ("XQ0037 调动改签离职电子签:①调动台账导出 ②HR调动信息置位(已发起名单+群提醒) "
|
||||
"③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进 ⑥签署完成核查回写,"
|
||||
"AI表格字段接力驱动、单步执行错峰定时")
|
||||
"③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进(含已发补录) "
|
||||
"⑥签署完成核查回写,AI表格字段接力驱动、单步执行错峰定时")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0037"]
|
||||
|
||||
@@ -1,11 +1,14 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0037 步骤5:HR 已发起工号回写钉钉 AI 表格「改签离职电子签跟进-日更新」(新增行)。
|
||||
|
||||
链路最后一步,与 step2/3/4 同一作用域闸门:仅处理「待办工号列表.json」内工号
|
||||
(step2 置位时登记,step4 发起后保留),字段从当天推送表「已发起名单」取。
|
||||
链路最后一步,字段从当天推送表「已发起名单」取。两类来源:
|
||||
A. 待办工号列表(step2 置位时登记,step4 发起后保留)—— 与 step3/4 同一作用域闸门;
|
||||
B. 「调动导出」第34列公式判定 = 已发 的人员(前序已发起、名单中补录,
|
||||
多为人工在 HR 发起且流程可能已办结,运行中流程反查不到),
|
||||
直接按已发起回写,发起时间取「操作时间」(非当天)。
|
||||
发起成功以 HR 系统为准:
|
||||
1. HR 核查:遍历运行中「改签离职电子签」流程按表单 base_code 匹配工号,
|
||||
再按流程主键查签署记录,is_initiate_sign 非空非 0 即已发起
|
||||
1. HR 核查(仅待办路径):遍历运行中「改签离职电子签」流程按表单 base_code
|
||||
匹配工号,再按流程主键查签署记录,is_initiate_sign 非空非 0 即已发起
|
||||
(step4 自动发起与人工在 HR 里发起同样命中);未发起/运行中流程未找到
|
||||
的保留待办,不回写 AI 表、不回填、不移除;
|
||||
2. HR 已发起者,候选再与名单表取交集(列表内但名单无行的打日志提示,不回写);
|
||||
@@ -41,7 +44,8 @@ import openpyxl
|
||||
from .xq35_step2_sign_new_contract import ( # noqa: E402
|
||||
AITABLE_BASE_ID, AITABLE_OPERATOR_UNIONID, _aitable_request)
|
||||
from .step2_transfer_initiate import ( # noqa: E402
|
||||
TARGET_SHEET, _hr_session, load_pending_list, remove_pending)
|
||||
JUDGE_SENT, KEY_CODE_COL, OP_TIME_COL, SOURCE_HEADER_ROW, SOURCE_SHEET,
|
||||
TARGET_SHEET, VERDICT_COL, _hr_session, load_pending_list, remove_pending)
|
||||
from .step3_transfer_todo import ( # noqa: E402
|
||||
WORKFORM_FORM_ID, _find_push_table, _log, get_business_data,
|
||||
list_running_workflows)
|
||||
@@ -95,6 +99,46 @@ def _ms_day(value):
|
||||
|
||||
|
||||
# ---------- 数据源:待办列表 + 名单表字段 ----------
|
||||
def load_sent_rows():
|
||||
"""「调动导出」第34列 = 已发 的数据行 -> {工号: 操作时间ms}。
|
||||
|
||||
已发 = 前序已发起(HR 侧发起,流程可能早已办结,运行中流程反查不到),
|
||||
故不走 check_hr_initiated,直接按已发起回写;发起时间取「操作时间」。
|
||||
第34列公式缓存由第②步刷新落值;取不到缓存(当天未跑②)时本轮跳过该路径。
|
||||
"""
|
||||
path, _header = _find_push_table()
|
||||
try:
|
||||
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||||
except PermissionError as exc:
|
||||
raise RuntimeError(
|
||||
f"文件被占用,无法读取:{path}\n请先在 WPS/Excel 中关闭该文件后重试。") from exc
|
||||
try:
|
||||
if SOURCE_SHEET not in wb.sheetnames:
|
||||
raise RuntimeError(f"{os.path.basename(path)} 缺少「{SOURCE_SHEET}」sheet")
|
||||
ws = wb[SOURCE_SHEET]
|
||||
sent, uncached = {}, 0
|
||||
for r in range(SOURCE_HEADER_ROW + 1, ws.max_row + 1):
|
||||
code = _s(ws.cell(r, KEY_CODE_COL).value)
|
||||
if not code:
|
||||
continue
|
||||
raw = ws.cell(r, VERDICT_COL).value
|
||||
if raw is None:
|
||||
uncached += 1
|
||||
continue
|
||||
if str(raw).strip() != JUDGE_SENT:
|
||||
continue
|
||||
sent[code] = _ms_day(ws.cell(r, OP_TIME_COL).value)
|
||||
finally:
|
||||
wb.close()
|
||||
if uncached:
|
||||
_log(f"[已发] 「{SOURCE_SHEET}」第{VERDICT_COL}列有 {uncached} 行取不到公式结果,"
|
||||
f"已发回写本轮跳过(请先执行第②步刷新公式后重试)")
|
||||
return {}
|
||||
_log(f"[已发] 「{SOURCE_SHEET}」第{VERDICT_COL}列 = {JUDGE_SENT} 的 {len(sent)} 人"
|
||||
f"{':' + '、'.join(sorted(sent)) if sent else ''}")
|
||||
return sent
|
||||
|
||||
|
||||
def fetch_field_choices():
|
||||
"""「现/原单位名称」字段选项集(两字段选项一致,取并集兜底)。
|
||||
|
||||
@@ -244,9 +288,10 @@ def backfill_init_dates(rows, items):
|
||||
return done
|
||||
|
||||
|
||||
def build_fields(row, today_ms, choices):
|
||||
def build_fields(row, init_ms, choices):
|
||||
"""名单行 + 发起时间 + 选项集 -> AI 表新增行 fields(空值字段不写)。
|
||||
|
||||
发起时间 init_ms:待办路径=当天;已发路径=「调动导出」操作时间。
|
||||
singleSelect(是否已发起改签离职/现单位名称/原单位名称)写入传选项名字符串;
|
||||
单位名称经 pick_unit 匹配选项集,未命中不写该字段(留空告警)。
|
||||
"""
|
||||
@@ -254,7 +299,7 @@ def build_fields(row, today_ms, choices):
|
||||
"姓名": row["姓名"],
|
||||
"工号": row["工号"],
|
||||
FIELD_INITIATED: "是",
|
||||
FIELD_INIT_TIME: today_ms,
|
||||
FIELD_INIT_TIME: init_ms,
|
||||
}
|
||||
t = _ms_day(row["调动时间"])
|
||||
if t:
|
||||
@@ -313,28 +358,42 @@ def check_hr_initiated(session, pending):
|
||||
def main(dry_run=None):
|
||||
dry_run = DRY_RUN if dry_run is None else dry_run
|
||||
pending = load_pending_list()
|
||||
if not pending:
|
||||
_log("[待办] 待办工号列表为空(本批次无人待办),无事可做")
|
||||
sent = load_sent_rows()
|
||||
if not pending and not sent:
|
||||
_log("[待办] 待办工号列表为空,且「调动导出」无已发人员,无事可做")
|
||||
return {"added": 0, "skip_exists": 0, "skip_noroster": 0,
|
||||
"not_initiated": 0, "backfill": 0}
|
||||
_log("[待办] 本批待办 {} 人:{}".format(
|
||||
len(pending), "、".join(f"{c}{n}" for c, n in sorted(pending.items()))))
|
||||
"not_initiated": 0, "backfill": 0, "sent": 0}
|
||||
if pending:
|
||||
_log("[待办] 本批待办 {} 人:{}".format(
|
||||
len(pending), "、".join(f"{c}{n}" for c, n in sorted(pending.items()))))
|
||||
roster = load_roster_rows()
|
||||
existing = fetch_follow_records()
|
||||
|
||||
# 发起成功以 HR 为准:未发起/无流程的保留待办,不回写不回填不移除
|
||||
session = _hr_session()
|
||||
initiated, miss = check_hr_initiated(session, pending)
|
||||
stats = {"added": 0, "skip_exists": 0, "skip_noroster": 0,
|
||||
"not_initiated": len(miss), "backfill": 0}
|
||||
for code, reason in sorted(miss.items()):
|
||||
_log(f"[跳过] {code} {pending[code]} | {reason},保留待办等下次")
|
||||
if not initiated:
|
||||
_log("[完成] HR 侧无人已发起,本轮不回写(试算模式仅核查)"
|
||||
if dry_run else "[完成] HR 侧无人已发起,本轮不回写")
|
||||
"not_initiated": 0, "backfill": 0, "sent": len(sent)}
|
||||
# 待办路径:发起成功以 HR 为准,未发起/无流程的保留待办,不回写不回填不移除
|
||||
initiated = {}
|
||||
if pending:
|
||||
session = _hr_session()
|
||||
initiated, miss = check_hr_initiated(session, pending)
|
||||
stats["not_initiated"] = len(miss)
|
||||
for code, reason in sorted(miss.items()):
|
||||
_log(f"[跳过] {code} {pending[code]} | {reason},保留待办等下次")
|
||||
# 已发路径:公式已判定前序已发起(流程可能已办结),直接按已发起回写
|
||||
sent_only = {c: ms for c, ms in sent.items() if c not in initiated}
|
||||
|
||||
now_ms = _ms_day(datetime.now())
|
||||
# 回写目标:工号 -> 发起时间(已发优先取操作时间,待办取当天)
|
||||
targets = {code: (sent.get(code) or now_ms) for code in initiated}
|
||||
targets.update({code: (ms or now_ms) for code, ms in sent_only.items()})
|
||||
|
||||
if not targets:
|
||||
_log("[完成] 本轮无人可回写,不动 AI 表"
|
||||
+ ("(试算模式仅核查)" if dry_run else ""))
|
||||
_log(f"[汇总] HR已发起=0 未发起或无流程={stats['not_initiated']} "
|
||||
f"名单缺行={stats['skip_noroster']} 新增={stats['added']} "
|
||||
f"已有跳过={stats['skip_exists']} 发起日期回填={stats['backfill']}"
|
||||
f"已发={len(sent_only)} 名单缺行={stats['skip_noroster']} "
|
||||
f"新增={stats['added']} 已有跳过={stats['skip_exists']} "
|
||||
f"发起日期回填={stats['backfill']}"
|
||||
f"{'(试算模式)' if dry_run else ''}")
|
||||
return stats
|
||||
|
||||
@@ -342,27 +401,28 @@ def main(dry_run=None):
|
||||
if not choices:
|
||||
raise RuntimeError("未能获取「现/原单位名称」字段选项集,终止回写以免单位名称写空")
|
||||
add_items, done_codes, init_items = [], [], []
|
||||
today_ms = _ms_day(datetime.now())
|
||||
for code in sorted(initiated):
|
||||
for code, init_ms in sorted(targets.items()):
|
||||
tag = "已发" if code in sent_only else "待办"
|
||||
row = roster.get(code)
|
||||
if row is None:
|
||||
_log(f"[跳过] {code} {pending[code]} | 名单表中无该工号,无法取字段")
|
||||
_log(f"[跳过·{tag}] {code} | 名单表中无该工号,无法取字段")
|
||||
stats["skip_noroster"] += 1
|
||||
continue
|
||||
move_ms = _ms_day(row["调动时间"])
|
||||
dup = next(((rid, m, im) for rid, m, im in existing.get(code, [])
|
||||
if m is not None and m == move_ms), None)
|
||||
if dup:
|
||||
_log(f"[跳过] {code} {row['姓名']} | 本笔调动({row['调动时间']})"
|
||||
_log(f"[跳过·{tag}] {code} {row['姓名']} | 本笔调动({row['调动时间']})"
|
||||
f"AI 表已有记录(record {dup[0]}),视为已回写")
|
||||
stats["skip_exists"] += 1
|
||||
done_codes.append(code)
|
||||
init_items.append((code, dup[2]))
|
||||
continue
|
||||
fields = build_fields(row, today_ms, choices)
|
||||
fields = build_fields(row, init_ms, choices)
|
||||
warn = "" if ("现单位名称" in fields and "原单位名称" in fields) \
|
||||
else "(存在无匹配选项的单位名称,已留空待人工核对)"
|
||||
_log(f"[回写] {code} {row['姓名']} | 现单位 {fields.get('现单位名称') or '空'} | "
|
||||
_log(f"[回写·{tag}] {code} {row['姓名']} | "
|
||||
f"现单位 {fields.get('现单位名称') or '空'} | "
|
||||
f"原单位 {fields.get('原单位名称') or '空'} | 调动 {row['调动时间']}{warn}")
|
||||
add_items.append(fields)
|
||||
|
||||
@@ -371,7 +431,7 @@ def main(dry_run=None):
|
||||
_log(f"[完成] AI 表新增 {len(add_items)} 行(record id:{ids})")
|
||||
stats["added"] = len(add_items)
|
||||
done_codes.extend(f["工号"] for f in add_items)
|
||||
init_items.extend((f["工号"], today_ms) for f in add_items)
|
||||
init_items.extend((f["工号"], targets[f["工号"]]) for f in add_items)
|
||||
elif add_items:
|
||||
_log(f"[完成] 待新增 {len(add_items)} 行(试算模式,未写入)")
|
||||
|
||||
@@ -383,8 +443,9 @@ def main(dry_run=None):
|
||||
if done_codes and not dry_run:
|
||||
remove_pending(done_codes)
|
||||
_log("[待办] 回写完成,已从待办列表移除:{}".format("、".join(done_codes)))
|
||||
_log(f"[汇总] HR已发起={len(initiated)} 未发起或无流程={stats['not_initiated']} "
|
||||
f"名单缺行={stats['skip_noroster']} 新增={stats['added']} "
|
||||
f"已有跳过={stats['skip_exists']} 发起日期回填={stats['backfill']}"
|
||||
_log(f"[汇总] 待办已发起={len(initiated)} 已发={len(sent_only)} "
|
||||
f"未发起或无流程={stats['not_initiated']} 名单缺行={stats['skip_noroster']} "
|
||||
f"新增={stats['added']} 已有跳过={stats['skip_exists']} "
|
||||
f"发起日期回填={stats['backfill']}"
|
||||
f"{'(试算模式)' if dry_run else ''}")
|
||||
return stats
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0037",
|
||||
"name": "调动改签离职电子签",
|
||||
"version": "1.1.6",
|
||||
"description": "XQ0037 调动改签离职电子签:按步骤执行 ①调动台账导出(近三月台账 + 近3天筛选)②按公式判定已发/需要追加「已发起名单」+ HR置位+群提醒 ③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进 ⑥签署完成核查回写;钉钉AI表格字段接力驱动,HR 会话由壳子注入",
|
||||
"version": "1.1.7",
|
||||
"description": "XQ0037 调动改签离职电子签:按步骤执行 ①调动台账导出(近三月台账 + 近3天筛选)②按公式判定已发/需要追加「已发起名单」+ HR置位+群提醒 ③待办完善信息提交 ④发起离职电子签 ⑤回写AI表格跟进(含已发补录) ⑥签署完成核查回写;钉钉AI表格字段接力驱动,HR 会话由壳子注入",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
|
||||
@@ -19,8 +19,8 @@ from .data import crm_export
|
||||
class CrmDataExportPlugin(ScenePlugin):
|
||||
id = "xq0048"
|
||||
name = "CRM数据导出"
|
||||
version = "1.0.0"
|
||||
description = ("37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出,"
|
||||
version = "1.1.6"
|
||||
description = ("37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出(导出内容可勾选),"
|
||||
"登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),"
|
||||
"按各报表日期规则自动计算区间,礼品卡订单按月拆分")
|
||||
platform = "" # CRM 为钉钉扫码登录,插件内自带登录流程,不使用底座共享登录态
|
||||
@@ -29,6 +29,8 @@ class CrmDataExportPlugin(ScenePlugin):
|
||||
permissions = {"platforms": []}
|
||||
# 与 plugin.json.fields 一致
|
||||
fields = {
|
||||
"reports": {"type": "array", "title": "导出内容", "default": [],
|
||||
"description": "勾选键列表(截图=__screenshot__,报表=接口#规则);空/缺省=全部导出"},
|
||||
"save_dir": {"type": "string", "title": "保存目录", "default": "",
|
||||
"description": "留空=D:\\资料\\财务\\CRM数据导出"},
|
||||
"debug_mode": {"type": "boolean", "title": "调试日志", "default": False},
|
||||
@@ -44,12 +46,23 @@ class CrmDataExportPlugin(ScenePlugin):
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
ctx.log(f"保存目录:{save_dir}")
|
||||
|
||||
result = crm_export.run_export(save_dir)
|
||||
report_keys = fields.get("reports")
|
||||
reports, include_shot = config.filter_reports(report_keys)
|
||||
if not reports and not include_shot:
|
||||
raise RuntimeError("未勾选任何导出内容,请至少勾选一项")
|
||||
if report_keys is None:
|
||||
ctx.log("导出内容:全部(截图 + %d 张报表)" % len(reports))
|
||||
else:
|
||||
ctx.log(f"导出内容:{'截图、' if include_shot else ''}{len(reports)} 张报表(按勾选)")
|
||||
|
||||
result = crm_export.run_export(save_dir, report_keys=report_keys)
|
||||
config.progress(100)
|
||||
|
||||
files = result.get("exports") or []
|
||||
summary = (f"截图 {1 if result.get('screenshot') else 0}/1,"
|
||||
f"报表 {result.get('done')}/{result.get('total')},共 {len(files) + 1} 个文件")
|
||||
shot_part = f"截图 {1 if result.get('screenshot') else 0}/1," if include_shot else ""
|
||||
summary = (f"{shot_part}"
|
||||
f"报表 {result.get('done')}/{result.get('total')},"
|
||||
f"共 {len(files) + (1 if result.get('screenshot') else 0)} 个文件")
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": {
|
||||
|
||||
@@ -45,6 +45,57 @@ def get_browser_profile_dir():
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0048')
|
||||
|
||||
|
||||
# ==================== 浏览器窗口(全屏 + 置顶) ====================
|
||||
def apply_window_mode(page):
|
||||
"""把浏览器窗口设为全屏并置顶。
|
||||
|
||||
窗口被其它窗口遮挡或最小化时,渲染进程可能一直不出帧,Page.captureScreenshot
|
||||
会等到超时(DrissionPage 默认 30s)。全屏 + 置顶用于规避这种遮挡型超时;
|
||||
失败仅告警,不影响后续流程。"""
|
||||
try:
|
||||
page.set.window.full()
|
||||
except Exception as e:
|
||||
log(f"设置窗口全屏失败(忽略):{e}", "WARN")
|
||||
if os.name == 'nt':
|
||||
try:
|
||||
_set_topmost(page.process_id)
|
||||
except Exception as e:
|
||||
log(f"设置窗口置顶失败(忽略):{e}", "WARN")
|
||||
|
||||
|
||||
def _set_topmost(pid):
|
||||
"""把指定进程的主窗口设为 HWND_TOPMOST(Win32 SetWindowPos,仅 Windows)。"""
|
||||
if not pid:
|
||||
return
|
||||
import ctypes
|
||||
from ctypes import wintypes
|
||||
|
||||
user32 = ctypes.windll.user32
|
||||
user32.IsWindowVisible.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowTextLengthW.argtypes = [wintypes.HWND]
|
||||
user32.GetWindowThreadProcessId.argtypes = [wintypes.HWND, ctypes.POINTER(wintypes.DWORD)]
|
||||
|
||||
hwnds = []
|
||||
|
||||
@ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM)
|
||||
def _collect(hwnd, _lparam):
|
||||
if user32.IsWindowVisible(hwnd) and user32.GetWindowTextLengthW(hwnd) > 0:
|
||||
proc = wintypes.DWORD()
|
||||
user32.GetWindowThreadProcessId(hwnd, ctypes.byref(proc))
|
||||
if proc.value == pid:
|
||||
hwnds.append(hwnd)
|
||||
return True
|
||||
|
||||
user32.EnumWindows.argtypes = [ctypes.WINFUNCTYPE(wintypes.BOOL, wintypes.HWND, wintypes.LPARAM),
|
||||
wintypes.LPARAM]
|
||||
user32.EnumWindows(_collect, 0)
|
||||
|
||||
user32.SetWindowPos.argtypes = [wintypes.HWND, wintypes.HWND, ctypes.c_int,
|
||||
ctypes.c_int, ctypes.c_int, ctypes.c_int, ctypes.c_uint]
|
||||
for hwnd in hwnds:
|
||||
user32.SetWindowPos(hwnd, wintypes.HWND(-1), 0, 0, 0, 0, 0x0001 | 0x0002) # NOSIZE | NOMOVE
|
||||
|
||||
|
||||
# ==================== 运行参数(项目规范:全局重试 3 次) ====================
|
||||
RETRY_MAX = 3 # 截图/单报表重试
|
||||
PAGE_SIZE = 13 # 与页面一致;实测服务端导出不受分页影响
|
||||
@@ -64,7 +115,8 @@ UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
# 规则:prev=前一天单日;prev_today=昨日~今日;month_to_today=本月1日~今日;
|
||||
# prev_prev=昨日~昨日;month1_to_prev=本月1日~前一天;last_month=上月完整;
|
||||
# last3_months=近 3 个自然月按月拆分(止日不超过前一天)
|
||||
# 日期参数字段:报表统计类为 reportDate;开卡订单/会员退卡为 period;
|
||||
# 日期参数字段:报表统计类为 reportDate;淘宝订单为 createTimePeriod(页面「购买时间」);
|
||||
# 微盟核销为 validateDatePeriod;开卡订单/会员退卡为 period;
|
||||
# 礼品卡订单为 receiveTimePeriod(接口限制跨度 ≤31 天,故按月拆分)
|
||||
REPORTS = [
|
||||
('团购支付数据', 'report/groupPay/export', 'prev', None, 'reportDate'),
|
||||
@@ -72,9 +124,9 @@ REPORTS = [
|
||||
('第三方支付(门店)', 'report/thirdPayShop/export', 'prev', None, 'reportDate'),
|
||||
('支付数据', 'report/unionPay/export', 'prev', None, 'reportDate'),
|
||||
('团购数据', 'report/groupData/export', 'prev_today', None, 'reportDate'),
|
||||
('淘宝订单数据', 'report/taobaoTicket/export', 'prev_today', None, 'reportDate'),
|
||||
('淘宝订单数据', 'report/taobaoTicket/export', 'prev_today', None, 'createTimePeriod'),
|
||||
('技师综合业绩', 'report/comprehensivePerformance/export', 'month_to_today', None, 'reportDate'),
|
||||
('微盟核销统计', 'report/weimeng/exportValidate', 'prev_prev', None, 'reportDate'),
|
||||
('微盟核销统计', 'report/weimeng/exportValidate', 'prev_prev', None, 'validateDatePeriod'), # 该页日期字段是 validateDatePeriod("起 止")
|
||||
('小程序订单', 'report/miniProgramOrder/export', 'last_month', None, 'reportDate'),
|
||||
('小程序订单', 'report/miniProgramOrder/export', 'month_to_today', None, 'reportDate'),
|
||||
('储值卡消费', 'report/debitCardConsume/export', 'month1_to_prev', None, 'reportDate'),
|
||||
@@ -87,6 +139,30 @@ REPORTS = [
|
||||
('礼品卡订单', 'giftcard/order/export', 'last3_months', None, 'receiveTimePeriod'),
|
||||
]
|
||||
|
||||
# ==================== 导出内容选择(UI 勾选) ====================
|
||||
SCREENSHOT_KEY = '__screenshot__' # 储值卡余额整页截图的勾选键
|
||||
|
||||
|
||||
def report_key(entry):
|
||||
"""报表稳定勾选键:导出接口#日期规则(与 UI 清单一一对应,跨版本稳定)。"""
|
||||
_title, path, rule, _extra, _date_key = entry
|
||||
return f'{path}#{rule}'
|
||||
|
||||
|
||||
def filter_reports(keys):
|
||||
"""按 UI 勾选键筛选导出内容。
|
||||
|
||||
keys 为 None(旧配置/未传)→ 全部导出;否则按勾选键过滤。
|
||||
返回 (报表列表, 是否含储值卡余额截图)。
|
||||
"""
|
||||
if keys is None:
|
||||
return list(REPORTS), True
|
||||
wanted = {str(k) for k in keys}
|
||||
include_shot = SCREENSHOT_KEY in wanted
|
||||
reports = [e for e in REPORTS if report_key(e) in wanted]
|
||||
return reports, include_shot
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
|
||||
@@ -27,6 +27,13 @@ from . import crm_login
|
||||
_auth_dead = False
|
||||
|
||||
|
||||
class ScanTimeoutError(RuntimeError):
|
||||
"""人工扫码/登录未完成——属人工未完成,不是浏览器异常。
|
||||
|
||||
必须与 DrissionPage 的 CDP 超时(内置 TimeoutError)区分:后者是浏览器卡顿,
|
||||
应正常重试,绝不能判定登录态失效、连带跳过全部报表。"""
|
||||
|
||||
|
||||
def _log(msg, level="INFO"):
|
||||
config.log(msg, level)
|
||||
|
||||
@@ -142,7 +149,7 @@ def _goto_ready(page, url):
|
||||
time.sleep(2)
|
||||
if _is_login_page(page.url):
|
||||
if not _wait_login(page):
|
||||
raise TimeoutError(f"登录未完成({config.LOGIN_WAIT}s 超时),请在窗口内完成钉钉扫码")
|
||||
raise ScanTimeoutError(f"登录未完成({config.LOGIN_WAIT}s 超时),请在窗口内完成钉钉扫码")
|
||||
page.get(url)
|
||||
continue
|
||||
if config.PAGE_TITLE_KEYWORD in (page.title or ''):
|
||||
@@ -168,6 +175,8 @@ def _capture_balance(save_dir, date_str, headless):
|
||||
co.set_user_data_path(profile_dir)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
if not headless:
|
||||
config.apply_window_mode(page) # 全屏 + 置顶,规避遮挡导致的截图超时
|
||||
# 先看浏览器 profile 自身会话:有效就不注入,避免用旧快照覆盖仍有效的会话
|
||||
page.get(config.BALANCE_URL)
|
||||
if _is_login_page(page.url) or not _api_ok(page):
|
||||
@@ -190,13 +199,13 @@ def _capture_balance(save_dir, date_str, headless):
|
||||
|
||||
|
||||
def _screenshot(save_dir, date_str):
|
||||
"""截图重试 3 次;登录超时属人工未完成,不再重开浏览器。"""
|
||||
"""截图重试 3 次;仅人工扫码超时不重试,浏览器卡顿(CDP 超时)照常重试。"""
|
||||
last_err = None
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
_log(f"第 {attempt}/{config.RETRY_MAX} 次截图 → {config.BALANCE_URL}")
|
||||
return _capture_balance(save_dir, date_str, config.HEADLESS)
|
||||
except TimeoutError:
|
||||
except ScanTimeoutError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
@@ -266,13 +275,13 @@ def _download(session, url, params):
|
||||
return None, False
|
||||
|
||||
|
||||
def _export_one(title, path, rule, extra, save_dir, date_key):
|
||||
def _export_one(title, path, rule, extra, save_dir, date_key, idx, total):
|
||||
"""导出单张报表(按月规则会产出多个文件),返回落盘路径列表。"""
|
||||
return [_export_window(title, path, beg, end, extra, save_dir, date_key)
|
||||
return [_export_window(title, path, beg, end, extra, save_dir, date_key, idx, total)
|
||||
for beg, end in _date_windows(rule)]
|
||||
|
||||
|
||||
def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
def _export_window(title, path, beg, end, extra, save_dir, date_key, idx, total):
|
||||
"""导出某个日期窗口(含 401 → 刷新登录态 → 重试),返回落盘路径。"""
|
||||
global _auth_dead
|
||||
|
||||
@@ -283,6 +292,7 @@ def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
if date_key == 'reportDate' and beg == end:
|
||||
date_val = f'{beg:%Y-%m-%d}'
|
||||
params = {'pageNum': 1, 'pageSize': config.PAGE_SIZE, date_key: date_val}
|
||||
date_desc = f'{date_key}={date_val}'
|
||||
if extra:
|
||||
params.update(extra)
|
||||
|
||||
@@ -301,7 +311,7 @@ def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
_auth_dead = True
|
||||
break
|
||||
try:
|
||||
_log(f"[{attempt}/{config.RETRY_MAX}] {filename} ← {path} {date_key}={date_val}")
|
||||
_log(f"[{idx}/{total}] {filename} ← {path} {date_desc}")
|
||||
content, auth_failed = _download(session, url, params)
|
||||
if content:
|
||||
with open(save_path, 'wb') as f:
|
||||
@@ -326,12 +336,14 @@ def _export_window(title, path, beg, end, extra, save_dir, date_key):
|
||||
|
||||
|
||||
# ==================== 主入口 ====================
|
||||
def run_export(save_dir='', date_str=''):
|
||||
"""截图 + 18 张报表导出。
|
||||
def run_export(save_dir='', date_str='', report_keys=None):
|
||||
"""截图 + 报表导出(可按勾选筛选导出内容)。
|
||||
|
||||
参数:
|
||||
save_dir 保存目录,默认 D:\\资料\\财务\\CRM数据导出
|
||||
date_str 截图文件名日期(YYYYMMDD),默认当日
|
||||
report_keys 勾选键列表(截图=__screenshot__,报表=接口#规则);
|
||||
None/缺省 = 全部导出
|
||||
返回:
|
||||
{'screenshot': 截图路径, 'exports': [xlsx 路径...], 'errors': [],
|
||||
'done': 成功报表数, 'total': 报表总数}
|
||||
@@ -342,6 +354,7 @@ def run_export(save_dir='', date_str=''):
|
||||
save_dir = (save_dir or '').strip().strip('"') or config.default_output_dir()
|
||||
date_str = (date_str or '').strip() or time.strftime('%Y%m%d')
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
reports, include_shot = config.filter_reports(report_keys)
|
||||
_auth_dead = False
|
||||
errors = []
|
||||
|
||||
@@ -352,31 +365,32 @@ def run_export(save_dir='', date_str=''):
|
||||
else:
|
||||
_log("登录态无效,本次运行需扫码一次(成功后后续步骤全部复用)……", "WARN")
|
||||
|
||||
# ---------- 1) 储值卡余额截图 ----------
|
||||
# ---------- 1) 储值卡余额截图(按勾选) ----------
|
||||
config.progress(5)
|
||||
shot = ''
|
||||
try:
|
||||
shot = _screenshot(save_dir, date_str)
|
||||
except TimeoutError as e:
|
||||
# 扫码超时属人工未完成,后续报表也必然 401,直接标记无救
|
||||
_auth_dead = True
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败(登录超时):{e}", "ERROR")
|
||||
except Exception as e:
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败:{e}", "ERROR")
|
||||
if include_shot:
|
||||
try:
|
||||
shot = _screenshot(save_dir, date_str)
|
||||
except ScanTimeoutError as e:
|
||||
# 扫码超时属人工未完成,后续报表也必然 401,直接标记无救
|
||||
_auth_dead = True
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败(登录超时):{e}", "ERROR")
|
||||
except Exception as e:
|
||||
errors.append(f"储值卡余额截图:{e}")
|
||||
_log(f"截图失败:{e}", "ERROR")
|
||||
config.progress(12)
|
||||
|
||||
# ---------- 2) 18 张报表导出 ----------
|
||||
# ---------- 2) 报表导出(按勾选) ----------
|
||||
saved, skipped = [], []
|
||||
done = 0
|
||||
total = len(config.REPORTS)
|
||||
for idx, (title, path, rule, extra, date_key) in enumerate(config.REPORTS, start=1):
|
||||
total = len(reports)
|
||||
for idx, (title, path, rule, extra, date_key) in enumerate(reports, start=1):
|
||||
if _auth_dead:
|
||||
skipped.append(title)
|
||||
continue
|
||||
try:
|
||||
saved.extend(_export_one(title, path, rule, extra, save_dir, date_key))
|
||||
saved.extend(_export_one(title, path, rule, extra, save_dir, date_key, idx, total))
|
||||
done += 1
|
||||
except Exception as e:
|
||||
errors.append(str(e))
|
||||
@@ -385,7 +399,8 @@ def run_export(save_dir='', date_str=''):
|
||||
if skipped:
|
||||
errors.append(f"{'、'.join(skipped)}:登录态失效,已跳过")
|
||||
|
||||
_log(f"本次运行完成:截图 {1 if shot else 0}/1,报表 {done}/{total}(文件 {len(saved)} 个)")
|
||||
shot_part = f"截图 {1 if shot else 0}/1," if include_shot else ""
|
||||
_log(f"本次运行完成:{shot_part}报表 {done}/{total}(文件 {len(saved)} 个)")
|
||||
if errors:
|
||||
raise RuntimeError(f"存在失败项:{';'.join(errors)}")
|
||||
return {'screenshot': shot, 'exports': saved, 'errors': [],
|
||||
|
||||
@@ -334,6 +334,8 @@ def _attempt(force, headless, wait_scan):
|
||||
co.set_user_data_path(profile_dir)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
if not headless:
|
||||
config.apply_window_mode(page) # 全屏 + 置顶,扫码窗口不被遮挡
|
||||
if not force and _check_reuse(page):
|
||||
# 静默重登可能已在浏览器内刷新会话,等首屏请求结束后同步文件快照
|
||||
time.sleep(config.LOGIN_SETTLE)
|
||||
|
||||
@@ -2,13 +2,13 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0048",
|
||||
"name": "CRM数据导出",
|
||||
"version": "1.0.0",
|
||||
"description": "37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出。登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),按各报表日期规则自动计算区间,礼品卡订单因接口限制跨度 ≤31 天按月拆分。",
|
||||
"version": "1.1.6",
|
||||
"description": "37du CRM(crm.37du.co)数据导出:储值卡余额整页截图 + 18 张报表自动导出(导出内容可勾选)。登录态钉钉扫码一次后缓存复用(约 30 分钟内免扫码),按各报表日期规则自动计算区间,礼品卡订单因接口限制跨度 ≤31 天按月拆分。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0048"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
@@ -16,6 +16,15 @@
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"reports": {
|
||||
"type": "array",
|
||||
"title": "导出内容",
|
||||
"items": {
|
||||
"type": "string"
|
||||
},
|
||||
"default": [],
|
||||
"description": "勾选键列表(截图=__screenshot__,报表=接口#规则);空/缺省=全部导出"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
|
||||
@@ -0,0 +1,12 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CRM数据导出</title>
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
<script type="module" src="/src/main.js"></script>
|
||||
</body>
|
||||
</html>
|
||||
+1585
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"name": "xq0048-ui",
|
||||
"private": true,
|
||||
"version": "1.0.0",
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
"dev": "vite",
|
||||
"build": "vite build"
|
||||
},
|
||||
"dependencies": {
|
||||
"@element-plus/icons-vue": "^2.3.2",
|
||||
"element-plus": "^2.14.5",
|
||||
"vue": "^3.5.13"
|
||||
},
|
||||
"devDependencies": {
|
||||
"@vitejs/plugin-vue": "^5.2.1",
|
||||
"vite": "^6.0.3"
|
||||
},
|
||||
"allowScripts": {
|
||||
"esbuild@0.25.12": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,635 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 未登录 / 结果横幅 -->
|
||||
<transition name="fade-slide">
|
||||
<el-alert v-if="needLogin" type="warning" :closable="false" show-icon title="未登录:请先在壳子(工作台)登录统一账户,再刷新本界面" />
|
||||
<el-alert v-else-if="banner" :type="banner.type" :closable="true" show-icon @close="banner = null">
|
||||
<template #title>{{ banner.text }}</template>
|
||||
</el-alert>
|
||||
</transition>
|
||||
|
||||
<!-- 执行配置(头部含多配置方案:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<el-card shadow="never" class="panel">
|
||||
<template #header>
|
||||
<div class="panel-head">
|
||||
<div class="panel-title">
|
||||
<span class="title-ico">
|
||||
<svg viewBox="0 0 24 24" width="17" height="17" fill="none" stroke="currentColor" stroke-width="2"
|
||||
stroke-linecap="round" stroke-linejoin="round">
|
||||
<path d="M21 15v4a2 2 0 0 1-2 2H5a2 2 0 0 1-2-2v-4" />
|
||||
<polyline points="7 10 12 15 17 10" />
|
||||
<line x1="12" y1="15" x2="12" y2="3" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">勾选导出内容,参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span v-if="lastSavedAt" class="saved">
|
||||
<i class="dot" />已保存 {{ lastSavedAt }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running" @change="onSchemeChange">
|
||||
<el-option v-for="o in schemeOptions" :key="o.value" :label="o.label" :value="o.value" />
|
||||
</el-select>
|
||||
<el-button size="small" :disabled="running" @click="saveSchemeAs">存为方案</el-button>
|
||||
<el-button size="small" text type="danger" :disabled="running || !schemeSel"
|
||||
@click="removeScheme">删除</el-button>
|
||||
</div>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<el-form label-position="top">
|
||||
<!-- 执行说明 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">执行说明</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="flow-desc">
|
||||
<div class="flow-item"><span class="flow-no">1</span>登录态预检:约 30 分钟内免扫码;失效时自动打开浏览器,钉钉扫码一次后全程复用</div>
|
||||
<div class="flow-item"><span class="flow-no">2</span>「报表统计/储值卡余额」整页截图 → 储值卡余额-YYYYMMDD.png</div>
|
||||
<div class="flow-item"><span class="flow-no">3</span>按勾选的报表自动计算日期区间,逐张导出 xlsx(礼品卡订单因接口限制跨度 ≤31 天,按月拆分)</div>
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 导出内容(按业务分组) -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">导出内容</span>
|
||||
<span class="sec-line" />
|
||||
<span class="sec-count">已选 <b>{{ form.reports.length }}</b> / {{ ALL_KEYS.length }} 项</span>
|
||||
<el-button size="small" text type="primary" :disabled="running" @click="selectAll">全选</el-button>
|
||||
<el-button size="small" text :disabled="running || !form.reports.length" @click="clearAll">清空</el-button>
|
||||
</div>
|
||||
<div class="groups">
|
||||
<div v-for="g in GROUPED" :key="g.name" class="grp">
|
||||
<div class="grp-head">
|
||||
<el-checkbox :model-value="g.all" :indeterminate="g.some" :disabled="running"
|
||||
@change="toggleGroup(g)">{{ g.name }}</el-checkbox>
|
||||
<span class="grp-count" :class="{ full: g.all }">{{ g.picked }}/{{ g.items.length }}</span>
|
||||
</div>
|
||||
<div class="grp-body">
|
||||
<el-checkbox v-for="it in g.items" :key="it.key" :model-value="form.reports.includes(it.key)"
|
||||
:disabled="running" class="rep-item" @change="toggleItem(it.key)">
|
||||
<span class="rep-name">{{ it.name }}</span>
|
||||
<el-tooltip :content="it.tag" placement="top" :show-after="150">
|
||||
<el-icon class="rep-info"><InfoFilled /></el-icon>
|
||||
</el-tooltip>
|
||||
</el-checkbox>
|
||||
</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="tip">日期区间由各报表规则自动计算:截图=当天;前一天;昨日~今日;昨日;本月1日~今日;本月1日~昨日;上月完整;近3个自然月(礼品卡订单按月拆分)</div>
|
||||
</section>
|
||||
|
||||
<!-- 执行设置 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">03</span>
|
||||
<span class="sec-name">执行设置</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid">
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running" clearable
|
||||
placeholder="留空 = D:\资料\财务\CRM数据导出" />
|
||||
</el-form-item>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">截图与全部 xlsx 统一输出到保存目录;「调试日志」开启后输出完整调试信息(默认关闭)</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" size="large" class="btn-run" :loading="running" @click="run">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" size="large" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button size="large" :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button size="large" text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<transition name="fade-slide">
|
||||
<div v-if="running" class="status">
|
||||
<el-progress :percentage="progress" :stroke-width="10" :show-text="false" class="status-bar" />
|
||||
<div class="status-row">
|
||||
<span class="pulse" />
|
||||
<span class="status-txt">正在执行,日志与进度实时显示在工作台下方【运行日志】区</span>
|
||||
<span class="status-pct">{{ progress }}%</span>
|
||||
</div>
|
||||
</div>
|
||||
</transition>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed } from 'vue'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { InfoFilled } from '@element-plus/icons-vue'
|
||||
|
||||
// 导出内容清单(key 与后端 config 一致:截图=__screenshot__,报表=导出接口#日期规则)
|
||||
const ITEMS = [
|
||||
{ key: '__screenshot__', name: '储值卡余额整页截图', tag: '截图·当天', group: '储值卡余额' },
|
||||
{ key: 'report/groupPay/export#prev', name: '团购支付数据', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/cashPay/export#prev', name: '现金支付', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/thirdPayShop/export#prev', name: '第三方支付(门店)', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/unionPay/export#prev', name: '支付数据', tag: '前一天', group: '支付数据' },
|
||||
{ key: 'report/groupData/export#prev_today', name: '团购数据', tag: '昨日~今日', group: '支付数据' },
|
||||
{ key: 'report/taobaoTicket/export#prev_today', name: '淘宝订单数据', tag: '昨日~今日', group: '支付数据' },
|
||||
{ key: 'report/comprehensivePerformance/export#month_to_today', name: '技师综合业绩', tag: '本月1日~今日', group: '业绩与核销' },
|
||||
{ key: 'report/weimeng/exportValidate#prev_prev', name: '微盟核销统计', tag: '昨日', group: '业绩与核销' },
|
||||
{ key: 'report/debitCardConsume/export#month1_to_prev', name: '储值卡消费', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/depositData/export#month1_to_prev', name: '储值卡线上充值', tag: '本月1日~昨日·渠道=管理端', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/overlordOrderDeposit/export#month1_to_prev', name: '霸王餐充值明细', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/overlordOrderConsume/export#month1_to_prev', name: '霸王餐消费明细', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
{ key: 'report/overlordOrderBalance/export#month1_to_prev', name: '霸王餐余额查询', tag: '本月1日~昨日', group: '储值卡与霸王餐' },
|
||||
{ key: 'member/order/export#month1_to_prev', name: '开卡订单', tag: '本月1日~昨日', group: '会员与卡券' },
|
||||
{ key: 'member/cancel/export#month1_to_prev', name: '会员退卡', tag: '本月1日~昨日', group: '会员与卡券' },
|
||||
{ key: 'giftcard/order/export#last3_months', name: '礼品卡订单', tag: '近3个自然月·按月拆分', group: '会员与卡券' },
|
||||
{ key: 'report/miniProgramOrder/export#last_month', name: '小程序订单(上月完整)', tag: '上月完整', group: '小程序' },
|
||||
{ key: 'report/miniProgramOrder/export#month_to_today', name: '小程序订单(本月至今)', tag: '本月1日~今日', group: '小程序' },
|
||||
]
|
||||
const ALL_KEYS = ITEMS.map((i) => i.key)
|
||||
const GROUPS = [...new Set(ITEMS.map((i) => i.group))]
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
reports: [...ALL_KEYS],
|
||||
save_dir: '',
|
||||
debug_mode: false,
|
||||
})
|
||||
|
||||
const {
|
||||
form, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.reports.length) {
|
||||
ElMessage.warning('请至少勾选一项导出内容')
|
||||
return false
|
||||
}
|
||||
return true
|
||||
},
|
||||
})
|
||||
|
||||
// 按业务分组:组级全选状态 + 已选计数
|
||||
const GROUPED = computed(() => GROUPS.map((name) => {
|
||||
const items = ITEMS.filter((i) => i.group === name)
|
||||
const picked = items.filter((i) => form.reports.includes(i.key)).length
|
||||
return {
|
||||
name,
|
||||
items,
|
||||
picked,
|
||||
all: picked === items.length,
|
||||
some: picked > 0 && picked < items.length,
|
||||
}
|
||||
}))
|
||||
|
||||
function toggleItem(key) {
|
||||
const idx = form.reports.indexOf(key)
|
||||
if (idx >= 0) form.reports.splice(idx, 1)
|
||||
else form.reports.push(key)
|
||||
}
|
||||
|
||||
function toggleGroup(g) {
|
||||
const keys = g.items.map((i) => i.key)
|
||||
if (g.all) {
|
||||
form.reports = form.reports.filter((k) => !keys.includes(k))
|
||||
} else {
|
||||
keys.forEach((k) => {
|
||||
if (!form.reports.includes(k)) form.reports.push(k)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
function selectAll() {
|
||||
form.reports = [...ALL_KEYS]
|
||||
}
|
||||
|
||||
function clearAll() {
|
||||
form.reports = []
|
||||
}
|
||||
</script>
|
||||
|
||||
<style scoped>
|
||||
/* ---------- 页面骨架 ---------- */
|
||||
.page {
|
||||
width: 100%;
|
||||
padding: 6px 4px 28px;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 14px;
|
||||
}
|
||||
|
||||
.fade-slide-enter-active,
|
||||
.fade-slide-leave-active {
|
||||
transition: opacity 0.25s ease, transform 0.25s ease;
|
||||
}
|
||||
|
||||
.fade-slide-enter-from,
|
||||
.fade-slide-leave-to {
|
||||
opacity: 0;
|
||||
transform: translateY(-6px);
|
||||
}
|
||||
|
||||
/* ---------- 主容器(无边框平铺:外层由壳子 iframe 的边框统一包裹) ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border-radius: 0;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
overflow: hidden;
|
||||
}
|
||||
|
||||
.panel :deep(.el-card__header) {
|
||||
padding: 6px 2px 16px;
|
||||
border-bottom: 1px solid var(--el-border-color-lighter);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.panel :deep(.el-card__body) {
|
||||
padding: 16px 2px 2px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部 ---------- */
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 12px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 12px;
|
||||
}
|
||||
|
||||
.title-ico {
|
||||
width: 36px;
|
||||
height: 36px;
|
||||
border-radius: 10px;
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--el-color-primary);
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-8), var(--el-color-primary-light-6));
|
||||
box-shadow: inset 0 0 0 1px var(--el-color-primary-light-5);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.title-txt {
|
||||
font-weight: 700;
|
||||
font-size: 15px;
|
||||
line-height: 1.2;
|
||||
color: var(--el-text-color-primary);
|
||||
}
|
||||
|
||||
.title-sub {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.3;
|
||||
}
|
||||
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
font-size: 12px;
|
||||
color: #2ea44f;
|
||||
background: rgba(46, 164, 79, 0.1);
|
||||
border: 1px solid rgba(46, 164, 79, 0.25);
|
||||
padding: 2px 10px;
|
||||
border-radius: 999px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.saved .dot {
|
||||
width: 6px;
|
||||
height: 6px;
|
||||
border-radius: 50%;
|
||||
background: #2ea44f;
|
||||
}
|
||||
|
||||
/* ---------- 表单分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.sec-badge {
|
||||
width: 24px;
|
||||
height: 24px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sec-name {
|
||||
font-size: 14px;
|
||||
font-weight: 600;
|
||||
color: var(--el-text-color-primary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--el-border-color-lighter), transparent);
|
||||
}
|
||||
|
||||
.sec-count {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-count b {
|
||||
color: var(--el-color-primary);
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
/* 执行说明 */
|
||||
.flow-desc {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 8px;
|
||||
}
|
||||
|
||||
.flow-item {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: 10px;
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.6;
|
||||
}
|
||||
|
||||
.flow-no {
|
||||
width: 20px;
|
||||
height: 20px;
|
||||
border-radius: 6px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font-size: 12px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
background: var(--el-color-primary-light-9);
|
||||
border: 1px solid var(--el-color-primary-light-7);
|
||||
flex-shrink: 0;
|
||||
margin-top: 2px;
|
||||
}
|
||||
|
||||
/* ---------- 导出内容分组 ---------- */
|
||||
.groups {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(340px, 1fr));
|
||||
gap: 10px;
|
||||
}
|
||||
|
||||
.grp {
|
||||
border: 1px solid var(--el-border-color-lighter);
|
||||
border-radius: 10px;
|
||||
padding: 10px 14px 12px;
|
||||
background: var(--el-fill-color-blank);
|
||||
transition: border-color 0.2s;
|
||||
}
|
||||
|
||||
.grp:hover {
|
||||
border-color: var(--el-color-primary-light-5);
|
||||
}
|
||||
|
||||
.grp-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: 8px;
|
||||
padding-bottom: 6px;
|
||||
margin-bottom: 4px;
|
||||
border-bottom: 1px dashed var(--el-border-color-lighter);
|
||||
}
|
||||
|
||||
.grp-head :deep(.el-checkbox__label) {
|
||||
font-weight: 600;
|
||||
font-size: 13px;
|
||||
}
|
||||
|
||||
.grp-count {
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
background: var(--el-fill-color);
|
||||
border-radius: 999px;
|
||||
padding: 1px 8px;
|
||||
}
|
||||
|
||||
.grp-count.full {
|
||||
color: var(--el-color-success);
|
||||
background: rgba(46, 164, 79, 0.1);
|
||||
}
|
||||
|
||||
.grp-body {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fill, minmax(150px, 1fr));
|
||||
gap: 2px 8px;
|
||||
margin-top: 4px;
|
||||
}
|
||||
|
||||
.grp-body :deep(.el-checkbox) {
|
||||
margin-right: 0;
|
||||
height: 26px;
|
||||
}
|
||||
|
||||
.grp-body :deep(.el-checkbox__label) {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 5px;
|
||||
font-size: 12.5px;
|
||||
color: var(--el-text-color-primary);
|
||||
padding-left: 4px;
|
||||
}
|
||||
|
||||
.rep-info {
|
||||
font-size: 13px;
|
||||
color: var(--el-text-color-placeholder);
|
||||
cursor: help;
|
||||
flex-shrink: 0;
|
||||
transition: color 0.2s;
|
||||
}
|
||||
|
||||
.rep-info:hover {
|
||||
color: var(--el-color-primary);
|
||||
}
|
||||
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: minmax(280px, 1fr) auto;
|
||||
gap: 0 18px;
|
||||
align-items: start;
|
||||
}
|
||||
|
||||
.grid :deep(.el-form-item) {
|
||||
margin-bottom: 0;
|
||||
}
|
||||
|
||||
.grid :deep(.el-form-item__label) {
|
||||
padding-bottom: 6px;
|
||||
font-weight: 500;
|
||||
}
|
||||
|
||||
.tip {
|
||||
width: 100%;
|
||||
font-size: 12px;
|
||||
color: var(--el-text-color-secondary);
|
||||
line-height: 1.6;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 10px;
|
||||
border-top: 1px dashed var(--el-border-color);
|
||||
padding-top: 18px;
|
||||
margin-top: 18px;
|
||||
}
|
||||
|
||||
.spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
border: none;
|
||||
border-radius: 10px;
|
||||
letter-spacing: 2px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
box-shadow: 0 6px 16px var(--el-color-primary-light-6);
|
||||
transition: filter 0.2s, box-shadow 0.2s, transform 0.15s;
|
||||
}
|
||||
|
||||
.btn-run:hover {
|
||||
filter: brightness(1.06);
|
||||
box-shadow: 0 8px 20px var(--el-color-primary-light-5);
|
||||
transform: translateY(-1px);
|
||||
}
|
||||
|
||||
.btn-run:active {
|
||||
transform: translateY(0);
|
||||
}
|
||||
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: 12px;
|
||||
background: linear-gradient(135deg, var(--el-color-primary-light-9), var(--el-color-primary-light-8));
|
||||
border: 1px solid var(--el-color-primary-light-6);
|
||||
box-shadow: 0 2px 10px var(--el-color-primary-light-7);
|
||||
}
|
||||
|
||||
.status-bar :deep(.el-progress-bar__outer) {
|
||||
background: rgba(64, 158, 255, 0.15);
|
||||
}
|
||||
|
||||
.status-bar :deep(.el-progress-bar__inner) {
|
||||
background: linear-gradient(90deg, var(--el-color-primary), var(--el-color-primary-dark-2));
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: 8px;
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.pulse {
|
||||
width: 8px;
|
||||
height: 8px;
|
||||
border-radius: 50%;
|
||||
background: var(--el-color-primary);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--el-color-primary-light-6);
|
||||
}
|
||||
|
||||
70% {
|
||||
box-shadow: 0 0 0 8px transparent;
|
||||
}
|
||||
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
flex: 1;
|
||||
font-size: 12.5px;
|
||||
color: var(--el-text-color-regular);
|
||||
line-height: 1.5;
|
||||
}
|
||||
|
||||
.status-pct {
|
||||
font-size: 14px;
|
||||
font-weight: 700;
|
||||
color: var(--el-color-primary);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
</style>
|
||||
@@ -0,0 +1,2 @@
|
||||
// 插件身份声明(API 实现收敛在 usePluginUI.js 公共 kit,各插件 ui-src 只需声明自己的 id)
|
||||
export const PLUGIN_ID = 'xq0048'
|
||||
@@ -0,0 +1,7 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
import zhCn from 'element-plus/es/locale/lang/zh-cn'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus, { locale: zhCn }).mount('#app')
|
||||
@@ -0,0 +1,340 @@
|
||||
// 插件 UI 公共 kit(vendored 进各插件 ui-src,构建期内联进产物,运行零外部依赖)。
|
||||
// 收敛三块通用逻辑,App.vue 只保留各插件差异部分(表单字段/校验/布局):
|
||||
// 1. 本机当前配置:加载、防抖自动保存、恢复默认(/api/plugin-config/<id>)
|
||||
// 2. 多配置方案:列表/应用/存为方案/删除(/api/plugin-configs,同名覆盖、密码明文保存;
|
||||
// 供壳子「定时任务」按 config_id 引用,到点自动取方案最新参数)
|
||||
// 3. 执行状态机:一键执行、强制停止、WS 实时进度 + 轮询兜底、未登录重试
|
||||
import { computed, onMounted, reactive, ref, watch } from 'vue'
|
||||
import { ElMessage, ElMessageBox } from 'element-plus'
|
||||
import { PLUGIN_ID } from './api'
|
||||
|
||||
async function j(url, opts) {
|
||||
const res = await fetch(url, opts)
|
||||
if (res.status === 401) {
|
||||
throw Object.assign(new Error('未登录:请先在壳子登录统一账户再打开本界面'), { code: 401 })
|
||||
}
|
||||
if (!res.ok) {
|
||||
let msg = `HTTP ${res.status}`
|
||||
try { msg = (await res.json()).detail || msg } catch (_) { /* 保留默认 */ }
|
||||
throw new Error(msg)
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
function loadConfig() {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
}
|
||||
|
||||
function saveConfig(data) {
|
||||
return j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
}
|
||||
|
||||
function listSchemes() {
|
||||
return j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
}
|
||||
|
||||
function saveScheme(name, fields) {
|
||||
return j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function deleteScheme(cfgId) {
|
||||
return j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, {
|
||||
method: 'DELETE',
|
||||
})
|
||||
}
|
||||
|
||||
function startRun(fields) {
|
||||
return j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
}
|
||||
|
||||
function getRun(runId) {
|
||||
return j(`/api/runs/${runId}`)
|
||||
}
|
||||
|
||||
function stopRun(runId) {
|
||||
return j(`/api/runs/${runId}/stop`, { method: 'POST' })
|
||||
}
|
||||
|
||||
function connectWS(onEvent) {
|
||||
const ws = new WebSocket((location.protocol === 'https:' ? 'wss://' : 'ws://')
|
||||
+ location.host + '/ws')
|
||||
ws.onmessage = (e) => { try { onEvent(JSON.parse(e.data)) } catch (_) { /* 忽略脏帧 */ } }
|
||||
return ws
|
||||
}
|
||||
|
||||
// ---- 工具 ----
|
||||
const clone = (o) => JSON.parse(JSON.stringify(o))
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用——
|
||||
// 空数组可能是有意配置(如 xq0031 仓库留空 = 全部不筛选),必须还原
|
||||
function mergeSaved(form, saved) {
|
||||
Object.keys(form).forEach((k) => {
|
||||
const v = saved ? saved[k] : undefined
|
||||
if (v === undefined || v === null || v === '') return
|
||||
form[k] = Array.isArray(v) ? [...v] : v
|
||||
})
|
||||
}
|
||||
|
||||
/**
|
||||
* 插件 UI 公共状态机
|
||||
* @param {Object} opts
|
||||
* @param {Function} opts.defaults 默认表单工厂;恢复默认时传入当前表单作参考
|
||||
* (如 xq0031 按当前 erp_system 带出对应默认组织/仓库)
|
||||
* @param {Function} [opts.validate] 执行前校验,失败自行 ElMessage 提示并返回 false
|
||||
* @param {Function} [opts.buildPayload] 定制提交参数(缺省 = 表单全量深拷贝)
|
||||
*/
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const banner = ref(null)
|
||||
const lastSavedAt = ref('')
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.warning('读取本机配置失败,已用默认值:' + e.message)
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes() // 方案列表一并加载:重开界面/切插件回来(iframe 重挂载)后,下拉仍列出全部已存方案
|
||||
})
|
||||
|
||||
// 配置变更自动保存(防抖 800ms),执行中不保存
|
||||
watch(form, () => {
|
||||
if (!loaded.value || running.value) return
|
||||
clearTimeout(saveTimer)
|
||||
saveTimer = setTimeout(() => saveNow(false), 800)
|
||||
}, { deep: true })
|
||||
|
||||
async function saveNow(explicit) {
|
||||
try {
|
||||
await saveConfig(clone(form))
|
||||
lastSavedAt.value = new Date().toLocaleTimeString('zh-CN', { hour12: false })
|
||||
if (explicit) ElMessage.success('配置已保存到本机')
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('配置保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
function resetDefaults() {
|
||||
Object.assign(form, defaults ? defaults(form) : {})
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// ---------- 多配置方案(定时任务引用的参数快照,在插件界面维护) ----------
|
||||
const schemes = ref([]) // [{id, name, fields, at}]
|
||||
const schemeSel = ref('') // '' = 当前配置(即表单本身)
|
||||
const schemeOptions = computed(() => [
|
||||
{ value: '', label: '当前配置(自动保存)' },
|
||||
...schemes.value.map((s) => ({ value: s.id, label: s.name })),
|
||||
])
|
||||
|
||||
async function refreshSchemes() {
|
||||
try {
|
||||
const r = await listSchemes()
|
||||
schemes.value = r.configs || []
|
||||
} catch (_) {
|
||||
/* 方案是辅助能力,加载失败静默(下拉仅剩当前配置) */
|
||||
}
|
||||
}
|
||||
|
||||
// 应用方案:载入方案字段(密码随方案明文保存)→ 防抖自动保存固化为当前配置;
|
||||
// 执行永远提交表单当前值,方案本身只作为定时任务的参数快照源
|
||||
function onSchemeChange(id) {
|
||||
if (!id) return // 切回「当前配置」:表单即当前配置,无需动作
|
||||
const s = schemes.value.find((x) => x.id === id)
|
||||
if (!s) return
|
||||
mergeSaved(form, s.fields)
|
||||
ElMessage.success(`已应用方案「${s.name}」`)
|
||||
}
|
||||
|
||||
async function saveSchemeAs() {
|
||||
const cur = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
let name = ''
|
||||
try {
|
||||
({ value: name } = await ElMessageBox.prompt(
|
||||
'方案保存到本机(同名覆盖,密码明文保存,每套方案可绑定不同账号),供「定时任务」引用:到点自动取该方案的最新参数执行。',
|
||||
'存为配置方案',
|
||||
{
|
||||
inputValue: cur ? cur.name : '',
|
||||
confirmButtonText: '保存方案',
|
||||
cancelButtonText: '取消',
|
||||
inputPattern: /\S/,
|
||||
inputErrorMessage: '请输入方案名称',
|
||||
}
|
||||
))
|
||||
} catch (_) {
|
||||
return // 用户取消
|
||||
}
|
||||
name = String(name).trim()
|
||||
if (!name) return
|
||||
const dup = schemes.value.find((x) => x.name === name)
|
||||
if (dup) {
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`已存在同名方案「${dup.name}」,保存将覆盖它的参数(多套不同配置请用不同名称)。`,
|
||||
'覆盖已有方案',
|
||||
{ type: 'warning', confirmButtonText: '覆盖保存', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
return // 用户取消覆盖
|
||||
}
|
||||
}
|
||||
try {
|
||||
const r = await saveScheme(name, clone(form))
|
||||
await refreshSchemes()
|
||||
schemeSel.value = r.config ? r.config.id : ''
|
||||
ElMessage.success(`方案「${name}」已保存`)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('方案保存失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
async function removeScheme() {
|
||||
const s = schemes.value.find((x) => x.id === schemeSel.value)
|
||||
if (!s) return
|
||||
try {
|
||||
await ElMessageBox.confirm(
|
||||
`删除配置方案「${s.name}」?引用它的定时任务到点会跳过触发并提示重选。`,
|
||||
'删除方案',
|
||||
{ type: 'warning', confirmButtonText: '删除', cancelButtonText: '取消' }
|
||||
)
|
||||
} catch (_) {
|
||||
return
|
||||
}
|
||||
try {
|
||||
await deleteScheme(s.id)
|
||||
schemeSel.value = ''
|
||||
await refreshSchemes()
|
||||
ElMessage.success('方案已删除')
|
||||
} catch (e) {
|
||||
ElMessage.error('方案删除失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
async function run() {
|
||||
if (running.value) return
|
||||
// 未登录不再静默返回:先重试一次配置读取(会话可能在打开后已恢复),仍失败则明确提示
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
ElMessage.success('登录态已恢复,请再次点击执行')
|
||||
return
|
||||
} catch (_) { /* 仍未登录 */ }
|
||||
ElMessage.warning('未登录:请先在壳子登录统一账户,再打开本界面')
|
||||
return
|
||||
}
|
||||
if (validate && !validate()) return
|
||||
await saveNow(false)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
banner.value = null
|
||||
try {
|
||||
const r = await startRun(buildPayload ? buildPayload(form) : clone(form))
|
||||
runId = r.run_id
|
||||
connect() // runId 就绪后再连 WS,避免早到的运行事件被过滤掉
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) needLogin.value = true
|
||||
banner.value = { type: 'error', text: '启动执行失败:' + e.message }
|
||||
}
|
||||
}
|
||||
|
||||
// 强制停止(整树强杀执行子进程,含浏览器)
|
||||
async function forceStop() {
|
||||
if (!runId || stopping.value) return
|
||||
stopping.value = true
|
||||
try {
|
||||
await stopRun(runId)
|
||||
ElMessage.warning('已发出强制停止指令,正在终止执行进程…')
|
||||
} catch (e) {
|
||||
ElMessage.error('停止失败:' + e.message)
|
||||
} finally {
|
||||
stopping.value = false
|
||||
}
|
||||
}
|
||||
|
||||
// 实时进度 + 完成(WS 只取进度/结束事件,日志由壳子下方日志区展示;断开后轮询兜底)
|
||||
function connect() {
|
||||
if (ws && ws.readyState <= 1) return
|
||||
ws = connectWS((ev) => {
|
||||
if (ev.run_id && ev.run_id !== runId) return // 只看本次运行
|
||||
if (ev.t === 'progress') progress.value = Math.max(progress.value, ev.pct || 0)
|
||||
else if (ev.t === 'run_done') ev.ok ? finished() : failed(ev.error || '执行失败')
|
||||
})
|
||||
ws.onclose = () => { ws = null }
|
||||
}
|
||||
|
||||
function startPolling() {
|
||||
stopPolling()
|
||||
pollTimer = setInterval(async () => {
|
||||
if (!runId) return
|
||||
try {
|
||||
const r = await getRun(runId)
|
||||
if (r.status === 'done') finished(r.result?.summary || '执行完成')
|
||||
else if (r.status === 'error') failed(r.error || '执行失败')
|
||||
} catch (_) { /* 下轮再试 */ }
|
||||
}, 5000)
|
||||
}
|
||||
|
||||
function stopPolling() {
|
||||
if (pollTimer) { clearInterval(pollTimer); pollTimer = null }
|
||||
}
|
||||
|
||||
function finished(summary) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
progress.value = 100
|
||||
banner.value = { type: 'success', text: summary || '执行完成' }
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
banner.value = { type: 'error', text: '执行失败:' + err }
|
||||
}
|
||||
|
||||
return {
|
||||
// 状态
|
||||
form, loaded, needLogin, banner, lastSavedAt, running, progress, stopping,
|
||||
// 当前配置
|
||||
saveNow, resetDefaults,
|
||||
// 多配置方案
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
// 执行
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子后端托管在 /pui/xq0048/ 下,
|
||||
// 构建产物直接输出到插件包 ui/ 目录(随插件 zip 发布,壳子零改动)。
|
||||
// dev 模式经代理访问本机壳子后端,便于联调。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0048/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5198,
|
||||
proxy: {
|
||||
'/api': 'http://127.0.0.1:8799',
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>CRM数据导出</title>
|
||||
<script type="module" crossorigin src="/pui/xq0048/assets/index-DLXNU8di.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0048/assets/index-CLtlaiAs.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,221 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险增减操作 插件入口。
|
||||
|
||||
流程编排(替代影刀版 4 个脚本的人工串行,WPS COM 替代人工 Ctrl+S 刷新公式):
|
||||
1) 花名册确保:源表缺失或超过 TTL(15 分钟)时自动从 HR 接口导出,新鲜度内复用;
|
||||
2) 筛选复制:按类别 include/exclude 过滤花名册数据写入各目标表(F列工号强制文本);
|
||||
3) WPS/Excel 后台重算公式(替代人工打开文件 Ctrl+S,供调度读取公式缓存值);
|
||||
4) 三阶段名额调度:更新「手动维护-在参名单」+ 精细更新「变更清单」+ 备份;
|
||||
5) 再次重算公式(刷新变更清单/在参名单公式列缓存);
|
||||
6) 生成增员/减员导入文件 + 导出变更清单独立工作簿(公式转值);
|
||||
7) HR 自动导入(可选开关,默认开启):浏览器自动化把调度生成的导入文件导入
|
||||
HR「待增减人员」(先全部减员再全部增员,仅导入本次调度成功的类别);
|
||||
8) 钉钉群通知(可选开关,默认开启):汇总 + 增/减员导入异常名单推送到钉钉群
|
||||
(失败不影响主流程)。
|
||||
|
||||
运行上下文:底座注入 HR 会话与 userId(config 全局钩子),平台 = hr,uses_month = False。
|
||||
字段(fields)由 plugin.json 权威定义:base_dir / ref_date / categories / roster_path /
|
||||
enable_validation / wps_recalc / export_change_sheet / gen_import_files / import_to_hr /
|
||||
dingtalk_notify。
|
||||
"""
|
||||
import os
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .logic import roster_filter, schedule, hr_import
|
||||
from .logic.wps_recalc import recalc_target, ComRecalcError
|
||||
from .report import notify, output
|
||||
|
||||
|
||||
class EmployerInsurancePlugin(ScenePlugin):
|
||||
"""雇主险名额调度(需求 XQ0002)。"""
|
||||
|
||||
id = "xq0002"
|
||||
name = "雇主险增减操作"
|
||||
version = "1.0.9"
|
||||
description = ("雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→"
|
||||
"三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件"
|
||||
"(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,"
|
||||
"替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0002"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / HR 会话 / userId ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
session = None
|
||||
try:
|
||||
session = ctx.get_session("hr")
|
||||
except Exception as e:
|
||||
ctx.log(f"HR 会话获取失败(花名册自动导出将回退共享 cookies):{e}", "WARN")
|
||||
config.set_session(session)
|
||||
|
||||
# ---- 解析运行参数 ----
|
||||
base_dir = (fields.get("base_dir") or "").strip() or config.DEFAULT_BASE_DIR
|
||||
config.set_base_dir(base_dir)
|
||||
config.set_ref_date(fields.get("ref_date") or "")
|
||||
cat_names = fields.get("categories") or []
|
||||
categories = [config.get_category(n) for n in cat_names] if cat_names else list(config.CATEGORIES)
|
||||
roster_path = (fields.get("roster_path") or "").strip()
|
||||
enable_validation = bool(fields.get("enable_validation", True))
|
||||
wps_recalc = bool(fields.get("wps_recalc", True))
|
||||
export_change_sheet = bool(fields.get("export_change_sheet", True))
|
||||
gen_import_files = bool(fields.get("gen_import_files", True))
|
||||
import_to_hr = bool(fields.get("import_to_hr", True))
|
||||
dingtalk_notify = bool(fields.get("dingtalk_notify", True))
|
||||
import_on = import_to_hr and gen_import_files
|
||||
if import_to_hr and not gen_import_files:
|
||||
ctx.log("已开启「自动导入HR系统」但「生成导入文件」未开启,本次无可导入文件,导入步骤将跳过", "WARN")
|
||||
|
||||
if not categories:
|
||||
raise ValueError("未选择任何类别")
|
||||
|
||||
notes: list = []
|
||||
ctx.log(f"===== 雇主险增减操作启动:业务日期 {config.today_date()},根目录 {base_dir} =====", "INFO")
|
||||
|
||||
# ---- 步骤1:花名册确保(5% ~ 10%) ----
|
||||
ctx.progress(5)
|
||||
try:
|
||||
roster_path = roster_filter.ensure_employee_file(roster_path, session)
|
||||
ctx.log(f"源表就绪:{roster_path}", "INFO")
|
||||
except Exception as e:
|
||||
notes.append(f"花名册准备失败(筛选复制与调度将受影响):{e}")
|
||||
ctx.log(f"花名册准备失败:{e}", "WARN")
|
||||
ctx.progress(10)
|
||||
|
||||
# ---- 步骤2:筛选复制(10% ~ 45%) ----
|
||||
ok_categories = []
|
||||
n = len(categories)
|
||||
for i, category in enumerate(categories):
|
||||
ctx.progress(10 + int(35 * i / n))
|
||||
try:
|
||||
roster_filter.filter_and_copy_roster(category, employee_path=roster_path)
|
||||
ok_categories.append(category)
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 筛选复制失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 筛选复制失败:{e}", "WARN")
|
||||
ctx.progress(45)
|
||||
|
||||
# ---- 步骤3:WPS/Excel 后台重算公式(45% ~ 60%,替代人工 Ctrl+S) ----
|
||||
recalc_ok = {}
|
||||
if wps_recalc:
|
||||
for i, category in enumerate(ok_categories):
|
||||
ctx.progress(45 + int(15 * i / max(n, 1)))
|
||||
try:
|
||||
recalc_target(config.category_target_file(category))
|
||||
recalc_ok[category["name"]] = True
|
||||
except ComRecalcError as e:
|
||||
notes.append(f"类别[{category['name']}] 公式重算失败(跳过该类别调度):{e}")
|
||||
ctx.log(f"类别[{category['name']}] 公式重算失败:{e}", "WARN")
|
||||
# 重算失败的类别不进入调度(公式缓存缺失会导致读取不到工种类别/投保方案/方案处理)
|
||||
to_schedule = [c for c in ok_categories if recalc_ok.get(c["name"])]
|
||||
else:
|
||||
ctx.log("已关闭 WPS/Excel 后台重算:请确认目标文件公式已人工刷新(打开保存过),"
|
||||
"否则调度将读取不到公式计算结果", "WARN")
|
||||
to_schedule = ok_categories
|
||||
ctx.progress(60)
|
||||
|
||||
# ---- 步骤4:三阶段名额调度 ----
|
||||
# 进度边界:开启 HR 导入时压缩为 60~80(步骤5/6/7 依次 80~84 / 84~90 / 90~100),
|
||||
# 关闭时沿用原 60~88 / 88~95 / 95~100
|
||||
s4_end, s4_span = (80, 20) if import_on else (88, 28)
|
||||
s5_end, s5_span = (84, 4) if import_on else (95, 7)
|
||||
s6_end, s6_span = (90, 6) if import_on else (100, 5)
|
||||
scheduled = []
|
||||
for i, category in enumerate(to_schedule):
|
||||
ctx.progress(60 + int(s4_span * i / max(len(to_schedule), 1)))
|
||||
try:
|
||||
schedule.schedule_category(category,
|
||||
enable_validation=enable_validation,
|
||||
gen_import_files=gen_import_files)
|
||||
scheduled.append(category)
|
||||
except schedule.DataValidationError:
|
||||
ctx.log("数据校验失败,已中断后续类别调度,请修正数据后重试", "ERROR")
|
||||
raise
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 调度失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 调度失败:{e}", "WARN")
|
||||
ctx.progress(s4_end)
|
||||
|
||||
# ---- 步骤5:再次重算公式(刷新变更清单/在参名单公式列缓存) ----
|
||||
if wps_recalc:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(s5_end - s5_span + int(s5_span * i / max(len(scheduled), 1)))
|
||||
try:
|
||||
recalc_target(config.category_target_file(category))
|
||||
except ComRecalcError as e:
|
||||
notes.append(f"类别[{category['name']}] 调度后重算失败(变更清单独立工作簿将取不到公式值):{e}")
|
||||
ctx.log(f"类别[{category['name']}] 调度后重算失败:{e}", "WARN")
|
||||
ctx.progress(s5_end)
|
||||
|
||||
# ---- 步骤6:导出变更清单独立工作簿 ----
|
||||
if export_change_sheet:
|
||||
for i, category in enumerate(scheduled):
|
||||
ctx.progress(s6_end - s6_span + int(s6_span * i / max(len(scheduled), 1)))
|
||||
try:
|
||||
output.export_change_sheet_workbook(category)
|
||||
except Exception as e:
|
||||
notes.append(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}")
|
||||
ctx.log(f"类别[{category['name']}] 导出变更清单工作簿失败:{e}", "WARN")
|
||||
ctx.progress(s6_end)
|
||||
|
||||
# ---- 步骤7:HR 自动导入(90% ~ 100%,仅本次调度成功的类别;先全部减员再全部增员) ----
|
||||
import_results = []
|
||||
if import_on:
|
||||
if not scheduled:
|
||||
ctx.log("无调度成功的类别,跳过 HR 自动导入", "WARN")
|
||||
else:
|
||||
def _on_import_progress(done, total):
|
||||
ctx.progress(90 + int(10 * done / max(total, 1)))
|
||||
|
||||
ctx.log(f"开始 HR 自动导入:先全部【减员】后【增员】,共 {len(scheduled) * 2} 个导入单元")
|
||||
try:
|
||||
import_results = hr_import.import_all(scheduled, on_progress=_on_import_progress)
|
||||
except hr_import.LoginRequiredError as e:
|
||||
notes.append(f"HR 自动导入未执行(登录态缺失):{e}")
|
||||
ctx.log(f"HR 自动导入未执行:{e}", "ERROR")
|
||||
except Exception as e:
|
||||
notes.append(f"HR 自动导入整体失败:{e}")
|
||||
ctx.log(f"HR 自动导入整体失败:{e}", "ERROR")
|
||||
ctx.progress(100)
|
||||
|
||||
# ---- 汇总 ----
|
||||
detail = {
|
||||
"处理类别": len(categories),
|
||||
"筛选复制成功": len(ok_categories),
|
||||
"调度成功": len(scheduled),
|
||||
}
|
||||
import_lines = hr_import.summarize_results(import_results) \
|
||||
if import_on and import_results else []
|
||||
if import_on:
|
||||
import_text = ";".join(import_lines) if import_lines else "无导入结果"
|
||||
tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹。"
|
||||
f"HR 导入结果:{import_text}。")
|
||||
else:
|
||||
tail = ("增/减员导入文件与变更清单独立工作簿已生成在各类别文件夹,"
|
||||
"请先执行【减员】导入再执行【增员】导入。")
|
||||
summary = ("雇主险增减操作完成({date}):处理 {total} 个类别,筛选复制 {filtered} 个、"
|
||||
"调度成功 {scheduled} 个。{tail}").format(
|
||||
date=config.today_date(), total=len(categories),
|
||||
filtered=len(ok_categories), scheduled=len(scheduled), tail=tail)
|
||||
if notes:
|
||||
summary += "\n注意事项:\n- " + "\n- ".join(notes)
|
||||
|
||||
# ---- 步骤8:钉钉群通知(汇总 + 导入异常名单;失败不影响主流程) ----
|
||||
if dingtalk_notify:
|
||||
notify.push_run_result(total=len(categories), filtered=len(ok_categories),
|
||||
scheduled=len(scheduled), import_on=import_on,
|
||||
import_lines=import_lines,
|
||||
import_results=import_results, notes=notes)
|
||||
else:
|
||||
ctx.log("钉钉群通知已关闭,跳过推送", "INFO")
|
||||
|
||||
return {"summary": summary, "notes": notes, "detail": detail,
|
||||
"path": base_dir, "date": config.today_date()}
|
||||
|
||||
|
||||
PLUGINS.append(EmployerInsurancePlugin())
|
||||
@@ -0,0 +1,408 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 雇主险增减操作 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log()/logger 输出日志、config.get_session()/get_user_id() 取登录态;
|
||||
运行参数(根目录 / 业务日期)由 __init__.py 的 run() 解析 fields 后注入(set_base_dir/set_ref_date)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from datetime import date, datetime
|
||||
|
||||
# ==================== 共享目录(登录态/缓存,与影刀版同路径) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
CACHE_DIR = os.path.join(_APP_DATA_DIR, 'cache')
|
||||
|
||||
# ==================== 钉钉群通知(report/notify.py 使用) ====================
|
||||
# prod=生产群 / dev=测试群(机器人 webhook 配置见 report/dingtalk_robot.py ENV_CONFIGS)
|
||||
DINGTALK_ENV = "prod"
|
||||
|
||||
# ==================== 默认根目录与业务日期(run() 注入覆盖) ====================
|
||||
DEFAULT_BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
|
||||
# ==================== 固定 Sheet 名称 ====================
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
|
||||
# ==================== 四大类别(合并调度/筛选口径,与 app 版 config 一致) ====================
|
||||
# 每类一个独立文件夹;include_dept/exclude_dept 用于筛选复制;
|
||||
# change_sheet_prefix 为各类「变更清单」sheet 名称前缀;scheme_suffix 为增员导入方案后缀。
|
||||
CATEGORIES = [
|
||||
{
|
||||
"name": "三十七度",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "三十七度"),
|
||||
"include_dept": [],
|
||||
"exclude_dept": ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"],
|
||||
"change_sheet_prefix": "37度-雇员变更清单",
|
||||
"scheme_suffix": "",
|
||||
},
|
||||
{
|
||||
"name": "水庄餐饮",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "水庄餐饮"),
|
||||
"include_dept": ["水庄大鹅事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "水庄-雇员变更清单",
|
||||
"scheme_suffix": "水庄",
|
||||
},
|
||||
{
|
||||
"name": "湖畔酒店",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "湖畔酒店"),
|
||||
"include_dept": ["金色湖畔事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "湖畔-雇员变更清单",
|
||||
"scheme_suffix": "湖畔",
|
||||
},
|
||||
{
|
||||
"name": "秒创传媒",
|
||||
"folder": os.path.join(DEFAULT_BASE_DIR, "秒创传媒"),
|
||||
"include_dept": ["秒创传媒事业部"],
|
||||
"exclude_dept": [],
|
||||
"change_sheet_prefix": "秒创-雇员变更清单",
|
||||
"scheme_suffix": "秒创",
|
||||
},
|
||||
]
|
||||
|
||||
# 过滤规则(与 aa.md 宏一致)
|
||||
EXCLUDE_REGIONS = ["虚拟大区"] # 统一排除的一级部门(各类别均生效)
|
||||
EXCLUDE_NAME_KEYWORDS = ["虚拟", "人资", "测试"] # 姓名(N列)含这些关键字的行剔除
|
||||
|
||||
# 源表/目标表格式规范(共享「37du花名册导出」输出统一格式)
|
||||
SOURCE_HEADER_MARK = "所属单位" # 源表表头定位标记(B列)
|
||||
EXPORT_TEMPLATE = "雇主险增减员导出模板" # 雇主险源表使用的自定义导出模板
|
||||
EXPORT_STATUSES = ["在职"]
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
# 数据切片(B~O)内 0-based 列索引
|
||||
CODE_COL = 4 # F列 工号(必须文本格式)
|
||||
JOIN_DATE_COL = 11 # M列 入职时间
|
||||
NAME_COL = 12 # N列 姓名
|
||||
ID_COL = 13 # O列 证件号(18位身份证号超出浮点精度,必须文本格式)
|
||||
|
||||
# ==================== 花名册列名映射(表头在第4行) ====================
|
||||
BIZ_COL_EMPLOYEE_ID = "证件号" # O列,员工唯一标识
|
||||
BIZ_COL_CATEGORY = "工种类别" # P列
|
||||
BIZ_COL_SCHEME = "投保方案" # Q列
|
||||
BIZ_COL_HANDLE = "方案处理" # W列,值: 增加投保 / 要替换 / /
|
||||
|
||||
# 在参名单数据起始行(第17行开始是数据区域,前16行是固定标题/兼职数据)
|
||||
DATA_START_ROW = 17
|
||||
|
||||
# ==================== 校验常量 ====================
|
||||
VALID_CATEGORIES = ["一类", "二类", "三类", "四类"]
|
||||
VALID_SCHEMES = ["人保-20万", "人保-50万", "人保-80万"]
|
||||
|
||||
# ==================== 增减员导入模板(雇主险根目录下官方模板) ====================
|
||||
ADD_IMPORT_TEMPLATE = "商业保险增员导入模板.xlsx"
|
||||
SUB_IMPORT_TEMPLATE = "商业保险减员导入模板.xlsx"
|
||||
|
||||
|
||||
# ==================== 运行参数钩子(run() 注入) ====================
|
||||
_base_dir = DEFAULT_BASE_DIR
|
||||
_ref_date = None # datetime.date;None 表示今天
|
||||
_log = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
|
||||
|
||||
def set_base_dir(path):
|
||||
global _base_dir
|
||||
_base_dir = (path or "").strip().strip('"') or DEFAULT_BASE_DIR
|
||||
|
||||
|
||||
def get_base_dir():
|
||||
return _base_dir
|
||||
|
||||
|
||||
def parse_ref_date(value):
|
||||
"""把 fields.ref_date(YYYY-MM-DD / YYYY.M.D 等)解析为 date;空返回今天。"""
|
||||
if not value:
|
||||
return date.today()
|
||||
s = str(value).strip()
|
||||
m = re.match(r"(\d{4})[-./年](\d{1,2})[-./月](\d{1,2})", s)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
pass
|
||||
return date.today()
|
||||
|
||||
|
||||
def set_ref_date(value):
|
||||
global _ref_date
|
||||
_ref_date = parse_ref_date(value)
|
||||
|
||||
|
||||
def ref_date():
|
||||
"""业务日期(默认今天)。"""
|
||||
return _ref_date or date.today()
|
||||
|
||||
|
||||
def date_str():
|
||||
"""YYYY.M.D(目标表/备份文件名,如 2026.9.22)。"""
|
||||
return ref_date().strftime("%Y.%m.%d")
|
||||
|
||||
|
||||
def date_short():
|
||||
"""M.D(变更清单 sheet 后缀,不补前导零,如 9.22 / 9.1)。"""
|
||||
return f"{ref_date().month}.{ref_date().day}"
|
||||
|
||||
|
||||
def today_date():
|
||||
"""YYYY-MM-DD(批改日期/增员减员日期/投保日期)。"""
|
||||
return ref_date().strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 类别辅助函数 ====================
|
||||
def get_category(name):
|
||||
"""按名称获取类别配置(支持精确名或唯一前缀,如「湖畔」/「湖畔酒店」)。"""
|
||||
name = (name or "").strip()
|
||||
for c in CATEGORIES:
|
||||
if c["name"] == name:
|
||||
return c
|
||||
matched = [c for c in CATEGORIES if c["name"].startswith(name)]
|
||||
if len(matched) == 1:
|
||||
return matched[0]
|
||||
raise ValueError(f"未知类别:{name},可选:{[c['name'] for c in CATEGORIES]}")
|
||||
|
||||
|
||||
def _target_file_date(filename):
|
||||
"""从目标文件名解析业务日期(优先 YYYY.M.D,回退 M.D 当年)。"""
|
||||
m = re.search(r"(\d{4})\.(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(int(m.group(1)), int(m.group(2)), int(m.group(3)))
|
||||
except ValueError:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", filename)
|
||||
if m:
|
||||
try:
|
||||
return date(ref_date().year, int(m.group(1)), int(m.group(2)))
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def find_latest_target(folder):
|
||||
"""在类别文件夹中定位最新的「*雇主险变更记录*.xlsx」目标文件。
|
||||
|
||||
按「文件名中的业务日期」选择最新(不依赖修改时间),避免昨日文件被改动/
|
||||
打开导致 mtime 更新而被误当成今日文件(曾因此把变更清单写进昨日文件)。
|
||||
"""
|
||||
if not os.path.isdir(folder):
|
||||
raise FileNotFoundError(f"类别文件夹不存在:{folder}")
|
||||
candidates = [
|
||||
os.path.join(folder, f)
|
||||
for f in os.listdir(folder)
|
||||
if f.lower().endswith(".xlsx") and "雇主险变更记录" in f
|
||||
]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"文件夹 {folder} 下未找到「*雇主险变更记录*.xlsx」文件,请先准备今日的雇主险变更记录模板")
|
||||
# 排序键:业务日期优先,同日期内再按修改时间兜底
|
||||
def _sort_key(path):
|
||||
return (_target_file_date(os.path.basename(path)) or date.min,
|
||||
os.path.getmtime(path))
|
||||
return max(candidates, key=_sort_key)
|
||||
|
||||
|
||||
def _category_dir(category):
|
||||
"""类别文件夹(base_dir 运行时可能被覆盖,须实时拼接而非 import 时固化)。"""
|
||||
return os.path.join(get_base_dir(), category["name"])
|
||||
|
||||
|
||||
def category_folder(category):
|
||||
return _category_dir(category)
|
||||
|
||||
|
||||
def category_target_file(category):
|
||||
"""类别目标文件(各文件夹内最新的雇主险变更记录)。"""
|
||||
return find_latest_target(_category_dir(category))
|
||||
|
||||
|
||||
def category_output_backup(category):
|
||||
"""类别「新在参名单」备份路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), f"新在参名单-{date_str()}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_workbook(category):
|
||||
"""类别「雇员变更清单」独立工作簿路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), f"{category['name']}-雇员变更清单-{date_str()}.xlsx")
|
||||
|
||||
|
||||
def category_change_sheet_name(category):
|
||||
"""类别「变更清单」sheet 名称(沿用历史模板命名:无横线、不补前导零)。"""
|
||||
return f"{category['change_sheet_prefix']}{date_short()}"
|
||||
|
||||
|
||||
def category_import_add_file(category):
|
||||
"""类别「增员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), "商业保险增员导入.xlsx")
|
||||
|
||||
|
||||
def category_import_sub_file(category):
|
||||
"""类别「减员导入」文件路径(放在类别文件夹内)。"""
|
||||
return os.path.join(_category_dir(category), "商业保险减员导入.xlsx")
|
||||
|
||||
|
||||
def add_import_template():
|
||||
return os.path.join(get_base_dir(), ADD_IMPORT_TEMPLATE)
|
||||
|
||||
|
||||
def sub_import_template():
|
||||
return os.path.join(get_base_dir(), SUB_IMPORT_TEMPLATE)
|
||||
|
||||
|
||||
def employee_file(path=""):
|
||||
"""花名册路径:传入优先,否则 {base_dir}\\员工花名册.xlsx。"""
|
||||
return (path or "").strip() or os.path.join(get_base_dir(), "员工花名册.xlsx")
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先在插件界面登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在插件界面完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
# ==================== 文本/日期辅助函数(logic/report 层共用) ====================
|
||||
def to_text(value):
|
||||
"""将工号等主键值统一转为文本,避免数字/文本混存导致 Excel 公式匹配失败。
|
||||
|
||||
整型 float(如 10086.0)去掉小数点后转 str,保证与文本工号(如"10086")一致。
|
||||
"""
|
||||
import numbers
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, numbers.Integral):
|
||||
return str(int(value))
|
||||
if isinstance(value, numbers.Real):
|
||||
f = float(value)
|
||||
if f.is_integer():
|
||||
return str(int(f))
|
||||
return str(value)
|
||||
|
||||
|
||||
def clean_text(value):
|
||||
"""转可写文本;None/NaN/空白返回 None。"""
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
s = str(value).strip()
|
||||
return s or None
|
||||
|
||||
|
||||
def parse_join_date(value):
|
||||
"""解析入职时间为 date 对象(兼容 datetime/字符串「YYYY-MM-DD」「YYYY.M.D」等)。"""
|
||||
from datetime import datetime as _dt
|
||||
if value is None:
|
||||
return None
|
||||
try:
|
||||
if value != value: # NaN
|
||||
return None
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
s = str(value).strip()
|
||||
m = re.match(r"(\d{4})[.\-/年](\d{1,2})[.\-/月](\d{1,2})", s)
|
||||
if m:
|
||||
try:
|
||||
return _dt(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def to_date(value):
|
||||
"""将日期/日期字符串统一转为 date 对象;无法解析时返回 None。"""
|
||||
from datetime import datetime as _dt
|
||||
if value is None:
|
||||
return None
|
||||
if isinstance(value, datetime):
|
||||
return value.date()
|
||||
if isinstance(value, date):
|
||||
return value
|
||||
s = str(value).strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d", "%Y/%m/%d", "%Y.%m.%d"):
|
||||
try:
|
||||
return _dt.strptime(s, fmt).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 data 层:花名册导出(接口版)。"""
|
||||
@@ -0,0 +1,453 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 员工花名册导出(接口版,由 xq0011 插件同模块内嵌移植)。
|
||||
|
||||
纯接口版(无需浏览器):访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
|
||||
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)-> 接收 "--end--|文件路径" 推送
|
||||
-> 下载临时文件 -> 按状态合并(追加「类型」列)。
|
||||
|
||||
插件化改造点:
|
||||
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
|
||||
2. 内置「雇主险增减员导出模板」(B~O 共 14 列:所属单位→证件号,与 app 版 roster_template 一致);
|
||||
3. 日志统一转发到 config.logger。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
import requests
|
||||
import pandas as pd
|
||||
import websocket # websocket-client
|
||||
|
||||
from ..config import logger, SESSIONS_DIR, EXPORT_TEMPLATE, EXPORT_STATUSES
|
||||
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
|
||||
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
|
||||
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
|
||||
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
|
||||
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
|
||||
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
|
||||
"rf_pt_users_export_define_select/getExecuteResult.mc")
|
||||
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
|
||||
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
|
||||
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
|
||||
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
|
||||
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
|
||||
|
||||
# 花名册查询固定入参(从浏览器抓包提取)
|
||||
ROSTER_QUERY_BASE_PARAMS = {
|
||||
"menuName": "员工花名册",
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"cancelNodeClick": "1",
|
||||
"clickFlag": "true",
|
||||
"in_use": "1",
|
||||
"commonQuery": "",
|
||||
"newCondition": "",
|
||||
"urlConditions": "",
|
||||
"exportConfig": "",
|
||||
"tableId": "assemble-hr_staff_base",
|
||||
"rosterId": ROSTER_ID,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": "POST_SYS_ADMIN,renshi",
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
"dataIds": "",
|
||||
"hideCols": "",
|
||||
}
|
||||
|
||||
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
|
||||
# 「雇主险增减员导出模板」(14 列 + 序号,B~O:所属单位→证件号,与 app 版 roster_template 一致)
|
||||
ROSTER_TEMPLATE_FILTERS_EMPLOYER = ",".join([
|
||||
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
|
||||
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
|
||||
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
|
||||
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
|
||||
"hr_staff_base.base_code", # 工号
|
||||
"hr_staff_base.age", # 年龄
|
||||
"hr_staff_base.sex", # 性别
|
||||
"pt_staff_stru.POST_ORG_NAME", # 岗位
|
||||
"pt_staff_stru.first_type_id", # 职位序列
|
||||
"hr_staff_base_ext.ext_insurance_type", # 参保类型
|
||||
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
|
||||
"hr_staff_base.join_date", # 入职时间
|
||||
"hr_staff_base.staff_name", # 姓名
|
||||
"hr_staff_base.idCard", # 证件号
|
||||
])
|
||||
|
||||
ROSTER_TEMPLATE_FILTERS = {
|
||||
"雇主险增减员导出模板": ROSTER_TEMPLATE_FILTERS_EMPLOYER,
|
||||
}
|
||||
|
||||
# ---------- 默认导出参数 ----------
|
||||
DEFAULT_TEMPLATE = EXPORT_TEMPLATE # 雇主险增减员导出模板
|
||||
DEFAULT_STATUSES = list(EXPORT_STATUSES) # ["在职"]
|
||||
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
|
||||
EXPORT_TIMEOUT_SECONDS = 300 # 异步导出等待超时(秒)
|
||||
MAX_ATTEMPTS = 3 # 项目级重试次数
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
|
||||
|
||||
|
||||
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_SALT = "yyryrtweasdasd" # 固定盐值
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def build_condition(query_field, query_type, query_value, query_text="",
|
||||
left_bracket="", right_bracket="", logic="AND", input_type="text"):
|
||||
"""构造一个符合前端格式的单条查询条件字典。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": query_text,
|
||||
"rightBracket": right_bracket,
|
||||
"logic": logic,
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery 字符串(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
# ==================== 登录态(底座注入优先,兜底共享 cookies) ====================
|
||||
def _build_session(session=None):
|
||||
"""取 HR 会话:优先用调用方(底座注入)传入的 session,否则读共享 cookies 构建。"""
|
||||
if session is not None:
|
||||
return session
|
||||
if not os.path.exists(SHARED_HR_COOKIE_FILE):
|
||||
raise LoginRequiredError(
|
||||
"未找到 HR 登录态 cookies,请先在插件界面完成 HR 登录后再重试。")
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
|
||||
cookies = json.load(f)
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies or []:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
return session
|
||||
|
||||
|
||||
# ==================== 动态日期参数 ====================
|
||||
def get_date_params():
|
||||
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
|
||||
now = datetime.now()
|
||||
year, month, day = now.year, now.month, now.day
|
||||
last_month_date = datetime(year, month, 1) - timedelta(days=1)
|
||||
return {
|
||||
"currentDate": f"{year}-{month:02d}-{day:02d}",
|
||||
"currentMonth": f"{year}{month:02d}",
|
||||
"currentMonthBar": f"{year}-{month:02d}",
|
||||
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
|
||||
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
|
||||
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{year}01",
|
||||
"curYearFirstMonBar": f"{year}-01",
|
||||
}
|
||||
|
||||
|
||||
def _get_leave_range(today=None):
|
||||
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
|
||||
today = today or date.today()
|
||||
last_month_end = today.replace(day=1) - timedelta(days=1)
|
||||
start = last_month_end.replace(day=1)
|
||||
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
# ==================== 查询条件构造 ====================
|
||||
def _build_in_service_conditions():
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
]
|
||||
|
||||
|
||||
def _build_leave_conditions(leave_start, leave_end):
|
||||
return [
|
||||
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
|
||||
query_text="1", left_bracket="(", right_bracket=")",
|
||||
input_type="select"),
|
||||
build_condition("`hr_staff_base.person_status`", "in", "2",
|
||||
query_text="2", left_bracket="(", right_bracket=")",
|
||||
input_type="multipleSelect"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
|
||||
left_bracket="(", input_type="date"),
|
||||
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
|
||||
right_bracket=")", input_type="date"),
|
||||
]
|
||||
|
||||
|
||||
# ==================== 自定义导出模板动态解析 ====================
|
||||
def resolve_template_filters(session, template_name):
|
||||
"""按模板名动态解析 exportFilters 字段串(失败回退内置模板)。"""
|
||||
try:
|
||||
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
|
||||
templates = r.get("jsonList") or []
|
||||
target = next((t for t in templates if t.get("ext1") == template_name), None)
|
||||
if not target:
|
||||
logger.warning("模板列表中未找到「%s」,回退内置模板", template_name)
|
||||
return None
|
||||
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
|
||||
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
|
||||
export_field = (r2.get("result") or {}).get("exportField") or ""
|
||||
fields = json.loads(export_field)
|
||||
if not fields:
|
||||
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
|
||||
return None
|
||||
filters = ",".join(f["tableCode"] for f in fields)
|
||||
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
|
||||
return filters
|
||||
except Exception as e:
|
||||
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
|
||||
return None
|
||||
|
||||
|
||||
# ==================== WebSocket 异步导出(单状态) ====================
|
||||
def _bind_session(session):
|
||||
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。"""
|
||||
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
|
||||
"useSealTreeData": "0"}, timeout=30)
|
||||
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
|
||||
if "成功" not in r.text and r.text.strip() != "1":
|
||||
raise LoginRequiredError(
|
||||
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
|
||||
"请先在插件界面重新完成 HR 登录后再重试。")
|
||||
|
||||
|
||||
def _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。"""
|
||||
_bind_session(session)
|
||||
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
|
||||
if "hr.37du.co" in (c.domain or ""))
|
||||
ws = websocket.WebSocket()
|
||||
ws.connect(WS_SERVICE_URL, header=[
|
||||
f"Cookie: {cookie_hdr}",
|
||||
"Origin: https://hr.37du.co",
|
||||
f"User-Agent: {USER_AGENT}",
|
||||
], timeout=10)
|
||||
try:
|
||||
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
|
||||
ack = json.loads(ws.recv())
|
||||
if ack.get("code") != "SUBCRIBE_THEME_ACK":
|
||||
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
|
||||
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
|
||||
|
||||
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
|
||||
if status == "离职":
|
||||
ls = leave_start or ""
|
||||
le = leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
|
||||
logger.info("离职时间范围:%s ~ %s", ls, le)
|
||||
else:
|
||||
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
|
||||
params.update(get_date_params())
|
||||
params["exportConfig"] = json.dumps(
|
||||
{"exportName": template_name,
|
||||
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
|
||||
ensure_ascii=False, separators=(",", ":"))
|
||||
params["_t"] = str(int(time.time() * 1000))
|
||||
|
||||
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
|
||||
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
|
||||
|
||||
file_url = None
|
||||
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
|
||||
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
|
||||
while time.time() < deadline:
|
||||
msg = json.loads(ws.recv())
|
||||
txt, code = msg.get("txt", ""), msg.get("code", "")
|
||||
if code != "NORMAL_PUSH_TO":
|
||||
continue
|
||||
if txt.startswith("--end--"):
|
||||
file_url = txt.split("|", 1)[1].strip()
|
||||
break
|
||||
if txt.startswith(("开始下载", "正在生成")):
|
||||
logger.info(" 进度:%s", txt)
|
||||
if not file_url:
|
||||
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
|
||||
logger.info("导出完成,文件地址:%s", file_url)
|
||||
finally:
|
||||
ws.close()
|
||||
|
||||
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
|
||||
dl = session.get(dl_url, timeout=120)
|
||||
if dl.status_code != 200 or not dl.content:
|
||||
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
|
||||
with open(temp_path, "wb") as f:
|
||||
f.write(dl.content)
|
||||
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
|
||||
return temp_path
|
||||
|
||||
|
||||
def _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start=None, leave_end=None, export_filters=None):
|
||||
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_ATTEMPTS + 1):
|
||||
try:
|
||||
return _export_one_status_once(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
except LoginRequiredError:
|
||||
raise # 确定性失败,不重试
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_ATTEMPTS:
|
||||
break
|
||||
delay = 2.0 * attempt
|
||||
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
|
||||
status, attempt, e, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 合并输出 ====================
|
||||
def _normalize_and_save(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||||
|
||||
统一输出格式:只保留第2行表头,丢弃第1行标题;「类型」列追加在最后一列;
|
||||
单 sheet,表头在第1行,数据第2行起。
|
||||
"""
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
out_dir = os.path.dirname(output_path)
|
||||
if out_dir:
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
merged.to_excel(output_path, index=False)
|
||||
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
|
||||
for _, path in files_with_status:
|
||||
try:
|
||||
os.remove(path)
|
||||
except Exception:
|
||||
pass
|
||||
return output_path
|
||||
|
||||
|
||||
# ==================== 导出主流程 ====================
|
||||
def export_roster(download_dir=None, output_path=None, template_name=None,
|
||||
statuses=None, leave_start=None, leave_end=None,
|
||||
ttl=DEFAULT_TTL_SECONDS, session=None):
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出)。
|
||||
|
||||
Args:
|
||||
session: 底座注入的 HR 会话(优先);None 时兜底读共享 cookies。
|
||||
其余参数与影刀版 export_roster 一致。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径
|
||||
"""
|
||||
download_dir = download_dir or os.path.dirname(output_path or "") or "."
|
||||
output_path = output_path or "花名册.xlsx"
|
||||
template_name = template_name or DEFAULT_TEMPLATE
|
||||
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
|
||||
if ttl is None:
|
||||
ttl = DEFAULT_TTL_SECONDS
|
||||
|
||||
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用
|
||||
if ttl > 0 and os.path.exists(output_path) \
|
||||
and os.path.getsize(output_path) > 0 \
|
||||
and time.time() - os.path.getmtime(output_path) <= ttl:
|
||||
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
|
||||
return output_path
|
||||
|
||||
leave_desc = ""
|
||||
if "离职" in statuses:
|
||||
ls, le = leave_start or "", leave_end or ""
|
||||
if not ls or not le:
|
||||
ls, le = _get_leave_range()
|
||||
leave_desc = f",离职时间 {ls} ~ {le}"
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s) =====",
|
||||
template_name, statuses, leave_desc)
|
||||
|
||||
session = _build_session(session)
|
||||
export_filters = resolve_template_filters(session, template_name)
|
||||
|
||||
files_with_status = []
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(session, status, download_dir, template_name,
|
||||
leave_start, leave_end, export_filters)
|
||||
files_with_status.append((status, path))
|
||||
|
||||
result = _normalize_and_save(files_with_status, output_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 logic 层:筛选复制 + 三阶段名额调度 + WPS/Excel 重算。"""
|
||||
@@ -0,0 +1,658 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - HR「待增减人员」增减员导入(浏览器自动化,移植影刀版 add_sub_import v1.8.0)。
|
||||
|
||||
流程:访问待增减人员页面 -> 更多操作 -> 减员/增员导入 -> 上传文件 -> 下一步(格式校验)
|
||||
-> 下一步(真正导入)-> 关闭;监听 getTmpDataPage.mc 捕获逐行导入结果。
|
||||
|
||||
插件化改造点(相对影刀版):
|
||||
1. 登录态:优先底座注入 session(config.get_session())的 cookies 注入浏览器,
|
||||
未注入/为空时兜底读共享 cookies 文件(hr_cookies.json);
|
||||
2. 导入文件路径经 config.category_import_add_file / category_import_sub_file 实时解析
|
||||
(base_dir 由 run() 注入,不依赖类别配置里的固化 folder);
|
||||
3. 一次运行共用一个浏览器:先全部类别【减员】再全部类别【增员】
|
||||
(替换/修改人员必须先撤旧方案再上新方案,先增员会方案冲突报错);
|
||||
4. 日志统一转发 config.logger;结果 dict 返回,由 __init__.py 汇总进 summary/notes。
|
||||
|
||||
关键语义(与影刀版一致,勿改):
|
||||
- getTmpDataPage.mc 仅在存在异常行时才返回逐行结果:全部成功时 HR 不调用结果接口,
|
||||
流程完整走完(两步「下一步」+「关闭」)且监听正常、未捕获异常行 -> 按文件条数推定全部成功;
|
||||
- 接口每页固定 15 条,弹窗只加载第一页:捕获首响应后按 pageNo 主动翻页拉全;
|
||||
- 需导入条数从导入文件 A 列最大序号统计(模板预格式化空白行不计);
|
||||
- 上传/校验/确认走 UI 控件(input[name=file] 设置路径跳过系统文件选择框)。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
|
||||
import requests
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from ..config import logger, SESSIONS_DIR, get_session
|
||||
|
||||
try:
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
_DRP_AVAILABLE = True
|
||||
_DRP_IMPORT_ERROR = None
|
||||
except ImportError as _e: # 模块可安全导入(开关关闭时不触发),使用时再报清晰错误
|
||||
_DRP_AVAILABLE = False
|
||||
_DRP_IMPORT_ERROR = _e
|
||||
|
||||
# ==================== 常量(与影刀版 add_sub_import 一致) ====================
|
||||
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
# HR 系统「待增减人员」页面
|
||||
ADD_SUB_URL = (
|
||||
"https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic"
|
||||
"#ajax&1&nworktoday-40175-13664-23874-98879&nworktoday-40175-13664"
|
||||
"|/RedseaPlatform/hrRoster/7984ae1a-16ec-11ed-bea9-822ff8ed5b28/"
|
||||
"getCustomCommonList.mc?menuName=待增减人员"
|
||||
)
|
||||
|
||||
BTN_MORE = "更多操作" # 「更多操作」下拉按钮
|
||||
MENU_ADD = "增员导入" # 下拉菜单:增员导入
|
||||
MENU_SUB = "减员导入" # 下拉菜单:减员导入
|
||||
BTN_NEXT = "下一步" # 导入弹窗「下一步」按钮(第 2/3 步)
|
||||
BTN_CLOSE = "关闭" # 导入完成弹窗「关闭」按钮
|
||||
|
||||
WAIT_SHORT = 0.6
|
||||
WAIT_MID = 2.0
|
||||
WAIT_LONG = 4.0
|
||||
|
||||
# 接口监听:第二步「下一步」导入内容结果(getTmpDataPage.mc)
|
||||
TMP_DATA_API_MARK = "getTmpDataPage.mc" # 导入内容结果接口(URL 子串过滤)
|
||||
TMP_DATA_STATE_OK = "1" # 接口 state 成功值
|
||||
TMP_DATA_WAIT = 8.0 # 等待导入结果接口响应的超时秒数
|
||||
|
||||
USER_AGENT = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
|
||||
|
||||
class LoginRequiredError(Exception):
|
||||
"""HR 登录态缺失/失效(页面被重定向到登录页或无可用 cookies)。"""
|
||||
|
||||
|
||||
class ElementNotFoundError(Exception):
|
||||
"""页面元素/控件未找到(页面结构变化或加载超时)。"""
|
||||
|
||||
|
||||
# ==================== 登录态:底座注入 session 优先,兜底共享 cookies 文件 ====================
|
||||
def _cookies_from_requests_session(session):
|
||||
"""从底座注入的 requests.Session 提取 37du.co 域 cookies(DrissionPage 字典格式)。"""
|
||||
cookies = []
|
||||
try:
|
||||
jar_items = list(session.cookies)
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar_items:
|
||||
domain = str(getattr(c, "domain", "") or "")
|
||||
if "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name, "value": c.value,
|
||||
"domain": domain, "path": getattr(c, "path", None) or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def _cookies_from_shared_file():
|
||||
"""读取共享 HR cookies 文件(37du.co 域),缺失/为空返回空列表。"""
|
||||
if not os.path.isfile(SHARED_HR_COOKIE_FILE):
|
||||
return []
|
||||
try:
|
||||
with open(SHARED_HR_COOKIE_FILE, encoding="utf-8") as f:
|
||||
cookies = json.load(f) or []
|
||||
except Exception as e:
|
||||
logger.warning("共享 HR cookies 文件读取失败 %s:%s", SHARED_HR_COOKIE_FILE, e)
|
||||
return []
|
||||
return [c for c in cookies if c.get("domain") and "37du.co" in str(c["domain"])]
|
||||
|
||||
|
||||
def _collect_browser_cookies():
|
||||
"""收集浏览器登录态 cookies:底座注入 session 优先,为空兜底共享 cookies 文件。"""
|
||||
cookies = []
|
||||
session = get_session()
|
||||
if session is not None:
|
||||
cookies = _cookies_from_requests_session(session)
|
||||
if cookies:
|
||||
logger.info("使用底座注入 HR 会话的 cookies:%d 个", len(cookies))
|
||||
if not cookies:
|
||||
cookies = _cookies_from_shared_file()
|
||||
if cookies:
|
||||
logger.info("使用共享 cookies 文件:%d 个(%s)", len(cookies), SHARED_HR_COOKIE_FILE)
|
||||
if not cookies:
|
||||
raise LoginRequiredError(
|
||||
"未找到可用 HR 登录态:底座未注入 HR 会话且共享 cookies 文件缺失/为空,"
|
||||
"请先在插件界面完成 HR 登录后再执行导入。")
|
||||
return cookies
|
||||
|
||||
|
||||
def _build_hr_session():
|
||||
"""构建可访问 HR 接口的 requests.Session(供结果接口翻页拉全)。
|
||||
|
||||
cookies 来源与浏览器一致(注入 session 优先,兜底共享文件);构建失败返回 None,
|
||||
调用方降级为仅统计监听到的第一页(与影刀版兜底语义一致)。
|
||||
"""
|
||||
cookies = []
|
||||
session = get_session()
|
||||
if session is not None:
|
||||
cookies = _cookies_from_requests_session(session)
|
||||
if not cookies:
|
||||
cookies = _cookies_from_shared_file()
|
||||
if not cookies:
|
||||
return None
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": USER_AGENT,
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
})
|
||||
for c in cookies:
|
||||
try:
|
||||
s.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
|
||||
except Exception:
|
||||
continue
|
||||
return s
|
||||
|
||||
|
||||
# ==================== 元素定位辅助(DrissionPage) ====================
|
||||
def _create_page():
|
||||
"""创建 ChromiumPage(统一配置,非无头,与影刀版一致)。"""
|
||||
co = ChromiumOptions()
|
||||
return ChromiumPage(co)
|
||||
|
||||
|
||||
def _click_text(page, text, timeout=10):
|
||||
"""按元素文本精确匹配并点击,找不到则抛错。"""
|
||||
ele = page.ele(f'xpath://*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _click_text_in(page, container, text, timeout=5):
|
||||
"""在指定容器内按文本匹配并点击。"""
|
||||
ele = container.ele(f'xpath:.//*[normalize-space(text())="{text}"]', timeout=timeout)
|
||||
if not ele:
|
||||
raise ElementNotFoundError(f"容器内未找到元素:{text}")
|
||||
ele.click()
|
||||
logger.info("已点击:%s", text)
|
||||
|
||||
|
||||
def _is_displayed(ele):
|
||||
"""判断元素是否可见且具有尺寸;异常时返回 False(保守不误判)。"""
|
||||
if ele is None:
|
||||
return False
|
||||
try:
|
||||
if not ele.states.is_displayed:
|
||||
return False
|
||||
w, h = ele.rect.size
|
||||
return w > 0 and h > 0
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _ensure_logged_in(page):
|
||||
"""访问待增减人员页面;若被重定向到登录页,抛 LoginRequiredError。"""
|
||||
page.get(ADD_SUB_URL)
|
||||
time.sleep(WAIT_LONG)
|
||||
if page.ele('@id=j_username', timeout=2):
|
||||
raise LoginRequiredError(
|
||||
"HR 登录态已失效(页面被重定向到登录页),请先在插件界面重新登录 HR 再执行导入。")
|
||||
logger.info("已进入待增减人员页面:%s", page.url)
|
||||
|
||||
|
||||
# ==================== 增员/减员导入页面流程 ====================
|
||||
def _open_more_operations(page):
|
||||
"""点击「更多操作」按钮,展开下拉菜单(幂等,已展开则跳过)。"""
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=2)
|
||||
if menu and _is_displayed(menu):
|
||||
logger.info("「更多操作」下拉已展开,跳过")
|
||||
time.sleep(WAIT_SHORT)
|
||||
return menu
|
||||
|
||||
more_btn = page.ele('css:#more-btns button.dropdown-toggle', timeout=15)
|
||||
if not more_btn:
|
||||
more_btn = page.ele('css:button.btn-success.dropdown-toggle', timeout=5)
|
||||
if not more_btn:
|
||||
_click_text(page, BTN_MORE)
|
||||
else:
|
||||
more_btn.click()
|
||||
logger.info("已点击「更多操作」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
menu = page.ele('css:#custom-btn-ul', timeout=5)
|
||||
if not menu:
|
||||
raise ElementNotFoundError("未找到「更多操作」下拉菜单(#custom-btn-ul)")
|
||||
logger.info("「更多操作」下拉已展开")
|
||||
return menu
|
||||
|
||||
|
||||
def _choose_import_menu(page, menu_label):
|
||||
"""在下拉菜单中选择「增员导入」或「减员导入」。"""
|
||||
menu = _open_more_operations(page)
|
||||
_click_text_in(page, menu, menu_label)
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _upload_file(page, file_path):
|
||||
"""在导入弹窗中上传指定文件(直接对 input[name=file] 设置路径,跳过系统文件选择框)。"""
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
file_input = page.ele('css:input[name="file"]', timeout=15)
|
||||
if not file_input:
|
||||
raise ElementNotFoundError("未找到文件上传控件(input[name=file])")
|
||||
file_input.input(file_path)
|
||||
logger.info("已选择导入文件:%s", file_path)
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
def _click_next(page):
|
||||
"""点击导入弹窗中的「下一步」按钮(btn-success 且可见)。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-success")'
|
||||
' and normalize-space(.)="下一步"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「下一步」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「下一步」")
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
|
||||
def _click_close(page):
|
||||
"""点击导入完成弹窗中的「关闭」按钮。"""
|
||||
btn = page.ele(
|
||||
'xpath://div[contains(@class,"sub-btn")]//button[contains(@class,"btn-default")'
|
||||
' and normalize-space(.)="关闭"]',
|
||||
timeout=10,
|
||||
)
|
||||
if not btn or not _is_displayed(btn):
|
||||
raise ElementNotFoundError("未找到可见的「关闭」按钮")
|
||||
btn.click()
|
||||
logger.info("已点击「关闭」")
|
||||
time.sleep(WAIT_SHORT)
|
||||
|
||||
|
||||
# ---------------------------------------------------------------
|
||||
# 接口监听:上传表格后解析结果(getTmpDataPage.mc),捕获返回的全部异常
|
||||
# ---------------------------------------------------------------
|
||||
def _extract_json_response(req):
|
||||
"""从监听到的请求中解析 JSON 响应;解析失败返回 None。"""
|
||||
try:
|
||||
return req.response.json()
|
||||
except Exception:
|
||||
body = getattr(req.response, "body", None)
|
||||
if isinstance(body, (dict, list)):
|
||||
return body
|
||||
if not body:
|
||||
return None
|
||||
try:
|
||||
return json.loads(body)
|
||||
except Exception:
|
||||
return None
|
||||
|
||||
|
||||
def _merge_datas(result, resp):
|
||||
"""从一次接口响应(resp)中提取并累计统计:需导入总条数、成功数、异常明细。"""
|
||||
for item in resp.get("datas") or []:
|
||||
item = item or {}
|
||||
msg = str(item.get("imp_fixed_msg", "") or "").strip()
|
||||
if not msg:
|
||||
continue
|
||||
result["total_count"] += 1
|
||||
# 成功行返回「导入成功;」固定文案,只计数量不纳入异常
|
||||
if "导入成功" in msg:
|
||||
result["success_count"] += 1
|
||||
continue
|
||||
result["exceptions"].append({
|
||||
"staff_code": str(item.get("imp_assi_staff_code_ext_table_field_base_id", "") or ""),
|
||||
"staff_name": str(item.get("imp_assi_staff_name_ext_table_field_base_id", "") or ""),
|
||||
"insurance_name": str(item.get("ext_insurance_name", "") or ""),
|
||||
"message": msg,
|
||||
})
|
||||
|
||||
|
||||
def _fetch_remaining_pages(result, first_url, first_body, page_count, page_size=15):
|
||||
"""getTmpDataPage 每页固定返回 15 条,弹窗只加载第一页:按 pageNo 主动翻页拉全。
|
||||
|
||||
该接口为 POST,分页参数(importId/imp_fixed_businessid/start/pageNo/pageSize)
|
||||
在请求 body 中,必须复用首次请求 body 改页码后 POST(直接 GET URL 拿不到目标页)。
|
||||
"""
|
||||
if page_count <= 1:
|
||||
return
|
||||
session = _build_hr_session()
|
||||
if session is None:
|
||||
logger.warning("分页拉取失败(无法构建 HR 会话),仅统计弹窗第一页")
|
||||
return
|
||||
for page_no in range(2, page_count + 1):
|
||||
start = (page_no - 1) * page_size
|
||||
body = re.sub(r"pageNo=\d+", f"pageNo={page_no}", first_body or "")
|
||||
body = re.sub(r"start=\d+", f"start={start}", body)
|
||||
body = re.sub(r"pageSize=\d+", f"pageSize={page_size}", body)
|
||||
try:
|
||||
resp = session.post(first_url, data=body, timeout=15)
|
||||
data = resp.json()
|
||||
except Exception as e:
|
||||
logger.warning("分页第 %s/%s 页拉取失败:%s", page_no, page_count, e)
|
||||
continue
|
||||
if str(data.get("state", "")).strip() != TMP_DATA_STATE_OK:
|
||||
logger.warning("分页第 %s/%s 页返回 state=%s,跳过",
|
||||
page_no, page_count, data.get("state"))
|
||||
continue
|
||||
logger.info("分页第 %s/%s 页返回 %s 条",
|
||||
page_no, page_count, len(data.get("datas") or []))
|
||||
_merge_datas(result, data)
|
||||
|
||||
|
||||
def _capture_import_exceptions(page, timeout=TMP_DATA_WAIT):
|
||||
"""监听导入结果接口(getTmpDataPage.mc),捕获全部逐行结果(监听须已开启)。
|
||||
|
||||
第一步「下一步」(格式校验/预览)也可能请求该接口但行内 imp_fixed_msg 为空,跳过;
|
||||
仅处理携带导入结果说明的响应。捕获首响应后按 pageCount 主动翻页拉全。
|
||||
|
||||
Returns:
|
||||
dict: {captured, state, meg, listen_ok, success_count, total_count, exceptions}
|
||||
"""
|
||||
result = {"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "success_count": 0, "total_count": 0}
|
||||
first_url = None
|
||||
first_body = ""
|
||||
page_count = 1
|
||||
deadline = time.time() + timeout
|
||||
last_hit = time.time()
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
remain = max(0.0, deadline - time.time())
|
||||
req = page.listen.wait(timeout=min(0.5, remain))
|
||||
except Exception as e:
|
||||
logger.warning("监听 %s 接口异常:%s", TMP_DATA_API_MARK, e)
|
||||
break
|
||||
if not req:
|
||||
# 已捕获过解析响应时,再确认一个间隔后结束,合并多次返回的结果
|
||||
if result["captured"] and time.time() - last_hit >= 1.0:
|
||||
break
|
||||
continue
|
||||
if not hasattr(req, "url"):
|
||||
continue
|
||||
if TMP_DATA_API_MARK not in (req.url or ""):
|
||||
continue
|
||||
resp = _extract_json_response(req)
|
||||
if not isinstance(resp, dict):
|
||||
continue
|
||||
# 预览/校验响应行内 imp_fixed_msg 为空 -> 跳过,继续等待最终结果
|
||||
if not any(str((it or {}).get("imp_fixed_msg", "") or "").strip()
|
||||
for it in (resp.get("datas") or [])):
|
||||
continue
|
||||
result["captured"] = True
|
||||
last_hit = time.time()
|
||||
state = str(resp.get("state", "")).strip()
|
||||
if state:
|
||||
result["state"] = state
|
||||
meg = str(resp.get("meg", "") or "").strip()
|
||||
if meg:
|
||||
result["meg"] = meg
|
||||
if first_url is None:
|
||||
first_url = req.url
|
||||
first_body = req.request.postData or ""
|
||||
try:
|
||||
page_count = max(1, int(resp.get("pageCount") or 1))
|
||||
except Exception:
|
||||
page_count = 1
|
||||
_merge_datas(result, resp)
|
||||
if first_url and page_count > 1:
|
||||
_fetch_remaining_pages(result, first_url, first_body, page_count)
|
||||
break
|
||||
return result
|
||||
|
||||
|
||||
def _count_import_rows(file_path):
|
||||
"""统计导入文件需导入条数(A 列最大序号;第 1 行标题/第 2 行表头/第 3 行示例,第 4 行起数据)。
|
||||
|
||||
官方模板自带大量预格式化空白行(max_row 可达数千),不能直接用 max_row 统计。
|
||||
"""
|
||||
try:
|
||||
wb = load_workbook(file_path, read_only=True)
|
||||
try:
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
max_seq = 0
|
||||
for seq in ws.iter_rows(min_row=4, max_row=ws.max_row,
|
||||
max_col=1, values_only=True):
|
||||
v = seq[0]
|
||||
if v is None or str(v).strip() == "":
|
||||
continue
|
||||
try:
|
||||
max_seq = max(max_seq, int(v))
|
||||
except (TypeError, ValueError):
|
||||
continue
|
||||
return max_seq
|
||||
finally:
|
||||
wb.close()
|
||||
except Exception as e:
|
||||
logger.warning("统计导入文件条数失败 %s:%s", file_path, e)
|
||||
return 0
|
||||
|
||||
|
||||
def _import_file_path(category, menu_label):
|
||||
"""按菜单解析类别导入文件路径(base_dir 运行时注入,实时拼接)。"""
|
||||
if menu_label == MENU_ADD:
|
||||
from ..config import category_import_add_file
|
||||
return category_import_add_file(category)
|
||||
from ..config import category_import_sub_file
|
||||
return category_import_sub_file(category)
|
||||
|
||||
|
||||
def _import_one(page, category, menu_label, expected_total=None):
|
||||
"""对单个类别执行一次导入(选菜单 -> 上传 -> 下一步 -> 下一步 -> 关闭)。
|
||||
|
||||
自第一个「下一步」之前即开启 getTmpDataPage.mc 监听(结果接口可能在格式校验或
|
||||
真正导入时触发,提前监听避免漏捕);异常仅记录上报,不中断导入流程。
|
||||
|
||||
Args:
|
||||
expected_total: 需导入条数(由 import_all 预检传入,避免重复读文件;None 时自行统计)。
|
||||
|
||||
Returns:
|
||||
dict: 导入结果(含 expected_total 需导入条数、exceptions 异常明细等)。
|
||||
"""
|
||||
file_path = _import_file_path(category, menu_label)
|
||||
if not os.path.isfile(file_path):
|
||||
raise FileNotFoundError(f"导入文件不存在:{file_path}")
|
||||
if expected_total is None:
|
||||
expected_total = _count_import_rows(file_path)
|
||||
|
||||
logger.info("===== 类别[%s] 开始%s,文件:%s(需导入 %d 条) =====",
|
||||
category["name"], menu_label, file_path, expected_total)
|
||||
_choose_import_menu(page, menu_label)
|
||||
_upload_file(page, file_path)
|
||||
|
||||
# 第一个「下一步」前开启监听,贯穿「格式校验/预览 + 真正导入」全过程;
|
||||
# 监听启动失败必须上报,否则未捕获异常会被误判为正常(假成功)
|
||||
listen_ok = True
|
||||
try:
|
||||
page.listen.start(TMP_DATA_API_MARK)
|
||||
except Exception as e:
|
||||
listen_ok = False
|
||||
logger.error("启动 %s 接口监听失败,无法捕获导入结果:%s", TMP_DATA_API_MARK, e)
|
||||
try:
|
||||
_click_next(page) # 第一步:格式校验/预览
|
||||
_click_next(page) # 第二步:真正导入内容(触发结果接口)
|
||||
import_result = _capture_import_exceptions(page)
|
||||
import_result["listen_ok"] = listen_ok
|
||||
import_result["expected_total"] = expected_total
|
||||
finally:
|
||||
try:
|
||||
page.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 全部成功时 HR 不调用结果接口:流程完整走完 + 监听正常 + 未捕获异常行 -> 按文件条数推定全部成功
|
||||
if (not import_result["captured"] and listen_ok and not import_result["exceptions"]):
|
||||
import_result["assumed_all_success"] = True
|
||||
import_result["success_count"] = expected_total
|
||||
import_result["total_count"] = expected_total
|
||||
|
||||
if import_result["exceptions"]:
|
||||
logger.error("类别[%s] %s:导入返回 %d 条异常:",
|
||||
category["name"], menu_label, len(import_result["exceptions"]))
|
||||
for exc in import_result["exceptions"]:
|
||||
logger.error(" - [%s/%s] 方案[%s]:%s",
|
||||
exc["staff_code"], exc["staff_name"],
|
||||
exc["insurance_name"], exc["message"])
|
||||
elif not listen_ok:
|
||||
logger.error("类别[%s] %s:接口监听启动失败,无法确认导入结果,请人工核对",
|
||||
category["name"], menu_label)
|
||||
elif import_result["captured"] and import_result["state"] != TMP_DATA_STATE_OK:
|
||||
logger.error("类别[%s] %s:导入接口 state=%s(meg=%s),导入可能失败",
|
||||
category["name"], menu_label, import_result["state"], import_result["meg"])
|
||||
elif import_result.get("assumed_all_success"):
|
||||
logger.info("类别[%s] %s:全部导入成功(HR 未返回结果接口,按文件 %d 条推定),无异常",
|
||||
category["name"], menu_label, expected_total)
|
||||
elif not import_result["captured"]:
|
||||
logger.warning("类别[%s] %s:未捕获到导入结果接口响应,无法确认导入结果",
|
||||
category["name"], menu_label)
|
||||
else:
|
||||
logger.info("类别[%s] %s:导入成功 %s 人,无异常",
|
||||
category["name"], menu_label, import_result.get("success_count", 0))
|
||||
|
||||
_click_close(page)
|
||||
logger.info("===== 类别[%s] %s完成 =====", category["name"], menu_label)
|
||||
return import_result
|
||||
|
||||
|
||||
# ==================== 对外入口:先减员后增员,全程共用一个浏览器 ====================
|
||||
def _skipped_result(category, menu, reason):
|
||||
"""构造「无待导入条目」的跳过单元结果(无 error,不计流程失败)。"""
|
||||
return {
|
||||
"category": category["name"], "menu": menu,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "expected_total": 0,
|
||||
"success_count": 0, "total_count": 0,
|
||||
"skipped": True, "skip_reason": reason,
|
||||
}
|
||||
|
||||
|
||||
def import_all(categories, on_progress=None):
|
||||
"""对指定类别执行 HR 导入(★先全部类别【减员】再【增员】,顺序不可换)。
|
||||
|
||||
预检:仅「导入文件存在且实际有待导入条目」的单元才会启动浏览器执行导入;
|
||||
需导入 0 条(无增员/减员变动)的单元直接跳过——本就没有需要导入的内容,
|
||||
不启动浏览器、也不报"流程失败"。
|
||||
|
||||
Args:
|
||||
categories: 类别配置列表(config.CATEGORIES 项,须为本次调度成功的类别,
|
||||
只导入本次新生成的导入文件,避免误传历史文件)。
|
||||
on_progress: 可选回调 on_progress(done, total),每个实际执行导入的
|
||||
「类别×菜单」单元完成后调用,供 __init__.py 上报进度。
|
||||
|
||||
Returns:
|
||||
list[dict]: 每单元结果:{category, menu, captured, state, meg, exceptions,
|
||||
listen_ok, expected_total, success_count, total_count,
|
||||
assumed_all_success?, error?, error_type?, skipped?}
|
||||
skipped=True 表示该单元导入文件无待导入条目(需导入 0 条),未启动浏览器导入,
|
||||
不视为流程失败(无 error 字段)。
|
||||
|
||||
Raises:
|
||||
LoginRequiredError: HR 登录态缺失/失效(整个导入未开始,无部分导入风险)。
|
||||
RuntimeError: DrissionPage 依赖缺失。
|
||||
"""
|
||||
if not _DRP_AVAILABLE:
|
||||
raise RuntimeError(f"缺少 DrissionPage 依赖(python-env 未内置),无法自动导入:{_DRP_IMPORT_ERROR}")
|
||||
if not categories:
|
||||
logger.info("无待导入类别,跳过 HR 导入")
|
||||
return []
|
||||
|
||||
# ---- 预检:按导入文件实际条数过滤出真正需要导入的单元(类别×菜单) ----
|
||||
results = []
|
||||
units = []
|
||||
for c in categories:
|
||||
for menu in (MENU_SUB, MENU_ADD):
|
||||
label = "减员" if menu == MENU_SUB else "增员"
|
||||
file_path = _import_file_path(c, menu)
|
||||
if not os.path.isfile(file_path):
|
||||
logger.warning("类别[%s] %s导入文件不存在,视为无需导入:%s",
|
||||
c["name"], label, file_path)
|
||||
results.append(_skipped_result(c, menu, "导入文件不存在"))
|
||||
continue
|
||||
expected_total = _count_import_rows(file_path)
|
||||
if expected_total <= 0:
|
||||
logger.info("类别[%s] %s导入文件无待导入条目,跳过导入:%s",
|
||||
c["name"], label, file_path)
|
||||
results.append(_skipped_result(c, menu, "无待导入条目"))
|
||||
continue
|
||||
units.append((c, menu, expected_total))
|
||||
|
||||
if not units:
|
||||
logger.info("各类别增/减员导入文件均无待导入条目,跳过 HR 自动导入(未启动浏览器)")
|
||||
return results
|
||||
|
||||
total_units = len(units)
|
||||
done = 0
|
||||
|
||||
page = _create_page()
|
||||
logger.info("浏览器已启动(导入全程共用)")
|
||||
try:
|
||||
cookies = _collect_browser_cookies()
|
||||
page.set.cookies(cookies)
|
||||
_ensure_logged_in(page)
|
||||
|
||||
for category, menu_label, expected_total in units:
|
||||
try:
|
||||
res = dict(_import_one(page, category, menu_label, expected_total=expected_total))
|
||||
res["category"] = category["name"]
|
||||
res["menu"] = menu_label
|
||||
results.append(res)
|
||||
except Exception as e:
|
||||
logger.error("类别[%s] %s失败:%s", category["name"], menu_label, e)
|
||||
results.append({
|
||||
"category": category["name"], "menu": menu_label,
|
||||
"captured": False, "state": "", "meg": "", "exceptions": [],
|
||||
"listen_ok": True, "expected_total": 0,
|
||||
"success_count": 0, "total_count": 0,
|
||||
"error": str(e), "error_type": type(e).__name__,
|
||||
})
|
||||
done += 1
|
||||
if on_progress:
|
||||
try:
|
||||
on_progress(done, total_units)
|
||||
except Exception:
|
||||
pass
|
||||
return results
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def summarize_results(results):
|
||||
"""把导入结果汇总为可读文本行列表(供插件 summary 拼接)。
|
||||
|
||||
口径与影刀版一致:需导入条数取自导入文件(expected_total,与接口是否捕获无关);
|
||||
成功/失败取接口返回的业务结果(全部成功时 HR 不返回接口,按文件条数推定成功);
|
||||
流程失败(登录/元素/文件缺失)的单元不纳入条数统计,仅报失败;
|
||||
跳过单元(skipped,无待导入条目)正常纳入统计(需导入 0 条),不报失败/待确认。
|
||||
"""
|
||||
lines = []
|
||||
for menu, label in ((MENU_SUB, "减员"), (MENU_ADD, "增员")):
|
||||
rs = [r for r in results if r.get("menu") == menu]
|
||||
if not rs:
|
||||
continue
|
||||
total = sum(r.get("expected_total") or 0 for r in rs if not r.get("error"))
|
||||
success = sum(r.get("success_count") or 0 for r in rs if not r.get("error"))
|
||||
fail = sum(len(r.get("exceptions") or []) for r in rs if not r.get("error"))
|
||||
flow_failed = [r["category"] for r in rs if r.get("error")]
|
||||
unconfirmed = [r["category"] for r in rs
|
||||
if not r.get("error") and not r.get("exceptions")
|
||||
and not r.get("assumed_all_success") and not r.get("skipped")
|
||||
and (not r.get("captured") or r.get("state") != TMP_DATA_STATE_OK)]
|
||||
line = f"{label}:需导入 {total} 条,成功 {success} 条,异常 {fail} 条"
|
||||
extras = []
|
||||
if unconfirmed:
|
||||
extras.append(f"{len(unconfirmed)} 个类别结果待人工确认({'、'.join(unconfirmed)})")
|
||||
if flow_failed:
|
||||
extras.append(f"流程失败({'、'.join(flow_failed)})")
|
||||
if extras:
|
||||
line += ";" + ";".join(extras)
|
||||
lines.append(line)
|
||||
return lines
|
||||
@@ -0,0 +1,158 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 筛选复制(由影刀版 roster_filter.py v2.0.0 移植)。
|
||||
|
||||
从员工花名册按类别 include/exclude 所属单位筛选数据,复制到各自类别目标表
|
||||
(各文件夹内最新的「*雇主险变更记录*.xlsx」),并剔除「入职时间 > 业务日期」的
|
||||
未来入职员工;F列工号强制文本格式(否则与在参名单 B列及表内公式匹配失败)。
|
||||
|
||||
源表缺失或超过 TTL(15 分钟)时调用 data.roster_export_api.export_roster 自动导出,
|
||||
替代影刀版对 share/roster_export.py 的懒加载;登录态经底座注入的 session。
|
||||
"""
|
||||
import os
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from ..config import (
|
||||
logger, SHEET_BIZ, SOURCE_HEADER_MARK, EXPORT_TEMPLATE, EXPORT_STATUSES,
|
||||
TARGET_HEADER_ROW, DATA_COLUMNS, CODE_COL, ID_COL, JOIN_DATE_COL, NAME_COL,
|
||||
EXCLUDE_REGIONS, EXCLUDE_NAME_KEYWORDS, category_folder, employee_file,
|
||||
find_latest_target, to_text, parse_join_date, ref_date, CACHE_DIR,
|
||||
)
|
||||
from ..data.roster_export_api import export_roster
|
||||
|
||||
|
||||
def _read_source(employee_path):
|
||||
"""读取源表(员工花名册):自动定位表头行(B 列=「所属单位」),返回 B~O 14 列切片。"""
|
||||
probe = pd.read_excel(employee_path, header=None, nrows=8)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
df = pd.read_excel(employee_path, header=header_row)
|
||||
if df.shape[1] < DATA_COLUMNS + 1:
|
||||
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
|
||||
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
return data[data.iloc[:, 0].notna()]
|
||||
|
||||
|
||||
def filter_and_copy_roster(category, employee_path="", target_file=None):
|
||||
"""从员工花名册按类别筛选数据,复制到该类别的雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
category: 类别配置(含 name/include_dept/exclude_dept)
|
||||
employee_path: 源表路径,默认 {base_dir}\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认取该类别文件夹内最新的「*雇主险变更记录*.xlsx」
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
category_name = category["name"]
|
||||
employee_path = os.path.abspath(employee_path or employee_file())
|
||||
target_file = os.path.abspath(target_file or find_latest_target(category_folder(category)))
|
||||
|
||||
if not os.path.exists(employee_path):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_path}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file}")
|
||||
|
||||
# ---------- 1. 读取源表并过滤 ----------
|
||||
data = _read_source(employee_path)
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
name = data.iloc[:, NAME_COL].astype(str).str.strip()
|
||||
include_dept = category.get("include_dept") or []
|
||||
exclude_dept = category.get("exclude_dept") or []
|
||||
mask = ~region.isin(EXCLUDE_REGIONS)
|
||||
if include_dept:
|
||||
mask &= dept.isin(include_dept)
|
||||
if exclude_dept:
|
||||
mask &= ~dept.isin(exclude_dept)
|
||||
for kw in EXCLUDE_NAME_KEYWORDS:
|
||||
mask &= ~name.str.contains(kw, na=False)
|
||||
|
||||
# 入职时间 > 业务日期 的行剔除(未来才入职的员工暂不纳入,留到当天再筛选出来)
|
||||
today = ref_date()
|
||||
join_dates = data.iloc[:, JOIN_DATE_COL].map(parse_join_date)
|
||||
future_mask = join_dates.map(lambda d: d is not None and d > today)
|
||||
n_future = int(future_mask.sum())
|
||||
mask &= ~future_mask
|
||||
filtered = data[mask]
|
||||
logger.info("类别[%s]:源表共 %d 行,过滤后 %d 行(保留 %s / 排除 %s,并排除 %s,姓名剔除含 %s,剔除未来入职 %d 人)",
|
||||
category_name, len(data), len(filtered),
|
||||
include_dept or "全部", exclude_dept or "无", " / ".join(EXCLUDE_REGIONS),
|
||||
" / ".join(EXCLUDE_NAME_KEYWORDS), n_future)
|
||||
if len(filtered) == 0:
|
||||
logger.warning("类别[%s] 筛选后没有数据!", category_name)
|
||||
|
||||
# ---------- 2. 写目标表(先覆盖写入,只清空超出新数据的旧行) ----------
|
||||
wb = load_workbook(target_file)
|
||||
if SHEET_BIZ not in wb.sheetnames:
|
||||
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
|
||||
ws = wb[SHEET_BIZ]
|
||||
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
|
||||
|
||||
# 找 B 列当前最后非空数据行(用于清空多余旧行)
|
||||
old_last = first_data_row - 1
|
||||
for r in range(first_data_row, ws.max_row + 1):
|
||||
if ws.cell(row=r, column=2).value is not None:
|
||||
old_last = r
|
||||
|
||||
# 写入 B~O(覆盖旧数据;F列工号 / O列证件号 强制文本格式)
|
||||
rows = filtered.values.tolist()
|
||||
cell = ws.cell
|
||||
for i, row in enumerate(rows, start=first_data_row):
|
||||
for j, val in enumerate(row, start=2):
|
||||
c = cell(row=i, column=j)
|
||||
# 工号/证件号为主键:18位身份证号超出浮点精度,文本化避免截断,保证公式/映射匹配
|
||||
if j - 2 in (CODE_COL, ID_COL):
|
||||
c.value = to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
|
||||
# 清空超出新数据的旧行
|
||||
new_last = first_data_row + len(rows) - 1
|
||||
if old_last > new_last:
|
||||
for r in range(new_last + 1, old_last + 1):
|
||||
for c in range(2, 2 + DATA_COLUMNS):
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("类别[%s] 已写入目标表 %s 第%d行起,共 %d 行", category_name, target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def ensure_employee_file(employee_path="", session=None):
|
||||
"""确保花名册源表可用:缺失或超过 TTL(15 分钟)时自动重新从 HR 接口导出。
|
||||
|
||||
新鲜度评估交给 export_roster 的 TTL 缓存:源表存在、非空且距上次导出
|
||||
不超过 15 分钟时直接复用,否则重新导出覆盖(不用陈旧花名册做调度)。
|
||||
|
||||
Args:
|
||||
employee_path: 花名册路径(留空=默认根目录/员工花名册.xlsx)
|
||||
session: 底座注入的 HR 会话(导出时使用)
|
||||
|
||||
Returns:
|
||||
源表绝对路径
|
||||
"""
|
||||
path = os.path.abspath(employee_path or employee_file())
|
||||
export_roster(
|
||||
download_dir=os.path.join(CACHE_DIR, "roster_tmp"),
|
||||
output_path=path,
|
||||
template_name=EXPORT_TEMPLATE,
|
||||
statuses=EXPORT_STATUSES,
|
||||
session=session,
|
||||
)
|
||||
if not os.path.exists(path):
|
||||
raise FileNotFoundError(f"花名册导出完成但源表仍不存在:{path}")
|
||||
return path
|
||||
@@ -0,0 +1,559 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 三阶段名额调度(由影刀版 employer_insurance_schedule.py v1.3.0 移植)。
|
||||
|
||||
阶段0 初始化(空闲名额池 / 当前参保映射 / 待转入队列)→
|
||||
阶段1 处理业务(增加投保批量 / 要替换逐行)→
|
||||
阶段2 分配名额(复用空闲名额 / 全新新增);
|
||||
含姓名核对修正(J列)、特殊情况槽位追踪(离职/参保减少被复用后保留占位)、
|
||||
以及类别级编排 schedule_category(读取目标文件 → 各阶段 → 输出)。
|
||||
|
||||
文件路径/日期/常量统一来自 config 层;输出(在参名单/变更清单/备份/增减员导入)
|
||||
由 report.output 负责(本模块在编排处懒加载,避免与 report 相互 import 成环)。
|
||||
"""
|
||||
import os
|
||||
from collections import defaultdict
|
||||
|
||||
import pandas as pd
|
||||
|
||||
from ..config import (
|
||||
logger, SHEET_BIZ, SHEET_IN_PARAM, DATA_START_ROW,
|
||||
BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME, BIZ_COL_HANDLE,
|
||||
VALID_CATEGORIES, VALID_SCHEMES, category_target_file,
|
||||
category_output_backup, category_change_sheet_name,
|
||||
add_import_template, sub_import_template, to_text, today_date,
|
||||
)
|
||||
|
||||
|
||||
class DataValidationError(Exception):
|
||||
"""数据校验失败异常:直接中断调度,禁止继续往后跑。"""
|
||||
|
||||
|
||||
def scheme_with_suffix(category, scheme):
|
||||
"""增员导入「保险方案名称」追加厂区后缀(如 人保-80万 -> 人保-80万-秒创)。
|
||||
|
||||
源数据投保方案为无后缀的人保-X万;HR 侧方案列表含厂区后缀,
|
||||
生成增员导入文件时按类别追加。已带对应后缀或后缀为空时原样返回。
|
||||
"""
|
||||
suffix = str(category.get("scheme_suffix") or "").strip()
|
||||
scheme = str(scheme or "").strip()
|
||||
if suffix and scheme and not scheme.endswith("-" + suffix):
|
||||
return f"{scheme}-{suffix}"
|
||||
return scheme
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、数据校验
|
||||
# ============================================================
|
||||
def validate_biz_data(biz_df):
|
||||
"""校验花名册业务数据的合法性。
|
||||
|
||||
校验规则:
|
||||
1. 工种类别(P列)必须为:一类/二类/三类/四类
|
||||
2. 方案处理 = "增加投保" 时,投保方案(Q列)必须为:人保-20万 / 50万 / 80万
|
||||
|
||||
返回 errors 错误列表,每个错误含 行号/员工ID/错误类型/详情;为空表示校验通过。
|
||||
"""
|
||||
errors = []
|
||||
for idx, row in biz_df.iterrows():
|
||||
row_num = idx + 5 # 数据从第5行开始(第4行是表头)
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
category = row[BIZ_COL_CATEGORY]
|
||||
scheme = row[BIZ_COL_SCHEME]
|
||||
handle = row[BIZ_COL_HANDLE]
|
||||
|
||||
if pd.isna(category) or category not in VALID_CATEGORIES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "工种类别非法",
|
||||
"详情": f"工种类别为 '{category}',允许值:{VALID_CATEGORIES}",
|
||||
})
|
||||
|
||||
if str(handle).strip() == "增加投保":
|
||||
if pd.isna(scheme) or scheme not in VALID_SCHEMES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "投保方案非法",
|
||||
"详情": f"增加投保但投保方案为 '{scheme}',允许值:{VALID_SCHEMES}",
|
||||
})
|
||||
return errors
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、阶段0:初始化(从在参名单构建状态)
|
||||
# ============================================================
|
||||
def initialize(in_param_df):
|
||||
"""从「手动维护-在参名单」构建三个核心数据结构。
|
||||
|
||||
1. idle_pools: 空闲名额池 {方案名称: [{type, employee_id}, ...]}
|
||||
2. employee_map: 当前参保员工映射 {证件号: 投保方案}
|
||||
3. pending_queues: 待转入队列(初始为空){方案名称: [证件号, ...]}
|
||||
|
||||
列索引(0-based): K列(10)证件号 / M列(12)当前投保方案 / R列(17)方案处理
|
||||
"""
|
||||
idle_pools = defaultdict(list)
|
||||
employee_map = {}
|
||||
pending_queues = defaultdict(list)
|
||||
|
||||
IDX_EMP_ID = 10
|
||||
IDX_CUR_SCHEME = 12
|
||||
IDX_HANDLE = 17
|
||||
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[IDX_EMP_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
|
||||
handle = str(row.iloc[IDX_HANDLE]).strip()
|
||||
scheme = row.iloc[IDX_CUR_SCHEME]
|
||||
|
||||
if handle in ["无需", "档次替换"]:
|
||||
# 正常参保或待替换,都视为当前已参保
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
employee_map[emp_id] = scheme
|
||||
elif handle == "离职减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({"type": "离职减少", "employee_id": emp_id})
|
||||
elif handle == "参保减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({"type": "参保减少", "employee_id": emp_id})
|
||||
# 其他值(如'/')忽略
|
||||
|
||||
# 按优先级排序(离职减少优先)
|
||||
for scheme in idle_pools:
|
||||
idle_pools[scheme].sort(key=lambda x: 1 if x["type"] == "离职减少" else 2)
|
||||
|
||||
return idle_pools, employee_map, pending_queues
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二点五、姓名核对修正(在参名单 J列 与 花名册 姓名比对)
|
||||
# ============================================================
|
||||
def collect_name_corrections(in_param_df, biz_df):
|
||||
"""核对「手动维护-在参名单」J列姓名与花名册「姓名」是否一致,并就地修正。
|
||||
|
||||
以证件号(在参名单 K列 / 花名册 O列)为关联键:
|
||||
- 在参名单中证件号存在、且花名册中能查到该证件号(覆盖离职减少/参保减少等全部行)
|
||||
- 两者姓名不一致且花名册姓名非空 → 记录一条修正,并把 in_param_df J列改为花名册姓名,
|
||||
使后续「删除记录 / 在参名单输出 / 减员导入」统一使用修正后姓名。
|
||||
- 花名册查不到(如已离职)无法核对,跳过不处理。
|
||||
|
||||
Returns:
|
||||
corrections: 修正列表,每项 {emp_id, old_name, new_name, category, scheme}
|
||||
"""
|
||||
biz_dict = {}
|
||||
for _, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
corrections = []
|
||||
for idx, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
biz_row = biz_dict.get(emp_id)
|
||||
if biz_row is None:
|
||||
continue # 花名册查不到,无法核对,跳过
|
||||
new_name = biz_row.get("姓名")
|
||||
if new_name is None or pd.isna(new_name) or str(new_name).strip() == "":
|
||||
continue
|
||||
new_name = str(new_name).strip()
|
||||
old_name = row.iloc[9]
|
||||
old_name_txt = "" if pd.isna(old_name) else str(old_name).strip()
|
||||
if old_name_txt == new_name:
|
||||
continue # 姓名一致,无需修正
|
||||
# 就地修正 in_param_df J列(姓名),供后续统一使用
|
||||
in_param_df.at[idx, in_param_df.columns[9]] = new_name
|
||||
corrections.append({
|
||||
"emp_id": emp_id,
|
||||
"old_name": old_name_txt or "未知",
|
||||
"new_name": new_name,
|
||||
"category": biz_row.get(BIZ_COL_CATEGORY),
|
||||
"scheme": biz_row.get(BIZ_COL_SCHEME),
|
||||
})
|
||||
|
||||
if corrections:
|
||||
logger.info("姓名核对修正:共 %d 条", len(corrections))
|
||||
for c in corrections:
|
||||
logger.info(" %s:%s → %s", c["emp_id"], c["old_name"], c["new_name"])
|
||||
else:
|
||||
logger.info("姓名核对完成:在参名单与花名册姓名全部一致")
|
||||
return corrections
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、阶段1:处理花名册业务
|
||||
# ============================================================
|
||||
def process_business(biz_df, idle_pools, employee_map, pending_queues):
|
||||
"""遍历花名册业务数据,产生待转入队列和额外空闲名额。
|
||||
|
||||
业务类型:
|
||||
1. 增加投保 → 批量加入待转入队列
|
||||
2. 要替换 → 逐行处理:产生"档次替换迁出"名额,员工置为未参保
|
||||
3. 其他 → 记录"非法事件跳过"
|
||||
|
||||
返回:idle_pools, employee_map, pending_queues, change_log
|
||||
"""
|
||||
change_log = []
|
||||
now = today_date()
|
||||
|
||||
# ---------- 1. 增加投保(批量处理) ----------
|
||||
df_add = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "增加投保"]
|
||||
if not df_add.empty:
|
||||
for scheme, group in df_add.groupby(BIZ_COL_SCHEME):
|
||||
if pd.isna(scheme) or scheme == "":
|
||||
for _, row in group.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "投保方案为空,无法增加投保",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
emp_ids = group[BIZ_COL_EMPLOYEE_ID].tolist()
|
||||
pending_queues[scheme].extend(emp_ids)
|
||||
for emp_id in emp_ids:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "增加投保",
|
||||
"详情": f"加入 {scheme} 待转入队列",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
# ---------- 2. 要替换(逐行处理,涉及状态变更) ----------
|
||||
df_replace = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "要替换"]
|
||||
for _, row in df_replace.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
target_scheme = row[BIZ_COL_SCHEME]
|
||||
|
||||
# 校验:员工必须当前已参保
|
||||
origin_scheme = employee_map.get(emp_id)
|
||||
if origin_scheme is None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "员工当前未参保,无法进行档次替换",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
if pd.isna(target_scheme) or target_scheme == "":
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "目标方案为空",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
# 产生"档次替换迁出"名额
|
||||
idle_pools[origin_scheme].append({"type": "档次替换迁出", "employee_id": emp_id})
|
||||
# 重新排序(离职减少 > 参保减少 > 档次替换迁出)
|
||||
idle_pools[origin_scheme].sort(
|
||||
key=lambda x: 1 if x["type"] == "离职减少"
|
||||
else 2 if x["type"] == "参保减少"
|
||||
else 3)
|
||||
|
||||
# 员工置为未参保
|
||||
employee_map[emp_id] = None
|
||||
pending_queues[target_scheme].append(emp_id)
|
||||
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "档次替换迁出",
|
||||
"详情": f"从 {origin_scheme} 迁出,进入 {target_scheme} 待转入",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
# ---------- 3. 其他未知类型 ----------
|
||||
df_other = biz_df[~biz_df[BIZ_COL_HANDLE].astype(str).str.strip().isin(["增加投保", "要替换"])]
|
||||
for _, row in df_other.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"未知业务类型: {row[BIZ_COL_HANDLE]}",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return idle_pools, employee_map, pending_queues, change_log
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四、阶段2:分配名额
|
||||
# ============================================================
|
||||
def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||||
"""逐个方案处理待转入队列,分配空闲名额或创建新名额。
|
||||
|
||||
逻辑:
|
||||
1. 队列中的每个员工必须未参保
|
||||
2. 有空闲名额 → 复用(记录来源)
|
||||
3. 无空闲名额 → 全新新增
|
||||
|
||||
返回:final_records, change_log, reused_source_employees
|
||||
"""
|
||||
final_records = []
|
||||
reused_source_employees = []
|
||||
all_schemes = set(idle_pools.keys()) | set(pending_queues.keys())
|
||||
now = today_date()
|
||||
|
||||
for scheme in all_schemes:
|
||||
queue = pending_queues.get(scheme, [])
|
||||
pool = idle_pools.get(scheme, [])
|
||||
|
||||
for emp_id in queue:
|
||||
# 校验:员工必须未参保
|
||||
if employee_map.get(emp_id) is not None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"员工已参保 {employee_map[emp_id]},不能重复参保",
|
||||
"时间": now,
|
||||
})
|
||||
continue
|
||||
|
||||
if pool:
|
||||
# 复用空闲名额(取出优先级最高的)
|
||||
slot = pool.pop(0)
|
||||
reused_source_employees.append(slot["employee_id"])
|
||||
employee_map[emp_id] = scheme
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": slot["type"],
|
||||
"来源员工ID": slot["employee_id"],
|
||||
})
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "复用空闲名额参保",
|
||||
"详情": f"复用 {slot['type']}(来源 {slot['employee_id']}),方案 {scheme}",
|
||||
"来源员工ID": slot["employee_id"],
|
||||
"时间": now,
|
||||
})
|
||||
else:
|
||||
# 全新新增
|
||||
employee_map[emp_id] = scheme
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": "全新新增",
|
||||
})
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "全新新增名额参保",
|
||||
"详情": f"新增名额,方案 {scheme}",
|
||||
"时间": now,
|
||||
})
|
||||
|
||||
return final_records, change_log, reused_source_employees
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四点半、特殊情况槽位追踪(report 层共用)
|
||||
# ============================================================
|
||||
def _find_special_slots(final_records, in_param_df):
|
||||
"""识别特殊情况:离职/参保减少名额被老员工复用,且该老员工释放的旧名额无人复用。
|
||||
|
||||
(例如 曹益娟参保减少20万→老员工胡兴复用,胡兴的X档旧名额没人用)。
|
||||
此时把源员工名额改为老员工旧方案(X档)保留在参名单,变更清单补一条"增加X档",
|
||||
既保证 增加>=删除 平衡,又把空闲名额放回池中供下次替换使用(避免同人两条名单)。
|
||||
|
||||
Returns:
|
||||
special_slots: [{source_id, source_name, source_category, new_scheme}, ...]
|
||||
"""
|
||||
# 初始参保映射:在参名单 M列(投保方案)非空视为"原已参保"
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
orig_scheme = row.iloc[12]
|
||||
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
# 槽位复用网络:来源员工ID -> 接收记录(用于链条追踪)
|
||||
slot_network = {}
|
||||
for _rec in final_records:
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
slot_network[str(_sid).strip()] = _rec
|
||||
|
||||
# 链条追踪:离职/参保减少释放的名额被老员工复用后,沿"来源员工ID"网络一路追踪,
|
||||
# 老员工每次"删除自己旧方案"即释放一个旧名额,若该名额被下一人复用则继续,直到:
|
||||
# - 接收者是全新新员工(无旧方案可删)→ 链条自然结束,增删本就平衡;
|
||||
# - 末端老员工释放的旧名额无人复用 → 该旧名额即"空闲名额"(X档)。
|
||||
special_slots = []
|
||||
for rec in final_records:
|
||||
if rec.get("名额来源") not in ("离职减少", "参保减少"):
|
||||
continue
|
||||
source_id = rec.get("来源员工ID")
|
||||
# 源员工自身也参保则跳过,避免同一个人出现两条名单
|
||||
if source_id is None or pd.isna(source_id) or source_id in final_emp_ids:
|
||||
continue
|
||||
source_id = str(source_id).strip()
|
||||
# 沿链条追踪,找到末端"未被复用的旧方案"(空闲名额 X档)
|
||||
current_owner = source_id
|
||||
visited = set()
|
||||
loose_end_scheme = None
|
||||
while current_owner not in visited:
|
||||
visited.add(current_owner)
|
||||
next_rec = slot_network.get(current_owner)
|
||||
if next_rec is None:
|
||||
break # 链条断裂
|
||||
receiver_id = str(next_rec["证件号"]).strip()
|
||||
# 接收者不是原已参保老员工(全新新员工)-> 无旧方案可释放,链条自然结束
|
||||
if receiver_id not in initial_employee_map:
|
||||
break
|
||||
# 接收者是老员工:释放自己的旧方案(X档);若该旧名额无人复用则即为空闲名额
|
||||
if receiver_id not in slot_network:
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == receiver_id]
|
||||
if not row_match.empty:
|
||||
loose_end_scheme = row_match.iloc[0].iloc[12]
|
||||
break
|
||||
current_owner = receiver_id # 旧名额被复用,继续追踪下一环
|
||||
if not loose_end_scheme:
|
||||
continue
|
||||
src_match = in_param_df[in_param_df.iloc[:, 10] == source_id]
|
||||
if src_match.empty:
|
||||
continue
|
||||
src_row = src_match.iloc[0]
|
||||
special_slots.append({
|
||||
"source_id": source_id,
|
||||
"source_name": src_row.iloc[9],
|
||||
"source_category": src_row.iloc[11],
|
||||
"new_scheme": loose_end_scheme,
|
||||
})
|
||||
return special_slots
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 五、类别级编排(读取目标文件 → 三阶段 → 输出)
|
||||
# ============================================================
|
||||
def _check_import_templates():
|
||||
"""前置校验增减员导入模板是否存在,任一缺失立即抛错。
|
||||
|
||||
模板在调度开始时校验(而非生成导入文件时才报),避免完整调度跑完后
|
||||
才发现模板缺失、需要重做的浪费。
|
||||
"""
|
||||
missing = [
|
||||
path for path in (add_import_template(), sub_import_template())
|
||||
if not os.path.isfile(path)
|
||||
]
|
||||
if missing:
|
||||
raise FileNotFoundError(
|
||||
"增减员导入模板缺失,请先补充模板后再调度:\n - " + "\n - ".join(missing))
|
||||
|
||||
|
||||
def schedule_category(category, enable_validation=True, gen_import_files=True):
|
||||
"""对单个类别执行调度全流程(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
Args:
|
||||
category: 类别配置
|
||||
enable_validation: 是否启用数据校验(校验失败抛 DataValidationError 中断)
|
||||
gen_import_files: 是否生成增员/减员导入文件
|
||||
|
||||
前置:目标文件已完成筛选复制(roster_filter)并经 WPS/Excel 重算公式。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
output_backup = category_output_backup(category)
|
||||
change_sheet_prefix = category["change_sheet_prefix"]
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
logger.info("=" * 70)
|
||||
logger.info("类别[%s] 目标文件:%s", category_name, target_file)
|
||||
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(f"目标表不存在:{target_file},请先完成筛选复制步骤")
|
||||
|
||||
# 检查必需 Sheet
|
||||
xl = pd.ExcelFile(target_file)
|
||||
for s in (SHEET_BIZ, SHEET_IN_PARAM):
|
||||
if s not in xl.sheet_names:
|
||||
raise ValueError(f"目标表缺少必需 Sheet:{s}")
|
||||
logger.info("文件结构检查通过。")
|
||||
|
||||
if gen_import_files:
|
||||
_check_import_templates()
|
||||
|
||||
# ---------- 读取并清洗花名册数据 ----------
|
||||
# O列(索引14)证件号强制 dtype=str:含空行的列会被 pandas 推断为 float64,
|
||||
# 18 位身份证号读取即截断(如 ...0009 -> ...0000),导致与在参名单匹配失败
|
||||
biz_df = pd.read_excel(target_file, sheet_name=SHEET_BIZ, header=3, dtype={14: str})
|
||||
logger.info("原始花名册数据:%d 行", len(biz_df))
|
||||
# 过滤:证件号为空 或 方案处理为 "/"
|
||||
biz_df = biz_df[
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID].notna() &
|
||||
(biz_df[BIZ_COL_HANDLE].astype(str).str.strip() != "/")
|
||||
]
|
||||
logger.info("清洗后花名册数据:%d 行", len(biz_df))
|
||||
|
||||
# ---------- 读取在参名单 ----------
|
||||
# K列(索引10)证件号同样强制 dtype=str,避免 float64 截断 18 位身份证号
|
||||
in_param_df = pd.read_excel(target_file, sheet_name=SHEET_IN_PARAM, header=5,
|
||||
dtype={10: str})
|
||||
logger.info("在参名单:%d 行", len(in_param_df))
|
||||
|
||||
# 主键文本化:证件号统一转文本(pandas 会把纯数字证件号读为 int64,openpyxl 落盘时
|
||||
# 转浮点会截断 18 位身份证号;统一文本化后匹配/输出全部一致且不丢精度)
|
||||
# 用整列赋值(允许自动升级 dtype),避免 float64 列 iloc 赋值报 LossySetitemError
|
||||
biz_df = biz_df.copy()
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID] = biz_df[BIZ_COL_EMPLOYEE_ID].map(to_text)
|
||||
in_param_df = in_param_df.copy()
|
||||
_id_col = in_param_df.columns[10]
|
||||
in_param_df[_id_col] = in_param_df[_id_col].map(to_text)
|
||||
column_names = in_param_df.columns.tolist()
|
||||
|
||||
# ---------- 姓名核对修正 ----------
|
||||
logger.info("核对在参名单与花名册姓名...")
|
||||
name_corrections = collect_name_corrections(in_param_df, biz_df)
|
||||
|
||||
# ---------- 数据校验 ----------
|
||||
if enable_validation:
|
||||
logger.info("正在校验数据...")
|
||||
errors = validate_biz_data(biz_df)
|
||||
if errors:
|
||||
for e in errors:
|
||||
logger.error(" 行%s 员工%s:%s - %s",
|
||||
e["行号"], e["员工ID"], e["错误类型"], e["详情"])
|
||||
raise DataValidationError(
|
||||
f"类别[{category_name}] 数据校验失败,共 {len(errors)} 个错误,已中断调度")
|
||||
logger.info("数据校验通过!")
|
||||
|
||||
# ---------- 阶段0:初始化 ----------
|
||||
logger.info("初始化状态...")
|
||||
idle_pools, employee_map, pending_queues = initialize(in_param_df)
|
||||
logger.info(" 空闲名额池:%d 个", sum(len(v) for v in idle_pools.values()))
|
||||
logger.info(" 当前参保员工:%d 人", len(employee_map))
|
||||
|
||||
# ---------- 阶段1:处理业务 ----------
|
||||
logger.info("处理花名册业务...")
|
||||
idle_pools, employee_map, pending_queues, change_log = process_business(
|
||||
biz_df, idle_pools, employee_map, pending_queues)
|
||||
logger.info(" 待转入总人数:%d 人", sum(len(v) for v in pending_queues.values()))
|
||||
logger.info(" 变更日志条数:%d", len(change_log))
|
||||
|
||||
# ---------- 阶段2:分配名额 ----------
|
||||
logger.info("分配名额...")
|
||||
final_records, change_log, reused_source_employees = allocate_slots(
|
||||
idle_pools, employee_map, pending_queues, change_log)
|
||||
logger.info(" 最终参保记录:%d 人", len(final_records))
|
||||
|
||||
# ---------- 阶段3+4:输出(懒加载 report,避免 import 成环) ----------
|
||||
from ..report.output import output_results, export_add_sub_import
|
||||
logger.info("输出结果...")
|
||||
output_results(
|
||||
final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, change_sheet_prefix, SHEET_IN_PARAM,
|
||||
name_corrections)
|
||||
|
||||
if gen_import_files:
|
||||
logger.info("生成增员/减员导入文件...")
|
||||
export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees)
|
||||
|
||||
logger.info("类别[%s] 调度完成!", category_name)
|
||||
return final_records
|
||||
@@ -0,0 +1,122 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - WPS/Excel COM 后台重算 + 取消筛选工具。
|
||||
|
||||
替代雇主险流程中「人工打开目标文件刷新公式(Ctrl+S 保存)」环节:
|
||||
openpyxl 写入数据后公式列的缓存结果会丢失,调度/导出变更清单前必须先重算落盘;
|
||||
同时移除所有 sheet 的 AutoFilter,保证每次处理结束文件以无筛选状态保存,
|
||||
后续人工「删除重新粘贴花名册」不再受筛选残留导致数据错位。
|
||||
底层用 WPS 表格 COM(Ket.Application,专业版/企业版)打开 → 取消筛选 →
|
||||
CalculateFullRebuild → Save;WPS 不可用时回退 MS Excel(Excel.Application)。
|
||||
目标文件若已被用户在 WPS/Excel 中打开则复用该工作簿,不打断用户会话。
|
||||
"""
|
||||
import os
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
class ComRecalcError(RuntimeError):
|
||||
"""公式重算失败(文件被占用 / 本机无 WPS 专业版或 MS Excel / COM 异常)。"""
|
||||
|
||||
|
||||
def recalc_target(file_path):
|
||||
"""对单个 xlsx 执行「取消全部筛选 → 全量重算公式 → 保存」。
|
||||
|
||||
目标文件已在 WPS/Excel 中打开时复用该工作簿(不关闭,保留用户会话);
|
||||
由本函数自行打开的工作簿在保存后关闭;仅当实例已无其他工作簿时才退出 COM。
|
||||
|
||||
Args:
|
||||
file_path: 目标文件绝对路径。
|
||||
|
||||
Raises:
|
||||
ComRecalcError: 重算失败(含本机无可用 COM 引擎 / COM 异常等)。
|
||||
"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.isfile(file_path):
|
||||
raise ComRecalcError(f"待重算文件不存在:{file_path}")
|
||||
|
||||
import pythoncom
|
||||
import win32com.client
|
||||
|
||||
pythoncom.CoInitialize()
|
||||
app = None
|
||||
engine = ""
|
||||
wb = None
|
||||
already_open = False
|
||||
try:
|
||||
# 优先 WPS 表格 COM(Ket.Application);失败回退 MS Excel
|
||||
try:
|
||||
app = win32com.client.Dispatch("Ket.Application")
|
||||
engine = "WPS"
|
||||
except Exception:
|
||||
try:
|
||||
app = win32com.client.Dispatch("Excel.Application")
|
||||
engine = "Excel"
|
||||
except Exception as e:
|
||||
raise ComRecalcError(
|
||||
"本机未检测到可用的 WPS 表格 COM / MS Excel COM,无法自动重算公式。\n"
|
||||
"请安装 WPS 专业版/企业版或 MS Excel 后重试,或关闭「WPS/Excel 后台重算公式」开关后人工打开文件 Ctrl+S 刷新公式。"
|
||||
) from e
|
||||
|
||||
# 不设置 Visible=False:Dispatch 可能附着到用户已打开的实例,隐藏其窗口
|
||||
app.DisplayAlerts = False # 关闭弹窗警告(finally 恢复)
|
||||
try:
|
||||
# 目标文件已在 WPS/Excel 中打开时复用该工作簿
|
||||
for w in app.Workbooks:
|
||||
try:
|
||||
if os.path.normcase(str(w.FullName or "")) == os.path.normcase(file_path):
|
||||
wb = w
|
||||
already_open = True
|
||||
break
|
||||
except Exception:
|
||||
continue
|
||||
if wb is None:
|
||||
wb = app.Workbooks.Open(file_path, UpdateLinks=2)
|
||||
|
||||
# 1. 取消所有 sheet 的筛选(筛选只是隐藏行,但会干扰人工维护花名册)
|
||||
removed = 0
|
||||
for ws in wb.Worksheets:
|
||||
try:
|
||||
if ws.AutoFilterMode:
|
||||
ws.AutoFilterMode = False
|
||||
removed += 1
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
# 2. 强制完整重算全部公式(openpyxl 写入后公式列缓存丢失)
|
||||
wb.Application.CalculateFullRebuild()
|
||||
|
||||
# 3. 把计算结果缓存写入 xlsx 磁盘
|
||||
wb.Save()
|
||||
logger.info("公式重算完成(%s COM):取消 %d 个 sheet 筛选%s:%s",
|
||||
engine, removed,
|
||||
"(复用已打开的工作簿)" if already_open else "", file_path)
|
||||
finally:
|
||||
try:
|
||||
app.DisplayAlerts = True
|
||||
except Exception:
|
||||
pass
|
||||
if wb is not None and not already_open:
|
||||
try:
|
||||
wb.Close(SaveChanges=False)
|
||||
except Exception:
|
||||
pass
|
||||
except ComRecalcError:
|
||||
raise
|
||||
except Exception as e:
|
||||
# 打开失败通常仍是文件被占用/锁定,给出可操作提示
|
||||
raise ComRecalcError(
|
||||
f"公式重算失败({engine or 'COM'}):{e}\n"
|
||||
"请确认该目标文件未被 WPS/Excel 以受保护/只读视图打开(关闭后再试)。"
|
||||
) from e
|
||||
finally:
|
||||
if app is not None:
|
||||
# 仅当实例已无其他工作簿时才退出,避免关掉用户正在使用的 WPS/Excel
|
||||
try:
|
||||
if app.Workbooks.Count == 0:
|
||||
app.Quit()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
pythoncom.CoUninitialize()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,86 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0002",
|
||||
"name": "雇主险增减操作",
|
||||
"version": "1.0.10",
|
||||
"description": "雇主险名额调度全流程:花名册导出→筛选复制→WPS/Excel 后台取消筛选并重算公式→三阶段名额调度→更新在参名单与变更清单→生成增员/减员导入文件(可选自动导入 HR 系统)→钉钉群推送汇总与导入异常名单,替代人工取消筛选与 Ctrl+S 刷新公式、人工上传导入环节",
|
||||
"category": "人事",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0002"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"base_dir": {
|
||||
"type": "string",
|
||||
"title": "雇主险根目录",
|
||||
"default": "D:\\资料\\人资\\雇主险",
|
||||
"description": "四类各占一个子文件夹(三十七度/水庄餐饮/湖畔酒店/秒创传媒),增/减员导入模板放在根目录"
|
||||
},
|
||||
"ref_date": {
|
||||
"type": "string",
|
||||
"title": "业务日期",
|
||||
"default": "",
|
||||
"description": "留空=今天;影响变更清单/在参名单/导入文件中的日期与备份文件名"
|
||||
},
|
||||
"categories": {
|
||||
"type": "array",
|
||||
"title": "处理类别(可多选)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["三十七度", "水庄餐饮", "湖畔酒店", "秒创传媒"]
|
||||
},
|
||||
"default": ["三十七度", "水庄餐饮", "湖畔酒店", "秒创传媒"],
|
||||
"description": "留空=全部类别"
|
||||
},
|
||||
"roster_path": {
|
||||
"type": "string",
|
||||
"title": "花名册路径",
|
||||
"default": "",
|
||||
"description": "留空=根目录/员工花名册.xlsx(源表缺失或超过 15 分钟 TTL 时自动从 HR 导出)"
|
||||
},
|
||||
"enable_validation": {
|
||||
"type": "boolean",
|
||||
"title": "启用数据校验",
|
||||
"default": true,
|
||||
"description": "校验工种类别与投保方案合法性,校验失败终止调度"
|
||||
},
|
||||
"wps_recalc": {
|
||||
"type": "boolean",
|
||||
"title": "WPS/Excel 后台重算公式",
|
||||
"default": true,
|
||||
"description": "筛选复制后/调度后自动打开目标文件取消全部筛选并全量重算公式保存,替代人工取消筛选与 Ctrl+S 刷新公式;需本机安装 WPS 专业版/企业版或 MS Excel"
|
||||
},
|
||||
"export_change_sheet": {
|
||||
"type": "boolean",
|
||||
"title": "导出变更清单独立工作簿",
|
||||
"default": true,
|
||||
"description": "调度后将各类别变更清单 sheet 复制为独立工作簿(公式转值,保留样式)"
|
||||
},
|
||||
"gen_import_files": {
|
||||
"type": "boolean",
|
||||
"title": "生成增员/减员导入文件",
|
||||
"default": true,
|
||||
"description": "调度后生成商业保险增员/减员导入.xlsx(HR 待增减人员页面上传素材)"
|
||||
},
|
||||
"import_to_hr": {
|
||||
"type": "boolean",
|
||||
"title": "自动导入HR系统",
|
||||
"default": true,
|
||||
"description": "调度完成后自动把增/减员导入文件导入 HR「待增减人员」(浏览器自动化,先减员后增员,仅导入本次调度成功的类别);需本机 Chrome/Edge 且执行中会弹出浏览器窗口;须同时开启「生成增员/减员导入文件」"
|
||||
},
|
||||
"dingtalk_notify": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉群通知",
|
||||
"default": true,
|
||||
"description": "执行完成后推送结果汇总与增/减员导入异常名单到钉钉群(推送失败不影响主流程)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 report 层:在参名单更新/变更清单/备份/增减员导入输出。"""
|
||||
@@ -0,0 +1,297 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 钉钉群机器人推送(自 workflows/share/dingtalk_robot.py 移植,插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 执行机运行环境无 .env 读取,故推送地址/加签密钥/页脚署名直接内联在下方
|
||||
「默认配置」区(单一真源),改推送目标时改常量即可;
|
||||
- 页脚署名默认 "37du 任务调度平台":
|
||||
注意:钉钉机器人若配置了"自定义关键词"安全校验,
|
||||
页脚署名需包含该关键词(如 小芒)才会被接受;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法(业务层统一走 report/notify.py,也可直接调用):
|
||||
main("需要推送的通知文本") 即可,标题/颜色/环境等均可选;
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK )
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = '' # 测试环境加签密钥(未配置则不加签)
|
||||
DEV_SERVER_NAME = '小芒 任务调度平台'
|
||||
|
||||
# 环境 → 机器人配置(main 的 env 参数选择;缺省/未知环境回退 prod)
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10 # HTTP 请求超时秒数
|
||||
DEFAULT_RETRY_TIMES = 3 # 失败重试次数(含首次)
|
||||
|
||||
# 通知状态 → 标题颜色
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff', # 蓝色
|
||||
'success': '#00b300', # 绿色
|
||||
'warning': '#ff9900', # 橙色
|
||||
'error': '#ff0000', # 红色
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
print(f"[WARN] 推送失败(第 {attempt + 1}/{DEFAULT_RETRY_TIMES} 次):{e}")
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(Markdown,引用块/加粗/超链接/列表等语法会被钉钉渲染)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
server_name: 页脚署名
|
||||
"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
print(f"[INFO] 钉钉机器人推送通知 [{status}]: {title}")
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。
|
||||
|
||||
当钉钉消息内容超过 max_chars 字符时,自动按行拆成多批发送,
|
||||
每批带「第 N/M 批」标题前缀,便于接收方识别。
|
||||
|
||||
Args:
|
||||
title: 消息标题
|
||||
content: 消息正文(长文本)
|
||||
status: info|success|warning|error,决定标题颜色
|
||||
server_name: 页脚署名
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000)
|
||||
"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1 # +1 for newline
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
print(f"[INFO] 分批推送 {i}/{total}: {batch_title}")
|
||||
self.send(batch_title, batch_content, status=status,
|
||||
server_name=server_name)
|
||||
|
||||
|
||||
# ==================== 块格式工具:调用方把每条记录格式化为 block 字符串列表,
|
||||
# 这里统一负责分批、加头尾、生成最终待推送的消息文本列表 ====================
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 字符串列表按 batch_size 条一批,生成带批次标题的消息文本列表。
|
||||
|
||||
Args:
|
||||
blocks: 每条记录格式化后的 block 字符串列表(调用方负责格式化业务字段)
|
||||
title_prefix: 批次标题前缀,如 "【请假审批】通过"
|
||||
batch_size: 每批最大条数(默认 10)
|
||||
|
||||
Returns:
|
||||
字符串列表,每项是一条完整的待推送 Markdown 文本,可直接传给 main(text=...)
|
||||
配合 batch=True 发送。
|
||||
"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
# 钉钉中引用块尾行后需空行(双换行)再进入新标题,否则会紧贴渲染
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 推送入口 ====================
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""
|
||||
钉钉群机器人推送入口(与影刀版「37du钉钉群机器人推送」指令同一套签名/分批/页脚逻辑)。
|
||||
只需把要推送的通知文本传进来即可,例如:
|
||||
|
||||
main("订单同步失败,错误原因:接口超时")
|
||||
|
||||
支持逐条推送多条:text 传「文本列表」时按顺序逐条发送,列表项可为纯文本,
|
||||
也可为字典 {text, title?, status?, batch?} 自定义该条标题、颜色与格式。
|
||||
消息正文一律按 Markdown 渲染(引用块/加粗/超链接/列表等语法直接生效)。
|
||||
|
||||
块格式分组(推荐,调用方不关心分批):
|
||||
text 传字典列表,每项形如 {title, blocks, status?, batch_size?},
|
||||
blocks 为每条记录格式化好的 block 字符串列表。模块自动按 batch_size
|
||||
(默认 10)分批、每批带「第N/M批」标题并逐条推送。示例:
|
||||
main([
|
||||
{"title": "【增员导入】异常名单(2 条)",
|
||||
"blocks": ["**🔹 三十七度‑张三**\n> 工号:...", "..."],
|
||||
"status": "error"},
|
||||
])
|
||||
|
||||
可选参数:
|
||||
title: 消息标题(默认 消息通知)
|
||||
status: info|success|warning|error,决定标题颜色(默认 info)
|
||||
webhook: 机器人 webhook(缺省按 env 选择;显式传入则优先)
|
||||
secret: 加签密钥(缺省按 env 选择;显式传入则优先)
|
||||
server_name: 页脚署名(缺省按 env 选择;显式传入则优先)
|
||||
env: 环境 prod|dev,决定缺省 webhook/secret/server_name(默认 prod)
|
||||
batch: 是否启用分批发送(默认 False)。
|
||||
True: 当内容超长时自动按行拆成多批发送,每批标题带「第N/M批」;
|
||||
False: 单条发送(内容超长可能被钉钉截断或报错)。
|
||||
max_chars: 单批最大字符数(默认 15000,钉钉 Markdown 上限约 20000),
|
||||
仅在 batch=True 时生效。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = webhook or cfg['webhook']
|
||||
secret = secret or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置,请先在 dingtalk_robot.py 中填写'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
# 块格式分组:调用方只传格式化好的 block 列表 + 标题,
|
||||
# 分批、加批次标题、逐条推送全部由本模块负责(调用方不关心批次)
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st,
|
||||
server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -0,0 +1,120 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 钉钉群通知(业务消息构建 + 推送,口径与影刀版 add_sub_import 一致)。
|
||||
|
||||
推送内容:
|
||||
1. 汇总一条:调度/筛选结果统计 + HR 导入结果(或人工导入提示)+ 注意事项;
|
||||
2. 增员/减员导入异常名单各一条(接口返回的业务异常明细 + 流程失败单元),
|
||||
名单过长由 dingtalk_robot 按批自动分批(每批 10 条)。
|
||||
消息状态色:全部正常 success(绿);有异常/待确认/注意事项 warning(橙);调度全军覆没 error(红)。
|
||||
推送失败只记 WARN 日志,不影响插件主流程。
|
||||
"""
|
||||
from ..config import DINGTALK_ENV, log
|
||||
from . import dingtalk_robot
|
||||
|
||||
TITLE_SUMMARY = "雇主险增减操作完成"
|
||||
|
||||
|
||||
def _import_issues(import_results):
|
||||
"""从 HR 导入结果中提取异常/流程失败明细,按菜单(增员导入/减员导入)分组。
|
||||
|
||||
Returns:
|
||||
dict: {menu: [{"category", "staff_code", "staff_name",
|
||||
"insurance_name", "message"}, ...]}
|
||||
"""
|
||||
grouped = {}
|
||||
for r in import_results or []:
|
||||
menu = r.get("menu") or "导入"
|
||||
if r.get("error"):
|
||||
# 流程失败(登录/元素/文件缺失等):无业务结果,合并为一条异常上报
|
||||
grouped.setdefault(menu, []).append({
|
||||
"category": r.get("category", ""),
|
||||
"staff_code": "", "staff_name": "", "insurance_name": "",
|
||||
"message": f"流程失败({r.get('error_type', 'Exception')}):{r['error']}",
|
||||
})
|
||||
continue
|
||||
for exc in r.get("exceptions") or []:
|
||||
grouped.setdefault(menu, []).append({
|
||||
"category": r.get("category", ""),
|
||||
"staff_code": exc.get("staff_code", ""),
|
||||
"staff_name": exc.get("staff_name", ""),
|
||||
"insurance_name": exc.get("insurance_name", ""),
|
||||
"message": exc.get("message", ""),
|
||||
})
|
||||
return grouped
|
||||
|
||||
|
||||
def _build_messages(total, filtered, scheduled, import_on, import_lines,
|
||||
import_results, notes):
|
||||
"""构建待推送消息列表(汇总 + 异常名单),块格式交由 dingtalk_robot 分批发送。"""
|
||||
issues = _import_issues(import_results)
|
||||
issue_total = sum(len(v) for v in issues.values())
|
||||
|
||||
# ---- 1. 汇总消息 ----
|
||||
summary_lines = [
|
||||
"**处理类别 {} 个:筛选复制成功 {} 个、调度成功 {} 个**".format(
|
||||
total, filtered, scheduled),
|
||||
]
|
||||
if import_on:
|
||||
summary_lines.extend(import_lines or ["HR 导入未执行(登录态缺失或整体失败,详见注意事项与日志)"])
|
||||
else:
|
||||
summary_lines.append("HR 自动导入未开启:请取各类别文件夹内导入文件,先【减员】后【增员】人工导入")
|
||||
blocks = ["\n\n".join(summary_lines)]
|
||||
if notes:
|
||||
blocks.append("**⚠️ 注意事项({})**\n\n{}".format(
|
||||
len(notes), "\n\n".join("> - {}".format(n) for n in notes)))
|
||||
if scheduled == 0:
|
||||
status = "error"
|
||||
elif notes or issue_total:
|
||||
status = "warning"
|
||||
else:
|
||||
status = "success"
|
||||
messages = [{"title": TITLE_SUMMARY, "blocks": blocks, "status": status}]
|
||||
|
||||
# ---- 2. 增员/减员导入异常名单(各一条独立消息) ----
|
||||
for menu, excs in issues.items():
|
||||
if not excs:
|
||||
continue
|
||||
exc_blocks = []
|
||||
for exc in excs:
|
||||
exc_blocks.append(
|
||||
"**🔹 {} / {}**\n\n"
|
||||
"> 工号:{}\n\n"
|
||||
"> 姓名:{}\n\n"
|
||||
"> 方案:{}\n\n"
|
||||
"> 异常:{}".format(
|
||||
exc.get("category", "") or "-",
|
||||
exc.get("staff_name", "") or "-",
|
||||
exc.get("staff_code", "") or "-",
|
||||
exc.get("staff_name", "") or "-",
|
||||
exc.get("insurance_name", "") or "-",
|
||||
exc.get("message", ""),
|
||||
))
|
||||
messages.append({
|
||||
"title": "【{}】异常名单({} 条)".format(menu, len(excs)),
|
||||
"blocks": exc_blocks,
|
||||
"status": "error",
|
||||
})
|
||||
return messages
|
||||
|
||||
|
||||
def push_run_result(total, filtered, scheduled, import_on, import_lines,
|
||||
import_results, notes):
|
||||
"""把本次运行结果推送到钉钉群(环境取 config.DINGTALK_ENV),失败不影响主流程。
|
||||
|
||||
Args:
|
||||
total/filtered/scheduled: 处理/筛选复制/调度成功的类别数
|
||||
import_on: 是否执行了 HR 自动导入
|
||||
import_lines: hr_import.summarize_results 的可读文本行(未执行时传 [])
|
||||
import_results: hr_import.import_all 的逐单元结果(未执行时传 [])
|
||||
notes: 本次运行的注意事项列表
|
||||
"""
|
||||
try:
|
||||
messages = _build_messages(total, filtered, scheduled, import_on,
|
||||
import_lines, import_results, notes)
|
||||
result = dingtalk_robot.main(messages, env=DINGTALK_ENV)
|
||||
if result.get("success"):
|
||||
log(f"钉钉群通知已推送:{result.get('message', '')}", "INFO")
|
||||
else:
|
||||
log(f"钉钉群通知推送失败:{result.get('message', '')}", "WARN")
|
||||
except Exception as e:
|
||||
log(f"钉钉群通知推送失败(不影响主流程):{e}", "WARN")
|
||||
@@ -0,0 +1,664 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 - 结果输出层(由影刀版 employer_insurance_schedule.py 阶段3/五点五 与
|
||||
export_change_sheet.py 合并移植)。
|
||||
|
||||
包含:
|
||||
- output_results:更新「手动维护-在参名单」(第17行起B~N列)+ 精细更新「变更清单」
|
||||
(清空并重写 B/M/N/四级部门/P~S 列)+ 姓名修正记录 + 备份新在参名单;
|
||||
- export_add_sub_import:按「人+投保方案」记录级集合差生成 增员/减员 导入文件;
|
||||
- export_change_sheet_workbook:将类别目标文件「变更清单」sheet 复制为独立工作簿
|
||||
(值+样式,公式转缓存结果,避免 #REF!)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from copy import copy
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import Workbook, load_workbook
|
||||
|
||||
from ..config import (
|
||||
logger, DATA_START_ROW, BIZ_COL_EMPLOYEE_ID, BIZ_COL_CATEGORY, BIZ_COL_SCHEME,
|
||||
category_import_add_file, category_import_sub_file, category_target_file,
|
||||
category_change_sheet_workbook, category_change_sheet_name,
|
||||
add_import_template, sub_import_template, today_date,
|
||||
to_text, clean_text, to_date,
|
||||
)
|
||||
from ..logic.schedule import _find_special_slots, scheme_with_suffix
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、输出结果(在参名单 + 变更清单 + 备份 + 姓名修正)
|
||||
# ============================================================
|
||||
def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, change_sheet_prefix, in_param_sheet,
|
||||
name_corrections=None):
|
||||
"""输出四部分内容:
|
||||
1. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
2. 精细更新"变更清单"(仅清空并重写B/M/N/P~S列数据)
|
||||
3. 备份新在参名单
|
||||
4. 姓名修正记录写入变更清单(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
"""
|
||||
# ---------- 1. 构建需要清空的员工ID集合 ----------
|
||||
emp_ids_to_clear = set()
|
||||
for rec in final_records:
|
||||
emp_ids_to_clear.add(rec["证件号"])
|
||||
emp_ids_to_clear.update(reused_source_employees)
|
||||
|
||||
# 构建初始参保映射:在参名单中存在原投保方案(M列)的员工视为"原已参保"
|
||||
# (不依赖R列方案处理值,避免老员工R列为空/其它值时漏掉"删除原方案"记录)
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
orig_scheme = row.iloc[12]
|
||||
if pd.notna(orig_scheme) and str(orig_scheme).strip() != "":
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
|
||||
# 特殊情况识别(公共函数):离职/参保减少名额被老员工复用,且老员工释放的旧名额无人复用
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
special_source_ids = set(s["source_id"] for s in special_slots)
|
||||
special_src_scheme = {s["source_id"]: s["new_scheme"] for s in special_slots}
|
||||
if special_slots:
|
||||
logger.info("特殊情况:离职/参保减少名额被老员工复用,链条末端空闲名额 %d 例(源员工改为空闲方案保留)",
|
||||
len(special_slots))
|
||||
for s in special_slots:
|
||||
logger.info(" 源 %s -> 改为方案 %s", s["source_id"], s["new_scheme"])
|
||||
|
||||
# ---------- 2. 保留的行 ----------
|
||||
handle_col = column_names[17]
|
||||
emp_id_col = column_names[10]
|
||||
keep_mask = (
|
||||
((in_param_df[handle_col] == "无需") & (~in_param_df[emp_id_col].isin(emp_ids_to_clear))) |
|
||||
((in_param_df[handle_col].isin(["离职减少", "参保减少"])) & (~in_param_df[emp_id_col].isin(reused_source_employees))) |
|
||||
(in_param_df[emp_id_col].isin(special_source_ids)) # 特殊情况源员工保留(改M列为老员工旧方案)
|
||||
)
|
||||
kept_df = in_param_df[keep_mask].copy()
|
||||
kept_emp_ids = set(kept_df[emp_id_col].tolist())
|
||||
|
||||
# ---------- 3. 构建员工信息字典 ----------
|
||||
biz_dict = {}
|
||||
for idx, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
# ---------- 4. 构建新参保记录(B~N列) ----------
|
||||
new_records = []
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id not in biz_dict:
|
||||
logger.warning("员工 %s 在花名册中找不到,跳过", emp_id)
|
||||
continue
|
||||
row_biz = biz_dict[emp_id]
|
||||
new_records.append({
|
||||
"B": to_text(row_biz.get("工号")), # B列工号必须为文本
|
||||
"C": row_biz.get("年龄"),
|
||||
"D": row_biz.get("性别"),
|
||||
"E": row_biz.get("岗位"),
|
||||
"F": row_biz.get("职位序列"),
|
||||
"G": row_biz.get("参保类型"),
|
||||
"H": row_biz.get("上下班交通方式"),
|
||||
"I": row_biz.get("入职时间"),
|
||||
"J": row_biz.get("姓名"),
|
||||
"K": row_biz.get("证件号"),
|
||||
"L": row_biz.get("工种类别"),
|
||||
"M": row_biz.get("投保方案"),
|
||||
"N": today_date(),
|
||||
})
|
||||
|
||||
# ---------- 5. 打开工作簿 ----------
|
||||
wb = load_workbook(target_file)
|
||||
ws = wb[in_param_sheet]
|
||||
max_row = ws.max_row
|
||||
|
||||
# ---------- 6. 读取现有数据 ----------
|
||||
existing_rows = []
|
||||
for row_idx in range(DATA_START_ROW, max_row + 1):
|
||||
row_data = []
|
||||
for col in range(1, 27):
|
||||
row_data.append(ws.cell(row=row_idx, column=col).value)
|
||||
existing_rows.append({
|
||||
"row_idx": row_idx,
|
||||
"data": row_data,
|
||||
"emp_id": ws.cell(row=row_idx, column=11).value, # K列
|
||||
})
|
||||
|
||||
# ---------- 7. 构建新数据列表 ----------
|
||||
new_rows = []
|
||||
|
||||
# 姓名修正映射(证件号 -> 新姓名),保留行 J列姓名统一改为花名册姓名
|
||||
corr_by_id = {c["emp_id"]: c["new_name"] for c in (name_corrections or [])}
|
||||
|
||||
# 7.1 保留行
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if emp_id in kept_emp_ids:
|
||||
row_data = row_info["data"]
|
||||
# 特殊情况源员工:M列改为老员工释放的旧方案(X档),N列投保日期更新为今天
|
||||
if emp_id in special_src_scheme:
|
||||
row_data[12] = special_src_scheme[emp_id]
|
||||
row_data[13] = today_date() # N列 投保日期
|
||||
# 姓名核对修正:J列姓名改为花名册姓名
|
||||
if emp_id in corr_by_id:
|
||||
row_data[9] = corr_by_id[emp_id]
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": emp_id,
|
||||
"action": "keep",
|
||||
})
|
||||
|
||||
# 7.2 清空需要替换的行(仅清空B~N列,R/S列不动;特殊情况源员工已保留,此处不清空)
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if (emp_id in emp_ids_to_clear and emp_id not in special_source_ids) or emp_id is None:
|
||||
row_data = row_info["data"].copy()
|
||||
for i in range(1, 14):
|
||||
row_data[i] = None
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": None,
|
||||
"action": "clear",
|
||||
})
|
||||
|
||||
# 7.3 填充新记录到空行
|
||||
empty_slots = [r for r in new_rows if r["action"] == "clear" and r["emp_id"] is None]
|
||||
empty_slots.sort(key=lambda x: x["row_idx"])
|
||||
|
||||
def _fill(row_data, rec):
|
||||
row_data[1] = rec["B"]
|
||||
row_data[2] = rec["C"]
|
||||
row_data[3] = rec["D"]
|
||||
row_data[4] = rec["E"]
|
||||
row_data[5] = rec["F"]
|
||||
row_data[6] = rec["G"]
|
||||
row_data[7] = rec["H"]
|
||||
row_data[8] = rec["I"]
|
||||
row_data[9] = rec["J"]
|
||||
row_data[10] = rec["K"]
|
||||
row_data[11] = rec["L"]
|
||||
row_data[12] = rec["M"]
|
||||
row_data[13] = rec["N"]
|
||||
|
||||
for rec in new_records:
|
||||
if empty_slots:
|
||||
slot = empty_slots.pop(0)
|
||||
row_data = slot["data"]
|
||||
_fill(row_data, rec)
|
||||
slot["emp_id"] = rec["K"]
|
||||
slot["action"] = "filled"
|
||||
else:
|
||||
# 追加新行(复制上一行样式)
|
||||
row_data = [None] * 26
|
||||
if existing_rows:
|
||||
src_row_idx = existing_rows[-1]["row_idx"]
|
||||
for col in range(1, 27):
|
||||
src_cell = ws.cell(row=src_row_idx, column=col)
|
||||
dst_cell = ws.cell(row=max_row + 1, column=col)
|
||||
if src_cell.has_style:
|
||||
dst_cell.font = copy(src_cell.font)
|
||||
dst_cell.border = copy(src_cell.border)
|
||||
dst_cell.fill = copy(src_cell.fill)
|
||||
dst_cell.number_format = src_cell.number_format
|
||||
dst_cell.alignment = copy(src_cell.alignment)
|
||||
last_row_data = existing_rows[-1]["data"]
|
||||
for i in range(14, 26):
|
||||
row_data[i] = last_row_data[i]
|
||||
_fill(row_data, rec)
|
||||
new_rows.append({
|
||||
"row_idx": None,
|
||||
"data": row_data,
|
||||
"emp_id": rec["K"],
|
||||
"action": "append",
|
||||
})
|
||||
|
||||
# ---------- 8. 更新现有行(B~N列,列号=索引+1;B列工号强制文本) ----------
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is not None:
|
||||
row_idx = row_info["row_idx"]
|
||||
row_data = row_info["data"]
|
||||
for idx in range(1, 14):
|
||||
c = ws.cell(row=row_idx, column=idx + 1)
|
||||
if idx == 1:
|
||||
c.value = to_text(row_data[idx])
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = row_data[idx]
|
||||
|
||||
# ---------- 9. 追加新行 ----------
|
||||
current_row = max_row + 1
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is None:
|
||||
row_idx = current_row
|
||||
row_data = row_info["data"]
|
||||
for col_idx, value in enumerate(row_data, start=1):
|
||||
c = ws.cell(row=row_idx, column=col_idx)
|
||||
if col_idx == 2:
|
||||
c.value = to_text(value)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = value
|
||||
current_row += 1
|
||||
|
||||
# ---------- 9.5 紧凑化:消除中间空行(只搬移 B~O 数据列,公式列 R/S/T/U/V/W 不动) ----------
|
||||
data_values = []
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
has_data = any(
|
||||
ws.cell(row=row_idx, column=c).value not in (None, "")
|
||||
for c in range(2, 16)
|
||||
)
|
||||
if has_data:
|
||||
data_values.append([ws.cell(row=row_idx, column=c).value for c in range(2, 16)])
|
||||
target_row = DATA_START_ROW
|
||||
for vals in data_values:
|
||||
for col, v in enumerate(vals, start=2):
|
||||
cell = ws.cell(row=target_row, column=col)
|
||||
if col == 2: # B列 工号 强制文本
|
||||
cell.value = to_text(v)
|
||||
cell.number_format = "@"
|
||||
elif col == 14: # N列 投保日期 -> 日期类型 + yyyy-mm-dd
|
||||
cell.value = to_date(v)
|
||||
if cell.value is not None:
|
||||
cell.number_format = "yyyy-mm-dd"
|
||||
else:
|
||||
cell.value = v
|
||||
target_row += 1
|
||||
# 清空多出部分的 B~O 列(公式列不动)
|
||||
for row_idx in range(target_row, current_row):
|
||||
for col in range(2, 16):
|
||||
ws.cell(row=row_idx, column=col).value = None
|
||||
|
||||
# ---------- 10. 重新编号A列 ----------
|
||||
seq = 1
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
if ws.cell(row=row_idx, column=11).value is not None:
|
||||
ws.cell(row=row_idx, column=1).value = seq
|
||||
seq += 1
|
||||
else:
|
||||
ws.cell(row=row_idx, column=1).value = None
|
||||
|
||||
# ============================================================
|
||||
# ★★★ 11. 精细更新变更清单 ★★★
|
||||
# ============================================================
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
# 收集所有以类别变更清单前缀开头、且不是当前目标名的Sheet作为候选模板
|
||||
candidates = [
|
||||
name for name in wb.sheetnames
|
||||
if name.startswith(change_sheet_prefix) and name != change_sheet_name
|
||||
]
|
||||
|
||||
def _template_sort_key(name):
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", name)
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (-1, -1)
|
||||
|
||||
template_name = max(candidates, key=_template_sort_key) if candidates else None
|
||||
|
||||
if template_name is not None:
|
||||
# 复制最近一次的历史模板Sheet(保留公式与样式)
|
||||
source = wb[template_name]
|
||||
target = wb.copy_worksheet(source)
|
||||
target.title = change_sheet_name
|
||||
logger.info("已从模板 [%s] 复制变更清单", template_name)
|
||||
else:
|
||||
# 没有任何历史模板,创建新Sheet(兜底)
|
||||
ws_change = wb.create_sheet(change_sheet_name)
|
||||
headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄",
|
||||
"员工职业类别", "每人责任限额", "方案组别编号", "是否有工伤保险",
|
||||
"工作单位", "", "备注", "批改日期", "新增费用会馆",
|
||||
"姓名", "证件号", "工种类别", "投保方案"]
|
||||
for col_idx, h in enumerate(headers, start=1):
|
||||
ws_change.cell(row=1, column=col_idx).value = h
|
||||
ws_change.cell(row=2, column=1).value = "公式"
|
||||
ws_change = wb[change_sheet_name]
|
||||
else:
|
||||
ws_change = wb[change_sheet_name]
|
||||
|
||||
# ---------- 定位 O列(费用会馆/四级部门列)----------
|
||||
# 表头名不固定(如「新增费用会馆\n(自留后续划成本用)」),按"包含「费用会馆」"模糊匹配
|
||||
DEPT_COL_MARK = "费用会馆"
|
||||
dept_col = 15
|
||||
for _col in range(1, 21):
|
||||
if any(DEPT_COL_MARK in str(ws_change.cell(row=_row, column=_col).value or "")
|
||||
for _row in (1, 2)):
|
||||
dept_col = _col
|
||||
break
|
||||
logger.info("变更清单四级部门列定位:%s(第%d列)", dept_col, dept_col)
|
||||
|
||||
# 花名册表四级部门列名(按"包含「四级部门」"模糊匹配表头,兜底固定名)
|
||||
biz_dept_col = next((c for c in biz_df.columns if "四级部门" in str(c)), "四级部门")
|
||||
|
||||
# 清空B列、M列备注、N列、四级部门列、P~S列 从第3行开始
|
||||
max_row_change = ws_change.max_row
|
||||
if max_row_change >= 3:
|
||||
for row in range(3, max_row_change + 1):
|
||||
ws_change.cell(row=row, column=2).value = None # B列
|
||||
ws_change.cell(row=row, column=13).value = None # M列 备注
|
||||
ws_change.cell(row=row, column=14).value = None # N列
|
||||
ws_change.cell(row=row, column=dept_col).value = None # 四级部门列
|
||||
for col in range(16, 20): # P~S列
|
||||
ws_change.cell(row=row, column=col).value = None
|
||||
|
||||
# 收集变更记录
|
||||
records = []
|
||||
|
||||
# 1. 删除记录(特殊情况源员工一并输出"增加老员工旧方案",保证增减平衡)
|
||||
for emp_id in emp_ids_to_clear:
|
||||
if emp_id in final_emp_ids:
|
||||
continue
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
if not row_match.empty:
|
||||
row = row_match.iloc[0]
|
||||
name = row.iloc[9]
|
||||
category = row.iloc[11]
|
||||
scheme = row.iloc[12]
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
# 特殊情况:源员工名额被老员工复用且老员工旧名额无人复用 -> 源员工改为该旧方案
|
||||
if emp_id in special_src_scheme:
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": special_src_scheme[emp_id]})
|
||||
else:
|
||||
records.append({"op": "删除", "name": "未知", "emp_id": emp_id,
|
||||
"category": "未知", "scheme": "未知"})
|
||||
|
||||
# 2. 增加记录。档次替换仅当「自己的名额档次替换、不涉及其他人」时合并为一条「修改」
|
||||
# 收集「自己的旧名额被他人复用」的员工集合(来源员工ID)
|
||||
reused_by_others = set()
|
||||
for _rec in final_records:
|
||||
_sid = _rec.get("来源员工ID")
|
||||
if _sid is not None and not pd.isna(_sid) and str(_sid).strip():
|
||||
reused_by_others.add(_sid)
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id in biz_dict:
|
||||
row_biz = biz_dict[emp_id]
|
||||
name = row_biz.get("姓名")
|
||||
category = row_biz.get("工种类别")
|
||||
scheme = row_biz.get("投保方案")
|
||||
else:
|
||||
name = category = scheme = None
|
||||
if emp_id in initial_employee_map:
|
||||
# 原已参保(档次替换):仅"自己的名额档次替换、不涉及其他人"才合并为「修改」
|
||||
pure_self_replace = (
|
||||
rec.get("名额来源") == "全新新增" and
|
||||
emp_id not in reused_by_others
|
||||
)
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
old_scheme = None
|
||||
if not row_match.empty:
|
||||
old_scheme = row_match.iloc[0].iloc[12]
|
||||
if pure_self_replace:
|
||||
remark = None
|
||||
if old_scheme is not None and str(old_scheme).strip() != "" and \
|
||||
scheme is not None and str(scheme).strip() != "":
|
||||
remark = f"由{old_scheme}替换为{scheme}"
|
||||
records.append({"op": "修改", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme, "remark": remark})
|
||||
else:
|
||||
# 涉及其他人的档次替换:正常两条(删除旧方案 + 增加新方案)
|
||||
records.append({"op": "删除", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": old_scheme})
|
||||
records.append({"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme})
|
||||
else:
|
||||
# 新参保人员:仅「全新新增」名额(纯新增,当日名额净增加)在 O列 填四级部门
|
||||
new_rec = {"op": "增加", "name": name, "emp_id": emp_id,
|
||||
"category": category, "scheme": scheme}
|
||||
if rec.get("名额来源") == "全新新增":
|
||||
biz_row_dept = biz_dict.get(emp_id)
|
||||
dept = clean_text(biz_row_dept.get(biz_dept_col)) if biz_row_dept is not None else None
|
||||
if dept is None:
|
||||
# 四级部门为空:回退填所属单位,并记录日志供人工核对
|
||||
dept = clean_text(biz_row_dept.get("所属单位")) if biz_row_dept is not None else None
|
||||
logger.warning("员工 %s(%s) 花名册四级部门为空,O列回退填所属单位:%s",
|
||||
name, emp_id, dept)
|
||||
new_rec["dept"] = dept
|
||||
records.append(new_rec)
|
||||
|
||||
# 写入新记录
|
||||
current_row_change = 3
|
||||
for rec in records:
|
||||
op = rec.get("op")
|
||||
name = rec.get("name")
|
||||
emp_id = rec.get("emp_id")
|
||||
category = rec.get("category")
|
||||
scheme = rec.get("scheme")
|
||||
if name is None or emp_id is None or category is None or scheme is None:
|
||||
logger.warning("跳过变更记录:%s %s 信息不完整", op, emp_id)
|
||||
continue
|
||||
ws_change.cell(row=current_row_change, column=2).value = op # B列
|
||||
ws_change.cell(row=current_row_change, column=13).value = rec.get("remark") # M列 备注
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date() # N列
|
||||
# 四级部门列:仅纯新增名额(全新新增)的「增加」记录才填
|
||||
if op == "增加" and rec.get("dept") is not None:
|
||||
ws_change.cell(row=current_row_change, column=dept_col).value = rec.get("dept")
|
||||
ws_change.cell(row=current_row_change, column=16).value = name # P列
|
||||
ws_change.cell(row=current_row_change, column=17).value = emp_id # Q列
|
||||
ws_change.cell(row=current_row_change, column=18).value = category # R列
|
||||
ws_change.cell(row=current_row_change, column=19).value = scheme # S列
|
||||
current_row_change += 1
|
||||
|
||||
# 3. 姓名修正记录(批改标志=修改,备注写明「修正姓名,原xx修正为xx」)
|
||||
for corr in (name_corrections or []):
|
||||
ws_change.cell(row=current_row_change, column=2).value = "修改"
|
||||
ws_change.cell(row=current_row_change, column=13).value = \
|
||||
f"修正姓名,原{corr['old_name']}修正为{corr['new_name']}"
|
||||
ws_change.cell(row=current_row_change, column=14).value = today_date()
|
||||
ws_change.cell(row=current_row_change, column=16).value = corr["new_name"]
|
||||
ws_change.cell(row=current_row_change, column=17).value = corr["emp_id"]
|
||||
ws_change.cell(row=current_row_change, column=18).value = corr.get("category")
|
||||
ws_change.cell(row=current_row_change, column=19).value = corr.get("scheme")
|
||||
current_row_change += 1
|
||||
|
||||
# ---------- 12. 保存工作簿 ----------
|
||||
wb.save(target_file)
|
||||
|
||||
# ---------- 13. 备份新在参名单 ----------
|
||||
df_final = pd.DataFrame(final_records)
|
||||
df_final.to_excel(output_backup, index=False)
|
||||
|
||||
logger.info("手动维护-在参名单已更新(保留 %d 个原有员工,清空 %d 个旧员工行,新增 %d 条参保记录)",
|
||||
len(kept_emp_ids), len(emp_ids_to_clear), len(new_records))
|
||||
logger.info("变更清单已精细更新(共 %d 条变更记录,含 %d 条姓名修正)",
|
||||
len(records) + len(name_corrections or []), len(name_corrections or []))
|
||||
logger.info("备份新在参名单已保存:%s", output_backup)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、生成增员/减员导入文件(HR「待增减人员」页面上传素材)
|
||||
# ============================================================
|
||||
def _write_import_file(template_path, out_path, rows):
|
||||
"""加载模板(保留第1~3行标题/表头/示例说明),第4行起写数据,另存为 out_path。"""
|
||||
if not os.path.isfile(template_path):
|
||||
raise FileNotFoundError(f"导入模板不存在:{template_path},无法生成导入文件 {out_path}")
|
||||
wb = load_workbook(template_path)
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
for i, row_vals in enumerate(rows):
|
||||
excel_row = 4 + i
|
||||
for col_idx, val in enumerate(row_vals, start=1):
|
||||
c = ws.cell(row=excel_row, column=col_idx)
|
||||
if col_idx == 2: # 工号/身份证列强制文本
|
||||
c.value = to_text(val)
|
||||
c.number_format = "@"
|
||||
else:
|
||||
c.value = val
|
||||
wb.save(out_path)
|
||||
logger.info("已生成导入文件:%s(%d 条)", out_path, len(rows))
|
||||
|
||||
|
||||
def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_source_employees):
|
||||
"""生成各类别「商业保险增员导入.xlsx / 商业保险减员导入.xlsx」(HR 上传素材)。
|
||||
|
||||
集合差模型:按「人 + 投保方案」记录级做差:
|
||||
- 减员 = 原参保记录 − 新参保记录
|
||||
- 增员 = 新参保记录 − 原参保记录
|
||||
离职减少/参保减少名额未被使用 → 新旧记录都在 → 不减员,方便下次直接替换。
|
||||
特殊情况:离职/参保减少名额被老员工复用且老员工旧名额无人复用 -> 源员工保留在
|
||||
参名单并改为空闲方案,该源员工同样纳入增员(新增该方案),保证不漏人。
|
||||
|
||||
★执行顺序:请务必先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
|
||||
若先增员会因人员方案冲突直接报错。
|
||||
"""
|
||||
# ---------- 1. 原参保记录集合 ----------
|
||||
orig_records = {} # to_text(证件号) -> 方案
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
scheme = row.iloc[12]
|
||||
if pd.isna(scheme) or str(scheme).strip() == "":
|
||||
continue
|
||||
orig_records[to_text(emp_id)] = scheme
|
||||
|
||||
# ---------- 2. 新参保记录集合(保留的原记录 + 新增记录 + 特殊情况保留源员工) ----------
|
||||
cleared_ids = set(to_text(e) for e in reused_source_employees)
|
||||
cleared_ids.update(to_text(rec["证件号"]) for rec in final_records)
|
||||
new_records_map = {
|
||||
emp_id: scheme for emp_id, scheme in orig_records.items()
|
||||
if emp_id not in cleared_ids
|
||||
}
|
||||
for rec in final_records:
|
||||
new_records_map[to_text(rec["证件号"])] = rec["投保方案"]
|
||||
# 特殊情况源员工(离职/参保减少名额被复用后保留在参名单,方案改为空闲方案):
|
||||
# 纳入"新参保记录"参与集合差,保证减员/增员对称、不漏人
|
||||
special_slots = _find_special_slots(final_records, in_param_df)
|
||||
for _s in special_slots:
|
||||
new_records_map[to_text(_s["source_id"])] = _s["new_scheme"]
|
||||
|
||||
# ---------- 3. 记录级集合差:减员名单 ----------
|
||||
sub_ids = [
|
||||
emp_id for emp_id, orig_scheme in orig_records.items()
|
||||
if emp_id not in new_records_map or new_records_map[emp_id] != orig_scheme
|
||||
]
|
||||
|
||||
# ---------- 4. 员工信息查询(biz_df 优先,其次 in_param_df) ----------
|
||||
emp_info = {} # to_text(证件号) -> {"工号": ..., "姓名": ...}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.iloc[1]), "姓名": row.iloc[9]}
|
||||
for _, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
emp_info[to_text(emp_id)] = {"工号": to_text(row.get("工号")), "姓名": row.get("姓名")}
|
||||
|
||||
def _code(emp_id):
|
||||
"""工号/身份证列:优先工号,空则回退证件号。"""
|
||||
return clean_text(emp_info.get(emp_id, {}).get("工号")) or clean_text(emp_id)
|
||||
|
||||
def _name(emp_id):
|
||||
return clean_text(emp_info.get(emp_id, {}).get("姓名"))
|
||||
|
||||
# ---------- 5. 组装行数据 ----------
|
||||
sub_rows, skipped_sub = [], 0
|
||||
for i, emp_id in enumerate(sub_ids, start=1):
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_sub += 1
|
||||
logger.warning("减员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
sub_rows.append([i, _code(emp_id), name, today_date()])
|
||||
|
||||
add_rows, skipped_add, seq = [], 0, 0
|
||||
for rec in final_records:
|
||||
emp_id = to_text(rec["证件号"])
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, rec["投保方案"]), today_date(),
|
||||
rec.get("名额来源") or "新增"])
|
||||
# 特殊情况源员工(保留在参名单,方案改为空闲方案)也需增员(新增该方案),不漏人
|
||||
for _s in special_slots:
|
||||
emp_id = to_text(_s["source_id"])
|
||||
new_scheme = _s["new_scheme"]
|
||||
# 方案未变(极少见边界)则无需增员
|
||||
if emp_id in orig_records and orig_records[emp_id] == new_scheme:
|
||||
continue
|
||||
name = _name(emp_id)
|
||||
if not name:
|
||||
skipped_add += 1
|
||||
logger.warning("增员:特殊情况源员工 %s 缺少姓名,跳过", emp_id)
|
||||
continue
|
||||
seq += 1
|
||||
add_rows.append([seq, _code(emp_id), name,
|
||||
scheme_with_suffix(category, new_scheme), today_date(),
|
||||
"特殊情况保留名额"])
|
||||
|
||||
# ---------- 6. 写入模板(保留第1~3行,第4行起填数据) ----------
|
||||
_write_import_file(sub_import_template(), category_import_sub_file(category), sub_rows)
|
||||
_write_import_file(add_import_template(), category_import_add_file(category), add_rows)
|
||||
|
||||
logger.info("类别[%s] 增员 %d 条 / 减员 %d 条(跳过:增员 %d / 减员 %d)",
|
||||
category["name"], len(add_rows), len(sub_rows), skipped_add, skipped_sub)
|
||||
logger.info("执行顺序提醒:请先执行【减员】导入,再执行【增员】导入(涉及替换/修改的人员先增员会因方案冲突报错)")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、导出变更清单独立工作簿(值 + 样式,公式转缓存结果)
|
||||
# ============================================================
|
||||
def export_change_sheet_workbook(category):
|
||||
"""将类别目标文件中「变更清单」sheet 复制为独立工作簿(值 + 样式,无公式)。
|
||||
|
||||
以 data_only=True 加载目标文件:公式单元格直接取缓存计算结果(值),普通单元格
|
||||
取原值;样式 / 列宽 / 行高 / 合并单元格原样保留,不改动原目标文件。
|
||||
|
||||
Returns:
|
||||
bool: 是否成功生成(文件缺失 / sheet 不存在时返回 False)。
|
||||
"""
|
||||
category_name = category["name"]
|
||||
target_file = category_target_file(category)
|
||||
change_sheet_name = category_change_sheet_name(category)
|
||||
out_path = category_change_sheet_workbook(category)
|
||||
|
||||
if not os.path.isfile(target_file):
|
||||
logger.warning("类别[%s] 目标文件不存在,跳过:%s", category_name, target_file)
|
||||
return False
|
||||
|
||||
wb = load_workbook(target_file, data_only=True)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
logger.warning("类别[%s] 工作簿中不存在变更清单 sheet [%s],跳过",
|
||||
category_name, change_sheet_name)
|
||||
return False
|
||||
src = wb[change_sheet_name]
|
||||
|
||||
out_wb = Workbook()
|
||||
out_ws = out_wb.active
|
||||
out_ws.title = change_sheet_name
|
||||
|
||||
# 复制单元格(值 + 样式)
|
||||
for row in src.iter_rows():
|
||||
for cell in row:
|
||||
dst = out_ws.cell(row=cell.row, column=cell.column, value=cell.value)
|
||||
if cell.has_style:
|
||||
dst.font = copy(cell.font)
|
||||
dst.border = copy(cell.border)
|
||||
dst.fill = copy(cell.fill)
|
||||
dst.number_format = cell.number_format
|
||||
dst.alignment = copy(cell.alignment)
|
||||
|
||||
# 复制列宽 / 行高
|
||||
for col_letter, dim in src.column_dimensions.items():
|
||||
if dim.width:
|
||||
out_ws.column_dimensions[col_letter].width = dim.width
|
||||
for row_idx, dim in src.row_dimensions.items():
|
||||
if dim.height:
|
||||
out_ws.row_dimensions[row_idx].height = dim.height
|
||||
# 复制合并单元格
|
||||
for mc in src.merged_cells.ranges:
|
||||
out_ws.merge_cells(str(mc))
|
||||
|
||||
out_wb.save(out_path)
|
||||
logger.info("类别[%s] 已导出变更清单独立工作簿:%s(sheet:%s,公式已转为值)",
|
||||
category_name, out_path, change_sheet_name)
|
||||
return True
|
||||
@@ -0,0 +1,6 @@
|
||||
requests
|
||||
pandas
|
||||
openpyxl
|
||||
websocket-client
|
||||
pywin32
|
||||
DrissionPage
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>雇主险增减操作</title>
|
||||
<script type="module" crossorigin src="/pui/xq0002/assets/index-CAJDpQI-.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0002/assets/index-klWce3Ko.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,195 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件入口。
|
||||
|
||||
流程编排(由影刀版 leave_approval.py 移植,登录态改由底座注入):
|
||||
1) 会话准备:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
|
||||
2) 拉取「请假」待办(纯接口,无待办不启动浏览器);
|
||||
3) 逐单取表单并校验:Group1 仅比对排班上班天数与填报天数;Group2 另需附件
|
||||
(病假/结婚证/产检 OCR,特殊事假/产假/丧假仅需附件);小时特假校验请假时段
|
||||
是否落在排班班段内(含前一天跨天夜班)+ 已上传附件;
|
||||
4) 校验通过且开启自动审批时,浏览器注入 HR cookies 后点击同意并确认;
|
||||
5) 生成审批报告落盘 + 钉钉群机器人推送(汇总 + 需人工处理明细)。
|
||||
"""
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data import hr_api
|
||||
from .data import hr_browser
|
||||
from .logic import leave_rules
|
||||
from .report import leave_report
|
||||
from .report import dingtalk_robot
|
||||
|
||||
|
||||
class LeaveApprovalPlugin(ScenePlugin):
|
||||
"""EHR系统请假流程审核(需求 XQ0003)。"""
|
||||
|
||||
id = "xq0003"
|
||||
name = "EHR系统请假流程审核"
|
||||
version = "1.0.0"
|
||||
description = ("自动审核 EHR 请假待办:按假期类型校验排班上班天数与填报天数是否一致,"
|
||||
"病假/结婚证/产检按附件 OCR 关键词核验,小时特假校验请假时段是否落在排班班段内;"
|
||||
"校验通过自动提交审批,并生成审批报告与钉钉群推送。")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0003"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "审批报告与服务端附件(附件/ 子目录)统一存放目录",
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean", "title": "自动提交审批", "default": True,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交",
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean", "title": "钉钉群推送", "default": True,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人",
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string", "title": "钉钉 Webhook", "default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string", "title": "钉钉加签密钥", "default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签",
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean", "title": "调试日志", "default": False,
|
||||
"description": "开启后输出 OCR 识别明细等调试信息",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / HR 会话 / userId / 输出目录 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
config.set_save_dir(save_dir)
|
||||
config.set_debug(bool(fields.get("debug_mode")))
|
||||
approve_enabled = bool(fields.get("approve_enabled", True))
|
||||
push_enabled = bool(fields.get("push_enabled", True))
|
||||
webhook = (fields.get("dingtalk_webhook") or "").strip()
|
||||
secret = (fields.get("dingtalk_secret") or "").strip()
|
||||
|
||||
subject = config.DEFAULT_SUBJECT
|
||||
session = config.require_session()
|
||||
ctx.log(f"===== 请假审批启动:输出目录 {save_dir},自动审批={'开' if approve_enabled else '关'} =====",
|
||||
"INFO")
|
||||
|
||||
# ---- 步骤1:会话校验 ----
|
||||
ctx.progress(5)
|
||||
user_id = hr_api.validate_session(session)
|
||||
config.set_user_id(user_id)
|
||||
|
||||
# ---- 步骤2:拉取请假待办 ----
|
||||
ctx.progress(10)
|
||||
docs = hr_api.fetch_documents(session, subject)
|
||||
ctx.log(f"共获取{subject}待办 {len(docs)} 条", "INFO")
|
||||
ctx.progress(15)
|
||||
|
||||
browser = None
|
||||
results = []
|
||||
try:
|
||||
if docs:
|
||||
for idx, doc in enumerate(docs, 1):
|
||||
try:
|
||||
detail = hr_api.fetch_doc_detail(doc)
|
||||
result = leave_rules.validate_doc(detail, session)
|
||||
|
||||
if approve_enabled and result.get("decision") == "通过":
|
||||
if browser is None:
|
||||
browser = hr_browser.build_browser(session)
|
||||
browser.get(detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = hr_browser.submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = submit["message"]
|
||||
# 提交失败兜底:单据状态未变,不能仍标为通过,归为「异常」交人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
ctx.log(f"审批提交: {submit['action']} {submit['message']}", "INFO")
|
||||
elif result.get("decision") != "通过":
|
||||
ctx.log(f"决策为{result.get('decision')},不自动提交审批(待人工处理)", "INFO")
|
||||
|
||||
results.append(result)
|
||||
ctx.log(f"已校验 {idx}/{len(docs)}: {result.get('creator')} - "
|
||||
f"{result.get('title')} -> {result.get('decision')}", "INFO")
|
||||
except Exception as e:
|
||||
ctx.log(f"处理单据失败: {doc.get('title')}, 错误: {e}", "ERROR")
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
ctx.progress(15 + int(75 * idx / len(docs)))
|
||||
else:
|
||||
ctx.log(f"{subject}无待审批单据,跳过浏览器操作", "INFO")
|
||||
|
||||
# ---- 步骤3:报告落盘 ----
|
||||
ctx.progress(92)
|
||||
report_text = leave_report.generate_report(results)
|
||||
report_path = leave_report.save_report(report_text, save_dir)
|
||||
ctx.progress(95)
|
||||
|
||||
# ---- 步骤4:钉钉推送 ----
|
||||
push_message = ""
|
||||
if push_enabled:
|
||||
push_items = leave_report.build_push_summary(results, subject)
|
||||
if not push_items:
|
||||
push_items = [{"text": f"暂无待审批的{subject}单据"}]
|
||||
push_res = dingtalk_robot.main(
|
||||
push_items, title=f"【{subject}审批】汇总",
|
||||
webhook=webhook, secret=secret)
|
||||
push_message = push_res.get("message", "")
|
||||
ctx.log(f"钉钉推送: {push_message}", "INFO")
|
||||
ctx.progress(100)
|
||||
|
||||
counts = {
|
||||
"total": len(results),
|
||||
"passed": sum(1 for r in results if r.get("decision") == "通过"),
|
||||
"rejected": sum(1 for r in results if r.get("decision") == "校验不通过未处理"),
|
||||
"review": sum(1 for r in results if r.get("decision") == "人工复核"),
|
||||
"abnormal": sum(1 for r in results if r.get("decision") == "异常"),
|
||||
"failed": sum(1 for r in results if r.get("decision") == "失败"),
|
||||
}
|
||||
if not docs:
|
||||
summary = f"暂无待审批的{subject}单据;报告:{report_path}"
|
||||
else:
|
||||
summary = (f"{subject}审批完成,共 {counts['total']} 单:通过 {counts['passed']},"
|
||||
f"校验不通过未处理 {counts['rejected']},人工复核 {counts['review']}")
|
||||
if counts["abnormal"]:
|
||||
summary += f",审批异常 {counts['abnormal']}"
|
||||
if counts["failed"]:
|
||||
summary += f",处理失败 {counts['failed']}"
|
||||
summary += f";报告:{report_path}"
|
||||
if push_message:
|
||||
summary += f";推送:{push_message}"
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": counts,
|
||||
"path": report_path,
|
||||
"results": results,
|
||||
"save_dir": save_dir,
|
||||
}
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
PLUGINS.append(LeaveApprovalPlugin())
|
||||
@@ -0,0 +1,203 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.logger 输出日志、config.require_session()/require_user_id() 取登录态。
|
||||
登录态由底座注入(hr 平台),插件不自行读 cookies 文件、不做自动补登。
|
||||
"""
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
# ==================== 输出配置 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\请假流程审批"
|
||||
ATTACHMENT_DIR_NAME = "附件"
|
||||
|
||||
# ==================== HR 系统接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
SHIFT_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_count_SelectBanci/getExecutePageResult.mc"
|
||||
ATTACHMENT_URL = f"{HR_BASE_URL}/RedseaPlatform/corePlatformOutUser/fjkFileDownload.mob"
|
||||
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
PAGE_MAX_SIZE = 500
|
||||
DEFAULT_TREE_CODE = "cq37du"
|
||||
DEFAULT_SUBJECT = "请假"
|
||||
|
||||
# 审批按钮:决策 -> (选择器, 按钮文案);仅「通过」会自动提交
|
||||
APPROVE_BUTTONS = {"通过": ("#chooseSubmit", "同意")}
|
||||
|
||||
# ==================== 假期类型编码 → 名称 ====================
|
||||
VACATION_TYPE_MAP = {
|
||||
"04": "病假",
|
||||
"05": "产假",
|
||||
"09": "事假",
|
||||
"11": "调休假",
|
||||
"15": "普通事假",
|
||||
"17": "特殊事假",
|
||||
"18": "小时特假",
|
||||
"19": "普通事假(晚/高峰)",
|
||||
"20": "普通事假(早/中)",
|
||||
"22": "半天休(仅限人资专用)",
|
||||
"23": "特别福利假",
|
||||
"24": "年度福利假",
|
||||
}
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
_save_dir = DEFAULT_SAVE_DIR
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress,业务层按阶段上报进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在壳子(工作台)完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
if not _user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
|
||||
return _user_id
|
||||
|
||||
|
||||
def set_save_dir(path):
|
||||
global _save_dir
|
||||
_save_dir = (path or "").strip() or DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
def get_save_dir():
|
||||
return _save_dir
|
||||
|
||||
|
||||
def get_attachment_dir():
|
||||
"""服务端附件本地保存目录:<save_dir>\\附件。"""
|
||||
return os.path.join(_save_dir, ATTACHMENT_DIR_NAME)
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局最大 3 次) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试次数耗尽。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
"""指数退避重试:首次失败后 1s、2s、4s(含抖动);连续失败记录错误并抛出。"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 统一重试入口
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
break
|
||||
delay = 1.0 * (2 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败,%.1fs 后重试: %s",
|
||||
func.__name__, attempt, delay, e)
|
||||
time.sleep(delay)
|
||||
logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, last_exc)
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} 连续 {max_attempts} 次失败: {last_exc}") from last_exc
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 数据层。"""
|
||||
@@ -0,0 +1,356 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - HR 接口层(由影刀版 leave_approval.py 接口部分移植)。
|
||||
|
||||
链路:
|
||||
1) WeProcess getProcessAndData 查请假流程待办(含 taskId/businessKey/formId)
|
||||
2) WfActivity getWfActivityByTaskId 取 formId(待办行缺失时兜底)
|
||||
3) WorkformEngine getBusinessDate 取请假表单数据
|
||||
4) rf_p_kq_count_SelectBanci 按工号+日期范围取排班(动态列 YYYY-MM-DD_bc_name/bc_time)
|
||||
5) fjkFileDownload.mob 下载表单附件
|
||||
|
||||
插件化改造点(与影刀版差异):
|
||||
1. 纯 requests 调用(底座注入的 requests.Session),不再用 DrissionPage SessionPage;
|
||||
2. 登录态失效统一抛 HRSessionExpiredError,由上层提示重新登录(不自动补登);
|
||||
3. 日志统一转发到 ctx.log(config.logger)。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
from urllib.parse import unquote
|
||||
|
||||
from ..config import (
|
||||
logger, retry, require_session,
|
||||
HR_BASE_URL, WE_PROCESS_QUERY_URL, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL,
|
||||
GET_CUR_USER_INFO_URL, SHIFT_URL, ATTACHMENT_URL,
|
||||
DEFAULT_PAGE_SIZE, PAGE_MAX_SIZE, DEFAULT_TREE_CODE,
|
||||
)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;非 JSON 视为登录态失效。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""校验注入的 HR 登录态有效,返回 current userId。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from None
|
||||
user_id = str(info.get("userId") or "") if isinstance(info, dict) else ""
|
||||
if not user_id:
|
||||
raise RuntimeError("HR 登录态无效(getCurUserInfo 未返回 userId),请重新登录 HR")
|
||||
return user_id
|
||||
|
||||
|
||||
# ==================== 请假流程待办 ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
|
||||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
data = hr_request_json(session, "POST", WE_PROCESS_QUERY_URL, params, "WeProcess")
|
||||
if str(data.get("state")) != "1":
|
||||
if str(data.get("state")) == "Nosession" or "会话过期" in str(data.get("meg", "")):
|
||||
raise HRSessionExpiredError(f"WeProcess 返回会话过期: {data.get('meg')}")
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: state={data.get('state')} meg={data.get('meg')}")
|
||||
return data
|
||||
|
||||
|
||||
def parse_we_process_list(data):
|
||||
"""解析待办行为单据字典;detail_url 用 reqType=WAIT(待办审批视图,页面才有审批按钮)。"""
|
||||
docs = []
|
||||
for row in data.get("jsonList") or data.get("datas") or []:
|
||||
title = str(row.get("title") or "").strip()
|
||||
task_id = str(row.get("taskId") or "")
|
||||
business_key = str(row.get("businessKey") or "")
|
||||
process_id = str(row.get("processId") or "")
|
||||
form_id = str(row.get("formId") or "")
|
||||
if not task_id or not business_key:
|
||||
logger.warning("跳过缺 taskId/businessKey 的待办行: %s", title)
|
||||
continue
|
||||
detail_url = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={form_id}&businessKey={business_key}&processId={process_id}"
|
||||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="
|
||||
)
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": str(row.get("createUserName") or row.get("createUserNameCn") or "").strip(),
|
||||
"time": str(row.get("createTime") or "").strip(),
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"processId": process_id,
|
||||
"formId": form_id,
|
||||
"detail_url": detail_url,
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""分页拉取全部待办,按 taskId 去重。"""
|
||||
all_docs = []
|
||||
page_no = 1
|
||||
while page_no <= 20: # 防御性分页上限
|
||||
data = fetch_we_process_page(session, subject, page_no=page_no, page_size=page_size)
|
||||
docs = parse_we_process_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", page_no, len(docs), len(all_docs))
|
||||
if len(docs) < page_size:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique_docs.append(doc)
|
||||
|
||||
if len(unique_docs) != len(all_docs):
|
||||
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
|
||||
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
|
||||
return unique_docs
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
# ==================== 表单详情 ====================
|
||||
def get_wf_activity_by_task_id(session, task_id):
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", url, {"taskId": task_id}, "WfActivity")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WfActivity 接口请求失败: {e}") from e
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data):
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id")
|
||||
if form_id:
|
||||
break
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(session, business_key, form_id):
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
logger.info("获取请假表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", url,
|
||||
{"businessKey": business_key, "formId": form_id}, "WorkformEngine")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WorkformEngine 接口请求失败: {e}") from e
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_doc_detail(doc):
|
||||
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
session = require_session()
|
||||
task_id = doc.get("taskId")
|
||||
business_key = doc.get("businessKey")
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"待办行缺 taskId/businessKey: {doc.get('title')}")
|
||||
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
# ==================== 排班查询 ====================
|
||||
def fetch_shift_page(session, user_id, base_code, begin_date, end_date,
|
||||
treecode=DEFAULT_TREE_CODE, page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页排班数据(按工号 base_code 查询)。"""
|
||||
params = {
|
||||
"treecode": treecode,
|
||||
"user_id": user_id,
|
||||
"sqlId": "kq_count_SelectBanci",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"staff_ids": "",
|
||||
"person_status": "1,4",
|
||||
"post_no": "",
|
||||
"post_type": "1",
|
||||
"post_level": "",
|
||||
"identity": "",
|
||||
"showType": "1",
|
||||
"dateType": "1",
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"bc_date": begin_date,
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", SHIFT_URL, params, "排班")
|
||||
|
||||
|
||||
def fetch_all_shift(session, user_id, base_code, begin_date, end_date,
|
||||
treecode=DEFAULT_TREE_CODE):
|
||||
"""分页抓取指定工号、日期范围内的全部排班记录。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
try:
|
||||
data = fetch_shift_page(
|
||||
session, user_id, base_code, begin_date, end_date,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("排班接口 HR 登录态失效,请重新登录 HR 后再执行") from None
|
||||
if data.get("state") != "1":
|
||||
logger.error("排班第 %d 页请求失败:%s", page_no, data.get("meg"))
|
||||
break
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("排班无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("排班已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def get_day_shift(shift_rows, date_str):
|
||||
"""从排班记录中提取指定日期的班次信息(动态列 YYYY-MM-DD_bc_name/bc_time)。"""
|
||||
info = {"bc_name": "", "bc_time": ""}
|
||||
for rec in shift_rows:
|
||||
name = rec.get(f"{date_str}_bc_name")
|
||||
time_ = rec.get(f"{date_str}_bc_time")
|
||||
if name or time_:
|
||||
info = {
|
||||
"bc_name": str(name if name is not None else ""),
|
||||
"bc_time": str(time_ if time_ is not None else ""),
|
||||
}
|
||||
break
|
||||
return info
|
||||
|
||||
|
||||
# ==================== 附件下载 ====================
|
||||
def download_attachment(session, file_id, save_dir):
|
||||
"""按附件 fileId 下载(兼容逗号分隔多附件),返回逗号拼接路径串;全失败返回 None。"""
|
||||
if not file_id:
|
||||
logger.warning("附件 fileId 为空,跳过下载")
|
||||
return None
|
||||
ids = [x.strip() for x in str(file_id).split(",") if x.strip()]
|
||||
saved = []
|
||||
for fid in ids:
|
||||
path = _download_one(session, fid, save_dir)
|
||||
if path:
|
||||
saved.append(path)
|
||||
if not saved:
|
||||
return None
|
||||
return ",".join(saved)
|
||||
|
||||
|
||||
def _download_one(session, file_id, save_dir):
|
||||
"""下载单个附件 fileId,返回本地保存路径;失败返回 None。"""
|
||||
if not file_id:
|
||||
return None
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
download_url = f"{ATTACHMENT_URL}?fileId={file_id}"
|
||||
try:
|
||||
resp = session.get(download_url, timeout=60)
|
||||
except Exception as e:
|
||||
logger.warning("附件请求失败(fileId=%s): %s", file_id, e)
|
||||
return None
|
||||
if resp is None or resp.status_code != 200:
|
||||
logger.warning("附件下载失败: HTTP %s (fileId=%s)",
|
||||
getattr(resp, "status_code", "?"), file_id)
|
||||
return None
|
||||
|
||||
# 从 Content-Disposition 解析真实文件名(可能带 UTF-8'' 编码)
|
||||
filename = None
|
||||
cd = resp.headers.get("Content-Disposition", "")
|
||||
if "filename=" in cd:
|
||||
raw = cd.split("filename=")[-1].strip().strip('"')
|
||||
if raw.startswith("UTF-8''"):
|
||||
raw = unquote(raw.split("UTF-8''", 1)[1])
|
||||
else:
|
||||
try:
|
||||
raw = raw.encode('latin-1').decode('utf-8')
|
||||
except (UnicodeDecodeError, UnicodeEncodeError):
|
||||
pass
|
||||
if raw:
|
||||
filename = raw
|
||||
|
||||
# 解析不到文件名时,用 fileId 兜底,并按 Content-Type 补扩展名
|
||||
if not filename:
|
||||
filename = file_id
|
||||
ct = (resp.headers.get("Content-Type") or "").split(";")[0].strip().lower()
|
||||
ext_map = {
|
||||
"image/png": ".png",
|
||||
"image/jpeg": ".jpg",
|
||||
"application/pdf": ".pdf",
|
||||
"application/octet-stream": ".bin",
|
||||
}
|
||||
filename += ext_map.get(ct, ".bin")
|
||||
|
||||
# 清理非法字符,防止路径注入
|
||||
filename = "".join(c for c in filename if c not in '\\/:*?"<>|')
|
||||
path = os.path.join(save_dir, filename)
|
||||
# 多附件可能出现同名文件导致覆盖:追加 fileId 短后缀区分
|
||||
counter = 1
|
||||
base, ext = os.path.splitext(filename)
|
||||
while os.path.exists(path):
|
||||
path = os.path.join(save_dir, f"{base}_{file_id[:8]}_{counter}{ext}")
|
||||
counter += 1
|
||||
with open(path, "wb") as f:
|
||||
f.write(resp.content)
|
||||
logger.info("附件已下载: %s", path)
|
||||
return path
|
||||
@@ -0,0 +1,124 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 浏览器审批层。
|
||||
|
||||
用途:表单数据全部走接口,仅在「通过」需要真实点击审批按钮时才启动浏览器。
|
||||
登录态来自底座注入的 requests.Session(hr 平台),插件不自行读 cookies 文件、不自动补登。
|
||||
"""
|
||||
import time
|
||||
|
||||
from ..config import logger, APPROVE_BUTTONS
|
||||
|
||||
|
||||
def _cookies_from_session(session):
|
||||
"""把注入 session 的 cookies 转成 DrissionPage 可用的 cookie 字典列表。"""
|
||||
cookies = []
|
||||
if session is None:
|
||||
return cookies
|
||||
try:
|
||||
jar = session.cookies
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar:
|
||||
domain = str(c.domain or "")
|
||||
if domain and "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": domain or ".37du.co",
|
||||
"path": c.path or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def build_browser(session):
|
||||
"""创建 ChromiumPage 并注入 HR 登录态;cookies 为空时抛错(提示先登录 HR)。"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
cookies = _cookies_from_session(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("未获取到 HR 登录 cookies,请先在壳子(工作台)完成 HR 登录后再执行")
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
page.set.cookies(cookies)
|
||||
logger.info("浏览器已启动并注入 HR cookies:%d 个", len(cookies))
|
||||
return page
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe。"""
|
||||
try:
|
||||
btn = page.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = page.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(page, decision):
|
||||
"""按校验结论执行真实审批提交。
|
||||
|
||||
Args:
|
||||
page: 停留在单据详情页的 ChromiumPage
|
||||
decision: 校验决策(仅「通过」会自动提交,其余不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(page, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
people = page.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 业务规则层。"""
|
||||
@@ -0,0 +1,375 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 请假校验规则(由影刀版移植)。
|
||||
|
||||
校验分组:
|
||||
Group 1(事假/调休假等):排班上班天数与填报天数一致 -> 通过
|
||||
Group 2(病假/产假等):天数一致 + 附件(OCR/仅附件)-> 通过
|
||||
小时特假:请假时段须完整落在排班班段内(含前一天跨天夜班)+ 已上传附件
|
||||
"""
|
||||
import math
|
||||
import re
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from ..config import logger, require_session, require_user_id, get_attachment_dir, VACATION_TYPE_MAP
|
||||
from ..data.hr_api import fetch_all_shift, get_day_shift, download_attachment
|
||||
from .ocr import check_leave_attachment, check_leave_attachment_detail, marriage_within_one_year
|
||||
|
||||
# 按小时请假的假期类型:不比对天数,按请假时段判断是否落在排班班段内
|
||||
HOURLY_LEAVE_TYPES = {
|
||||
"小时特假",
|
||||
}
|
||||
|
||||
# Group 1:仅校验排班上班天数与填报天数一致
|
||||
LEAVE_TYPE_GROUP_1 = {
|
||||
"事假", "调休假", "半天休(仅限人资专用)",
|
||||
"普通事假", "普通事假(早/中)", "普通事假(晚/高峰)",
|
||||
"年度福利假",
|
||||
}
|
||||
|
||||
# Group 2:校验天数一致 + 需上传附件
|
||||
LEAVE_TYPE_GROUP_2 = {
|
||||
"病假", "特别福利假", "特殊事假", "产假",
|
||||
}
|
||||
|
||||
|
||||
# ==================== 表单解析 ====================
|
||||
def _first_non_null(result, *keys):
|
||||
"""返回第一个值非 None 的字段(不能用 or 链:0 / 0.0 / "" 是合法值但为 falsy)。"""
|
||||
for k in keys:
|
||||
v = result.get(k)
|
||||
if v is not None:
|
||||
return v
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_vacation_type(result):
|
||||
raw = _first_non_null(result, "vacation_type", "leave_type", "sub_type")
|
||||
raw = str(raw).strip() if raw is not None else ""
|
||||
if raw in VACATION_TYPE_MAP:
|
||||
return VACATION_TYPE_MAP[raw]
|
||||
return raw
|
||||
|
||||
|
||||
def parse_leave_form(result):
|
||||
"""把 WorkformEngine 表单数据解析为统一的中文键字典。"""
|
||||
return {
|
||||
"请假人员ID": result.get("staff_id"),
|
||||
"工号": result.get("staff_code"),
|
||||
"请假人员": result.get("staff_name"),
|
||||
"组织全路径": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"假期类型": _resolve_vacation_type(result),
|
||||
# 开始日期优先 start_date(跨天/夜班场景 begin_date 可能取成申请日导致起止倒挂)
|
||||
"开始日期": result.get("start_date") or result.get("begin_date"),
|
||||
"开始时间": result.get("start_time"),
|
||||
"开始段": result.get("begin_other_name"),
|
||||
"结束日期": result.get("end_date"),
|
||||
"结束时间": result.get("end_time"),
|
||||
"结束段": result.get("end_other_name"),
|
||||
"请假天数": _first_non_null(result, "leave_days", "leave_day", "leave_days_new", "ot_day"),
|
||||
"请假小时": _first_non_null(result, "leave_hours", "leave_hour", "ot_hour"),
|
||||
"请假原因": result.get("leave_reason"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
|
||||
def _get_hr_context():
|
||||
"""取注入的 HR 会话与 userId(失败抛错提示重新登录)。"""
|
||||
return require_session(), require_user_id()
|
||||
|
||||
|
||||
# ==================== 天数校验 ====================
|
||||
def _get_date_range(begin_date, end_date):
|
||||
start_date = begin_date[:10] if begin_date else None
|
||||
end_date = end_date[:10] if end_date else None
|
||||
return start_date, end_date
|
||||
|
||||
|
||||
def _get_work_days_count(start_date, end_date, staff_code):
|
||||
"""获取请假区间内实际上班天数(休息与否只以 bc_name 为准)。"""
|
||||
session, user_id = _get_hr_context()
|
||||
rows = fetch_all_shift(session, user_id, staff_code, start_date, end_date)
|
||||
if not rows:
|
||||
raise RuntimeError("未能获取到任何排班数据")
|
||||
|
||||
work_days = []
|
||||
current = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
while current <= end_dt:
|
||||
day = current.strftime("%Y-%m-%d")
|
||||
info = get_day_shift(rows, day)
|
||||
bc_name = info["bc_name"]
|
||||
if bc_name and not bc_name.startswith("休息"):
|
||||
work_days.append(day)
|
||||
current += timedelta(days=1)
|
||||
|
||||
logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days))
|
||||
return len(work_days)
|
||||
|
||||
|
||||
# ==================== 小时假校验 ====================
|
||||
def _parse_leave_time(value):
|
||||
"""解析 "YYYY-MM-DD HH:MM[:SS]" -> (date, 当日分钟数);解析失败返回 None。"""
|
||||
if not value:
|
||||
return None
|
||||
m = re.search(r"(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2})", str(value))
|
||||
if not m:
|
||||
return None
|
||||
try:
|
||||
day = datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
return None
|
||||
return day, int(m.group(4)) * 60 + int(m.group(5))
|
||||
|
||||
|
||||
def _shift_min_range(bc_time):
|
||||
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);跨天夜班 end<start。"""
|
||||
if not bc_time:
|
||||
return None
|
||||
m = re.search(r"(\d{1,2}):(\d{2})\s*~\s*(\d{1,2}):(\d{2})", str(bc_time))
|
||||
if not m:
|
||||
return None
|
||||
return int(m.group(1)) * 60 + int(m.group(2)), int(m.group(3)) * 60 + int(m.group(4))
|
||||
|
||||
|
||||
def _fmt_min(m):
|
||||
return f"{m // 60:02d}:{m % 60:02d}"
|
||||
|
||||
|
||||
def _hourly_leave_within_shift(shift_rows, leave_date, leave_end_date, start_min, end_min):
|
||||
"""判断小时假请假时段是否完整落在某天排班班段内(含前一天跨天夜班)。
|
||||
|
||||
返回 (是否通过, 命中班段日期, 命中bc_time)。
|
||||
"""
|
||||
end_abs = end_min + (leave_end_date - leave_date).days * 1440
|
||||
if end_abs < start_min:
|
||||
end_abs += 1440 # 请假自身跨天兜底
|
||||
for delta in (0, -1):
|
||||
day = (leave_date + timedelta(days=delta)).strftime("%Y-%m-%d")
|
||||
info = get_day_shift(shift_rows, day)
|
||||
r = _shift_min_range(info["bc_time"])
|
||||
if r is None:
|
||||
continue
|
||||
s, e = r
|
||||
base = delta * 1440
|
||||
if s == 0 and e == 0:
|
||||
iv = (base, base + 1440) # 全天班(罕见)
|
||||
elif e < s:
|
||||
iv = (base + s, base + e + 1440) # 跨天夜班
|
||||
else:
|
||||
iv = (base + s, base + e) # 当日班段
|
||||
if iv[0] <= start_min and end_abs <= iv[1]:
|
||||
return True, day, info["bc_time"]
|
||||
return False, None, None
|
||||
|
||||
|
||||
def _validate_hourly_leave(result, session, leave_info, staff_code, attachment, vacation_type):
|
||||
"""小时特假校验:请假时段完整落在排班班段内(含前一天跨天夜班)+ 已上传附件。"""
|
||||
leave_hours = leave_info.get("请假小时")
|
||||
leave_start = _parse_leave_time(leave_info.get("开始时间"))
|
||||
leave_end = _parse_leave_time(leave_info.get("结束时间"))
|
||||
|
||||
if leave_start is None:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "无法解析请假开始时间"
|
||||
return result
|
||||
if leave_end is None:
|
||||
leave_end = leave_start
|
||||
|
||||
try:
|
||||
hr_session, user_id = _get_hr_context()
|
||||
query_start = (leave_start[0] - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
query_end = leave_end[0].strftime("%Y-%m-%d")
|
||||
shift_rows = fetch_all_shift(hr_session, user_id, staff_code, query_start, query_end)
|
||||
except Exception as e:
|
||||
logger.warning("小时假获取排班数据失败: %s", str(e))
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"获取排班数据失败: {e}"
|
||||
return result
|
||||
|
||||
ok, hit_day, hit_bc = _hourly_leave_within_shift(
|
||||
shift_rows, leave_start[0], leave_end[0], leave_start[1], leave_end[1])
|
||||
|
||||
if not ok:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = (
|
||||
f"请假时段 {_fmt_min(leave_start[1])}~{_fmt_min(leave_end[1])} "
|
||||
f"未落在请假当天({query_end})或前一天({query_start})的排班班段内"
|
||||
)
|
||||
return result
|
||||
|
||||
if not attachment:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "未上传附件"
|
||||
return result
|
||||
|
||||
result["decision"] = "通过"
|
||||
result["附件路径"] = download_attachment(session, attachment, get_attachment_dir())
|
||||
result["leave_info"]["排班班段"] = f"{hit_day} {hit_bc}"
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},请假小时: {leave_hours},"
|
||||
f"请假时段 {_fmt_min(leave_start[1])}~{_fmt_min(leave_end[1])} 落在排班班段 "
|
||||
f"{hit_day} {hit_bc} 内,附件已上传)"
|
||||
)
|
||||
return result
|
||||
|
||||
|
||||
# ==================== 附件校验 ====================
|
||||
def _verify_attachment(session, vacation_type, reason, file_id):
|
||||
"""按假期类型校验附件内容,返回 (decision, note, attachment_path)。"""
|
||||
path = download_attachment(session, file_id, get_attachment_dir())
|
||||
if not path:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
|
||||
paths = [p for p in path.split(",") if p]
|
||||
if not paths:
|
||||
return "人工复核", "附件下载失败,需人工核验", None
|
||||
logger.info("附件校验开始: vacation_type=%s, 附件数=%d, 路径=%s", vacation_type, len(paths), paths)
|
||||
|
||||
def _first_hit(checker):
|
||||
return next((p for p in paths if checker(p)), None)
|
||||
|
||||
def _kw_hint(p, leave_type):
|
||||
"""返回该附件 OCR 命中的关键词列表(顿号拼接),用于备注便于人工判断。"""
|
||||
_, hits, _ = check_leave_attachment_detail(p, leave_type)
|
||||
return "、".join(hits) if hits else ""
|
||||
|
||||
if vacation_type == "病假":
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "sick"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'sick')})" if _kw_hint(hit, "sick") else ""
|
||||
return "通过", f"附件OCR检测通过(病假,共{len(paths)}份){kw_desc}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中病假关键词,需人工核验", path
|
||||
|
||||
if vacation_type == "特别福利假":
|
||||
reason = reason or ""
|
||||
if "婚" in reason:
|
||||
hit = None
|
||||
reg_kw = ""
|
||||
for p in paths:
|
||||
ok, _, hits = check_leave_attachment_detail(p, "marriage")
|
||||
if ok:
|
||||
hit = p
|
||||
reg_kw = "、".join(hits)
|
||||
break
|
||||
if hit is None:
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中结婚证关键词,需人工核验", path
|
||||
ok, reg_date = marriage_within_one_year(hit)
|
||||
kw_desc = f"(命中关键词: {reg_kw})" if reg_kw else ""
|
||||
if ok:
|
||||
return "通过", f"结婚证OCR检测通过,登记日期{reg_date}在1年内{kw_desc}", path
|
||||
return "人工复核", f"结婚登记日期{reg_date if reg_date else '未识别'}不在1年内{kw_desc},需人工核验", path
|
||||
if "产" in reason or "孕" in reason:
|
||||
hit = _first_hit(lambda p: check_leave_attachment(p, "maternity"))
|
||||
if hit:
|
||||
kw_desc = f"(命中关键词: {_kw_hint(hit, 'maternity')})" if _kw_hint(hit, "maternity") else ""
|
||||
return "通过", f"产检附件OCR检测通过(共{len(paths)}份){kw_desc}", path
|
||||
return "人工复核", f"共{len(paths)}份附件OCR均未命中产检关键词,需人工核验", path
|
||||
if "丧" in reason:
|
||||
return "通过", f"丧假附件已上传({len(paths)}份)", path
|
||||
return "人工复核", f"特别福利假具体类型无法识别(理由: {reason}),需人工核验", path
|
||||
|
||||
# 特殊事假 / 产假:有附件即通过
|
||||
return "通过", f"附件已上传({len(paths)}份)", path
|
||||
|
||||
|
||||
# ==================== 单据校验入口 ====================
|
||||
def validate_doc(doc, session):
|
||||
"""校验单张请假单据,返回审批决策字典。"""
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
leave_info = parse_leave_form(form_data)
|
||||
|
||||
staff_id = leave_info.get("请假人员ID")
|
||||
staff_code = leave_info.get("工号")
|
||||
vacation_type = leave_info.get("假期类型")
|
||||
begin_date = leave_info.get("开始日期")
|
||||
end_date = leave_info.get("结束日期")
|
||||
leave_days = leave_info.get("请假天数")
|
||||
attachment = leave_info.get("附件")
|
||||
is_hourly = vacation_type in HOURLY_LEAVE_TYPES
|
||||
|
||||
result = {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "通过",
|
||||
"note": "",
|
||||
"leave_info": leave_info,
|
||||
}
|
||||
|
||||
if not vacation_type:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "无法识别假期类型"
|
||||
return result
|
||||
|
||||
if not staff_id:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人员ID缺失"
|
||||
return result
|
||||
|
||||
if not staff_code:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假人工号缺失"
|
||||
return result
|
||||
|
||||
# 小时假(如小时特假)不走天数比对,提前按请假时段校验排班班段
|
||||
if is_hourly:
|
||||
return _validate_hourly_leave(result, session, leave_info, staff_code, attachment, vacation_type)
|
||||
|
||||
start_date, end_date = _get_date_range(begin_date, end_date)
|
||||
if not start_date or not end_date:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = "请假起止日期缺失"
|
||||
return result
|
||||
|
||||
try:
|
||||
actual_work_days = _get_work_days_count(start_date, end_date, staff_code)
|
||||
except Exception as e:
|
||||
logger.warning("计算上班天数失败: %s", str(e))
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"获取排班数据失败: {e}"
|
||||
return result
|
||||
|
||||
try:
|
||||
fill_days = float(leave_days) if leave_days else 0
|
||||
except (TypeError, ValueError):
|
||||
fill_days = 0
|
||||
|
||||
leave_info["实际上班天数"] = actual_work_days
|
||||
leave_info["填报天数"] = fill_days
|
||||
|
||||
# 请半天假(0.5天)仍占用1个排班上班日,故用向上取整比对
|
||||
days_mismatch = actual_work_days != math.ceil(round(fill_days, 2))
|
||||
|
||||
if vacation_type in LEAVE_TYPE_GROUP_1:
|
||||
if days_mismatch:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致"
|
||||
else:
|
||||
result["decision"] = "通过"
|
||||
result["note"] = (
|
||||
f"审批通过(假期类型: {vacation_type},上班天数: {actual_work_days},"
|
||||
f"填报天数: {fill_days})"
|
||||
)
|
||||
|
||||
elif vacation_type in LEAVE_TYPE_GROUP_2:
|
||||
# 需附件的假期:天数一致 + 附件内容校验(OCR/仅附件);无法确认 -> 人工复核
|
||||
reasons = []
|
||||
if days_mismatch:
|
||||
reasons.append(f"排班上班天数({actual_work_days}天)与填报天数({fill_days}天)不一致")
|
||||
if not attachment:
|
||||
reasons.append("未上传附件")
|
||||
|
||||
if reasons:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = ";".join(reasons)
|
||||
else:
|
||||
result["decision"], result["note"], result["附件路径"] = _verify_attachment(
|
||||
session, vacation_type, leave_info.get("请假原因"), attachment
|
||||
)
|
||||
else:
|
||||
result["decision"] = "校验不通过未处理"
|
||||
result["note"] = f"无法识别的假期类型: {vacation_type}"
|
||||
|
||||
return result
|
||||
@@ -0,0 +1,265 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 附件 OCR 校验(可选依赖,懒初始化)。
|
||||
|
||||
行为与影刀版一致:病假/婚假/产检假按关键词命中检测,结婚证按登记日期判断 1 年内。
|
||||
插件化差异:rapidocr/onnxruntime 属可选依赖,首次使用时才初始化引擎;
|
||||
缺库或初始化失败时优雅降级(返回 False / 空),由上层转为「人工复核」,不崩溃。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger, is_debug
|
||||
|
||||
_OCR_LEAVE_KEYWORDS = {
|
||||
# 病假/医疗类:对应医院诊断证明、病历、检验单等
|
||||
"sick": {
|
||||
"医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情",
|
||||
"检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单",
|
||||
},
|
||||
# 婚假类:对应结婚证、婚姻登记证明
|
||||
"marriage": {
|
||||
"结婚证", "婚姻登记", "结婚登记", "持证人", "婚姻登记机关",
|
||||
"婚姻证", "中华人民共和国结婚证",
|
||||
},
|
||||
# 产检假类:对应产检报告、B超单、妊娠诊断证明
|
||||
"maternity": {
|
||||
"医院", "门诊", "就诊", "诊断", "病历", "医嘱", "病假", "病情",
|
||||
"检查", "检验", "处方", "诊断证明", "疾病", "治疗", "医技报告单",
|
||||
"产检", "产前检查", "孕检", "妊娠", "怀孕", "孕周", "预产期",
|
||||
"超声检查", "B超", "胎儿", "产科", "孕期", "产前筛查", "胎心",
|
||||
},
|
||||
}
|
||||
_OCR_CONFIDENCE_THRESHOLD = 0.5
|
||||
_OCR_VALID_TYPES = set(_OCR_LEAVE_KEYWORDS.keys()) | {"all"}
|
||||
|
||||
_ocr_engine = None # 已初始化的引擎
|
||||
_ocr_init_failed = False # 初始化失败标记:避免每张附件重复尝试导入/初始化
|
||||
_ocr_legacy = False # True = rapidocr_onnxruntime(返回 (结果列表, 耗时) 元组)
|
||||
|
||||
|
||||
def ocr_available():
|
||||
"""OCR 是否可用(可触发懒初始化)。"""
|
||||
return _ensure_engine() is not None
|
||||
|
||||
|
||||
def _ensure_engine():
|
||||
"""懒初始化 OCR 引擎;缺库或失败返回 None(上层降级为人工复核)。
|
||||
|
||||
优先 rapidocr(>=3.x,影刀版同款,结果对象带 boxes/txts/scores),
|
||||
其次 rapidocr_onnxruntime(老包,返回 (结果列表, 耗时) 元组)。
|
||||
"""
|
||||
global _ocr_engine, _ocr_init_failed, _ocr_legacy
|
||||
if _ocr_engine is not None:
|
||||
return _ocr_engine
|
||||
if _ocr_init_failed:
|
||||
return None
|
||||
try:
|
||||
from rapidocr import RapidOCR
|
||||
_ocr_engine = RapidOCR()
|
||||
_ocr_legacy = False
|
||||
logger.info("OCR 引擎初始化成功(rapidocr)")
|
||||
return _ocr_engine
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
from rapidocr_onnxruntime import RapidOCR
|
||||
_ocr_engine = RapidOCR()
|
||||
_ocr_legacy = True
|
||||
logger.info("OCR 引擎初始化成功(rapidocr_onnxruntime)")
|
||||
except Exception as e:
|
||||
_ocr_init_failed = True
|
||||
_ocr_engine = None
|
||||
logger.warning("OCR 引擎不可用(附件转人工复核): %s", e)
|
||||
return _ocr_engine
|
||||
|
||||
|
||||
def _ocr_read_text(file_path, debug=False):
|
||||
"""OCR 识别图片,返回 (清洗后拼接文本, 原始拼接文本)。"""
|
||||
engine = _ensure_engine()
|
||||
if engine is None:
|
||||
logger.warning("OCR 引擎未初始化,跳过识别: %s", file_path)
|
||||
raise RuntimeError("OCR 引擎未初始化(rapidocr 缺失或初始化失败)")
|
||||
if not os.path.isfile(file_path):
|
||||
logger.warning("OCR 附件文件不存在,跳过识别: %s", file_path)
|
||||
raise FileNotFoundError(f"附件文件不存在: {file_path}")
|
||||
|
||||
import numpy as np
|
||||
from PIL import Image, ImageEnhance, ImageOps
|
||||
|
||||
with Image.open(file_path) as img:
|
||||
# 应用 EXIF 方向信息,修正手机横拍导致的旋转
|
||||
img = ImageOps.exif_transpose(img)
|
||||
gray_img = img.convert("L")
|
||||
enhancer = ImageEnhance.Contrast(gray_img)
|
||||
enhanced_img = enhancer.enhance(2.0)
|
||||
img_array = np.array(enhanced_img)
|
||||
|
||||
result = engine(img_array)
|
||||
if _ocr_legacy or isinstance(result, tuple):
|
||||
# rapidocr_onnxruntime: ([ [box, text, score], ... ], 耗时)
|
||||
res_list = result[0] if isinstance(result, tuple) else result
|
||||
txts, scores = [], []
|
||||
for item in (res_list or []):
|
||||
try:
|
||||
txts.append(str(item[1]))
|
||||
scores.append(float(item[2]))
|
||||
except (IndexError, TypeError, ValueError):
|
||||
continue
|
||||
else:
|
||||
txts = getattr(result, "txts", None)
|
||||
scores = getattr(result, "scores", None)
|
||||
if txts is None:
|
||||
txts = ()
|
||||
if scores is None:
|
||||
scores = ()
|
||||
|
||||
logger.info("【OCR识别结果】文件: %s, 识别到 %d 个文本块", os.path.basename(file_path), len(txts))
|
||||
if debug or is_debug():
|
||||
for idx, (txt, score) in enumerate(zip(txts, scores)):
|
||||
logger.info(" [%02d] 置信度:%.3f | 文本: %s", idx, score, txt)
|
||||
|
||||
raw_text = ""
|
||||
full_text = ""
|
||||
for text, score in zip(txts, scores):
|
||||
if score < _OCR_CONFIDENCE_THRESHOLD:
|
||||
continue
|
||||
raw_text += text
|
||||
full_text += text.replace(" ", "").replace("\u3000", "")
|
||||
|
||||
# 过滤乱码特殊符号,保留常用字符
|
||||
clean_pattern = re.compile(r'[^\u4e00-\u9fa5a-zA-Z0-9,。!?;:、《》“”‘’()【】.,;:!?年月日]')
|
||||
full_text = clean_pattern.sub('', full_text)
|
||||
return full_text, raw_text
|
||||
|
||||
|
||||
def _target_keywords(leave_type):
|
||||
if leave_type == "all":
|
||||
target = set()
|
||||
for kw_set in _OCR_LEAVE_KEYWORDS.values():
|
||||
target.update(kw_set)
|
||||
return target
|
||||
return _OCR_LEAVE_KEYWORDS[leave_type]
|
||||
|
||||
|
||||
def check_leave_attachment(file_path, leave_type="sick", debug=False):
|
||||
"""检测附件图片是否包含对应假期关键词;文件异常/识别失败/未命中均返回 False。"""
|
||||
if leave_type not in _OCR_VALID_TYPES:
|
||||
return False
|
||||
if not os.path.isfile(file_path):
|
||||
return False
|
||||
if _ensure_engine() is None:
|
||||
logger.warning("OCR 不可用,附件转人工复核: %s", file_path)
|
||||
return False
|
||||
|
||||
try:
|
||||
full_text, _ = _ocr_read_text(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
logger.warning("OCR 识别异常(leave_type=%s): %s", leave_type, e)
|
||||
return False
|
||||
|
||||
if debug:
|
||||
logger.info("【清洗后匹配文本】\n%s\n%s", full_text, "=" * 60)
|
||||
|
||||
hit_words = [kw for kw in _target_keywords(leave_type) if kw in full_text]
|
||||
if debug:
|
||||
logger.info("【命中关键词】: %s", hit_words)
|
||||
return len(hit_words) > 0
|
||||
|
||||
|
||||
def check_leave_attachment_detail(file_path, leave_type="sick", debug=False):
|
||||
"""检测附件是否命中关键词,返回 (是否命中, 命中关键词列表, OCR全文)。"""
|
||||
if leave_type not in _OCR_VALID_TYPES:
|
||||
return False, [], ""
|
||||
if not os.path.isfile(file_path):
|
||||
return False, [], ""
|
||||
if _ensure_engine() is None:
|
||||
logger.warning("OCR 不可用,附件转人工复核: %s", file_path)
|
||||
return False, [], ""
|
||||
|
||||
try:
|
||||
full_text, raw_text = _ocr_read_text(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
logger.warning("OCR 识别异常(leave_type=%s): %s", leave_type, e)
|
||||
return False, [], ""
|
||||
|
||||
hit_words = [kw for kw in _target_keywords(leave_type) if kw in full_text]
|
||||
logger.info("【OCR关键词匹配】假期类型: %s, 命中: %s", leave_type, hit_words if hit_words else "无")
|
||||
return len(hit_words) > 0, hit_words, raw_text
|
||||
|
||||
|
||||
def _ocr_extract_dates(text):
|
||||
"""从文本中提取所有日期,支持 "20XX年X月X日"、"XXXX-XX-XX"、"XXXX/XX/XX" 等格式。"""
|
||||
dates = []
|
||||
patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in patterns:
|
||||
for m in re.finditer(pat, text):
|
||||
try:
|
||||
dates.append(datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date())
|
||||
except ValueError:
|
||||
continue
|
||||
return dates
|
||||
|
||||
|
||||
def _ocr_extract_registration_date(text):
|
||||
"""从结婚证文本中提取"登记日期"字段对应的日期;找不到返回 None。"""
|
||||
reg_match = re.search(r'登记日期', text)
|
||||
if not reg_match:
|
||||
return None
|
||||
|
||||
text_after = text[reg_match.end():]
|
||||
date_patterns = [
|
||||
r'(\d{4})\s*年\s*(\d{1,2})\s*月\s*(\d{1,2})\s*日?',
|
||||
r'(\d{4})\s*[-/.年]\s*(\d{1,2})\s*[-/.月]\s*(\d{1,2})\s*日?',
|
||||
]
|
||||
for pat in date_patterns:
|
||||
m = re.search(pat, text_after)
|
||||
if m:
|
||||
try:
|
||||
return datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def marriage_within_one_year(file_path, today=None, debug=False):
|
||||
"""识别结婚证登记日期并判断是否在当前日期 1 年内。
|
||||
|
||||
优先查找"登记日期"关键词附近的日期,找不到则取识别到的最大日期兜底。
|
||||
返回 (是否1年内, 登记日期)。
|
||||
"""
|
||||
if today is None:
|
||||
today = datetime.now().date()
|
||||
if not os.path.isfile(file_path):
|
||||
return False, None
|
||||
if _ensure_engine() is None:
|
||||
logger.warning("OCR 不可用,结婚证登记日期转人工复核: %s", file_path)
|
||||
return False, None
|
||||
|
||||
try:
|
||||
full_text, _ = _ocr_read_text(file_path, debug=debug)
|
||||
except Exception as e:
|
||||
if debug:
|
||||
logger.warning("[识别异常] %s", e)
|
||||
return False, None
|
||||
|
||||
dates = _ocr_extract_dates(full_text)
|
||||
if not dates:
|
||||
if debug:
|
||||
logger.info("【未识别到任何日期】")
|
||||
return False, None
|
||||
|
||||
reg_date = _ocr_extract_registration_date(full_text)
|
||||
if reg_date is None:
|
||||
reg_date = max(dates)
|
||||
if debug:
|
||||
logger.info("【未找到登记日期关键词,使用最大日期兜底】")
|
||||
|
||||
ok = reg_date <= today and (today - reg_date).days <= 365
|
||||
if debug:
|
||||
logger.info("【识别日期】: %s", dates)
|
||||
logger.info("【登记日期】: %s,1年内: %s", reg_date, ok)
|
||||
return ok, reg_date
|
||||
@@ -0,0 +1,58 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0003",
|
||||
"name": "EHR系统请假流程审核",
|
||||
"version": "1.0.0",
|
||||
"description": "自动审核 EHR 请假待办:拉取待办与请假表单,按假期类型校验排班上班天数与填报天数是否一致,病假/产假等按附件 OCR 关键词核验(病假/结婚证/产检),小时特假校验请假时段是否落在排班班段内;校验通过自动提交审批,并生成审批报告与钉钉群推送。",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0003"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\请假流程审批",
|
||||
"description": "审批报告与服务端附件(附件/ 子目录)统一存放目录"
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "自动提交审批",
|
||||
"default": true,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交"
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉群推送",
|
||||
"default": true,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人"
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉 Webhook",
|
||||
"default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址"
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉加签密钥",
|
||||
"default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出 OCR 识别明细等调试信息"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 报告与推送层。"""
|
||||
@@ -0,0 +1,230 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 钉钉群机器人推送(自 XQ0034 移植,插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 默认 webhook/加签密钥来自插件字段(UI 配置),字段为空时回退本文件默认配置;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法:
|
||||
main("需要推送的通知文本");
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK)
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = ''
|
||||
DEV_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY_TIMES = 3
|
||||
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff',
|
||||
'success': '#00b300',
|
||||
'warning': '#ff9900',
|
||||
'error': '#ff0000',
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.warning("推送失败(第 %d/%d 次):%s", attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
logger.info("分批推送 %d/%d: %s", i, total, batch_title)
|
||||
self.send(batch_title, batch_content, status=status, server_name=server_name)
|
||||
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 列表按 batch_size 条一批,生成带批次标题的消息文本列表。"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""钉钉群机器人推送入口。
|
||||
|
||||
text 支持:
|
||||
- 纯文本:单条 Markdown 推送;
|
||||
- 字典列表 {title, blocks, status?, batch_size?}:块格式分组,自动分批逐条推送;
|
||||
- 文本列表:按顺序逐条发送。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = (webhook or '').strip() or cfg['webhook']
|
||||
secret = (secret or '').strip() or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -0,0 +1,205 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 EHR系统请假流程审核 插件 - 报告生成与推送摘要(由影刀版移植)。"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
def _name(r):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("请假人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _vtype(r):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
return info.get("假期类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 leave_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("请假人员", "请假人员"),
|
||||
("工号", "工号"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("假期类型", "假期类型"),
|
||||
("开始日期", "开始日期"),
|
||||
("开始段", "开始段"),
|
||||
("结束日期", "结束日期"),
|
||||
("结束段", "结束段"),
|
||||
("请假天数", "请假天数"),
|
||||
("请假小时", "请假小时"),
|
||||
("排班班段", "排班班段"),
|
||||
("实际上班天数", "实际上班天数"),
|
||||
("填报天数", "填报天数"),
|
||||
("附件", "附件"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""生成请假审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+异常/失败)。"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"请假审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("leave_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_vtype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
if rejected:
|
||||
lines.append("《请假审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
path = r.get("附件路径") or "下载失败"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 详情页链接: {url} | 附件: {path}")
|
||||
lines.append("")
|
||||
|
||||
if abnormal:
|
||||
lines.append("《请假审批异常待人工确认清单》")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 假期类型: {_vtype(r)} | 原因: {r.get('note') or r.get('error') or ''} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_leave_block(r):
|
||||
"""将单条请假审批结果格式化为块格式 Markdown。"""
|
||||
info = r.get("leave_info", {}) or {}
|
||||
name = info.get("请假人员") or r.get("creator") or "未知"
|
||||
vtype = info.get("假期类型") or ""
|
||||
lines = [f"**🔹 {name}‑{vtype}**"]
|
||||
label_map = [
|
||||
("请假人员", "请假人员"),
|
||||
("工号", "工号"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("假期类型", "假期类型"),
|
||||
]
|
||||
for key, label in label_map:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
start = info.get("开始日期")
|
||||
start_seg = info.get("开始段")
|
||||
if start:
|
||||
if start_seg:
|
||||
lines.append(f"> 开始日期:{start}|开始段:{start_seg}")
|
||||
else:
|
||||
lines.append(f"> 开始日期:{start}")
|
||||
end = info.get("结束日期")
|
||||
end_seg = info.get("结束段")
|
||||
if end:
|
||||
if end_seg:
|
||||
lines.append(f"> 结束日期:{end}|结束段:{end_seg}")
|
||||
else:
|
||||
lines.append(f"> 结束日期:{end}")
|
||||
for key, label in [("请假天数", "请假天数"), ("请假小时", "请假小时"),
|
||||
("实际上班天数", "实际上班天数"), ("填报天数", "填报天数")]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
if note:
|
||||
lines.append(f"> 备注:{note}")
|
||||
url = r.get("detail_url") or ""
|
||||
if url:
|
||||
lines.append(f"> 详情页:[查看详情]({url})")
|
||||
# 钉钉 Markdown 引用块内每行需用双换行分隔才会换行
|
||||
return '\n\n'.join(lines)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""按结果类型生成块格式 Markdown 推送分组(通过的单据仅计数,不逐条推送)。"""
|
||||
if not results:
|
||||
return []
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
if not passed and not rejected and not review and not abnormal and not failed:
|
||||
return []
|
||||
|
||||
messages = []
|
||||
|
||||
def _push_group(title_prefix, records):
|
||||
if not records:
|
||||
return
|
||||
blocks = [_format_leave_block(r) for r in records]
|
||||
messages.append({"title": title_prefix, "blocks": blocks})
|
||||
|
||||
summary_lines = [f"本次共审批 **{len(results)}** 条:"]
|
||||
for label, cnt in [("通过", len(passed)),
|
||||
("校验不通过未处理", len(rejected)),
|
||||
("需人工复核", len(review)),
|
||||
("审批异常", len(abnormal)),
|
||||
("处理失败", len(failed))]:
|
||||
summary_lines.append(f"- {label}:{cnt} 条")
|
||||
messages.append({"title": f"【{subject}审批】汇总", "blocks": ["\n".join(summary_lines)]})
|
||||
|
||||
_push_group(f"【{subject}审批】校验不通过未处理", rejected)
|
||||
_push_group(f"【{subject}审批】需人工复核", review)
|
||||
_push_group(f"【{subject}审批】审批异常", abnormal)
|
||||
_push_group(f"【{subject}审批】处理失败", failed)
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def save_report(text, save_dir):
|
||||
"""把报告落盘为 <save_dir>/请假审批报告_YYYYMMDD_HHMMSS.txt,返回路径。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
filename = f"请假审批报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
|
||||
path = os.path.join(save_dir, filename)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
logger.info("审批报告已保存: %s", path)
|
||||
return path
|
||||
@@ -0,0 +1,6 @@
|
||||
requests
|
||||
DrissionPage
|
||||
rapidocr
|
||||
onnxruntime
|
||||
Pillow
|
||||
numpy
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>EHR系统请假流程审核</title>
|
||||
<script type="module" crossorigin src="/pui/xq0003/assets/index-B2Ej4o3H.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0003/assets/index-Ka-PutnU.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,207 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件入口。
|
||||
|
||||
流程编排(由影刀版 overtime_approval.py 移植,登录态改由底座注入):
|
||||
1) 会话准备:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
|
||||
2) 拉取「加班」待办(纯接口,无待办不启动浏览器);
|
||||
3) 逐单取表单并校验:按加班类型(延时/法定假日/休息日)校验加班日期、时长、排班
|
||||
与打卡区间,延时加班另做提前到岗型与弹性到岗兑换校验;
|
||||
4) 校验通过且开启自动审批时,浏览器注入 HR cookies 后点击同意并确认;
|
||||
5) 生成审批报告落盘 + 钉钉群机器人推送(汇总 + 需人工处理明细)。
|
||||
"""
|
||||
import time
|
||||
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .data import hr_api
|
||||
from .data import hr_browser
|
||||
from .data.hr_api import HRSessionExpiredError
|
||||
from .logic import overtime_rules
|
||||
from .report import overtime_report
|
||||
from .report import dingtalk_robot
|
||||
|
||||
|
||||
class OvertimeApprovalPlugin(ScenePlugin):
|
||||
"""EHR系统加班流程审核(需求 XQ0004)。"""
|
||||
|
||||
id = "xq0004"
|
||||
name = "EHR系统加班流程审核"
|
||||
version = "1.0.0"
|
||||
description = ("自动审核 EHR 加班待办:拉取待办与加班表单,按加班类型(延时/法定假日/休息日)"
|
||||
"校验加班日期、时长、排班与打卡区间及弹性到岗兑换;校验通过自动提交审批,"
|
||||
"并生成审批报告与钉钉群推送。")
|
||||
platform = "hr"
|
||||
uses_month = False
|
||||
capabilities = ["xq0004"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": config.DEFAULT_SAVE_DIR,
|
||||
"description": "审批报告统一存放目录",
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean", "title": "自动提交审批", "default": True,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交",
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean", "title": "钉钉群推送", "default": True,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人",
|
||||
},
|
||||
"push_env": {
|
||||
"type": "string", "title": "推送环境", "default": "dev",
|
||||
"description": "dev=内置测试群,prod=内置生产群;填写自定义 Webhook 时以自定义为准",
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string", "title": "钉钉 Webhook", "default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址",
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string", "title": "钉钉加签密钥", "default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签",
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean", "title": "调试日志", "default": False,
|
||||
"description": "开启后输出接口返回等调试信息",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / HR 会话 / userId / 输出目录 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
config.set_save_dir(save_dir)
|
||||
config.set_debug(bool(fields.get("debug_mode")))
|
||||
approve_enabled = bool(fields.get("approve_enabled", True))
|
||||
push_enabled = bool(fields.get("push_enabled", True))
|
||||
push_env = (fields.get("push_env") or "dev").strip().lower() or "dev"
|
||||
webhook = (fields.get("dingtalk_webhook") or "").strip()
|
||||
secret = (fields.get("dingtalk_secret") or "").strip()
|
||||
|
||||
subject = config.DEFAULT_SUBJECT
|
||||
session = config.require_session()
|
||||
ctx.log(f"===== 加班审批启动:输出目录 {save_dir},自动审批={'开' if approve_enabled else '关'} =====",
|
||||
"INFO")
|
||||
|
||||
# ---- 步骤1:会话校验 ----
|
||||
ctx.progress(5)
|
||||
user_id = hr_api.validate_session(session)
|
||||
config.set_user_id(user_id)
|
||||
|
||||
# ---- 步骤2:拉取加班待办 ----
|
||||
ctx.progress(10)
|
||||
docs = hr_api.fetch_documents(session, subject)
|
||||
ctx.log(f"共获取{subject}待办 {len(docs)} 条", "INFO")
|
||||
ctx.progress(15)
|
||||
|
||||
browser = None
|
||||
results = []
|
||||
try:
|
||||
if docs:
|
||||
for idx, doc in enumerate(docs, 1):
|
||||
try:
|
||||
detail = hr_api.fetch_doc_detail(doc)
|
||||
result = overtime_rules.validate_doc(detail, session)
|
||||
|
||||
if approve_enabled and result.get("decision") == "通过":
|
||||
if browser is None:
|
||||
browser = hr_browser.build_browser(session)
|
||||
browser.get(detail["detail_url"])
|
||||
time.sleep(1.5) # 等待详情页与审批按钮加载
|
||||
orig_decision = result.get("decision")
|
||||
submit = hr_browser.submit_approval(browser, orig_decision)
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = submit["message"]
|
||||
# 提交失败兜底:单据状态未变,不能仍标为通过,归为「异常」交人工跟进
|
||||
if submit["ok"] == "false":
|
||||
result["decision"] = "异常"
|
||||
result["note"] = (
|
||||
f"机器结论[{orig_decision}]但审批提交失败:{submit['message']}"
|
||||
)
|
||||
ctx.log(f"审批提交: {submit['action']} {submit['message']}", "INFO")
|
||||
elif result.get("decision") != "通过":
|
||||
ctx.log(f"决策为{result.get('decision')},不自动提交审批(待人工处理)", "INFO")
|
||||
|
||||
results.append(result)
|
||||
ctx.log(f"已校验 {idx}/{len(docs)}: {result.get('creator')} - "
|
||||
f"{result.get('title')} -> {result.get('decision')}", "INFO")
|
||||
except Exception as e:
|
||||
ctx.log(f"处理单据失败: {doc.get('title')}, 错误: {e}", "ERROR")
|
||||
results.append({
|
||||
"creator": doc.get("creator", "未知"),
|
||||
"title": doc.get("title", "未知"),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "失败",
|
||||
"error": str(e),
|
||||
})
|
||||
ctx.progress(15 + int(75 * idx / len(docs)))
|
||||
else:
|
||||
ctx.log(f"{subject}无待审批单据,跳过浏览器操作", "INFO")
|
||||
|
||||
# ---- 步骤3:报告落盘 ----
|
||||
ctx.progress(92)
|
||||
report_text = overtime_report.generate_report(results)
|
||||
report_path = overtime_report.save_report(report_text, save_dir)
|
||||
ctx.progress(95)
|
||||
|
||||
# ---- 步骤4:钉钉推送 ----
|
||||
push_message = ""
|
||||
if push_enabled:
|
||||
push_items = overtime_report.build_push_summary(results, subject)
|
||||
if not push_items:
|
||||
push_items = [{"text": f"暂无待审批的{subject}单据"}]
|
||||
push_res = dingtalk_robot.main(
|
||||
push_items, title=f"【{subject}审批】汇总",
|
||||
webhook=webhook, secret=secret, env=push_env)
|
||||
push_message = push_res.get("message", "")
|
||||
ctx.log(f"钉钉推送: {push_message}", "INFO")
|
||||
ctx.progress(100)
|
||||
|
||||
counts = {
|
||||
"total": len(results),
|
||||
"passed": sum(1 for r in results if r.get("decision") == "通过"),
|
||||
"rejected": sum(1 for r in results if r.get("decision") == "校验不通过未处理"),
|
||||
"review": sum(1 for r in results if r.get("decision") == "人工复核"),
|
||||
"overdue": sum(1 for r in results if r.get("decision") == "超期"),
|
||||
"abnormal": sum(1 for r in results if r.get("decision") == "异常"),
|
||||
"failed": sum(1 for r in results if r.get("decision") == "失败"),
|
||||
}
|
||||
if not docs:
|
||||
summary = f"暂无待审批的{subject}单据;报告:{report_path}"
|
||||
else:
|
||||
summary = (f"{subject}审批完成,共 {counts['total']} 单:通过 {counts['passed']},"
|
||||
f"校验不通过未处理 {counts['rejected']},人工复核 {counts['review']}")
|
||||
if counts["overdue"]:
|
||||
summary += f",超期待人资处理 {counts['overdue']}"
|
||||
if counts["abnormal"]:
|
||||
summary += f",审批异常 {counts['abnormal']}"
|
||||
if counts["failed"]:
|
||||
summary += f",处理失败 {counts['failed']}"
|
||||
summary += f";报告:{report_path}"
|
||||
if push_message:
|
||||
summary += f";推送:{push_message}"
|
||||
|
||||
return {
|
||||
"summary": summary,
|
||||
"detail": counts,
|
||||
"path": report_path,
|
||||
"results": results,
|
||||
"save_dir": save_dir,
|
||||
}
|
||||
except HRSessionExpiredError as e:
|
||||
# 与影刀版 run_flow 一致:中途 HR 会话失效时给出明确提示,而非原始异常冒泡
|
||||
ctx.log(f"HR 登录态已失效,请重新登录后再执行: {e}", "ERROR")
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from e
|
||||
finally:
|
||||
if browser is not None:
|
||||
try:
|
||||
browser.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
PLUGINS.append(OvertimeApprovalPlugin())
|
||||
@@ -0,0 +1,213 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.logger 输出日志、config.require_session() 取登录态。
|
||||
登录态由底座注入(hr 平台),插件不自行读 cookies 文件、不做自动补登。
|
||||
"""
|
||||
import random
|
||||
import time
|
||||
from functools import wraps
|
||||
|
||||
# ==================== 输出配置 ====================
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\加班流程审批"
|
||||
|
||||
# ==================== HR 系统接口 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
WE_PROCESS_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/WeProcess.mc?method=getProcessAndData"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
PUNCH_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId/redApiExec.mc"
|
||||
|
||||
DEFAULT_PAGE_SIZE = 100
|
||||
DEFAULT_TREE_CODE = "cq37du"
|
||||
DEFAULT_SUBJECT = "加班"
|
||||
|
||||
# ==================== 加班审批规则常量 ====================
|
||||
WORK_START_TIME = "09:00"
|
||||
WORK_END_TIME = "18:00"
|
||||
FLEX_TRIGGER_TIME = "23:00"
|
||||
# 次日弹性上班扣减:次日打卡晚于该时刻(13:00)视为跨过中午休息,扣除午餐时长 LUNCH_BREAK_HOURS
|
||||
FLEX_LATE_LUNCH_TRIGGER_TIME = "13:00"
|
||||
# 次日弹性上班扣减时扣除的中午休息时长(小时)
|
||||
LUNCH_BREAK_HOURS = 1
|
||||
OT_MIN_HOURS = 1
|
||||
# 跨天打卡判定:次日首条打卡时间早于该时刻(6点),视为归属加班当天的跨天有效打卡
|
||||
CROSS_DAY_BEFORE_HOUR = 6
|
||||
# 加班审核周期:加班日期距今天不超过该天数才允许审核
|
||||
OT_REVIEW_DAYS = 8
|
||||
# 月度截止:每月该日期 12:00 之后,不再审核上一个月的加班流程
|
||||
MONTH_CUTOFF_DAY = 2
|
||||
MONTH_CUTOFF_HOUR = 12
|
||||
# 职能排班半天加班时长:上午3.5小时、下午4.5小时(休息日/节假日加班整天仍为9小时)
|
||||
ZHINENG_HALF_MORNING_HOURS = 3.5
|
||||
ZHINENG_HALF_AFTERNOON_HOURS = 4.5
|
||||
# 职能排班上午/下午分界:申请加班开始时间早于该时刻(12点)视为上午半天
|
||||
ZHINENG_HALF_CUTOFF_HOUR = 12
|
||||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)视为提前到岗型,
|
||||
# 常规"晚于规定下班时间18:00""当日有下班打卡"校验不适用,改以到岗打卡为区间合规证据。
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
|
||||
# ==================== 审批提交 ====================
|
||||
# 仅自动提交"同意"(校验通过);校验不通过未处理一律不自动提交,保留待人工处理
|
||||
APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
}
|
||||
|
||||
# ==================== 编码 → 名称 ====================
|
||||
OT_TYPE_MAP = {"1": "延时加班", "2": "法定假日加班", "3": "休息日加班"}
|
||||
SUBSIDY_TYPE_MAP = {"1": "转调休", "2": "转补贴"}
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
_save_dir = DEFAULT_SAVE_DIR
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress,业务层按阶段上报进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在壳子(工作台)完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
if not _user_id:
|
||||
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
|
||||
return _user_id
|
||||
|
||||
|
||||
def set_save_dir(path):
|
||||
global _save_dir
|
||||
_save_dir = (path or "").strip() or DEFAULT_SAVE_DIR
|
||||
|
||||
|
||||
def get_save_dir():
|
||||
return _save_dir
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
|
||||
|
||||
# ==================== 重试装饰器(全局最大 3 次) ====================
|
||||
class RetryExhaustedError(Exception):
|
||||
"""重试次数耗尽。"""
|
||||
|
||||
|
||||
def retry(max_attempts: int = 3, no_retry_on: tuple = ()):
|
||||
"""指数退避重试:首次失败后 1s、2s、4s(含抖动);连续失败记录错误并抛出。"""
|
||||
|
||||
def decorator(func):
|
||||
@wraps(func)
|
||||
def wrapper(*args, **kwargs):
|
||||
last_exc = None
|
||||
for attempt in range(1, max_attempts + 1):
|
||||
try:
|
||||
return func(*args, **kwargs)
|
||||
except no_retry_on:
|
||||
raise
|
||||
except Exception as e: # noqa: BLE001 - 统一重试入口
|
||||
last_exc = e
|
||||
if attempt >= max_attempts:
|
||||
break
|
||||
delay = 1.0 * (2 ** (attempt - 1)) * random.uniform(0.5, 1.5)
|
||||
logger.warning("%s 第 %d 次失败,%.1fs 后重试: %s",
|
||||
func.__name__, attempt, delay, e)
|
||||
time.sleep(delay)
|
||||
logger.error("%s 连续 %d 次尝试失败,放弃并记录: %s",
|
||||
func.__name__, max_attempts, last_exc)
|
||||
raise RetryExhaustedError(
|
||||
f"{func.__name__} 连续 {max_attempts} 次失败: {last_exc}") from last_exc
|
||||
|
||||
return wrapper
|
||||
|
||||
return decorator
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 数据层。"""
|
||||
@@ -0,0 +1,348 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - HR 接口层(由影刀版 overtime_approval.py 接口部分移植)。
|
||||
|
||||
链路:
|
||||
1) WeProcess getProcessAndData 查加班流程待办(含 taskId/businessKey/formId)
|
||||
2) WfActivity getWfActivityByTaskId 取 formId
|
||||
3) WorkformEngine getBusinessDate 取加班表单数据
|
||||
4) rf_s_kq_count_leave_yc_day_all 按员工+日期范围取每日考勤(班次名/班次起止)
|
||||
5) rf_s_kq_leave_record_SelectByStaffID 取请假记录(弹性兑换前置校验)
|
||||
6) rf_s_kq_data_queryByStaffId 取打卡明细(kq_time/bc_date/time_order)
|
||||
|
||||
插件化改造点(与影刀版差异):
|
||||
1. 纯 requests 调用(底座注入的 requests.Session),不再用 DrissionPage SessionPage;
|
||||
2. 登录态失效统一抛 HRSessionExpiredError,由上层提示重新登录(不自动补登);
|
||||
3. 日志统一转发到 ctx.log(config.logger)。
|
||||
"""
|
||||
from ..config import (
|
||||
logger, retry, require_session,
|
||||
HR_BASE_URL, WE_PROCESS_QUERY_URL, WF_ACTIVITY_URL, WORKFORM_ENGINE_URL,
|
||||
GET_CUR_USER_INFO_URL, ATTENDANCE_DAILY_URL, LEAVE_RECORD_URL, PUNCH_RECORD_URL,
|
||||
DEFAULT_PAGE_SIZE,
|
||||
)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON 或 Nosession,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求并校验返回 JSON;非 JSON 视为登录态失效。"""
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
text = resp.text or ""
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def fetch_cur_user_info(session):
|
||||
"""调用 getCurUserInfo,返回 userId / rootId(treecode)。"""
|
||||
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""校验注入的 HR 登录态有效,返回 current userId。"""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
except HRSessionExpiredError:
|
||||
raise RuntimeError("HR 登录态已失效,请重新登录 HR 后再执行") from None
|
||||
user_id = str(info.get("userId") or "") if isinstance(info, dict) else ""
|
||||
if not user_id:
|
||||
raise RuntimeError("HR 登录态无效(getCurUserInfo 未返回 userId),请重新登录 HR")
|
||||
return user_id
|
||||
|
||||
|
||||
# ==================== 加班流程待办 ====================
|
||||
def fetch_we_process_page(session, subject, page_no=1, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""拉一页流程待办(title 按标题模糊匹配)。"""
|
||||
params = {
|
||||
"version": "", "PACKAGE_ID": "cq37du", "process_type": "", "defProcessType": "",
|
||||
"struId": "", "rootId": "cq37du", "taskIds": "", "title": subject,
|
||||
"state": "", "startTime": "", "endTime": "",
|
||||
"sortType": "desc", "sortName": "CREATE_TIME",
|
||||
"commonQuery": "[]", "start": str((page_no - 1) * page_size),
|
||||
"pageNo": str(page_no), "pageSize": str(page_size),
|
||||
}
|
||||
data = hr_request_json(session, "POST", WE_PROCESS_QUERY_URL, params, "WeProcess")
|
||||
if str(data.get("state")) != "1":
|
||||
if str(data.get("state")) == "Nosession" or "会话过期" in str(data.get("meg", "")):
|
||||
raise HRSessionExpiredError(f"WeProcess 返回会话过期: {data.get('meg')}")
|
||||
raise RuntimeError(f"WeProcess 接口返回失败: state={data.get('state')} meg={data.get('meg')}")
|
||||
return data
|
||||
|
||||
|
||||
def parse_we_process_list(data):
|
||||
"""解析待办行为单据字典;detail_url 用 reqType=WAIT(待办审批视图,页面才有审批按钮)。"""
|
||||
docs = []
|
||||
for row in data.get("jsonList") or data.get("datas") or []:
|
||||
title = str(row.get("title") or "").strip()
|
||||
task_id = str(row.get("taskId") or "")
|
||||
business_key = str(row.get("businessKey") or "")
|
||||
process_id = str(row.get("processId") or "")
|
||||
form_id = str(row.get("formId") or "")
|
||||
if not task_id or not business_key:
|
||||
logger.warning("跳过缺 taskId/businessKey 的待办行: %s", title)
|
||||
continue
|
||||
detail_url = (
|
||||
f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc?method=goToWorkFlow"
|
||||
f"&formId={form_id}&businessKey={business_key}&processId={process_id}"
|
||||
f"&taskId={task_id}&reqType=WAIT&headType=&systemId="
|
||||
)
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": str(row.get("createUserName") or row.get("createUserNameCn") or "").strip(),
|
||||
"time": str(row.get("createTime") or "").strip(),
|
||||
"taskId": task_id,
|
||||
"businessKey": business_key,
|
||||
"processId": process_id,
|
||||
"formId": form_id,
|
||||
"detail_url": detail_url,
|
||||
})
|
||||
return docs
|
||||
|
||||
|
||||
def get_documents(session, subject, page_size=DEFAULT_PAGE_SIZE):
|
||||
"""分页拉取全部待办,按 taskId 去重。"""
|
||||
all_docs = []
|
||||
page_no = 1
|
||||
while page_no <= 20: # 防御性分页上限
|
||||
data = fetch_we_process_page(session, subject, page_no=page_no, page_size=page_size)
|
||||
docs = parse_we_process_list(data)
|
||||
all_docs.extend(docs)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", page_no, len(docs), len(all_docs))
|
||||
if len(docs) < page_size:
|
||||
break
|
||||
page_no += 1
|
||||
|
||||
seen = set()
|
||||
unique_docs = []
|
||||
for doc in all_docs:
|
||||
key = doc.get("taskId") or doc.get("detail_url") or doc.get("title")
|
||||
if key in seen:
|
||||
continue
|
||||
seen.add(key)
|
||||
unique_docs.append(doc)
|
||||
|
||||
if len(unique_docs) != len(all_docs):
|
||||
logger.warning("去重前 %d 条,去重后 %d 条(已过滤 %d 条重复单据)",
|
||||
len(all_docs), len(unique_docs), len(all_docs) - len(unique_docs))
|
||||
return unique_docs
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_documents(session, subject):
|
||||
return get_documents(session, subject=subject)
|
||||
|
||||
|
||||
# ==================== 表单详情 ====================
|
||||
def get_wf_activity_by_task_id(session, task_id):
|
||||
url = f"{WF_ACTIVITY_URL}?method=getWfActivityByTaskId"
|
||||
logger.info("获取 formId: taskId=%s", task_id)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", url, {"taskId": task_id}, "WfActivity")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WfActivity 接口请求失败: {e}") from e
|
||||
logger.debug("WfActivity 返回: %s", json_data)
|
||||
return json_data
|
||||
|
||||
|
||||
def extract_form_id(wf_activity_data):
|
||||
form_id = (
|
||||
wf_activity_data.get("formId")
|
||||
or wf_activity_data.get("FormId")
|
||||
or wf_activity_data.get("form_id")
|
||||
)
|
||||
if not form_id:
|
||||
for key in ("data", "result"):
|
||||
data_obj = wf_activity_data.get(key, {})
|
||||
if isinstance(data_obj, dict):
|
||||
form_id = data_obj.get("formId") or data_obj.get("FormId") or data_obj.get("form_id")
|
||||
if form_id:
|
||||
break
|
||||
if not form_id:
|
||||
raise ValueError(f"无法从 WfActivity 返回数据中提取 formId: {wf_activity_data}")
|
||||
logger.info("提取到 formId: %s", form_id)
|
||||
return form_id
|
||||
|
||||
|
||||
def get_business_data(session, business_key, form_id):
|
||||
url = f"{WORKFORM_ENGINE_URL}?method=getBusinessDate"
|
||||
logger.info("获取加班表单: businessKey=%s, formId=%s", business_key, form_id)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", url,
|
||||
{"businessKey": business_key, "formId": form_id}, "WorkformEngine")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"WorkformEngine 接口请求失败: {e}") from e
|
||||
|
||||
result = json_data.get("result")
|
||||
if json_data.get("state") != "1" or not isinstance(result, dict):
|
||||
raise RuntimeError(f"WorkformEngine 接口返回失败: {json_data}")
|
||||
logger.info("WorkformEngine 返回成功")
|
||||
return result
|
||||
|
||||
|
||||
@retry(max_attempts=3, no_retry_on=(HRSessionExpiredError,))
|
||||
def fetch_doc_detail(doc):
|
||||
"""纯接口取单据详情:taskId/businessKey 直接取自 WeProcess 行(免 SSO 解析)。"""
|
||||
session = require_session()
|
||||
task_id = doc.get("taskId")
|
||||
business_key = doc.get("businessKey")
|
||||
if not task_id or not business_key:
|
||||
raise RuntimeError(f"待办行缺 taskId/businessKey: {doc.get('title')}")
|
||||
|
||||
wf_activity_data = get_wf_activity_by_task_id(session, task_id)
|
||||
form_id = extract_form_id(wf_activity_data)
|
||||
form_data = get_business_data(session, business_key, form_id)
|
||||
return {**doc, "formId": form_id, "formData": form_data}
|
||||
|
||||
|
||||
# ==================== 每日考勤(排班 + 班次时段) ====================
|
||||
def get_attendance_daily(session, staff_id, start_date, end_date):
|
||||
"""按员工+日期范围查询每日考勤(含班次起止时间与上下班打卡)。
|
||||
|
||||
kq_status_total 按考勤状态分类返回记录:0=休息日、1=正常班、9=未打卡、11=异常,
|
||||
需四种状态各查一次,再按 work_day 合并去重,才能同时拿到班次名/班次时段与休息日记录。
|
||||
"""
|
||||
by_day = {}
|
||||
for status in ("0", "1", "9", "11"):
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"begin_date": start_date,
|
||||
"end_date": end_date,
|
||||
"kq_status_total": status,
|
||||
}
|
||||
logger.info("获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s",
|
||||
status, staff_id, start_date, end_date)
|
||||
try:
|
||||
json_data = hr_request_json(
|
||||
session, "POST", ATTENDANCE_DAILY_URL, params, "考勤逐日")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"考勤逐日接口请求失败: {e}") from e
|
||||
|
||||
for r in json_data.get("data", []) or []:
|
||||
by_day.setdefault(str(r.get("work_day", "")), r)
|
||||
records = [by_day[k] for k in sorted(by_day)]
|
||||
logger.info("考勤逐日合并返回 %d 天", len(records))
|
||||
return records
|
||||
|
||||
|
||||
# ==================== 请假记录 ====================
|
||||
def fetch_leave_record_page(session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
data = {
|
||||
"sub_type": sub_type,
|
||||
"staff_id": staff_id,
|
||||
"begin_date": begin_date,
|
||||
"end_date": end_date,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"pageSize": str(page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
}
|
||||
logger.info("获取请假记录: staff_id=%s, %s 至 %s, 第%d页",
|
||||
staff_id, begin_date, end_date, page_no)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", LEAVE_RECORD_URL, data, "请假记录")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"请假记录接口请求失败: {e}") from e
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"请假记录接口返回失败: {json_data}")
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"请假记录接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_leave_records(session, staff_id, begin_date, end_date,
|
||||
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
all_records = []
|
||||
page_info = fetch_leave_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=page_size, sub_type=sub_type)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("请假记录总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_leave_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=p, page_size=page_size, sub_type=sub_type)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
return all_records
|
||||
|
||||
|
||||
# ==================== 打卡明细 ====================
|
||||
def fetch_punch_record_page(session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""请求单页员工打卡明细(kq_time 真实打卡时间 / bc_date 考勤归属日 / time_order 1上2下)。"""
|
||||
data = {
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": str(page_no),
|
||||
"pageSize": str(page_size),
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": begin_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": begin_date,
|
||||
"end": end_date,
|
||||
"sub_type": sub_type,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s, 第%d页",
|
||||
staff_id, begin_date, end_date, page_no)
|
||||
try:
|
||||
json_data = hr_request_json(session, "POST", PUNCH_RECORD_URL, data, "打卡明细")
|
||||
except HRSessionExpiredError:
|
||||
raise
|
||||
except Exception as e:
|
||||
raise RuntimeError(f"打卡明细接口请求失败: {e}") from e
|
||||
|
||||
if json_data.get("success") is not True or json_data.get("code") != 200:
|
||||
raise RuntimeError(f"打卡明细接口返回失败: {json_data}")
|
||||
page_info = json_data.get("data")
|
||||
if not isinstance(page_info, dict):
|
||||
raise RuntimeError(f"打卡明细接口未返回 data 字段: {json_data}")
|
||||
return page_info
|
||||
|
||||
|
||||
def get_punch_records(session, staff_id, begin_date, end_date,
|
||||
page_size=DEFAULT_PAGE_SIZE, sub_type="-1"):
|
||||
"""查询员工某时间段内的全部打卡明细(自动分页)。"""
|
||||
all_records = []
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=1, page_size=page_size, sub_type=sub_type)
|
||||
total = int(page_info.get("total", 0))
|
||||
page_total = int(page_info.get("pageCount", 1))
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("打卡明细总数: %d, 第1页获取 %d 条", total, len(records))
|
||||
|
||||
if page_total > 1:
|
||||
for p in range(2, page_total + 1):
|
||||
page_info = fetch_punch_record_page(
|
||||
session, staff_id, begin_date, end_date,
|
||||
page_no=p, page_size=page_size, sub_type=sub_type)
|
||||
records = page_info.get("list", []) or []
|
||||
all_records.extend(records)
|
||||
logger.info("第 %d 页获取 %d 条,累计 %d 条", p, len(records), len(all_records))
|
||||
return all_records
|
||||
@@ -0,0 +1,124 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 浏览器审批层。
|
||||
|
||||
用途:表单数据全部走接口,仅在「通过」需要真实点击审批按钮时才启动浏览器。
|
||||
登录态来自底座注入的 requests.Session(hr 平台),插件不自行读 cookies 文件、不自动补登。
|
||||
"""
|
||||
import time
|
||||
|
||||
from ..config import logger, APPROVE_BUTTONS
|
||||
|
||||
|
||||
def _cookies_from_session(session):
|
||||
"""把注入 session 的 cookies 转成 DrissionPage 可用的 cookie 字典列表。"""
|
||||
cookies = []
|
||||
if session is None:
|
||||
return cookies
|
||||
try:
|
||||
jar = session.cookies
|
||||
except Exception:
|
||||
return cookies
|
||||
for c in jar:
|
||||
domain = str(c.domain or "")
|
||||
if domain and "37du.co" not in domain:
|
||||
continue
|
||||
cookies.append({
|
||||
"name": c.name,
|
||||
"value": c.value,
|
||||
"domain": domain or ".37du.co",
|
||||
"path": c.path or "/",
|
||||
})
|
||||
return cookies
|
||||
|
||||
|
||||
def build_browser(session):
|
||||
"""创建 ChromiumPage 并注入 HR 登录态;cookies 为空时抛错(提示先登录 HR)。"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
cookies = _cookies_from_session(session)
|
||||
if not cookies:
|
||||
raise RuntimeError("未获取到 HR 登录 cookies,请先在壳子(工作台)完成 HR 登录后再执行")
|
||||
page = ChromiumPage(ChromiumOptions())
|
||||
page.set.cookies(cookies)
|
||||
logger.info("浏览器已启动并注入 HR cookies:%d 个", len(cookies))
|
||||
return page
|
||||
|
||||
|
||||
def _find_button(page, selector, timeout=3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe。"""
|
||||
try:
|
||||
btn = page.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = page.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(page, decision):
|
||||
"""按校验结论执行真实审批提交。
|
||||
|
||||
Args:
|
||||
page: 停留在单据详情页的 ChromiumPage
|
||||
decision: 校验决策(仅「通过」会自动提交,其余不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(page, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
|
||||
def _visible(el):
|
||||
try:
|
||||
return el.states.is_displayed
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
# 普通流程确认框 #custom-confirm-modal-ok 为主;选人弹窗 .wf-select-people 为特殊单据才触发
|
||||
confirm = None
|
||||
for _ in range(20):
|
||||
c1 = page.ele("#custom-confirm-modal-ok", timeout=0.2)
|
||||
if c1 is not None and _visible(c1):
|
||||
confirm = c1
|
||||
break
|
||||
people = page.ele(".wf-select-people", timeout=0.2)
|
||||
if people is not None and _visible(people):
|
||||
try:
|
||||
c2 = people.ele("css:.modal-footer button.btn.btn-primary", timeout=0.2)
|
||||
except Exception:
|
||||
c2 = None
|
||||
if c2 is not None and _visible(c2):
|
||||
confirm = c2
|
||||
break
|
||||
time.sleep(0.2)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮(#custom-confirm-modal-ok 或 .modal-footer .btn.btn-primary),审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 业务规则层。"""
|
||||
@@ -0,0 +1,598 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 加班校验规则层。
|
||||
|
||||
迁移自 workflows/XQ0001-0100/XQ0004 EHR系统加班流程审核/overtime_approval.py:
|
||||
- 登录态改造:SessionPage → 底座注入 requests.Session(data.hr_api.get_* 接口)
|
||||
- 日志改造:print 输出与进程退出提示 → config.logger
|
||||
- 规则逻辑(时长取整/弹性兑换/休息日法定假日加班/审核周期)原样保留
|
||||
"""
|
||||
import calendar
|
||||
import math
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from chinese_calendar import get_holiday_detail, is_in_lieu
|
||||
|
||||
from ..config import (
|
||||
logger,
|
||||
WORK_START_TIME,
|
||||
WORK_END_TIME,
|
||||
FLEX_TRIGGER_TIME,
|
||||
FLEX_LATE_LUNCH_TRIGGER_TIME,
|
||||
LUNCH_BREAK_HOURS,
|
||||
OT_MIN_HOURS,
|
||||
CROSS_DAY_BEFORE_HOUR,
|
||||
OT_REVIEW_DAYS,
|
||||
MONTH_CUTOFF_DAY,
|
||||
MONTH_CUTOFF_HOUR,
|
||||
ZHINENG_HALF_MORNING_HOURS,
|
||||
ZHINENG_HALF_AFTERNOON_HOURS,
|
||||
ZHINENG_HALF_CUTOFF_HOUR,
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES,
|
||||
OT_TYPE_MAP,
|
||||
SUBSIDY_TYPE_MAP,
|
||||
)
|
||||
from ..data.hr_api import get_attendance_daily, get_leave_records, get_punch_records
|
||||
|
||||
|
||||
# ==================== 加班表单解析 ====================
|
||||
def parse_overtime_form(result):
|
||||
ot_type_code = result.get("ot_type")
|
||||
subsidy_type_code = result.get("subsidy_type")
|
||||
|
||||
overtime_info = {
|
||||
"加班人员ID": result.get("staff_id"),
|
||||
"加班人员": result.get("staff_name"),
|
||||
"组织全路径": result.get("org_full_path"),
|
||||
"岗位": result.get("post_name"),
|
||||
"加班类型": OT_TYPE_MAP.get(ot_type_code, ot_type_code),
|
||||
"补贴类型": SUBSIDY_TYPE_MAP.get(subsidy_type_code, subsidy_type_code),
|
||||
"加班日期": result.get("ot_date"),
|
||||
"加班开始时间": result.get("start_time"),
|
||||
"加班结束时间": result.get("end_time"),
|
||||
"加班时长(小时)": result.get("ot_hour") or result.get("expect_hour"),
|
||||
"加班天数(天)": result.get("ot_day"),
|
||||
"系统判断加班时长(小时)": result.get("judge_ot_hour"),
|
||||
"系统判断加班天数(天)": result.get("judge_ot_day"),
|
||||
"附件": result.get("file"),
|
||||
}
|
||||
|
||||
judge_start = result.get("judge_start_time")
|
||||
judge_end = result.get("judge_end_time")
|
||||
# 接口对未判定场景返回字符串"无数据",需过滤,避免拼出"10:00:00 至 无数据"
|
||||
if (judge_start and judge_end
|
||||
and "无" not in str(judge_start) and "无" not in str(judge_end)):
|
||||
overtime_info["系统判定加班时间"] = f"{judge_start} 至 {judge_end}"
|
||||
else:
|
||||
overtime_info["系统判定加班时间"] = None
|
||||
|
||||
return overtime_info
|
||||
|
||||
|
||||
# ==================== 加班校验规则 ====================
|
||||
def _parse_dt(value):
|
||||
if not value:
|
||||
return None
|
||||
for fmt in ("%Y-%m-%d %H:%M:%S", "%Y-%m-%d %H:%M"):
|
||||
try:
|
||||
return datetime.strptime(str(value), fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _calc_delayed_hours(start, end):
|
||||
total = (end - start).total_seconds() / 3600
|
||||
if total < 1:
|
||||
return 0.0
|
||||
return 1.0 + math.floor((total - 1) / 0.5) * 0.5
|
||||
|
||||
|
||||
def _calc_flex_d(actual_checkout, flex_trigger):
|
||||
return 1.0 + math.floor((actual_checkout - flex_trigger).total_seconds() / 1800) * 0.5
|
||||
|
||||
|
||||
def _calc_day_ot_threshold(days):
|
||||
return 8.0 * days + int(days)
|
||||
|
||||
|
||||
def _next_day(date_str):
|
||||
d = datetime.strptime(date_str, "%Y-%m-%d")
|
||||
return (d + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _is_within_arrival_window(punch_str, start_dt,
|
||||
before_hours=OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
|
||||
after_minutes=OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES):
|
||||
"""提前到岗型加班:判断打卡时间是否落在加班开始时间附近的到岗证据窗口内。"""
|
||||
p = _parse_dt(punch_str)
|
||||
if p is None:
|
||||
return False
|
||||
return (start_dt - timedelta(hours=before_hours)) <= p <= (start_dt + timedelta(minutes=after_minutes))
|
||||
|
||||
|
||||
def _is_spring_festival(date_str):
|
||||
try:
|
||||
date = datetime.strptime(date_str, "%Y-%m-%d").date()
|
||||
is_holiday, holiday_name = get_holiday_detail(date)
|
||||
return (is_holiday and holiday_name == 'Spring Festival'
|
||||
and not is_in_lieu(date) and date.weekday() < 5)
|
||||
except Exception as e:
|
||||
logger.warning("春节法定假日判定失败(%s): %s", date_str, str(e))
|
||||
return False
|
||||
|
||||
|
||||
def _get_shift(session, staff_id, date_str):
|
||||
if not date_str or not staff_id:
|
||||
return "未知"
|
||||
try:
|
||||
records = get_attendance_daily(session, staff_id, date_str, date_str)
|
||||
for r in records:
|
||||
if str(r.get("work_day", "")) == date_str:
|
||||
bc = r.get("bc_name")
|
||||
if bc:
|
||||
return str(bc)
|
||||
# 休息日记录 bc_name 为空,以异常状态标识判断(abnormal_name/kq_status_name1);
|
||||
# 用前缀"休息"匹配,兼容"休息"/"休息(调)"/"休息(补)"等变体
|
||||
if str(r.get("abnormal_name") or r.get("kq_status_name1") or "").startswith("休息"):
|
||||
return "休息"
|
||||
return "无排班"
|
||||
return "无排班"
|
||||
except Exception as e:
|
||||
logger.warning("获取排班失败(%s): %s", date_str, str(e))
|
||||
return "获取失败"
|
||||
|
||||
|
||||
def _is_zhineng_schedule(session, staff_id, date_str):
|
||||
"""
|
||||
判断员工是否为职能排班(休息日/节假日加班半天规则专用)。
|
||||
|
||||
不看加班当天(当天排班通常显示'休息'),而是查看当月每日考勤中的其他天:
|
||||
只要任一天班次包含'职能'(如 职能正班A),即按职能排班处理。
|
||||
排班获取失败时优雅降级返回 False,沿用默认半天4小时规则。
|
||||
"""
|
||||
if not date_str or not staff_id:
|
||||
return False
|
||||
try:
|
||||
year = int(date_str[:4])
|
||||
month = int(date_str[5:7])
|
||||
first_day = f"{year:04d}-{month:02d}-01"
|
||||
last_day = f"{year:04d}-{month:02d}-{calendar.monthrange(year, month)[1]:02d}"
|
||||
records = get_attendance_daily(session, staff_id, first_day, last_day)
|
||||
return any("职能" in (r.get("bc_name") or "") for r in records)
|
||||
except Exception as e:
|
||||
logger.warning("获取排班判断职能失败(%s): %s", date_str, str(e))
|
||||
return False
|
||||
|
||||
|
||||
def _check_attendance(session, staff_id, ot_date):
|
||||
return {"加班当天班次": _get_shift(session, staff_id, ot_date)}
|
||||
|
||||
|
||||
def _extract_shift_times(daily_records, date_str):
|
||||
"""从每日考勤记录中提取指定日期的班次起止时间("HH:MM"),无则返回 (None, None)。
|
||||
|
||||
数据源为 rf_s_kq_count_leave_yc_day_all 接口返回的每日记录
|
||||
(字段 work_day + bc_begin_time/bc_end_time),据此可拿到员工当天实际排班的
|
||||
下班时间(如维护早班 08:00-17:00),避免延时加班校验错误使用默认 18:00。
|
||||
"""
|
||||
for r in daily_records:
|
||||
if str(r.get("work_day", "")) != date_str:
|
||||
continue
|
||||
b = r.get("bc_begin_time")
|
||||
e = r.get("bc_end_time")
|
||||
return (str(b).strip()[:5] if b else None,
|
||||
str(e).strip()[:5] if e else None)
|
||||
return None, None
|
||||
|
||||
|
||||
def _check_punch_records(session, staff_id, ot_date):
|
||||
if not ot_date or not staff_id:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"次日班次开始时间": None, "打卡备注": "缺少加班日期或员工ID"}
|
||||
|
||||
start = datetime.strptime(ot_date, "%Y-%m-%d")
|
||||
prev_day = (start - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
# 打卡明细接口返回 kq_time=真实打卡时间 与 bc_date=考勤归属日,
|
||||
# 跨天打卡(次日0点~6点)由系统归入加班当天,无需人工拼接/修正日期;
|
||||
# 范围扩到前一天是为了兼容提前到岗型加班(开始<=6点)到岗打卡被归到前一天的情况。
|
||||
punches = get_punch_records(session, staff_id, prev_day, next_day)
|
||||
if not punches:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"次日班次开始时间": None, "打卡备注": "当天及次日无打卡记录"}
|
||||
# 按考勤归属日 bc_date 分组;time_order:1=上班打卡、2=下班打卡
|
||||
arrivals = {}
|
||||
checkouts = {}
|
||||
all_by_date = {}
|
||||
for r in punches:
|
||||
bd = str(r.get("bc_date", "")).strip()
|
||||
t = str(r.get("kq_time", "")).strip()
|
||||
if not bd or not t:
|
||||
continue
|
||||
all_by_date.setdefault(bd, []).append(t)
|
||||
if str(r.get("time_order", "")).strip() == "1":
|
||||
arrivals.setdefault(bd, []).append(t)
|
||||
elif str(r.get("time_order", "")).strip() == "2":
|
||||
checkouts.setdefault(bd, []).append(t)
|
||||
# 班次起止时间仍由考勤逐日接口提供;未获取到时由上层回退默认 09:00/18:00
|
||||
daily = get_attendance_daily(session, staff_id, prev_day, next_day)
|
||||
shift_begin, shift_end = _extract_shift_times(daily, ot_date)
|
||||
# 次日班次开始时间:弹性到岗兑换计算晚到时长时,次日上班时间优先取排班开始时间
|
||||
next_shift_begin, _ = _extract_shift_times(daily, next_day)
|
||||
|
||||
def _sorted(date_str):
|
||||
return sorted(all_by_date.get(date_str, []))
|
||||
|
||||
# 当日最早/最晚打卡:优先按上下班类型取,缺该类型时回退取当天全部打卡
|
||||
day_all = _sorted(ot_date)
|
||||
day_arrivals = sorted(arrivals.get(ot_date, []))
|
||||
day_checkouts = sorted(checkouts.get(ot_date, []))
|
||||
day_first = day_arrivals[0] if day_arrivals else (day_all[0] if day_all else None)
|
||||
day_last = day_checkouts[-1] if day_checkouts else (day_all[-1] if day_all else None)
|
||||
# 次日最早打卡(弹性兑换用)
|
||||
next_arrivals = sorted(arrivals.get(next_day, []))
|
||||
next_all = _sorted(next_day)
|
||||
next_first = next_arrivals[0] if next_arrivals else (next_all[0] if next_all else None)
|
||||
# 前一天最晚打卡(提前到岗型加班用)
|
||||
prev_all = _sorted(prev_day)
|
||||
prev_last = prev_all[-1] if prev_all else None
|
||||
return {
|
||||
"当日最早打卡": day_first,
|
||||
"当日最晚打卡": day_last,
|
||||
"次日最早打卡": next_first,
|
||||
"前一天最晚打卡": prev_last,
|
||||
"班次开始时间": shift_begin,
|
||||
"班次结束时间": shift_end,
|
||||
"次日班次开始时间": next_shift_begin,
|
||||
"打卡备注": "",
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning("获取打卡明细失败: %s", str(e))
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"次日班次开始时间": None, "打卡备注": f"获取失败: {e}"}
|
||||
|
||||
|
||||
def _check_leave_covers_morning(session, staff_id, date_str):
|
||||
prev_day = (datetime.strptime(date_str, "%Y-%m-%d") - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
try:
|
||||
records = get_leave_records(session, staff_id, prev_day, date_str)
|
||||
except Exception as e:
|
||||
logger.warning("获取请假记录失败: %s", str(e))
|
||||
return False
|
||||
|
||||
# 上班时间优先取排班开始时间,未获取到排班时段时回退默认 09:00
|
||||
shift_begin = None
|
||||
try:
|
||||
daily = get_attendance_daily(session, staff_id, date_str, date_str)
|
||||
shift_begin, _ = _extract_shift_times(daily, date_str)
|
||||
except Exception as e:
|
||||
logger.warning("获取排班时段失败(%s): %s", date_str, str(e))
|
||||
morning_time = shift_begin or WORK_START_TIME
|
||||
morning = datetime.strptime(f"{date_str} {morning_time}", "%Y-%m-%d %H:%M")
|
||||
for r in records:
|
||||
start = _parse_dt(r.get("start_time"))
|
||||
end = _parse_dt(r.get("end_time"))
|
||||
if start and end and start <= morning <= end:
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _validate_delayed(info, punch, session, staff_id):
|
||||
ot_date = info.get("加班日期")
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
end = _parse_dt(info.get("加班结束时间"))
|
||||
actual_checkout = _parse_dt(punch.get("当日最晚打卡"))
|
||||
reasons = []
|
||||
# 申请结束时间晚于实际下班打卡、但实际在岗时长(按系统取整)仍满足申请时长时,用于附加到通过备注
|
||||
end_checkout_note = ""
|
||||
|
||||
# 1. 日期校验:加班开始日期与申请加班日期不一致时直接校验不通过未处理,
|
||||
# 无需再校验后续的时长、区间合规等内容
|
||||
if start is None:
|
||||
reasons.append("加班开始时间缺失")
|
||||
elif start.strftime("%Y-%m-%d") != ot_date:
|
||||
reason = f"加班开始日期({start:%Y-%m-%d})与申请加班日期({ot_date})不一致"
|
||||
info["计算加班时长(小时)"] = None
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = 0
|
||||
info["弹性额度D(小时)"] = 0
|
||||
return "校验不通过未处理", reason
|
||||
|
||||
# 2. 时长校验
|
||||
hours = None
|
||||
if end is None:
|
||||
reasons.append("加班结束时间缺失")
|
||||
elif start is not None:
|
||||
hours = _calc_delayed_hours(start, end)
|
||||
if hours < OT_MIN_HOURS:
|
||||
reasons.append(f"加班时长为{hours:g}小时,不足{OT_MIN_HOURS}小时")
|
||||
|
||||
# 3. 区间合规校验
|
||||
# 班次起止时间优先用打卡明细携带的班次时段(bc_begin_time/bc_end_time),
|
||||
# 未获取到时回退默认 09:00/18:00(常规班次),避免非18点下班班次被误判。
|
||||
shift_begin = punch.get("班次开始时间") or WORK_START_TIME
|
||||
shift_end = punch.get("班次结束时间") or WORK_END_TIME
|
||||
work_start = datetime.strptime(f"{ot_date} {shift_begin}", "%Y-%m-%d %H:%M")
|
||||
work_end = datetime.strptime(f"{ot_date} {shift_end}", "%Y-%m-%d %H:%M")
|
||||
# 提前到岗型延时加班:加班开始时间早于当天班次开始时间。
|
||||
# 常规"晚于规定下班时间""当日有下班打卡"校验不适用,改以加班开始时间附近的到岗打卡作为证据:
|
||||
# - 开始<=6点时,到岗打卡可能被系统归到前一天(跨天打卡),需回看前一天记录;
|
||||
# - 6点~9点开始的,到岗打卡归属当天,只看当天记录。
|
||||
is_pre_shift = start is not None and start < work_start
|
||||
if is_pre_shift:
|
||||
candidates = [punch.get("当日最早打卡")]
|
||||
cross_cutoff = start.replace(hour=CROSS_DAY_BEFORE_HOUR, minute=0, second=0, microsecond=0)
|
||||
if start <= cross_cutoff:
|
||||
candidates.append(punch.get("前一天最晚打卡"))
|
||||
arrival_punch = next(
|
||||
(c for c in candidates if _is_within_arrival_window(c, start)),
|
||||
None,
|
||||
)
|
||||
if arrival_punch is None:
|
||||
reasons.append(f"提前到岗型加班,未找到加班开始时间({start:%H:%M})附近的到岗打卡")
|
||||
else:
|
||||
info["到岗打卡"] = arrival_punch
|
||||
else:
|
||||
if start is not None and start < work_end:
|
||||
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({shift_end})")
|
||||
if end is not None:
|
||||
if actual_checkout is None:
|
||||
reasons.append("当日无下班打卡记录,无法校验区间合规")
|
||||
elif start is not None and hours is not None:
|
||||
# 核心原则:申请的加班时长必须与打卡可支撑的实际在岗时长相符。
|
||||
# 按系统取整规则(_calc_delayed_hours),用实际打卡区间(申请开始->实际下班打卡)
|
||||
# 计算实际在岗时长,>= 申请时长即通过(申请结束时间比打卡晚几分钟也属正常)。
|
||||
# 例:申请 18:00-23:05(取整5h),实际打卡23:00:45,实际在岗取整后也是5h,应通过
|
||||
actual_hours = _calc_delayed_hours(start, actual_checkout)
|
||||
if actual_hours >= hours:
|
||||
if end > actual_checkout:
|
||||
end_checkout_note = (
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡({actual_checkout:%H:%M:%S}),"
|
||||
f"实际在岗时长按系统取整为{actual_hours:g}小时,满足申请时长"
|
||||
)
|
||||
else:
|
||||
reasons.append(
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S}),"
|
||||
f"实际在岗时长按取整仅{actual_hours:g}小时,不足申请{hours:g}小时"
|
||||
)
|
||||
|
||||
info["计算加班时长(小时)"] = hours
|
||||
if reasons:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = 0
|
||||
return "校验不通过未处理", ";".join(reasons)
|
||||
|
||||
# 4. 弹性到岗兑换
|
||||
deduction = 0.0
|
||||
flex_note = ""
|
||||
d_hours = 0.0
|
||||
flex_trigger = datetime.strptime(f"{ot_date} {FLEX_TRIGGER_TIME}", "%Y-%m-%d %H:%M")
|
||||
|
||||
if actual_checkout is not None and actual_checkout >= flex_trigger:
|
||||
d_hours = _calc_flex_d(actual_checkout, flex_trigger)
|
||||
next_day = _next_day(ot_date)
|
||||
next_shift = _get_shift(session, staff_id, next_day)
|
||||
|
||||
if next_shift in ("休息", "无排班"):
|
||||
flex_note = f"次日({next_day})为休息日,不触发弹性兑换"
|
||||
elif next_shift in ("获取失败", "未知"):
|
||||
flex_note = f"次日({next_day})排班获取失败,不触发弹性兑换"
|
||||
elif _check_leave_covers_morning(session, staff_id, next_day):
|
||||
flex_note = f"次日({next_day})请假覆盖早上上班时间,不触发弹性兑换"
|
||||
else:
|
||||
# 次日上班时间优先取排班开始时间,未获取到排班时段时回退默认 09:00
|
||||
next_shift_begin = punch.get("次日班次开始时间") or WORK_START_TIME
|
||||
work_start = datetime.strptime(f"{next_day} {next_shift_begin}", "%Y-%m-%d %H:%M")
|
||||
p = _parse_dt(punch.get("次日最早打卡"))
|
||||
|
||||
if p is None:
|
||||
flex_note = f"次日({next_day})无打卡记录,不触发弹性兑换"
|
||||
elif p <= work_start:
|
||||
flex_note = f"次日打卡({p:%H:%M})准时或提前,无需兑换"
|
||||
else:
|
||||
# 有晚到,校验:加班时长 + 晚到 <= 实际在岗时长(按系统取整)
|
||||
# 实际在岗时长 = 加班开始->实际下班打卡 按延时取整(1h起算0.5h累加)
|
||||
actual_work = _calc_delayed_hours(start, actual_checkout)
|
||||
lunch_trigger = datetime.strptime(
|
||||
f"{next_day} {FLEX_LATE_LUNCH_TRIGGER_TIME}", "%Y-%m-%d %H:%M"
|
||||
)
|
||||
|
||||
if p <= work_start + timedelta(hours=d_hours):
|
||||
# T < P <= T+D:晚到时长 = P-T,次日打卡超过13:00时
|
||||
# 再扣1小时午餐,按1小时起算向上取整(不足1小时不扣)
|
||||
late_raw = (p - work_start).total_seconds() / 3600
|
||||
if p > lunch_trigger:
|
||||
late_raw -= LUNCH_BREAK_HOURS
|
||||
late_hours = math.ceil(late_raw) if late_raw >= OT_MIN_HOURS else 0
|
||||
if late_hours < 1:
|
||||
flex_note = f"次日打卡({p:%H:%M})晚到不足1小时,不触发弹性兑换"
|
||||
else:
|
||||
if hours + late_hours > actual_work:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
return "校验不通过未处理", (
|
||||
f"弹性兑换校验校验不通过未处理:申请加班{hours:g}h + 晚到{late_hours}h "
|
||||
f"> 实际在岗时长{actual_work:g}h"
|
||||
)
|
||||
deduction = float(late_hours)
|
||||
flex_note = f"次日打卡({p:%H:%M})晚到,兑换{late_hours}小时"
|
||||
else:
|
||||
if hours + d_hours > actual_work:
|
||||
info["弹性扣减(小时)"] = 0
|
||||
info["有效加班时长(小时)"] = hours
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
return "校验不通过未处理", (
|
||||
f"弹性兑换校验校验不通过未处理:申请加班{hours:g}h + 兑换额度{d_hours:g}h "
|
||||
f"> 实际在岗时长{actual_work:g}h"
|
||||
)
|
||||
deduction = float(d_hours)
|
||||
flex_note = (
|
||||
f"次日打卡({p:%H:%M})超出弹性区间(D={d_hours:g}h),"
|
||||
f"按D兑换,超出部分交考勤处理"
|
||||
)
|
||||
else:
|
||||
if actual_checkout is not None:
|
||||
flex_note = f"实际下班打卡({actual_checkout:%H:%M})早于{FLEX_TRIGGER_TIME},弹性额度D=0"
|
||||
|
||||
effective = max(0.0, float(hours) - deduction)
|
||||
info["弹性扣减(小时)"] = deduction
|
||||
info["有效加班时长(小时)"] = effective
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
note = f"审批通过,有效加班时长{effective:g}小时"
|
||||
extra_parts = [end_checkout_note, flex_note]
|
||||
extra = ";".join(p for p in extra_parts if p)
|
||||
if extra:
|
||||
note += f"({extra})"
|
||||
return "通过", note
|
||||
|
||||
|
||||
def _validate_day_ot(info, punch, session, staff_id, require_holiday):
|
||||
ot_date = info.get("加班日期")
|
||||
reasons = []
|
||||
|
||||
shift = info.get("加班当天班次", "")
|
||||
if shift not in ("休息", "获取失败", "未知", "无排班"):
|
||||
reasons.append(f"当天排班为'{shift}',非休息日")
|
||||
|
||||
if require_holiday and not _is_spring_festival(ot_date):
|
||||
reasons.append(f"{ot_date}不在春节法定节假日列表中")
|
||||
|
||||
# 加班时长 > 0:休息日加班按天计,表单 ot_hour 常为 0(aa.md 中 ot_hours=0.0、ot_days=1.00),
|
||||
# 此时用申报起止时间推算实际加班时长,避免误校验不通过未处理
|
||||
ot_hour = info.get("加班时长(小时)") or info.get("系统判断加班时长(小时)")
|
||||
try:
|
||||
ot_hour = float(ot_hour)
|
||||
except (TypeError, ValueError):
|
||||
ot_hour = 0.0
|
||||
if ot_hour <= 0:
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
end = _parse_dt(info.get("加班结束时间"))
|
||||
if start and end and end > start:
|
||||
ot_hour = (end - start).total_seconds() / 3600
|
||||
if ot_hour <= 0:
|
||||
reasons.append("加班时长为0或缺失")
|
||||
|
||||
first = _parse_dt(punch.get("当日最早打卡"))
|
||||
last = _parse_dt(punch.get("当日最晚打卡"))
|
||||
interval = None
|
||||
# 打卡明细接口已按考勤归属日 bc_date 分组,跨天打卡(次日0点~6点)归入加班当天,
|
||||
# 因此当日最早/最晚打卡已包含跨天下班打卡,无需再参考次日打卡补全。
|
||||
if first is None or last is None:
|
||||
reasons.append("当天缺少上班或下班打卡")
|
||||
else:
|
||||
interval = (last - first).total_seconds() / 3600
|
||||
|
||||
apply_days = info.get("加班天数(天)") or info.get("系统判断加班天数(天)")
|
||||
try:
|
||||
apply_days = float(apply_days)
|
||||
except (TypeError, ValueError):
|
||||
apply_days = 0.0
|
||||
if apply_days <= 0:
|
||||
reasons.append("申报天数缺失或为0")
|
||||
elif interval is not None:
|
||||
threshold = _calc_day_ot_threshold(apply_days)
|
||||
# 职能排班半天(0.5天)加班:上午3.5小时、下午4.5小时,不再统一按4小时半天处理;
|
||||
# 上/下午按申请加班开始时间判定(早于12:00视为上午半天)
|
||||
if abs(apply_days - 0.5) < 1e-9 and _is_zhineng_schedule(session, staff_id, ot_date):
|
||||
start = _parse_dt(info.get("加班开始时间"))
|
||||
if start is not None and start.hour < ZHINENG_HALF_CUTOFF_HOUR:
|
||||
threshold = ZHINENG_HALF_MORNING_HOURS
|
||||
else:
|
||||
threshold = ZHINENG_HALF_AFTERNOON_HOURS
|
||||
if interval < threshold:
|
||||
reasons.append(
|
||||
f"打卡间隔{interval:.2f}小时不足申报{apply_days:g}天所需的{threshold:g}小时"
|
||||
)
|
||||
|
||||
info["打卡时间间隔(小时)"] = interval
|
||||
info["申报天数(天)"] = apply_days
|
||||
if reasons:
|
||||
return "校验不通过未处理", ";".join(reasons)
|
||||
return "通过", f"审批通过(申报{apply_days:g}天,打卡间隔{interval:.2f}小时)"
|
||||
|
||||
|
||||
def check_review_period(ot_date, today=None):
|
||||
"""
|
||||
加班日期有效性前置校验,返回 (是否可审核, 原因)。
|
||||
|
||||
规则:
|
||||
1. 审核周期 OT_REVIEW_DAYS 天:加班日期距今天超过该天数,不再审核;
|
||||
2. 月度截止:每月 MONTH_CUTOFF_DAY 号 MONTH_CUTOFF_HOUR:00 之后,
|
||||
不再审核上一个月的加班流程。
|
||||
"""
|
||||
if not ot_date:
|
||||
return False, "加班日期缺失,无法校验审核周期"
|
||||
try:
|
||||
ot_day = datetime.strptime(ot_date, "%Y-%m-%d")
|
||||
except (TypeError, ValueError):
|
||||
return False, f"加班日期格式非法: {ot_date}"
|
||||
|
||||
today = today or datetime.now()
|
||||
today_date = today.date()
|
||||
|
||||
# 规则1:8天审核周期
|
||||
if (today_date - ot_day.date()).days > OT_REVIEW_DAYS:
|
||||
return False, f"加班日期({ot_date})距今超过{OT_REVIEW_DAYS}天审核周期,不再审核"
|
||||
|
||||
# 规则2:每月2号12点之后不再审核上月加班
|
||||
if ot_day.date() < today_date.replace(day=1):
|
||||
if today.day > MONTH_CUTOFF_DAY or (today.day == MONTH_CUTOFF_DAY and today.hour >= MONTH_CUTOFF_HOUR):
|
||||
return False, (f"加班日期({ot_date})属于上月或更早,已超过本月{MONTH_CUTOFF_DAY}号"
|
||||
f"{MONTH_CUTOFF_HOUR}点,不再审核上月加班流程")
|
||||
|
||||
return True, ""
|
||||
|
||||
|
||||
def validate_doc(doc, session):
|
||||
form_data = doc.get("formData", {}) or {}
|
||||
overtime_info = parse_overtime_form(form_data)
|
||||
|
||||
# 前置校验:加班日期有效性(8天审核周期 + 每月2号12点后不再审核上月加班)
|
||||
valid, period_reason = check_review_period(overtime_info.get("加班日期"))
|
||||
if not valid:
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": "超期",
|
||||
"note": period_reason,
|
||||
"overtime_info": overtime_info,
|
||||
}
|
||||
|
||||
staff_id = overtime_info.get("加班人员ID")
|
||||
ot_date = overtime_info.get("加班日期")
|
||||
|
||||
attendance_info = _check_attendance(session, staff_id, ot_date)
|
||||
punch_info = _check_punch_records(session, staff_id, ot_date)
|
||||
overtime_info.update(attendance_info)
|
||||
overtime_info.update(punch_info)
|
||||
|
||||
ot_type_code = str(form_data.get("ot_type") or "")
|
||||
if ot_type_code == "1":
|
||||
decision, note = _validate_delayed(overtime_info, punch_info, session, staff_id)
|
||||
elif ot_type_code == "3":
|
||||
decision, note = _validate_day_ot(overtime_info, punch_info, session, staff_id, require_holiday=False)
|
||||
elif ot_type_code == "2":
|
||||
require_holiday = _is_spring_festival(ot_date)
|
||||
decision, note = _validate_day_ot(overtime_info, punch_info, session, staff_id, require_holiday=require_holiday)
|
||||
else:
|
||||
decision, note = "校验不通过未处理", f"无法识别加班类型: {ot_type_code}"
|
||||
|
||||
return {
|
||||
"title": doc.get("title", ""),
|
||||
"creator": doc.get("creator", ""),
|
||||
"time": doc.get("time", ""),
|
||||
"detail_url": doc.get("detail_url", ""),
|
||||
"decision": decision,
|
||||
"note": note,
|
||||
"overtime_info": overtime_info,
|
||||
}
|
||||
@@ -0,0 +1,64 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0004",
|
||||
"name": "EHR系统加班流程审核",
|
||||
"version": "1.0.0",
|
||||
"description": "自动审核 EHR 加班待办:拉取待办与加班表单,按加班类型(延时/法定假日/休息日)校验加班日期、时长、排班与打卡区间及弹性到岗兑换;校验通过自动提交审批,并生成审批报告与钉钉群推送。",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
"platform": "hr",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0004"],
|
||||
"permissions": {
|
||||
"platforms": ["hr"]
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "输出目录",
|
||||
"default": "D:\\资料\\人资\\加班流程审批",
|
||||
"description": "加班审批报告存放目录"
|
||||
},
|
||||
"approve_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "自动提交审批",
|
||||
"default": true,
|
||||
"description": "开启后,校验结论为「通过」的单据会在流程详情页自动点击同意;关闭则只校验不提交"
|
||||
},
|
||||
"push_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "钉钉群推送",
|
||||
"default": true,
|
||||
"description": "开启后把汇总与需人工处理明细推送到钉钉群机器人"
|
||||
},
|
||||
"push_env": {
|
||||
"type": "string",
|
||||
"title": "推送环境",
|
||||
"default": "dev",
|
||||
"description": "dev=内置测试群,prod=内置生产群;填写自定义 Webhook 时以自定义为准"
|
||||
},
|
||||
"dingtalk_webhook": {
|
||||
"type": "string",
|
||||
"title": "钉钉 Webhook",
|
||||
"default": "",
|
||||
"description": "留空使用内置默认机器人;需要发到其他群时填写完整 webhook 地址"
|
||||
},
|
||||
"dingtalk_secret": {
|
||||
"type": "string",
|
||||
"title": "钉钉加签密钥",
|
||||
"default": "",
|
||||
"description": "机器人启用加签安全设置时填写,留空表示不加签"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "开启后输出接口返回等调试信息"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 报告与推送层。"""
|
||||
@@ -0,0 +1,230 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 钉钉群机器人推送(插件内单一真源)。
|
||||
|
||||
推送原理(HTTP Webhook,零第三方依赖,仅标准库,符合插件自包含约束):
|
||||
按钉钉加签规则(HMAC-SHA256 + Base64 + URL 编码)生成签名,
|
||||
向机器人 Webhook 推送 Markdown 消息,失败自动重试 3 次。
|
||||
|
||||
约定:
|
||||
- 默认 webhook/加签密钥来自插件字段(UI 配置),字段为空时回退本文件默认配置;
|
||||
- env='dev' 走测试环境机器人,避免调试时误发生产群。
|
||||
|
||||
用法:
|
||||
main("需要推送的通知文本");
|
||||
text 传「块格式分组」字典列表 [{title, blocks, status?}] 时由本模块自动分批逐条推送。
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
# ==================== 默认配置 ====================
|
||||
DEFAULT_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=65dd3f38dea12d2419743aad62ed25f5544ae1ff2ff7d2f667682e0dc912ff6e'
|
||||
DEFAULT_SECRET = '' # 加签密钥(未配置则不加签)
|
||||
DEFAULT_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
# 测试环境配置(env='dev' 时使用;默认使用 DEFAULT_WEBHOOK)
|
||||
DEV_WEBHOOK = 'https://oapi.dingtalk.com/robot/send?access_token=26613569642db03fae6fd19cc932a4b08d82fd09afd35ccfd3ddee5884b5cb66'
|
||||
DEV_SECRET = ''
|
||||
DEV_SERVER_NAME = '37du 任务调度平台'
|
||||
|
||||
ENV_CONFIGS = {
|
||||
'prod': {'webhook': DEFAULT_WEBHOOK, 'secret': DEFAULT_SECRET, 'server_name': DEFAULT_SERVER_NAME},
|
||||
'dev': {'webhook': DEV_WEBHOOK, 'secret': DEV_SECRET, 'server_name': DEV_SERVER_NAME},
|
||||
}
|
||||
|
||||
DEFAULT_TIMEOUT = 10
|
||||
DEFAULT_RETRY_TIMES = 3
|
||||
|
||||
_STATUS_COLORS = {
|
||||
'info': '#0077ff',
|
||||
'success': '#00b300',
|
||||
'warning': '#ff9900',
|
||||
'error': '#ff0000',
|
||||
}
|
||||
|
||||
|
||||
def _build_sign(secret, timestamp_ms):
|
||||
"""按钉钉加签规则计算签名(HMAC-SHA256 + Base64 + URL 编码)。"""
|
||||
string_to_sign = f"{timestamp_ms}\n{secret}"
|
||||
hmac_code = hmac.new(
|
||||
secret.encode('utf-8'), string_to_sign.encode('utf-8'), digestmod=hashlib.sha256
|
||||
).digest()
|
||||
return urllib.parse.quote_plus(base64.b64encode(hmac_code))
|
||||
|
||||
|
||||
def _build_url(webhook, secret=''):
|
||||
"""拼接最终推送地址:配置了 secret 时追加 timestamp + sign 参数。"""
|
||||
if not secret:
|
||||
return webhook
|
||||
ts = int(round(time.time() * 1000))
|
||||
separator = '&' if '?' in webhook else '?'
|
||||
return f"{webhook}{separator}timestamp={ts}&sign={_build_sign(secret, ts)}"
|
||||
|
||||
|
||||
class DingTalkRobot:
|
||||
"""钉钉群机器人推送器。"""
|
||||
|
||||
def __init__(self, webhook='', secret='', server_name='', timeout=DEFAULT_TIMEOUT):
|
||||
self.webhook = (webhook or DEFAULT_WEBHOOK).strip()
|
||||
self.secret = (secret or DEFAULT_SECRET).strip()
|
||||
self.server_name = (server_name or DEFAULT_SERVER_NAME).strip()
|
||||
self.timeout = timeout
|
||||
if not self.webhook:
|
||||
raise ValueError('webhook 不能为空')
|
||||
|
||||
def _post(self, payload):
|
||||
"""推送 payload 到机器人,errcode != 0 视为失败;失败自动重试。"""
|
||||
last_err = None
|
||||
for attempt in range(DEFAULT_RETRY_TIMES):
|
||||
try:
|
||||
url = _build_url(self.webhook, self.secret)
|
||||
data = json.dumps(payload, ensure_ascii=False).encode('utf-8')
|
||||
req = urllib.request.Request(
|
||||
url,
|
||||
data=data,
|
||||
headers={'Content-Type': 'application/json; charset=utf-8'},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=self.timeout) as resp:
|
||||
body = resp.read().decode('utf-8')
|
||||
resp_data = json.loads(body)
|
||||
if resp_data.get('errcode') != 0:
|
||||
raise RuntimeError(
|
||||
f"钉钉机器人返回错误 errcode={resp_data.get('errcode')}, "
|
||||
f"errmsg={resp_data.get('errmsg')}"
|
||||
)
|
||||
return
|
||||
except Exception as e:
|
||||
last_err = e
|
||||
logger.warning("推送失败(第 %d/%d 次):%s", attempt + 1, DEFAULT_RETRY_TIMES, e)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(f"推送失败,重试 {DEFAULT_RETRY_TIMES} 次后仍出错:{last_err}")
|
||||
|
||||
def send(self, title, content, status='info', server_name=''):
|
||||
"""发送统一通知(Markdown:标题按状态着色,正文直接渲染,带页脚)。"""
|
||||
color = _STATUS_COLORS.get(status, _STATUS_COLORS['info'])
|
||||
now = datetime.now().strftime('%Y-%m-%d %H:%M:%S')
|
||||
display_name = (server_name or self.server_name).strip()
|
||||
footer = f"\n\n---\n\n###### {display_name} | {now}"
|
||||
|
||||
text = f"**<font color='{color}'>{title}</font>**\n\n"
|
||||
text += content.strip() + "\n"
|
||||
text += footer
|
||||
|
||||
payload = {'msgtype': 'markdown', 'markdown': {'title': title, 'text': text}}
|
||||
logger.info("钉钉机器人推送通知 [%s]: %s", status, title)
|
||||
self._post(payload)
|
||||
|
||||
def send_in_batches(self, title, content, status='info', server_name='',
|
||||
max_chars=15000):
|
||||
"""分批发送长内容(按行智能拆分,避免切断单行数据)。"""
|
||||
lines = content.strip().split('\n')
|
||||
batches = []
|
||||
current_batch = []
|
||||
current_len = 0
|
||||
|
||||
for line in lines:
|
||||
line_len = len(line) + 1
|
||||
if current_len + line_len > max_chars and current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
current_batch = [line]
|
||||
current_len = line_len
|
||||
else:
|
||||
current_batch.append(line)
|
||||
current_len += line_len
|
||||
|
||||
if current_batch:
|
||||
batches.append('\n'.join(current_batch))
|
||||
|
||||
total = len(batches)
|
||||
for i, batch_content in enumerate(batches, 1):
|
||||
batch_title = f"{title}(第{i}/{total}批)" if total > 1 else title
|
||||
logger.info("分批推送 %d/%d: %s", i, total, batch_title)
|
||||
self.send(batch_title, batch_content, status=status, server_name=server_name)
|
||||
|
||||
|
||||
def compose_batch_messages(blocks, title_prefix, batch_size=10):
|
||||
"""把块格式 block 列表按 batch_size 条一批,生成带批次标题的消息文本列表。"""
|
||||
if not blocks:
|
||||
return []
|
||||
result = []
|
||||
total_batches = (len(blocks) + batch_size - 1) // batch_size
|
||||
for bi in range(total_batches):
|
||||
batch = blocks[bi * batch_size:(bi + 1) * batch_size]
|
||||
header = f"###### {title_prefix}(第{bi + 1}/{total_batches}批)\n\n"
|
||||
footer = f"\n\n###### 本批共{len(batch)}条"
|
||||
content = header + '\n\n'.join(batch) + footer
|
||||
result.append(content)
|
||||
return result
|
||||
|
||||
|
||||
def main(text, title='消息通知', status='info', webhook='', secret='', server_name='',
|
||||
env='prod', batch=False, max_chars=15000):
|
||||
"""钉钉群机器人推送入口。
|
||||
|
||||
text 支持:
|
||||
- 纯文本:单条 Markdown 推送;
|
||||
- 字典列表 {title, blocks, status?, batch_size?}:块格式分组,自动分批逐条推送;
|
||||
- 文本列表:按顺序逐条发送。
|
||||
|
||||
返回: {"success": bool, "message": str}
|
||||
"""
|
||||
try:
|
||||
if text is None or (isinstance(text, str) and not str(text).strip()) \
|
||||
or (isinstance(text, list) and not text):
|
||||
return {'success': False, 'message': '通知文本不能为空'}
|
||||
env_key = (env or 'prod').strip().lower()
|
||||
if env_key not in ENV_CONFIGS:
|
||||
return {'success': False, 'message': f'未知环境 [{env_key}],可选:{" / ".join(ENV_CONFIGS)}'}
|
||||
cfg = ENV_CONFIGS[env_key]
|
||||
webhook = (webhook or '').strip() or cfg['webhook']
|
||||
secret = (secret or '').strip() or cfg['secret']
|
||||
server_name = server_name or cfg['server_name']
|
||||
if not webhook:
|
||||
return {'success': False, 'message': f'环境 [{env_key}] 的 webhook 未配置'}
|
||||
robot = DingTalkRobot(webhook=webhook, secret=secret, server_name=server_name)
|
||||
|
||||
items = text if isinstance(text, list) else [text]
|
||||
sent = 0
|
||||
last_title, last_status = title, status
|
||||
for item in items:
|
||||
if isinstance(item, dict) and item.get('blocks') is not None:
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bs = int(item.get('batch_size', 10) or 10)
|
||||
for batch_content in compose_batch_messages(item['blocks'], ti, bs):
|
||||
robot.send(str(ti), str(batch_content), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
continue
|
||||
if isinstance(item, dict):
|
||||
t = item.get('text')
|
||||
ti = item.get('title', title)
|
||||
st = item.get('status', status)
|
||||
bc = item.get('batch', batch)
|
||||
mc = item.get('max_chars', max_chars)
|
||||
else:
|
||||
t, ti, st, bc, mc = item, title, status, batch, max_chars
|
||||
if t is None or not str(t).strip():
|
||||
continue
|
||||
if bc:
|
||||
robot.send_in_batches(str(ti), str(t), status=st,
|
||||
server_name=server_name, max_chars=mc)
|
||||
else:
|
||||
robot.send(str(ti), str(t), status=st, server_name=server_name)
|
||||
sent += 1
|
||||
last_title, last_status = ti, st
|
||||
if sent == 0:
|
||||
return {'success': False, 'message': '通知文本为空'}
|
||||
if len(items) == 1:
|
||||
return {'success': True, 'message': f'已推送通知 [{env_key}/{last_status}]:{last_title}'}
|
||||
return {'success': True, 'message': f'已推送 {sent} 条通知 [{env_key}]'}
|
||||
except Exception as e:
|
||||
return {'success': False, 'message': str(e)}
|
||||
@@ -0,0 +1,249 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 EHR系统加班流程审核 插件 - 报告生成与推送摘要(由影刀版移植)。"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from ..config import logger
|
||||
|
||||
|
||||
def _name(r):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班人员") or r.get("creator") or "未知"
|
||||
|
||||
|
||||
def _otype(r):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
return info.get("加班类型") or "未知"
|
||||
|
||||
|
||||
def _format_detail(info):
|
||||
"""将 overtime_info 字典格式化为易读的明细行。"""
|
||||
fields = [
|
||||
("加班人员", "加班人员"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("岗位", "岗位"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
("加班日期", "加班日期"),
|
||||
("加班开始时间", "加班开始时间"),
|
||||
("加班结束时间", "加班结束时间"),
|
||||
("加班时长(小时)", "加班时长"),
|
||||
("加班天数(天)", "加班天数"),
|
||||
("系统判断加班时长(小时)", "系统判定时长"),
|
||||
("系统判断加班天数(天)", "系统判定天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("加班当天班次", "当天班次"),
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("前一天最晚打卡", "前一天最晚打卡"),
|
||||
("到岗打卡", "到岗打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性额度D(小时)", "弹性额度D"),
|
||||
("打卡时间间隔(小时)", "打卡间隔"),
|
||||
("申报天数(天)", "申报天数"),
|
||||
("打卡备注", "打卡备注"),
|
||||
]
|
||||
parts = []
|
||||
for key, label in fields:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
parts.append(f"{label}={val}")
|
||||
return " | ".join(parts)
|
||||
|
||||
|
||||
def generate_report(results):
|
||||
"""
|
||||
生成加班审批报告:汇总行 + 每条明细 + 校验不通过未处理清单 + 人工复核清单(+处理失败)。
|
||||
|
||||
输出:
|
||||
- 每条审批的完整明细(含加班日期、时长、打卡、排班等)
|
||||
- 《加班审批校验不通过未处理人员明细清单》:员工姓名、加班类型、校验不通过原因
|
||||
- 《附件人工复核待办清单》:员工姓名、加班类型、详情页链接
|
||||
- 《超期加班待人资处理清单》:员工姓名、加班类型、处理原因、详情页链接(供人资人工处理)
|
||||
"""
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
|
||||
summary = f"共 {len(results)} 单:通过 {len(passed)},校验不通过未处理 {len(rejected)},人工复核 {len(review)}"
|
||||
if overdue:
|
||||
summary += f",超期待人资处理 {len(overdue)}"
|
||||
if abnormal:
|
||||
summary += f",审批异常 {len(abnormal)}"
|
||||
if failed:
|
||||
summary += f",处理失败 {len(failed)}"
|
||||
|
||||
lines = [
|
||||
"加班审批报告",
|
||||
"=" * 60,
|
||||
summary,
|
||||
"",
|
||||
]
|
||||
|
||||
# ----- 明细清单(所有审批单的完整数据) -----
|
||||
lines.append("【审批明细】")
|
||||
for i, r in enumerate(results, 1):
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
decision = r.get("decision", "未知")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
lines.append(f" #{i} {_name(r)}({_otype(r)})-> {decision}")
|
||||
detail = _format_detail(info)
|
||||
if detail:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 校验不通过未处理清单 -----
|
||||
if rejected:
|
||||
lines.append("《加班审批校验不通过未处理人员明细清单》")
|
||||
for i, r in enumerate(rejected, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 校验不通过原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 人工复核清单 -----
|
||||
if review:
|
||||
lines.append("《附件人工复核待办清单》")
|
||||
for i, r in enumerate(review, 1):
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 超期待人资处理清单 -----
|
||||
if overdue:
|
||||
lines.append("《超期加班待人资处理清单》")
|
||||
lines.append("(已超出审核周期,需人资人工处理,对应员工及原因如下)")
|
||||
for i, r in enumerate(overdue, 1):
|
||||
reason = r.get("note") or r.get("error") or ""
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 处理原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 处理失败 -----
|
||||
if failed:
|
||||
lines.append("【处理失败】")
|
||||
for i, r in enumerate(failed, 1):
|
||||
lines.append(f"{i}. {_name(r)} | {r.get('title', '')} | 错误: {r.get('error', '')}")
|
||||
lines.append("")
|
||||
|
||||
# ----- 审批异常(审批提交失败,需人工跟进) -----
|
||||
if abnormal:
|
||||
lines.append("《加班审批异常待人工确认清单》")
|
||||
lines.append("(机器已出结论但审批提交未成功,OA 中单据状态未变,需人工跟进)")
|
||||
for i, r in enumerate(abnormal, 1):
|
||||
reason = r.get("note") or r.get("error") or "未知"
|
||||
url = r.get("detail_url") or "无"
|
||||
lines.append(f"{i}. 员工姓名: {_name(r)} | 加班类型: {_otype(r)} | 原因: {reason} | 详情页链接: {url}")
|
||||
lines.append("")
|
||||
|
||||
return "\n".join(lines)
|
||||
|
||||
|
||||
def _format_overtime_block(r):
|
||||
"""将单条加班审批结果格式化为块格式 Markdown。"""
|
||||
info = r.get("overtime_info", {}) or {}
|
||||
name = info.get("加班人员") or r.get("creator") or "未知"
|
||||
otype = info.get("加班类型") or ""
|
||||
lines = [f"**🔹 {name}‑{otype}**"]
|
||||
for key, label in [
|
||||
("加班人员", "加班人员"),
|
||||
("岗位", "岗位"),
|
||||
("组织全路径", "组织全路径"),
|
||||
("加班类型", "加班类型"),
|
||||
("补贴类型", "补贴类型"),
|
||||
]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
date = info.get("加班日期")
|
||||
if date:
|
||||
lines.append(f"> 加班日期:{date}")
|
||||
start = info.get("加班开始时间")
|
||||
end = info.get("加班结束时间")
|
||||
if start or end:
|
||||
lines.append(f"> 加班时段:{start or ''} ~ {end or ''}")
|
||||
for key, label in [("加班时长(小时)", "加班时长"), ("加班天数(天)", "加班天数"),
|
||||
("系统判定加班时间", "系统判定时间"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("申报天数(天)", "申报天数")]:
|
||||
val = info.get(key)
|
||||
if val is not None and val != "" and val != "无":
|
||||
lines.append(f"> {label}:{val}")
|
||||
note = r.get("note") or r.get("error") or ""
|
||||
if note:
|
||||
lines.append(f"> 备注:{note}")
|
||||
url = r.get("detail_url") or ""
|
||||
if url:
|
||||
lines.append(f"> 详情页:[查看详情]({url})")
|
||||
# 钉钉 Markdown 引用块内每行需用双换行(空行)分隔才会换行,单换行会被合并
|
||||
return '\n\n'.join(lines)
|
||||
|
||||
|
||||
def build_push_summary(results, subject=""):
|
||||
"""
|
||||
按结果类型生成块格式 Markdown 推送分组。
|
||||
|
||||
返回:字典列表,每项 {"title": 分组标题, "blocks": [每条记录格式化后的 block 字符串]},
|
||||
分批/推送由机器人推送模块内部完成(调用方不关心批次)。
|
||||
"""
|
||||
if not results:
|
||||
return []
|
||||
passed = [r for r in results if r.get("decision") == "通过"]
|
||||
rejected = [r for r in results if r.get("decision") == "校验不通过未处理"]
|
||||
review = [r for r in results if r.get("decision") == "人工复核"]
|
||||
overdue = [r for r in results if r.get("decision") == "超期"]
|
||||
abnormal = [r for r in results if r.get("decision") == "异常"]
|
||||
failed = [r for r in results if r.get("decision") == "失败"]
|
||||
if not passed and not rejected and not review and not overdue and not abnormal and not failed:
|
||||
return []
|
||||
|
||||
messages = []
|
||||
|
||||
def _push_group(title_prefix, records):
|
||||
if not records:
|
||||
return
|
||||
blocks = [_format_overtime_block(r) for r in records]
|
||||
messages.append({"title": title_prefix, "blocks": blocks})
|
||||
|
||||
# 汇总消息先发:本次审批各类别数量(一条,含 0 的类别)
|
||||
summary_lines = [f"本次共审批 **{len(results)}** 条:"]
|
||||
for label, cnt in [("通过", len(passed)),
|
||||
("校验不通过未处理", len(rejected)),
|
||||
("需人工复核", len(review)),
|
||||
("超期待人资处理", len(overdue)),
|
||||
("审批异常", len(abnormal)),
|
||||
("处理失败", len(failed))]:
|
||||
summary_lines.append(f"- {label}:{cnt} 条")
|
||||
messages.append({"title": f"【{subject}审批】汇总", "blocks": ["\n".join(summary_lines)]})
|
||||
|
||||
# 通过的单据数量太多,不再逐条推送明细,只保留汇总计数与需人工处理的明细
|
||||
_push_group(f"【{subject}审批】校验不通过未处理", rejected)
|
||||
_push_group(f"【{subject}审批】需人工复核", review)
|
||||
_push_group(f"【{subject}审批】超期待人资处理", overdue)
|
||||
_push_group(f"【{subject}审批】审批异常", abnormal)
|
||||
_push_group(f"【{subject}审批】处理失败", failed)
|
||||
|
||||
return messages
|
||||
|
||||
|
||||
def save_report(text, save_dir):
|
||||
"""把报告落盘为 <save_dir>/加班审批报告_YYYYMMDD_HHMMSS.txt,返回路径。"""
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
filename = f"加班审批报告_{datetime.now().strftime('%Y%m%d_%H%M%S')}.txt"
|
||||
path = os.path.join(save_dir, filename)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
f.write(text)
|
||||
logger.info("审批报告已保存: %s", path)
|
||||
return path
|
||||
@@ -0,0 +1,3 @@
|
||||
requests
|
||||
DrissionPage
|
||||
chinese_calendar
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>EHR系统加班流程审核</title>
|
||||
<script type="module" crossorigin src="/pui/xq0004/assets/index-Br4JMqLc.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0004/assets/index-DYuos9Vi.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,184 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0008 重庆社保增减员办理 插件入口。
|
||||
|
||||
需求 XQ0008(重庆社保增减员导入名单制作)为主体,合并 XQ0014(重庆社保系统增减员办理)
|
||||
+ XQ0015/XQ0016(参保成功/异常/社保转移告知书制作与下发),八个可选阶段按业务顺序
|
||||
串行(可自由勾选):
|
||||
|
||||
0) 目录预检:校验统一资料根目录(base_dir)是否满足各阶段需求(源名单/台账/模板/花名册/告知书模板)
|
||||
1) 增员名单制作:源表《参保名单》筛重庆+参保类型+办理状态空,按参保单位分组复制
|
||||
《增员模版.xls》生成《XX增员导入名单.xls》(转移参保-增员 / 新参保-增员 分目录)
|
||||
2) 减员名单制作:源表《停保名单》筛重庆+停保/转移停保+办理停保空,生成《XX减员导入名单.xls》
|
||||
3) 增员系统办理:逐参保单位读取台账账号,登录重庆人社政务平台(法人用户+图形验证码),
|
||||
「城保参保单位人员增加」上传导入 → 预申报提交 → 审核结论回写「办理状态」
|
||||
4) 减员系统办理:同上「城保参保单位人员减少」,回写「办理停保」
|
||||
5) 增员核查回盘:对「办理状态=待审核」单位核查(参保成功/参保失败/400回待办),
|
||||
下载回盘表核对五项参保状态追加个人编号
|
||||
6) 减员核查回盘:对「办理停保=待审核」单位核查(停保成功/停保失败),下载回盘表留档
|
||||
7) 告知书制作:生成 员工参与社会保险/参保异常/社保转移 三类告知书(Word+PDF),
|
||||
构造 OA 工作沟通推送数据落盘;可开关自动推 OA(需先在工作台登录 OA)
|
||||
|
||||
运行上下文:平台 = ""(社保系统办理按参保单位逐账号浏览器自动化登录;OA 推送仅在
|
||||
告知书阶段启用时懒取底座 oa 会话)。字段由 plugin.json 权威定义:base_dir / ledger_dir /
|
||||
phases / run_limit / debug_mode / notice_branch / notice_push_oa / notice_test_mode。
|
||||
"""
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .logic import dir_check, notice_gen, oa_push, roster_gen
|
||||
from .logic.web_import import ImportEngine
|
||||
from .logic.web_review import ReviewEngine
|
||||
|
||||
# 阶段定义(key, 名称);多选按序串行,留空=全部
|
||||
_PHASES = [
|
||||
("dir_check", "目录预检"),
|
||||
("add_list", "增员名单制作"),
|
||||
("stop_list", "减员名单制作"),
|
||||
("add_import", "增员系统办理"),
|
||||
("stop_import", "减员系统办理"),
|
||||
("add_review", "增员核查回盘"),
|
||||
("stop_review", "减员核查回盘"),
|
||||
("notice", "告知书制作"),
|
||||
]
|
||||
_PHASE_LABELS = {k: n for k, n in _PHASES}
|
||||
|
||||
|
||||
class ChongqingSocialChangePlugin(ScenePlugin):
|
||||
"""重庆社保增减员办理(需求 XQ0008 + XQ0014 + XQ0015/XQ0016)。"""
|
||||
|
||||
id = "xq0008"
|
||||
name = "重庆社保增减员办理"
|
||||
version = "1.0.5"
|
||||
description = ("重庆社保增减员全流程(XQ0008 名单制作 + XQ0014 系统办理/核查回盘 + "
|
||||
"XQ0015/XQ0016 告知书制作下发):目录预检、增/减员名单制作、增/减员系统办理、"
|
||||
"增/减员核查回盘、告知书制作与 OA 推送八阶段可选串行。逐参保单位读取台账账号"
|
||||
"登录重庆人社政务平台完成导入申报与审核核查,生成三类告知书并构造 OA 工作沟通推送")
|
||||
platform = ""
|
||||
uses_month = False
|
||||
capabilities = ["xq0008"]
|
||||
permissions = {"platforms": []}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / 进度 / 目录 / 运行参数 ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
base_dir = (fields.get("base_dir") or "").strip() or config.DEFAULT_BASE_DIR
|
||||
config.set_base_dir(base_dir)
|
||||
config.set_ledger_dir(fields.get("ledger_dir") or "")
|
||||
config.set_debug(bool(fields.get("debug_mode", False)))
|
||||
config.set_run_limit(fields.get("run_limit") or 0)
|
||||
config.set_notice_branch(fields.get("notice_branch") or "all")
|
||||
config.set_notice_test_mode(bool(fields.get("notice_test_mode", False)))
|
||||
config.set_notice_push_oa(bool(fields.get("notice_push_oa", False)))
|
||||
|
||||
# ---- 解析阶段选择 ----
|
||||
sel = [str(p).strip() for p in (fields.get("phases") or []) if str(p).strip()]
|
||||
keys = [k for k, _ in _PHASES if k in sel] or [k for k, _ in _PHASES]
|
||||
labels = [_PHASE_LABELS[k] for k in keys]
|
||||
ctx.log(f"===== 重庆社保增减员办理启动:资料根目录 {config.get_base_dir()} =====", "INFO")
|
||||
ctx.log(f"执行阶段:{' → '.join(labels)}", "INFO")
|
||||
if not keys:
|
||||
return {"summary": "未选择任何执行阶段", "detail": {}, "notes": [], "path": base_dir}
|
||||
|
||||
# ---- 各阶段进度区间(平均切分) ----
|
||||
n = len(keys)
|
||||
notes: list = []
|
||||
detail: dict = {}
|
||||
for i, key in enumerate(keys):
|
||||
span = (int(100 * i / n), int(100 * (i + 1) / n))
|
||||
label = _PHASE_LABELS[key]
|
||||
ctx.progress(span[0])
|
||||
try:
|
||||
result = self._run_phase(key, span, ctx)
|
||||
detail[key] = {"label": label, "result": result}
|
||||
ctx.log(f"【{label}】完成:{_safe_message(result)}", "INFO")
|
||||
except Exception as e:
|
||||
notes.append(f"【{label}】执行失败:{e}")
|
||||
detail[key] = {"label": label, "result": {"success": False, "message": str(e)}}
|
||||
ctx.log(f"【{label}】执行失败:{e}", "ERROR")
|
||||
finally:
|
||||
ctx.progress(span[1])
|
||||
ctx.progress(100)
|
||||
|
||||
# ---- 汇总 ----
|
||||
fail_phases = [k for k, v in detail.items()
|
||||
if not (v.get("result") or {}).get("success", True)]
|
||||
tail = ""
|
||||
if notes:
|
||||
tail = "\n注意事项:\n- " + "\n- ".join(notes)
|
||||
summary = ("重庆社保增减员办理完成:{done}。{fail}").format(
|
||||
done="、".join(labels),
|
||||
fail=f"失败阶段:{'、'.join(fail_phases)}" if fail_phases else "全部成功")
|
||||
summary += tail
|
||||
return {"summary": summary, "detail": detail, "notes": notes,
|
||||
"path": base_dir, "phases": labels}
|
||||
|
||||
def _run_phase(self, key, span, ctx):
|
||||
"""按阶段执行,返回 JSON 安全 dict。"""
|
||||
if key == "dir_check":
|
||||
report = dir_check.check_directory()
|
||||
for c in report["checks"]:
|
||||
ctx.log(f" [{'✓' if c['ok'] else '✗'}] {c['name']}:{c['detail']}")
|
||||
return {"success": report["ok"], "message": "目录预检完成", "checks": report["checks"]}
|
||||
if key == "add_list":
|
||||
total, detail_map = roster_gen.make_add_lists()
|
||||
return {"success": True, "message": f"增员名单制作完成,共 {total} 份",
|
||||
"detail": detail_map}
|
||||
if key == "stop_list":
|
||||
total, detail_map = roster_gen.make_stop_lists()
|
||||
return {"success": True, "message": f"减员名单制作完成,共 {total} 份",
|
||||
"detail": detail_map}
|
||||
if key == "add_import":
|
||||
return ImportEngine("add").run(progress_span=span)
|
||||
if key == "stop_import":
|
||||
return ImportEngine("stop").run(progress_span=span)
|
||||
if key == "add_review":
|
||||
return ReviewEngine("add").run(progress_span=span)
|
||||
if key == "stop_review":
|
||||
return ReviewEngine("stop").run(progress_span=span)
|
||||
if key == "notice":
|
||||
return self._run_notice(ctx)
|
||||
raise ValueError(f"未知阶段:{key}")
|
||||
|
||||
def _run_notice(self, ctx):
|
||||
"""告知书制作:生成三类告知书 + 构造 OA 推送数据;按开关自动推送。"""
|
||||
# 花名册优先走 HR 接口取数(需已登录 HR);未登录/失效时回退源表「附-在职花名册」/本地文件
|
||||
try:
|
||||
config.set_hr_session(ctx.get_session("hr"))
|
||||
except Exception as e:
|
||||
config.set_hr_session(None)
|
||||
ctx.log(f"HR 登录态不可用,花名册将回退源表/本地文件:{e}", "WARN")
|
||||
result = notice_gen.make_notices()
|
||||
summary_parts = [f"生成 {result['total']} 份告知书(docx+pdf)",
|
||||
f"构造 {result['messages_count']} 条 OA 推送数据"]
|
||||
# 自动推送(需先在工作台登录 OA)
|
||||
if config.get_notice_push_oa():
|
||||
if not result["messages"]:
|
||||
summary_parts.append("OA 推送跳过(无可推送数据)")
|
||||
else:
|
||||
try:
|
||||
config.set_oa_session(ctx.get_session("oa"))
|
||||
push = oa_push.push_messages(result["messages"])
|
||||
result["push"] = push
|
||||
summary_parts.append(f"OA 推送:{push['message']}")
|
||||
if not push["success"]:
|
||||
result["success"] = False
|
||||
except Exception as e:
|
||||
result["push"] = {"success": False, "message": str(e), "results": []}
|
||||
summary_parts.append(f"OA 推送未执行:{e}")
|
||||
ctx.log(f"OA 推送未执行(请先在工作台登录 OA):{e}", "WARN")
|
||||
else:
|
||||
summary_parts.append("未开启自动 OA 推送(推送数据已落盘 oa_messages.json)")
|
||||
result.setdefault("success", True)
|
||||
result["message"] = ";".join(summary_parts)
|
||||
return result
|
||||
|
||||
|
||||
def _safe_message(result):
|
||||
"""取结果 dict 的 message 字段做日志(结果可能为 None)。"""
|
||||
if isinstance(result, dict):
|
||||
return result.get("message", "")
|
||||
return str(result or "")
|
||||
|
||||
|
||||
PLUGINS.append(ChongqingSocialChangePlugin())
|
||||
@@ -0,0 +1,581 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0008 重庆社保增减员办理 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
业务模块统一经 config.log()/logger 输出日志、config.progress() 上报进度;
|
||||
运行参数(根目录 / 台账目录 / 调试开关 / 每次限制数)由 __init__.py 的 run()
|
||||
解析 fields 后注入(set_base_dir / set_ledger_dir / set_debug / set_run_limit)。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
|
||||
# ==================== 共享目录(缓存/调试,与其它插件同路径约定) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
CACHE_DIR = os.path.join(_APP_DATA_DIR, 'cache')
|
||||
# 本插件的崩溃恢复缓存 / 调试截图 / 验证码调试图目录
|
||||
CKPT_DIR = os.path.join(CACHE_DIR, 'xq0008')
|
||||
|
||||
# ==================== 默认根目录(run() 注入覆盖) ====================
|
||||
DEFAULT_BASE_DIR = r"D:\资料\人资\重庆社保增减员办理"
|
||||
|
||||
# ==================== 文件模式 ====================
|
||||
SOURCE_KEYWORD = "社保变更及增减名单" # 源名单文件名关键字(对齐原版精确匹配,防同名老文件误选)
|
||||
SOURCE_GLOB = f"*{SOURCE_KEYWORD}*.xlsx" # 源名单(年月动态,取最新)
|
||||
LEDGER_GLOB = "*社保户头管理台账*.xlsx" # 台账(可能加前后缀,取最新)
|
||||
TEMPLATE_ADD = "增员模版.xls"
|
||||
TEMPLATE_STOP = "减员模版.xls"
|
||||
OUTPUT_DIR_ADD_NEW = "新参保-增员" # 增员产出子目录(按参保类型分文件夹)
|
||||
OUTPUT_DIR_ADD_TRANS = "转移参保-增员"
|
||||
OUTPUT_DIR_STOP = "停保-减员" # 减员产出子目录
|
||||
|
||||
# ==================== 统一目录子结构(真实布局) ====================
|
||||
ROSTER_WORK_DIR = "社保增减名单制作" # 名单制作输出与模板目录(base_dir 下)
|
||||
ROSTER_TPL_DIR = "模板" # 增员/减员模版所在子目录
|
||||
REPLAY_ROOT = "回盘打印" # 回盘表目录(base_dir 下)
|
||||
NOTICE_DIR = "告知书下发" # 告知书根目录(base_dir 下)
|
||||
NOTICE_TPL_DIR = "模板" # 告知书模板子目录
|
||||
NOTICE_OUTPUT_NAME = "输出" # 告知书输出子目录
|
||||
|
||||
|
||||
def roster_output_dir(sub):
|
||||
"""名单制作输出目录:{base_dir}/社保增减名单制作/<sub>。"""
|
||||
return os.path.join(get_base_dir(), ROSTER_WORK_DIR, sub)
|
||||
|
||||
|
||||
def roster_template_dir():
|
||||
"""增员/减员模版目录:{base_dir}/社保增减名单制作/模板。"""
|
||||
return os.path.join(get_base_dir(), ROSTER_WORK_DIR, ROSTER_TPL_DIR)
|
||||
|
||||
|
||||
def notice_output_root():
|
||||
"""告知书输出根:{base_dir}/告知书下发/输出。"""
|
||||
return os.path.join(get_base_dir(), NOTICE_DIR, NOTICE_OUTPUT_NAME)
|
||||
|
||||
|
||||
def notice_template_dir():
|
||||
"""告知书模板目录:{base_dir}/告知书下发/模板。"""
|
||||
return os.path.join(get_base_dir(), NOTICE_DIR, NOTICE_TPL_DIR)
|
||||
|
||||
|
||||
def replay_dir(sub):
|
||||
"""回盘表目录:{base_dir}/回盘打印/<sub>。"""
|
||||
return os.path.join(get_base_dir(), REPLAY_ROOT, sub)
|
||||
|
||||
|
||||
REPLAY_PREFIX = "人员增减申请回盘表" # 回盘表文件名前缀
|
||||
|
||||
# ==================== 目标区域 / 参保类型 ====================
|
||||
TARGET_REGION = "重庆"
|
||||
ADD_TYPES = ("新参保", "转移参保") # 名单制作覆盖两种参保类型
|
||||
WEB_ADD_TYPES = ("新参保", "转移参保") # 增员系统办理/核查覆盖两种参保类型(与 import_add.py 一致)
|
||||
STOP_TYPES = ("停保", "转移停保") # 减员两类都办
|
||||
|
||||
# ==================== 台账「缴费比例」sheet 数据列(0-based,表头占 1-2 行已跳过) ====================
|
||||
LEDGER_COL = {"户头": 1, "城市": 3, "在用": 4, "信用代码": 8, "平台用户名": 10, "平台密码": 11}
|
||||
|
||||
# ==================== 源名单结构 ====================
|
||||
SOURCE_HEADER_ROW = 3 # 表头在第3行
|
||||
SHEET_KEY_ADD = "参保名单" # 增员 sheet 关键字(如 202609参保名单)
|
||||
SHEET_KEY_STOP = "停保名单" # 减员 sheet 关键字(如 202609停保名单)
|
||||
SHEET_KEY_LEDGER = "缴费比例" # 台账 sheet 关键字(如 2026年9月缴费比例)
|
||||
|
||||
# ==================== 增员名单制作(XQ0008 generate_add.py 移植) ====================
|
||||
# 源表列名 ↔ 模板列名映射(键为模板列含义,值为源表列名)
|
||||
COLUMN_MAP_ADD = {
|
||||
'姓名': '姓名',
|
||||
'证件号码': '身份证号码',
|
||||
'民族': '民族',
|
||||
'月基本工资额': '工资', # 月基本工资额取「工资申报」列
|
||||
'户口性质': '户口性质',
|
||||
'文化程度': '文化程度',
|
||||
'联系电话': '电话号码',
|
||||
'单位名称': '参保单位',
|
||||
'社保号': '社保号',
|
||||
'参保单位全称': '参保单位全称',
|
||||
'备注': '备注',
|
||||
}
|
||||
# 学历映射
|
||||
EDU_MAP = {
|
||||
'硕士研究生': '14.硕士研究生',
|
||||
'本科': '21.大学本科',
|
||||
'大专': '31.大学专科',
|
||||
'高中': '61.普通中学',
|
||||
'职高/中专/中技': '44.职业高中',
|
||||
'初中': '71.初级中学',
|
||||
'小学': '81.小学',
|
||||
}
|
||||
# 民族映射
|
||||
NATION_MAP = {
|
||||
'汉族': '01.汉族', '蒙古族': '02.蒙古族', '回族': '03.回族', '藏族': '04.藏族',
|
||||
'维吾尔族': '05.维吾尔族', '苗族': '06.苗族', '彝族': '07.彝族', '壮族': '08.壮族',
|
||||
'布依族': '09.布依族', '朝鲜族': '10.朝鲜族', '满族': '11.满族', '侗族': '12.侗族',
|
||||
'瑶族': '13.瑶族', '白族': '14.白族', '土家族': '15.土家族', '哈尼族': '16.哈尼族',
|
||||
'哈萨克族': '17.哈萨克族', '傣族': '18.傣族', '黎族': '19.黎族', '傈僳族': '20.傈僳族',
|
||||
'佤族': '21.佤族', '畲族': '22.畲族', '高山族': '23.高山族', '拉祜族': '24.拉祜族',
|
||||
'水族': '25.水族', '东乡族': '26.东乡族', '纳西族': '27.纳西族', '景颇族': '28.景颇族',
|
||||
'柯尔克孜族': '29.柯尔克孜族', '土族': '30.土族', '达斡尔族': '31.达斡尔族',
|
||||
'仫佬族': '32.仫佬族', '羌族': '33.羌族', '布朗族': '34.布朗族', '撒拉族': '35.撒拉族',
|
||||
'毛南族': '36.毛南族', '仡佬族': '37.仡佬族', '锡伯族': '38.锡伯族', '阿昌族': '39.阿昌族',
|
||||
'普米族': '40.普米族', '塔吉克族': '41.塔吉克族', '怒族': '42.怒族',
|
||||
'乌孜别克族': '43.乌孜别克族', '俄罗斯族': '44.俄罗斯族', '鄂温克族': '45.鄂温克族',
|
||||
'德昂族': '46.德昂族', '保安族': '47.保安族', '裕固族': '48.裕固族', '京族': '49.京族',
|
||||
'塔塔尔族': '50.塔塔尔族', '独龙族': '51.独龙族', '鄂伦春族': '52.鄂伦春族',
|
||||
'赫哲族': '53.赫哲族', '门巴族': '54.门巴族', '珞巴族': '55.珞巴族', '基诺族': '56.基诺族',
|
||||
'少数民族': '57.少数民族', '其他': '99.其他',
|
||||
}
|
||||
# 户籍类型映射
|
||||
RESIDENCE_MAP = {
|
||||
'本地城镇': '11.本市城镇',
|
||||
'本地农村': '21.本市农村',
|
||||
'外地城镇': '12.外市城镇',
|
||||
'外地农村': '22.外市农村',
|
||||
}
|
||||
# 增员固定默认值
|
||||
DEFAULT_VALUES_ADD = {
|
||||
'个人身份': '24.工人',
|
||||
'证件类型': '01.居民身份证(户口簿)',
|
||||
'国籍': 'CHN.中国',
|
||||
'专职技能': '499.未定职级',
|
||||
'技能等级': '无',
|
||||
'工种': '',
|
||||
'备注': '',
|
||||
}
|
||||
# 增员模板(表头 B2:U2,数据从第4行起)
|
||||
TPL_DATA_START_ROW = 4
|
||||
TPL_COLS_ADD = [
|
||||
'证件号码', '姓名', '民族', '首次参加工作日期', '月基本工资额', '工种', '个人身份',
|
||||
'户口性质', '联系电话', '文化程度', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间', '证件类型', '国籍',
|
||||
'备注', '专职技能', '技能等级',
|
||||
]
|
||||
# 需按日期写入的模板列(工伤=当日,其余=本月1日)
|
||||
DATE_COLS_ADD = {
|
||||
'首次参加工作日期', '养老保险参保时间', '失业保险参保时间',
|
||||
'医疗保险参保时间', '工伤保险参保时间', '生育保险参保时间',
|
||||
}
|
||||
|
||||
# ==================== 减员名单制作(XQ0008 generate_stop.py 移植) ====================
|
||||
COLUMN_MAP_STOP = {
|
||||
'个人编号': '社保编号',
|
||||
'证件号码': '身份证号码',
|
||||
'姓名': '停保人姓名',
|
||||
'单位社保号': '单位社保号',
|
||||
'单位名称': '参保单位',
|
||||
'单位全称': '单位全称',
|
||||
}
|
||||
DEFAULT_VALUES_STOP = {
|
||||
'减少原因': '在职人员主动解除劳动合同',
|
||||
'养老保险减少标志': '1 减少',
|
||||
'失业保险减少标志': '1 减少',
|
||||
'医疗保险减少标志': '1 减少',
|
||||
'工伤保险减少标志': '1 减少',
|
||||
'生育保险减少标志': '1 减少',
|
||||
'失业原因': '3 劳动者自愿辞职',
|
||||
}
|
||||
# 减员模板(表头 B2:L2,数据从第4行起)
|
||||
TPL_COLS_STOP = [
|
||||
'个人编号', '证件号码', '姓名', '减少时间', '减少原因',
|
||||
'养老保险减少标志', '失业保险减少标志', '医疗保险减少标志',
|
||||
'工伤保险减少标志', '生育保险减少标志', '失业原因',
|
||||
]
|
||||
DATE_COLS_STOP = {'减少时间'}
|
||||
STOP_LEAVE_DATE_COL = "离职日期"
|
||||
STOP_PROCESSED_COL = "办理停保"
|
||||
|
||||
|
||||
# ==================== 核查回盘常量(check_review / check_review_stop) ====================
|
||||
CHECK_STATUS = "待审核"
|
||||
DONE_STATUS = "已办结"
|
||||
ERR_400_KEYWORD = "status 400"
|
||||
RUN_400_CLEAR = True # 400系统错误:True=运行结束后统一清空状态回待办(重新走名单制作+办理)
|
||||
MENU_QUERY = "已申报查询"
|
||||
API_KEYWORD = "queryYsbWs04orWs01"
|
||||
API_UNIT_INFO = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/declare/server/gourd/"
|
||||
"cloud/ggfw/declare/query/DwCx/dwyl/getAab001")
|
||||
MENU_PAGE_URL = ("https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/"
|
||||
"onlineoffice/OdCommon")
|
||||
PAGE_SIZE = 10
|
||||
MAX_PAGES = 50
|
||||
INS_STATUSES = ["养老参保状态", "失业参保状态", "医疗参保状态",
|
||||
"工伤参保状态", "生育参保状态"]
|
||||
INS_OK = "参保缴费"
|
||||
|
||||
# ==================== 告知书制作(XQ0015/XQ0016 notice_mail_merge.py 移植) ====================
|
||||
# 统一目录:模板在 {base_dir}/告知书下发/模板,输出在 {base_dir}/告知书下发/输出/YYYYMM
|
||||
NOTICE_HEADER_ROW = 3 # 参保名单 sheet 表头行
|
||||
NOTICE_MAIN_COLS = 51 # 主表字段到「费用」列(AY)为止
|
||||
# 三类告知书模板(file=告知书下发/模板 下的文件名;folder=输出子目录;status/type=过滤条件)
|
||||
NOTICE_TEMPLATES = {
|
||||
"新参保": {
|
||||
"file": "员工参与社会保险告知书模板.docx",
|
||||
"folder": "员工参与社会保险告知书",
|
||||
"status": "已参",
|
||||
"type": "新参保",
|
||||
},
|
||||
"参保异常": {
|
||||
"file": "参保异常告知模板.docx",
|
||||
"folder": "参保异常告知书",
|
||||
"status": "参保失败",
|
||||
"type": "新参保",
|
||||
},
|
||||
"社保转移": {
|
||||
"file": "社保转移告知模板.docx",
|
||||
"folder": "社保转移告知书",
|
||||
"status": "已参",
|
||||
"type": "转移参保",
|
||||
},
|
||||
}
|
||||
NOTICE_BRANCHES = ("新参保", "转移参保") # 告知书执行分支(可分别/全部)
|
||||
# 社保转移数据源 sheet(转移参保数据已并入同文件「变更-职能及干部/变更-门店」sheet)
|
||||
TRANSFER_SHEET_GENERATE = ("变更-职能及干部", "变更-门店")
|
||||
TRANSFER_SHEET_PUSH = "变更-门店"
|
||||
TRANSFER_CHANGE_COL = "是否变更"
|
||||
TRANSFER_CHANGE_VALUE = "是"
|
||||
TRANSFER_COL_MAP = {"新区域": "区域", "个人费用": "费用"}
|
||||
# 旧占位符 → 新占位符(模板兼容旧写法)
|
||||
LEGACY_PLACEHOLDERS = {
|
||||
"{{当前月15日}}": "{{当月15日}}",
|
||||
"{{重庆}}": "{{区域}}",
|
||||
"{{当前月+1}}": "{{下月}}",
|
||||
"{{费用*2}}": "{{一次性扣款}}",
|
||||
}
|
||||
# 推送人映射:键可为「二级部门(经营中心)」或「二级部门为空时的所属单位回退值」(如 水庄大鹅事业部)。
|
||||
# 优先于花名册人事查找(覆盖映射不依赖员工是否在花名册)。
|
||||
DEPT2_PUSH_OVERRIDE = {
|
||||
"金色印象海口经营中心": ["37000700"],
|
||||
"金色印象昆明经营中心": ["37002511"],
|
||||
"金色印象南宁经营中心": ["37009626"],
|
||||
"金色印象深圳经营中心": ["37018211"],
|
||||
"金色印象郑州经营中心": ["37006992"],
|
||||
"水庄大鹅事业部": ["37036104"], # 所属单位回退值(非二级部门),直接推送 37036104 唐佳膑
|
||||
}
|
||||
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]}
|
||||
CC_RECEIVER_NAME = "周卫"
|
||||
CC_RECEIVER_ID = "37001166"
|
||||
NOTICE_OA_TEST_RECEIVERS = ["37036361", "37001166"] # 测试模式接收人(夏一平 + 周卫)
|
||||
# OA 推送文案(subject/content 支持 {y}/{m}/{push_date} 动态替换)
|
||||
NOTICE_OA_MESSAGE_TEMPLATES = (
|
||||
{
|
||||
"key": "参保类",
|
||||
"rule_keys": ("新参保", "参保异常"),
|
||||
"subject": "{y}年{m}月员工参保结果告知书",
|
||||
"content": (
|
||||
"各位店长、人行伙伴:\n"
|
||||
"各区域门店{m}月新参保已完成,以下是各门店《参保成功告知书》/《参保异常告知书》,现需涉及的门店对员工本人进行传达告知(下载并签收);\n"
|
||||
"其中参保异常人员,重庆户籍的可以在渝快办APP上查询办理停保,"
|
||||
"如办理不成功,也可打12333咨询社保机构,异地区域拨打区号+12333;若员工处理完毕,请店长报备至人资周卫,以便下月再参;\n"
|
||||
"请门店在{m}月26日前完成签署并将《签收回执》传递人行,"
|
||||
"人行跟进本经营中心所有人员的告知书回收,{m}月28日前传递人资周卫。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
{
|
||||
"key": "社保转移",
|
||||
"rule_keys": ("社保转移",),
|
||||
"subject": "{y}年{m}月员工参保单位变更确认",
|
||||
"content": (
|
||||
"各位领导/同事:\n"
|
||||
"根据《社保执行细则》,本月人力资源部已输出“工作与参保单位不一致”的人员,"
|
||||
"现需要涉及门店/经营中心与员工本人进行转移确认(下载变更告知书、打印并与员工清晰讲解),"
|
||||
"在{m}月27日下班前完成签署并将《社保缴纳确认单》传递分部人行,"
|
||||
"在{m}月29日内传递人资周卫处。\n"
|
||||
"特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。"
|
||||
"员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。\n"
|
||||
"@@R人力资源部\n"
|
||||
"@@R{push_date}"
|
||||
),
|
||||
"category": "工作安排",
|
||||
},
|
||||
)
|
||||
NOTICE_OA_HIGHLIGHTS = {
|
||||
"参保类": [
|
||||
("《参保成功告知书》", "#c0392b"),
|
||||
("《参保异常告知书》", "#c0392b"),
|
||||
("《签收回执》", "#c0392b"),
|
||||
("{m}月26日前", "#c0392b"),
|
||||
("{m}月28日前", "#c0392b"),
|
||||
],
|
||||
"社保转移": [
|
||||
("《社保缴纳确认单》", "#c0392b"),
|
||||
("{m}月25日下班前", "#c0392b"),
|
||||
("27日内", "#c0392b"),
|
||||
("特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。", "#c0392b"),
|
||||
],
|
||||
}
|
||||
|
||||
# ==================== OA 工作沟通推送(work_communication.py 移植) ====================
|
||||
OA_BASE_URL = "https://oa.37du.co"
|
||||
PERSON_SEARCH_URL = f"{OA_BASE_URL}/sys/common/dataxml.jsp"
|
||||
ATT_UPLOAD_URL = f"{OA_BASE_URL}/sys/attachment/sys_att_main/sysAttMain.do"
|
||||
ATT_UPLOADER_URL = f"{OA_BASE_URL}/sys/attachment/uploaderServlet"
|
||||
WORK_COMMUNICATION_ADD_URL = (f"{OA_BASE_URL}/km/collaborate/km_collaborate_main/"
|
||||
"kmCollaborateMain.do?method=add")
|
||||
KM_COLLABORATE_SAVE_URL = (f"{OA_BASE_URL}/km/collaborate/km_collaborate_main/"
|
||||
"kmCollaborateMain.do")
|
||||
TODO_COUNT_URL = f"{OA_BASE_URL}/sys/notify/sys_notify_todo/sysNotifyTodo.do"
|
||||
FD_CONTENT_PREFIX = b"\xe4\x99\x89\xe5\xa0\xa0\xe4\xb5\x85\xe4\x89\x81\xe5\x8d\x85\xe3\x98\xb4".decode("utf-8")
|
||||
FD_CATEGORY_MAP = {
|
||||
"工作交流": "15e4c970dd59cd559f096644cecadbc7",
|
||||
"信息传递": "15e4c980ff72365007fc1a741ceb0c7d",
|
||||
"工作安排": "17646e8283a07a43be3003d485492a4f",
|
||||
"项目沟通": "1767a1195ec34b0de7d53764c84812f1",
|
||||
"温馨提示": "17efb81557d1e74c532aa78407a95189",
|
||||
"其他": "15e4c985cd9a92cc54cb20c413d9b29e",
|
||||
}
|
||||
FD_CATEGORY_DEFAULT = FD_CATEGORY_MAP["工作安排"]
|
||||
KM_COLLABORATE_MODEL = "com.landray.kmss.km.collaborate.model.KmCollaborateMain"
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_base_dir = DEFAULT_BASE_DIR
|
||||
_ledger_dir = ""
|
||||
_debug = False
|
||||
_run_limit = None
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
"""注入 ctx.progress(RunContext.progress),各模块可上报细粒度进度。"""
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
else:
|
||||
log(f"进度 {pct}%", "DEBUG")
|
||||
|
||||
|
||||
def set_base_dir(path):
|
||||
global _base_dir
|
||||
_base_dir = (path or "").strip().strip('"') or DEFAULT_BASE_DIR
|
||||
|
||||
|
||||
def get_base_dir():
|
||||
return _base_dir
|
||||
|
||||
|
||||
def set_ledger_dir(path):
|
||||
global _ledger_dir
|
||||
_ledger_dir = (path or "").strip().strip('"') or ""
|
||||
|
||||
|
||||
def get_ledger_dir():
|
||||
return _ledger_dir or _base_dir
|
||||
|
||||
|
||||
def set_debug(flag):
|
||||
global _debug
|
||||
_debug = bool(flag)
|
||||
|
||||
|
||||
def is_debug():
|
||||
return _debug
|
||||
|
||||
|
||||
def set_run_limit(value):
|
||||
global _run_limit
|
||||
v = value
|
||||
try:
|
||||
v = int(v)
|
||||
except (TypeError, ValueError):
|
||||
v = None
|
||||
_run_limit = v if v and v > 0 else None
|
||||
|
||||
|
||||
def get_run_limit():
|
||||
return _run_limit
|
||||
|
||||
|
||||
# ==================== 告知书 / OA 推送运行参数钩子(run() 注入) ====================
|
||||
_notice_branch = "all" # '新参保' | '转移参保' | 'all'
|
||||
_notice_test_mode = False # True=OA 推送接收人覆盖为测试接收人
|
||||
_notice_push_oa = False # True=生成告知书后自动推 OA 工作沟通
|
||||
_oa_session = None # 底座注入的 OA requests.Session(未登录时为 None)
|
||||
|
||||
|
||||
def set_notice_branch(value):
|
||||
global _notice_branch
|
||||
v = str(value or "all").strip()
|
||||
_notice_branch = v if v in ("新参保", "转移参保", "all") else "all"
|
||||
|
||||
|
||||
def get_notice_branch():
|
||||
return _notice_branch
|
||||
|
||||
|
||||
def set_notice_test_mode(flag):
|
||||
global _notice_test_mode
|
||||
_notice_test_mode = bool(flag)
|
||||
|
||||
|
||||
def get_notice_test_mode():
|
||||
return _notice_test_mode
|
||||
|
||||
|
||||
def set_notice_push_oa(flag):
|
||||
global _notice_push_oa
|
||||
_notice_push_oa = bool(flag)
|
||||
|
||||
|
||||
def get_notice_push_oa():
|
||||
return _notice_push_oa
|
||||
|
||||
|
||||
def set_oa_session(session):
|
||||
global _oa_session
|
||||
_oa_session = session
|
||||
|
||||
|
||||
def get_oa_session():
|
||||
return _oa_session
|
||||
|
||||
|
||||
# ==================== 花名册数据源钩子(run() 注入) ====================
|
||||
_hr_session = None # 底座注入的 HR requests.Session(花名册接口取数用,未登录为 None)
|
||||
|
||||
|
||||
def set_hr_session(session):
|
||||
global _hr_session
|
||||
_hr_session = session
|
||||
|
||||
|
||||
def get_hr_session():
|
||||
return _hr_session
|
||||
|
||||
|
||||
# ==================== 通用辅助 ====================
|
||||
def _to_text(value):
|
||||
"""转可写文本:证件号/电话等长数字统一为字符串,避免丢精度/科学计数。"""
|
||||
if value is None:
|
||||
return ''
|
||||
try:
|
||||
import math
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
if isinstance(value, float) and value.is_integer():
|
||||
return str(int(value))
|
||||
return str(value).strip()
|
||||
|
||||
|
||||
def _clean_value(value):
|
||||
"""None/NaN 归一为 '',其余原样(用于写入单元格)。"""
|
||||
if value is None:
|
||||
return ''
|
||||
import math
|
||||
if isinstance(value, float) and math.isnan(value):
|
||||
return ''
|
||||
return value
|
||||
|
||||
|
||||
def _safe_name(value):
|
||||
"""单位名转安全文件名:None/NaN/空白 → '未知单位';只剥掉尾部一个「店」。"""
|
||||
if value is None:
|
||||
return '未知单位'
|
||||
try:
|
||||
import pandas as pd
|
||||
if pd.isna(value) or not str(value).strip():
|
||||
return '未知单位'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
name = str(value).replace("/", "_").replace("\\", "_").replace(":", "_").strip()
|
||||
if name.endswith("店"):
|
||||
name = name[:-1]
|
||||
return name
|
||||
|
||||
|
||||
def _norm_id(v):
|
||||
"""身份证号规范化:去空格、转大写;数值型转整数字符串。"""
|
||||
if v is None:
|
||||
return ''
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
v = int(v)
|
||||
return str(v).strip().upper()
|
||||
|
||||
|
||||
def _id_hit(cid, ref_ids):
|
||||
"""身份证匹配:规范化后精确匹配。"""
|
||||
return bool(cid) and cid in ref_ids
|
||||
|
||||
|
||||
def _latest_file(directory, pattern):
|
||||
"""目录内按模式取最新文件(排除 Excel 临时文件 ~$)。"""
|
||||
from glob import glob
|
||||
candidates = [p for p in glob(os.path.join(directory, pattern))
|
||||
if not os.path.basename(p).startswith("~$")]
|
||||
if not candidates:
|
||||
raise FileNotFoundError(f"在 {directory} 下未找到匹配 {pattern} 的文件")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def _pick_sheet(xl, exact_name, keyword, pattern=None):
|
||||
"""优先精确 sheet 名,其次按关键字/正则匹配;正则匹配时取年月最新。"""
|
||||
names = [n.strip() for n in xl.sheet_names]
|
||||
if exact_name in names:
|
||||
return exact_name
|
||||
if pattern:
|
||||
hits = [(int(m.group(1)), int(m.group(2)), n)
|
||||
for n in names if (m := re.match(pattern, n))]
|
||||
if hits:
|
||||
return max(hits)[2]
|
||||
for n in names:
|
||||
if keyword in n:
|
||||
return n
|
||||
raise ValueError(f"未找到目标 sheet(精确={exact_name},关键字={keyword}),"
|
||||
f"实际 sheets:{xl.sheet_names}")
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:源名单 / 台账读取、按业务口径筛选分组。"""
|
||||
@@ -0,0 +1,183 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:源名单(参保名单/停保名单)与社保户头管理台账的读取、筛选、取号。
|
||||
|
||||
统一承载 XQ0008(名单制作)与 XQ0014(系统办理/核查)共用的数据读取逻辑:
|
||||
- load_records(kind, operation_type, status_filter):读源名单并按业务口径筛选
|
||||
- load_units / load_check_tasks:按参保单位分组(办理/核查任务)
|
||||
- load_accounts:从台账取各单位政务平台账号
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def read_source(kind):
|
||||
"""定位并解析源名单,返回 (source_file, sheet_name)。
|
||||
|
||||
kind: 'add' 参保名单 sheet / 'stop' 停保名单 sheet(sheet 名年月动态,取最新)。
|
||||
"""
|
||||
source_file = config._latest_file(config.get_base_dir(), config.SOURCE_GLOB)
|
||||
now = datetime.now()
|
||||
xl = __import__('pandas').ExcelFile(source_file)
|
||||
if kind == 'add':
|
||||
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}{config.SHEET_KEY_ADD}",
|
||||
config.SHEET_KEY_ADD)
|
||||
else:
|
||||
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}{config.SHEET_KEY_STOP}",
|
||||
config.SHEET_KEY_STOP,
|
||||
pattern=r"(20\d{2})(1[0-2]|[1-9])停保名单")
|
||||
return source_file, sheet_name
|
||||
|
||||
|
||||
def load_records(kind, operation_type=None, status_filter="empty", exclude_ids=frozenset()):
|
||||
"""读源名单并按业务口径筛选,返回 DataFrame(表头第3行)。
|
||||
|
||||
- kind: 'add'(参保名单)/ 'stop'(停保名单)
|
||||
- operation_type: 增员时的参保类型('新参保'/'转移参保');减员忽略(固定两类都办)
|
||||
- status_filter: 'empty' 办理状态/办理停保为空;'待审核' 等于该值
|
||||
- exclude_ids: 排除的身份证号集合(上次已回写人员,防重复申报/核查)
|
||||
"""
|
||||
import pandas as pd
|
||||
source_file, sheet_name = read_source(kind)
|
||||
print_source = os.path.basename(source_file)
|
||||
# 对齐原版 dtype 保护:add 只指定身份证/电话两列为文本(18 位身份证防 float 丢精度),
|
||||
# stop 全列文本;dtype 字典引用 sheet 不存在的列不会报错
|
||||
dtype = {"身份证号码": str, "电话号码": str} if kind == 'add' else str
|
||||
df = pd.read_excel(source_file, sheet_name=sheet_name,
|
||||
header=config.SOURCE_HEADER_ROW - 1, dtype=dtype)
|
||||
|
||||
if kind == 'add':
|
||||
status_col = "办理状态"
|
||||
# 增员可传单值或元组(如 config.WEB_ADD_TYPES 两类都办)
|
||||
op_types = operation_type if isinstance(operation_type, (tuple, list, set)) \
|
||||
else (operation_type,)
|
||||
mask = (df["区域"].astype(str).str.strip() == config.TARGET_REGION)
|
||||
mask &= (df["参保类型"].astype(str).str.strip().isin(op_types))
|
||||
else:
|
||||
status_col = config.STOP_PROCESSED_COL
|
||||
mask = (df["区域"].astype(str).str.strip() == config.TARGET_REGION)
|
||||
mask &= (df["类型"].astype(str).str.strip().isin(config.STOP_TYPES))
|
||||
|
||||
if status_filter == "empty":
|
||||
st_text = df[status_col].astype(str).str.strip().str.lower()
|
||||
mask &= (df[status_col].isna() | st_text.isin(['', 'nan', 'none', 'nat']))
|
||||
else:
|
||||
mask &= (df[status_col].astype(str).str.strip() == status_filter)
|
||||
|
||||
sub = df[mask].copy()
|
||||
if exclude_ids and '身份证号码' in sub.columns:
|
||||
before = len(sub)
|
||||
ref = [config._norm_id(x) for x in exclude_ids]
|
||||
sub = sub[~sub['身份证号码'].map(lambda v: config._id_hit(config._norm_id(v), ref))]
|
||||
dropped = before - len(sub)
|
||||
if dropped:
|
||||
config.log(f" 已排除 {dropped} 行上次运行已回写的人员(防重复申报/核查)")
|
||||
return sub, source_file, sheet_name, status_col
|
||||
|
||||
|
||||
def load_units(kind, operation_type=None, status_filter="empty", exclude_ids=frozenset()):
|
||||
"""读取名单并筛选,返回 [(参保类型, 参保单位, 人数), ...](按类型+单位分组,名称排序)。
|
||||
|
||||
减员(kind='stop')参保类型恒为 None(停保/转移停保合并按单位分组)。
|
||||
"""
|
||||
sub, source_file, sheet_name, status_col = load_records(
|
||||
kind, operation_type, status_filter, exclude_ids)
|
||||
print_source = os.path.basename(source_file)
|
||||
if kind == 'add':
|
||||
desc = f"{config.TARGET_REGION} ∩ 参保类型∈{'/'.join(config.WEB_ADD_TYPES)}"
|
||||
else:
|
||||
desc = f"{config.TARGET_REGION} ∩ 类型∈{'/'.join(config.STOP_TYPES)}"
|
||||
config.log(f"源名单:{print_source}(sheet: {sheet_name})")
|
||||
if sub.empty:
|
||||
config.log(f"没有筛选到数据({desc} ∩ {status_col}={'空' if status_filter == 'empty' else status_filter})")
|
||||
return [], source_file, sheet_name
|
||||
if kind == 'add':
|
||||
sub["_type"] = sub["参保类型"].astype(str).str.strip()
|
||||
sub["_unit"] = sub["参保单位"].astype(str).str.strip()
|
||||
grouped = sub.groupby(["_type", "_unit"]).size()
|
||||
units = [(t, u, int(n)) for (t, u), n in grouped.items()]
|
||||
units.sort(key=lambda x: (x[0], x[1]))
|
||||
unit_desc = "个(类型+单位)分组"
|
||||
else:
|
||||
grouped = sub.groupby(sub["参保单位"].astype(str).str.strip()).size()
|
||||
units = [(None, u, int(n)) for u, n in grouped.items()]
|
||||
units.sort(key=lambda x: x[1])
|
||||
unit_desc = "个参保单位"
|
||||
config.log(f"筛选结果:共 {sum(n for _, _, n in units)} 人 / {len(units)} {unit_desc}")
|
||||
return units, source_file, sheet_name
|
||||
|
||||
|
||||
def load_check_tasks(kind, status_filter=config.CHECK_STATUS, exclude_ids=frozenset()):
|
||||
"""读取名单筛选 办理状态/办理停保=待审核 的行,分组。
|
||||
|
||||
增员按参保类型+单位分组(回盘文件按类型分目录),减员按单位分组。
|
||||
返回 [{unit, type, count, cids(set)}],供核查流程使用。
|
||||
"""
|
||||
operation_type = config.WEB_ADD_TYPES if kind == 'add' else None
|
||||
sub, source_file, sheet_name, status_col = load_records(
|
||||
kind, operation_type, status_filter, exclude_ids)
|
||||
print_source = os.path.basename(source_file)
|
||||
config.log(f"源名单:{print_source}(sheet: {sheet_name})")
|
||||
if sub.empty:
|
||||
config.log(f"没有筛选到数据({status_col}={status_filter})")
|
||||
return [], source_file, sheet_name
|
||||
sub = sub.copy()
|
||||
sub["_unit"] = sub["参保单位"].astype(str).str.strip()
|
||||
tasks = []
|
||||
if kind == 'add':
|
||||
sub["_type"] = sub["参保类型"].astype(str).str.strip()
|
||||
for (unit, t), g in sub.groupby(["_unit", "_type"]):
|
||||
cids = {config._norm_id(v) for v in g['身份证号码']}
|
||||
cids.discard('')
|
||||
tasks.append({"unit": unit, "type": t, "count": len(cids), "cids": cids})
|
||||
tasks.sort(key=lambda x: (x['unit'], x['type']))
|
||||
unit_desc = "个(类型+单位)分组"
|
||||
else:
|
||||
for unit, g in sub.groupby("_unit"):
|
||||
cids = {config._norm_id(v) for v in g['身份证号码']}
|
||||
cids.discard('')
|
||||
tasks.append({"unit": unit, "type": None, "count": len(cids), "cids": cids})
|
||||
tasks.sort(key=lambda x: x['unit'])
|
||||
unit_desc = "个参保单位"
|
||||
config.log(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / "
|
||||
f"{len(tasks)} {unit_desc}({status_col}={status_filter})")
|
||||
return tasks, source_file, sheet_name
|
||||
|
||||
|
||||
def load_accounts(unit_names):
|
||||
"""从台账「YYYY年M月缴费比例」sheet 取各单位账号。
|
||||
|
||||
返回 {参保单位: {"username":..., "username_src": "信用代码|平台用户名", "password":...}},
|
||||
取不到的单位不在返回值中(由预检统一报错)。
|
||||
"""
|
||||
import pandas as pd
|
||||
ledger_file = config._latest_file(config.get_ledger_dir(), config.LEDGER_GLOB)
|
||||
now = datetime.now()
|
||||
xl = pd.ExcelFile(ledger_file)
|
||||
sheet_name = config._pick_sheet(xl, f"{now.year}年{now.month}月缴费比例",
|
||||
config.SHEET_KEY_LEDGER,
|
||||
pattern=r"(20\d{2})年(1[0-2]|[1-9])月缴费比例")
|
||||
config.log(f"台账:{os.path.basename(ledger_file)}(sheet: {sheet_name})")
|
||||
|
||||
# 表头为 1-2 行合并结构:跳过前 2 行,B列(户头)非空即数据行
|
||||
df = pd.read_excel(ledger_file, sheet_name=sheet_name, header=None, skiprows=2)
|
||||
df = df[df[config.LEDGER_COL["户头"]].notna()].copy()
|
||||
for c in config.LEDGER_COL.values():
|
||||
df[c] = df[c].map(config._to_text)
|
||||
|
||||
pool = df[(df[config.LEDGER_COL["城市"]] == config.TARGET_REGION)
|
||||
& (df[config.LEDGER_COL["在用"]] == "是")]
|
||||
accounts = {}
|
||||
for name in unit_names:
|
||||
hit = pool[pool[config.LEDGER_COL["户头"]] == name]
|
||||
if hit.empty:
|
||||
continue # 预检阶段统一报「台账未匹配」
|
||||
row = hit.iloc[0]
|
||||
credit, plat_user, plat_pwd = (
|
||||
row[config.LEDGER_COL["信用代码"]], row[config.LEDGER_COL["平台用户名"]],
|
||||
row[config.LEDGER_COL["平台密码"]])
|
||||
# 用户名规则:I列信用代码优先,空则回退 K列平台用户名
|
||||
username, src = (credit, "信用代码") if credit else (plat_user, "平台用户名")
|
||||
accounts[name] = {"username": username, "username_src": src, "password": plat_pwd}
|
||||
return accounts
|
||||
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""名单回写(JSON 缓存防崩溃,运行结束统一写 Excel 一次)。
|
||||
|
||||
原影刀版 import_add/import_stop/check_review/check_review_stop 各自维护一套
|
||||
「内存累积 + JSON 缓存 + 结束统一落盘」机制,此处收敛为 Writeback 类:
|
||||
|
||||
- 每个账号办完:回写内容只追加进内存 + 写轻量 JSON 缓存(防中途崩溃丢失,不碰 Excel)
|
||||
- 运行结束 flush() 统一写 Excel 一次,保存成功校验后删除缓存
|
||||
- 下次启动若发现残留缓存(上次崩溃)先恢复回写再办新单
|
||||
- kind 区分回写列:add → 办理状态;stop → 办理停保;缓存文件名也分开,增/减互不干扰
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
class Writeback:
|
||||
"""按 kind(add/stop)绑定的名单回写器。"""
|
||||
|
||||
def __init__(self, kind):
|
||||
self.kind = kind
|
||||
cache_name = ("writeback_pending.json" if kind == "add"
|
||||
else "writeback_pending_stop.json")
|
||||
self._cache_path = os.path.join(config.CKPT_DIR, cache_name)
|
||||
self._status_col = "办理状态" if kind == "add" else config.STOP_PROCESSED_COL
|
||||
self._pending_status = {}
|
||||
self._pending_remark = {}
|
||||
self._source_file = None
|
||||
self._source_sheet = None
|
||||
|
||||
# ---------------- 源名单绑定(flush 依赖) ----------------
|
||||
def bind_source(self, source_file, source_sheet):
|
||||
self._source_file = source_file
|
||||
self._source_sheet = source_sheet
|
||||
|
||||
def has_pending(self):
|
||||
return bool(self._pending_status or self._pending_remark)
|
||||
|
||||
# ---------------- JSON 缓存 ----------------
|
||||
def _save_ckpt(self):
|
||||
"""把累积的回写内容写 JSON 缓存(临时文件+替换,避免写一半损坏)。"""
|
||||
data = [{"id": cid, "status": self._pending_status.get(cid, ""),
|
||||
"remark": self._pending_remark.get(cid, "")}
|
||||
for cid in dict.fromkeys(list(self._pending_status)
|
||||
+ list(self._pending_remark))]
|
||||
os.makedirs(config.CKPT_DIR, exist_ok=True)
|
||||
tmp = self._cache_path + ".tmp"
|
||||
with open(tmp, "w", encoding="utf-8") as f:
|
||||
json.dump(data, f, ensure_ascii=False, indent=1)
|
||||
os.replace(tmp, self._cache_path)
|
||||
|
||||
def load_ckpt(self):
|
||||
"""启动时恢复上次未回写的累积内容(崩溃恢复)。返回已回写人员的身份证号集合。"""
|
||||
recovered = set()
|
||||
if not os.path.isfile(self._cache_path):
|
||||
return recovered
|
||||
try:
|
||||
with open(self._cache_path, "r", encoding="utf-8") as f:
|
||||
for it in json.load(f):
|
||||
cid = it.get("id")
|
||||
if it.get("status"):
|
||||
self._pending_status[cid] = it["status"]
|
||||
if it.get("remark"):
|
||||
self._pending_remark[cid] = it["remark"]
|
||||
if cid:
|
||||
recovered.add(cid)
|
||||
except Exception as e:
|
||||
config.log(f" 恢复回写缓存失败:{e}")
|
||||
return recovered
|
||||
|
||||
# ---------------- 累积 ----------------
|
||||
def writeback_source(self, status_map, remark_map):
|
||||
"""按身份证号码聚合回写内容(内存 + JSON 缓存,不碰 Excel)。"""
|
||||
self._pending_status.update(status_map or {})
|
||||
self._pending_remark.update(remark_map or {})
|
||||
try:
|
||||
self._save_ckpt()
|
||||
except Exception as e:
|
||||
config.log(f" 回写缓存写入失败(不影响办理,仅崩溃后需人工补状态):{e}")
|
||||
|
||||
# ---------------- 统一落盘 ----------------
|
||||
def flush(self):
|
||||
"""把累积的回写内容统一写回源名单 Excel(openpyxl 直改原文件),
|
||||
保存成功(校验)后删除 JSON 缓存。保存失败则缓存保留,下次启动自动恢复。"""
|
||||
if not self.has_pending():
|
||||
return 0
|
||||
if not self._source_file:
|
||||
raise RuntimeError("无源名单文件记录,无法回写")
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(self._source_file)
|
||||
ws = wb[self._source_sheet]
|
||||
# 表头第3行定位列号
|
||||
hdr = {}
|
||||
for c in ws[config.SOURCE_HEADER_ROW]:
|
||||
if c.value is not None:
|
||||
hdr[str(c.value).strip()] = c.column
|
||||
col_id = hdr.get('身份证号码')
|
||||
col_status = hdr.get(self._status_col)
|
||||
col_remark = hdr.get('备注')
|
||||
if not col_id or not col_status:
|
||||
raise RuntimeError(f"源名单缺少身份证号码/{self._status_col}列,无法回写")
|
||||
changed = 0
|
||||
pending_ids = set(self._pending_status) | set(self._pending_remark)
|
||||
ref = [config._norm_id(x) for x in pending_ids]
|
||||
for row in ws.iter_rows(min_row=config.SOURCE_HEADER_ROW + 1):
|
||||
cid = config._norm_id(row[col_id - 1].value)
|
||||
if cid and config._id_hit(cid, ref):
|
||||
r = row[0].row
|
||||
if cid in self._pending_status:
|
||||
ws.cell(row=r, column=col_status, value=self._pending_status[cid])
|
||||
if cid in self._pending_remark and col_remark:
|
||||
# 备注追加不覆盖:新备注换行追加(已存在则不重复追加)
|
||||
cell = ws.cell(row=r, column=col_remark)
|
||||
old = str(cell.value or '').strip()
|
||||
new = str(self._pending_remark[cid]).strip()
|
||||
if new not in old:
|
||||
cell.value = f"{old}\n{new}" if old else new
|
||||
changed += 1
|
||||
try:
|
||||
wb.save(self._source_file)
|
||||
except PermissionError:
|
||||
# 缓存保留,下次启动自动恢复回写
|
||||
raise RuntimeError(f"源名单文件被占用(请关闭 Excel 后重跑),回写未保存")
|
||||
self._pending_status.clear()
|
||||
self._pending_remark.clear()
|
||||
if os.path.isfile(self._cache_path):
|
||||
os.unlink(self._cache_path)
|
||||
config.log(f" 源名单回写完成:更新 {changed} 行 → "
|
||||
f"{os.path.basename(self._source_file)}(缓存已清除)")
|
||||
config.log(" 注意:openpyxl 保存会清掉公式缓存(如「区域」列 XLOOKUP),"
|
||||
"下次运行前请先用 Excel 打开并保存一次该名单以重算公式")
|
||||
return changed
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""业务逻辑层(聚合子包)。"""
|
||||
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""目录预检:校验 base_dir(统一目录)是否满足插件各阶段需求。
|
||||
|
||||
用户设置资料根目录后,可先运行「目录预检」阶段确认目录结构齐备(真实布局):
|
||||
- 根目录:源名单《*社保变更及增减名单*.xlsx》、员工花名册.xlsx
|
||||
- 台账目录(默认根目录,可单独设置):社保户头管理台账*.xlsx(含缴费比例 sheet)
|
||||
- 社保增减名单制作/模板/:增员模版.xls、减员模版.xls
|
||||
- 告知书下发/模板/:三类告知书模板
|
||||
(名单制作输出/、回盘打印/、告知书下发/输出/ 由各阶段运行时自动创建,不预检)
|
||||
输出逐项 {名称, 是否就绪, 说明},未就绪项汇总列出,供用户补齐后重跑。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _current_month_file(dir_path, pattern):
|
||||
"""目录内匹配 pattern 且文件名月份=当月的文件(告知书数据源要求当月)。"""
|
||||
if not os.path.isdir(dir_path):
|
||||
return None, "目录不存在"
|
||||
found = [n for n in os.listdir(dir_path)
|
||||
if n.lower().endswith(".xlsx") and not n.startswith("~$")
|
||||
and re.match(pattern.replace("*", ".*"), n)]
|
||||
if not found:
|
||||
return None, f"未找到匹配 {pattern} 的 xlsx"
|
||||
now = datetime.now()
|
||||
for name in found:
|
||||
m = re.search(r"(20\d{2})年(\d{1,2})月", name) or re.search(r"(20\d{2})(\d{2})", name)
|
||||
if m and (int(m.group(1)), int(m.group(2))) == (now.year, now.month):
|
||||
return os.path.join(dir_path, name), "当月文件"
|
||||
return None, f"均为历史月份:{sorted(found)[:5]}"
|
||||
|
||||
|
||||
def _check_sheets(excel_path, required):
|
||||
"""校验 xlsx 是否包含所有必需 sheet(关键字匹配)。返回 (ok, 缺失列表)。"""
|
||||
try:
|
||||
import pandas as pd
|
||||
xl = pd.ExcelFile(excel_path)
|
||||
names = [n.strip() for n in xl.sheet_names]
|
||||
missing = [kw for kw in required
|
||||
if not any(kw in n for n in names)]
|
||||
return (not missing), missing
|
||||
except Exception as e:
|
||||
return False, [f"读取失败:{e}"]
|
||||
|
||||
|
||||
def check_directory():
|
||||
"""执行目录预检。返回 dict {ok, missing, checks}。
|
||||
|
||||
checks: [{name, ok, detail}] 逐项清单(缺失/异常项 ok=False)。
|
||||
"""
|
||||
base = config.get_base_dir()
|
||||
ledger = config.get_ledger_dir()
|
||||
checks = []
|
||||
|
||||
def add(name, ok, detail):
|
||||
checks.append({"name": name, "ok": bool(ok), "detail": detail})
|
||||
|
||||
# ---- 0. 目录本身 ----
|
||||
base_ok = os.path.isdir(base)
|
||||
add("资料根目录", base_ok, base if base_ok else f"目录不存在:{base}")
|
||||
|
||||
# ---- 1. 名单制作 / 系统办理:源名单 ----
|
||||
src_file = None
|
||||
candidates = []
|
||||
if base_ok:
|
||||
candidates = [p for p in os.listdir(base)
|
||||
if p.lower().endswith(".xlsx") and not p.startswith("~$")
|
||||
and config.SOURCE_KEYWORD in p]
|
||||
add(f"源名单(*{config.SOURCE_KEYWORD}*.xlsx)", bool(candidates),
|
||||
"、".join(sorted(candidates)[:3]) or "未找到,请放入当月《社保变更及增减名单》")
|
||||
if candidates:
|
||||
src_file = os.path.join(base, max(
|
||||
candidates, key=lambda n: os.path.getmtime(os.path.join(base, n))))
|
||||
|
||||
# ---- 2. 告知书数据源:当月文件 ----
|
||||
if base_ok:
|
||||
cur, note = _current_month_file(base, f"*{config.SOURCE_KEYWORD}*")
|
||||
else:
|
||||
cur, note = None, "根目录不存在"
|
||||
add("源名单(当月文件,告知书用)", cur is not None, note)
|
||||
|
||||
# ---- 3. 源名单关键 sheet ----
|
||||
if src_file:
|
||||
ok, missing = _check_sheets(src_file, ["参保名单", "停保名单"])
|
||||
add("源名单关键 sheet(参保名单/停保名单)", ok, "缺失:" + "、".join(missing) if missing else "齐备")
|
||||
else:
|
||||
add("源名单关键 sheet(参保名单/停保名单)", False, "源名单缺失,跳过校验")
|
||||
|
||||
# ---- 4. 名单制作:模板 + 输出目录 ----
|
||||
tpl_dir = config.roster_template_dir()
|
||||
add_exact = os.path.join(tpl_dir, config.TEMPLATE_ADD)
|
||||
add_hit = (os.path.isfile(add_exact)
|
||||
or any("增员模版" in f for f in os.listdir(tpl_dir)) if os.path.isdir(tpl_dir) else False)
|
||||
add("增员模版(社保增减名单制作/模板/增员模版.xls)", add_hit,
|
||||
f"{tpl_dir}\\{config.TEMPLATE_ADD}" if base_ok else "根目录不存在")
|
||||
stop_exact = os.path.join(tpl_dir, config.TEMPLATE_STOP)
|
||||
stop_hit = (os.path.isfile(stop_exact)
|
||||
or any("减员模版" in f for f in os.listdir(tpl_dir)) if os.path.isdir(tpl_dir) else False)
|
||||
add("减员模版(社保增减名单制作/模板/减员模版.xls)", stop_hit,
|
||||
f"{tpl_dir}\\{config.TEMPLATE_STOP}" if base_ok else "根目录不存在")
|
||||
|
||||
# ---- 5. 台账(含缴费比例 sheet) ----
|
||||
ledger_ok = os.path.isdir(ledger)
|
||||
ledger_file = None
|
||||
if ledger_ok:
|
||||
cand = [p for p in os.listdir(ledger)
|
||||
if p.lower().endswith(".xlsx") and "社保户头管理台账" in p and not p.startswith("~$")]
|
||||
if cand:
|
||||
ledger_file = os.path.join(ledger, max(cand, key=lambda n: os.path.getmtime(os.path.join(ledger, n))))
|
||||
add("社保户头管理台账", ledger_file is not None,
|
||||
os.path.basename(ledger_file) if ledger_file else f"未找到(目录:{ledger})")
|
||||
if ledger_file:
|
||||
ok, missing = _check_sheets(ledger_file, ["缴费比例"])
|
||||
add("台账「缴费比例」sheet", ok, "缺失:" + "、".join(missing) if missing else "齐备")
|
||||
else:
|
||||
add("台账「缴费比例」sheet", False, "台账缺失,跳过校验")
|
||||
|
||||
# ---- 6. 告知书:花名册 + 三类模板 ----
|
||||
roster = os.path.join(base, "员工花名册.xlsx")
|
||||
add("员工花名册(告知书二级部门/接收人)", base_ok and os.path.isfile(roster),
|
||||
roster if base_ok else "根目录不存在")
|
||||
tpl_dir_notice = config.notice_template_dir()
|
||||
tpl_dir_ok = os.path.isdir(tpl_dir_notice)
|
||||
for key, tpl in config.NOTICE_TEMPLATES.items():
|
||||
p = os.path.join(tpl_dir_notice, tpl["file"])
|
||||
add(f"告知书模板[{key}](告知书下发/模板/{tpl['file']})", tpl_dir_ok and os.path.isfile(p),
|
||||
p if tpl_dir_ok else f"模板目录不存在:{tpl_dir_notice}")
|
||||
|
||||
missing = [c for c in checks if not c["ok"]]
|
||||
return {"ok": not missing, "missing": len(missing), "checks": checks}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,366 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""OA 工作沟通推送(work_communication.py 移植,适配插件底座)。
|
||||
|
||||
原影刀版用 DrissionPage SessionPage + 读共享 oa_cookies.json;插件版改为:
|
||||
- 登录态由底座注入(config.get_oa_session(),即 ctx.get_session("oa") 返回的
|
||||
requests.Session,已带 OA cookies),不读 cookie 文件
|
||||
- 请求直接用 requests.Session API(resp = session.get/post(...))
|
||||
|
||||
流程:解析接收人(工号/姓名 → 人员ID)→ 上传附件(getuserkey→二进制→submit绑定)→
|
||||
提交工作沟通(取新建页 fdId + 通知方式随机字段 → POST method=save 保存)。
|
||||
push_messages(messages) 逐条推送,返回 {success, message, doc_id, results}。
|
||||
"""
|
||||
import base64
|
||||
import mimetypes
|
||||
import os
|
||||
import re
|
||||
import time
|
||||
import xml.etree.ElementTree as ET
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
# 附件二进制上传时的请求头(Referer 指向 OA 根地址,避免被服务端拦截)
|
||||
_DEFAULT_HEADERS = {
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36",
|
||||
"Referer": f"{config.OA_BASE_URL}/",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
}
|
||||
|
||||
|
||||
class OALoginExpiredError(Exception):
|
||||
"""OA 登录态失效:接口返回登录页等非 JSON 内容。"""
|
||||
|
||||
|
||||
# ==================== 登录态(底座注入的 requests.Session) ====================
|
||||
def get_oa_session():
|
||||
"""取底座注入的 OA requests.Session;未登录时抛友好错误。"""
|
||||
session = config.get_oa_session()
|
||||
if session is None:
|
||||
raise RuntimeError("未注入 OA 登录态,请先在工作台(壳子)登录 OA 系统再运行本阶段")
|
||||
return session
|
||||
|
||||
|
||||
def is_session_valid(session):
|
||||
"""调轻量接口 sumTodoCount 判断 OA 会话是否有效。"""
|
||||
try:
|
||||
resp = session.get(config.TODO_COUNT_URL,
|
||||
params={"method": "sumTodoCount"}, timeout=10)
|
||||
if resp is None or resp.status_code != 200:
|
||||
return False
|
||||
text = resp.text or ""
|
||||
return bool(text) and text.lstrip().startswith(("{", "["))
|
||||
except Exception as e:
|
||||
config.log(f"OA 会话校验异常:{e}", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 通用响应校验 ====================
|
||||
def _check_response(resp, label):
|
||||
"""校验响应:存在性 / 状态码 / 登录态。返回 resp。"""
|
||||
if resp is None:
|
||||
raise RuntimeError(f"{label}请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"{label}接口状态码异常: {resp.status_code}")
|
||||
text = resp.text or ""
|
||||
if "login.jsp" in text or "j_username" in text:
|
||||
raise OALoginExpiredError(f"{label}接口返回登录页,OA 登录态已失效")
|
||||
return resp
|
||||
|
||||
|
||||
def oa_request_json(session, method, url, params, label, timeout=20, headers=None):
|
||||
"""通用「发送请求 + 校验响应」:发出请求 → 校验 → 返回 JSON。"""
|
||||
resp = (session.get(url, params=params, timeout=timeout, headers=headers)
|
||||
if method.upper() == "GET"
|
||||
else session.post(url, data=params, timeout=timeout, headers=headers))
|
||||
resp = _check_response(resp, label)
|
||||
text = resp.text or ""
|
||||
try:
|
||||
return resp.json()
|
||||
except Exception:
|
||||
raise RuntimeError(f"{label}接口返回非 JSON 数据(状态码 {resp.status_code}): {text[:200]}")
|
||||
|
||||
|
||||
# ==================== 人员搜索 ====================
|
||||
def search_person(session, keyword, org_type="15"):
|
||||
"""按工号或姓名搜索人员,返回 (person_id, person_name);未找到返回 None。"""
|
||||
params = {
|
||||
"s_bean": "organizationDialogSearch",
|
||||
"orgType": org_type,
|
||||
"deptLimit": "",
|
||||
"isExternal": "",
|
||||
"key": keyword,
|
||||
"s_ajax": "true",
|
||||
}
|
||||
resp = _check_response(session.get(config.PERSON_SEARCH_URL, params=params, timeout=20),
|
||||
"人员搜索")
|
||||
try:
|
||||
root = ET.fromstring(resp.text)
|
||||
except ET.ParseError as e:
|
||||
config.log(f"人员搜索[{keyword}]响应解析失败: {e}", "WARN")
|
||||
return None
|
||||
matches = []
|
||||
for node in root.iter("data"):
|
||||
pid = node.get("id")
|
||||
pname = node.get("name")
|
||||
if pid and pname:
|
||||
matches.append((pid, pname))
|
||||
if not matches:
|
||||
config.log(f"未搜索到人员: {keyword}", "WARN")
|
||||
return None
|
||||
for pid, pname in matches:
|
||||
if keyword in (pid, pname):
|
||||
config.log(f"搜索到人员: {pname} (ID: {pid})")
|
||||
return (pid, pname)
|
||||
if len(matches) > 1:
|
||||
config.log(f"关键字[{keyword}]模糊匹配到 {len(matches)} 人,默认取第一个: {matches[0]}", "WARN")
|
||||
pid, pname = matches[0]
|
||||
config.log(f"搜索到人员: {pname} (ID: {pid})")
|
||||
return (pid, pname)
|
||||
|
||||
|
||||
# ==================== 附件上传 ====================
|
||||
def upload_attachment(session, file_path):
|
||||
"""上传单个附件,返回最终附件 ID(attid)。getuserkey → 二进制上传 → submit 绑定。"""
|
||||
file_path = os.path.abspath(file_path)
|
||||
if not os.path.exists(file_path):
|
||||
raise FileNotFoundError(f"附件文件不存在: {file_path}")
|
||||
file_name = os.path.basename(file_path)
|
||||
file_size = str(os.path.getsize(file_path))
|
||||
file_type = mimetypes.guess_type(file_name)[0] or "application/octet-stream"
|
||||
last_modified = time.strftime(
|
||||
"%a %b %d %Y %H:%M:%S GMT+0800", time.localtime(os.path.getmtime(file_path)))
|
||||
fd_sign = base64.b64encode(file_name.encode("utf-8")).decode("utf-8")
|
||||
fd_sign = fd_sign.replace("+", "").replace("/", "").replace("=", "")
|
||||
|
||||
# 1) 获取 userkey
|
||||
resp1 = oa_request_json(session, "GET", config.ATT_UPLOAD_URL, {
|
||||
"method": "handleAttUpload", "gettype": "getuserkey", "format": "json",
|
||||
"filesize": file_size, "md5": "", "fileName": file_name,
|
||||
"isSupportDirect": "false", "s_ajax": "true",
|
||||
}, "附件上传-获取userkey", headers=_DEFAULT_HEADERS)
|
||||
userkey = resp1.get("token", {}).get("header", {}).get("userkey")
|
||||
if not userkey:
|
||||
raise RuntimeError(f"获取 userkey 失败: {resp1}")
|
||||
config.log(" 1. 获取 userkey 成功")
|
||||
|
||||
# 2) 上传二进制
|
||||
uploader_url = f"{config.ATT_UPLOADER_URL}?gettype=upload&format=json&userkey={userkey}"
|
||||
# 底座注入的共享会话默认带 Content-Type: application/x-www-form-urlencoded,
|
||||
# 会导致 requests 在 files 上传时不再自动生成 multipart/form-data 边界头,
|
||||
# 服务端(Apache Commons FileUpload)以 InvalidContentTypeException 拒绝。
|
||||
# 上传前临时清除该默认头,让 requests 生成正确的 multipart 请求,随后恢复。
|
||||
saved_ct = session.headers.pop("Content-Type", None)
|
||||
try:
|
||||
with open(file_path, "rb") as f:
|
||||
files = {"file": (file_name, f, file_type)}
|
||||
data2 = {"id": "WU_FILE_0", "name": file_name, "type": file_type,
|
||||
"lastModifiedDate": last_modified, "size": file_size}
|
||||
resp2 = _check_response(session.post(uploader_url, data=data2, files=files,
|
||||
timeout=60, headers=_DEFAULT_HEADERS),
|
||||
"附件上传-二进制")
|
||||
finally:
|
||||
if saved_ct is not None:
|
||||
session.headers["Content-Type"] = saved_ct
|
||||
try:
|
||||
filekey = resp2.json().get("filekey")
|
||||
except Exception:
|
||||
filekey = None
|
||||
if not filekey:
|
||||
raise RuntimeError(f"二进制上传失败: {resp2.text[:200]}")
|
||||
config.log(f" 2. 二进制上传成功, filekey: {filekey[:16]}...")
|
||||
|
||||
# 3) submit 绑定附件
|
||||
resp3 = oa_request_json(session, "GET", config.ATT_UPLOAD_URL, {
|
||||
"method": "handleAttUpload", "gettype": "submit", "format": "json",
|
||||
"filekey": filekey, "filename": file_name, "fdKey": "attachment",
|
||||
"fdModelName": config.KM_COLLABORATE_MODEL, "fdAttType": "byte",
|
||||
"width": "null", "height": "null", "proportion": "true",
|
||||
"fdSign": fd_sign, "s_ajax": "true",
|
||||
}, "附件上传-提交绑定", headers=_DEFAULT_HEADERS)
|
||||
attid = resp3.get("attid")
|
||||
if str(resp3.get("status")) != "1" or not attid:
|
||||
raise RuntimeError(f"提交绑定附件失败: {resp3}")
|
||||
config.log(f" 3. 提交绑定成功, attid: {attid}")
|
||||
return attid
|
||||
|
||||
|
||||
# ==================== 工作沟通提交 ====================
|
||||
def _encode_fd_content(content):
|
||||
"""把沟通内容编码为 OA 要求的 fdContent 格式:固定前缀 + {base64(HTML)}。"""
|
||||
return config.FD_CONTENT_PREFIX + "{" + \
|
||||
base64.b64encode(content.encode("utf-8")).decode("utf-8") + "}"
|
||||
|
||||
|
||||
def _get_add_page_fd_info(session):
|
||||
"""打开新建工作沟通页,解析出草稿 fdId、通知方式随机字段名、当前用户 ID。"""
|
||||
resp = _check_response(session.get(config.WORK_COMMUNICATION_ADD_URL, timeout=20),
|
||||
"新建工作沟通-取页面")
|
||||
html = resp.text or ""
|
||||
m = re.search(r'name="fdId"\s+value="([^"]*)"', html)
|
||||
fd_id = m.group(1) if m else ""
|
||||
m2 = re.search(r'name="(__notify_type_[a-f0-9]+)"', html)
|
||||
notify_field = m2.group(1) if m2 else ""
|
||||
m3 = re.search(r'name="docCreatorId"\s+value="([^"]*)"', html)
|
||||
creator_id = m3.group(1) if m3 else ""
|
||||
if not fd_id:
|
||||
raise RuntimeError("新建工作沟通页面解析失败:未找到 fdId")
|
||||
config.log(f"获取新建草稿 fdId: {fd_id}, 通知方式字段: {notify_field}, "
|
||||
f"页面当前用户ID: {creator_id or '无'}")
|
||||
return fd_id, notify_field, creator_id
|
||||
|
||||
|
||||
def submit_work_communication(session, receiver_ids, receiver_names, subject, content,
|
||||
attachment_ids=None, creator_id=None,
|
||||
category_id=config.FD_CATEGORY_DEFAULT):
|
||||
"""提交工作沟通(新建),成功返回沟通文档 ID(fdId)。多值分隔符用「;」。"""
|
||||
if category_id in config.FD_CATEGORY_MAP:
|
||||
category_id = config.FD_CATEGORY_MAP[category_id]
|
||||
elif not category_id:
|
||||
category_id = config.FD_CATEGORY_DEFAULT
|
||||
|
||||
receiver_ids_str = ";".join(receiver_ids) if isinstance(receiver_ids, list) else receiver_ids
|
||||
receiver_names_str = ";".join(receiver_names) if isinstance(receiver_names, list) else receiver_names
|
||||
if isinstance(attachment_ids, list):
|
||||
attachment_ids_str = ";".join(attachment_ids)
|
||||
else:
|
||||
attachment_ids_str = attachment_ids or ""
|
||||
|
||||
fd_id, notify_field, page_creator_id = _get_add_page_fd_info(session)
|
||||
creator_id = creator_id or page_creator_id
|
||||
if not creator_id:
|
||||
raise ValueError("docCreatorId(creator_id) 必填,且无法从新建页自动提取,请显式传入")
|
||||
|
||||
data = {
|
||||
"fdId": fd_id,
|
||||
"fdNumber": "",
|
||||
"participantIds": receiver_ids_str,
|
||||
"participantNames": receiver_names_str,
|
||||
"docSubject": subject,
|
||||
"fdIsPriority": "",
|
||||
"fdCategoryId": category_id,
|
||||
"fdContent": _encode_fd_content(content),
|
||||
"attachmentForms.attachment.fdModelId": "",
|
||||
"attachmentForms.attachment.extParam": "",
|
||||
"attachmentForms.attachment.fdModelName": config.KM_COLLABORATE_MODEL,
|
||||
"attachmentForms.attachment.fdKey": "attachment",
|
||||
"attachmentForms.attachment.fdAttType": "",
|
||||
"attachmentForms.attachment.fdMulti": "",
|
||||
"attachmentForms.attachment.deletedAttachmentIds": "",
|
||||
"attachmentForms.attachment.attachmentIds": attachment_ids_str,
|
||||
"__landray_fileattachment": "",
|
||||
"fdNotifyType": "todo",
|
||||
"__notify_type_placeholder": "todo",
|
||||
"_fdPartnerOperating": "true",
|
||||
"fdPartnerOperating": "true",
|
||||
"fdIsOnlyView": "false",
|
||||
"fdIsReminders": "false",
|
||||
"fdRemindersDay_hidden": "",
|
||||
"fdRemindersDay": "2",
|
||||
"docCreatorId": creator_id,
|
||||
}
|
||||
if notify_field:
|
||||
data[notify_field] = data.pop("__notify_type_placeholder")
|
||||
else:
|
||||
data.pop("__notify_type_placeholder", None)
|
||||
|
||||
resp = _check_response(session.post(config.KM_COLLABORATE_SAVE_URL,
|
||||
params={"method": "save", "s_seq": "1"},
|
||||
data=data, timeout=30),
|
||||
"工作沟通提交")
|
||||
text = resp.text or ""
|
||||
if "您的操作已成功" in text:
|
||||
config.log(f"工作沟通发送成功, 文档ID: {fd_id}")
|
||||
return fd_id
|
||||
raise RuntimeError(f"提交工作沟通失败: {text[:200]}")
|
||||
|
||||
|
||||
# ==================== 一键推送入口 ====================
|
||||
def _to_list(value):
|
||||
"""把单个字符串或列表统一成列表。"""
|
||||
if not value:
|
||||
return []
|
||||
return [value] if isinstance(value, str) else list(value)
|
||||
|
||||
|
||||
def send_work_communication(receiver_keywords, subject, content,
|
||||
attachment_paths=None, creator_id=None, category=None):
|
||||
"""发送单条工作沟通:解析接收人 → 上传附件 → 提交。返回沟通文档 ID。"""
|
||||
if not subject or not subject.strip():
|
||||
raise ValueError("subject(标题) 不能为空")
|
||||
if not content or not content.strip():
|
||||
raise ValueError("content(内容) 不能为空")
|
||||
session = get_oa_session()
|
||||
if not is_session_valid(session):
|
||||
raise OALoginExpiredError("OA 登录态已失效,请重新在工作台登录 OA")
|
||||
|
||||
# 1. 解析接收人
|
||||
receiver_ids, receiver_names, unresolved = [], [], []
|
||||
for kw in _to_list(receiver_keywords):
|
||||
kw = str(kw).strip()
|
||||
if not kw:
|
||||
continue
|
||||
result = search_person(session, kw)
|
||||
if result:
|
||||
pid, pname = result
|
||||
receiver_ids.append(pid)
|
||||
receiver_names.append(pname)
|
||||
config.log(f"接收人[{kw}] -> {pname} (ID: {pid})")
|
||||
else:
|
||||
unresolved.append(kw)
|
||||
if not receiver_ids:
|
||||
raise RuntimeError("未解析到任何接收人,请检查传入的工号/姓名")
|
||||
if unresolved:
|
||||
raise RuntimeError(f"以下接收人解析失败,已中止发送: {', '.join(unresolved)}")
|
||||
|
||||
# 2. 上传附件(任一失败即整体失败)
|
||||
attachment_ids = []
|
||||
for path in _to_list(attachment_paths):
|
||||
attid = upload_attachment(session, path)
|
||||
attachment_ids.append(attid)
|
||||
config.log(f"附件[{path}] -> attid: {attid}")
|
||||
|
||||
# 3. 提交沟通
|
||||
return submit_work_communication(
|
||||
session=session, receiver_ids=receiver_ids, receiver_names=receiver_names,
|
||||
subject=subject, content=content, attachment_ids=attachment_ids or None,
|
||||
creator_id=creator_id, category_id=category)
|
||||
|
||||
|
||||
def _send_wrapped(receiver_keywords, subject, content, attachment_paths="",
|
||||
creator_id="", category="工作安排"):
|
||||
"""单条工作沟通推送(捕获异常,返回 result dict)。"""
|
||||
try:
|
||||
doc_id = send_work_communication(
|
||||
receiver_keywords=receiver_keywords, subject=subject, content=content,
|
||||
attachment_paths=attachment_paths or None, creator_id=creator_id or None,
|
||||
category=category)
|
||||
return {"success": True, "message": f"工作沟通发送成功,文档ID: {doc_id}", "doc_id": doc_id}
|
||||
except Exception as e:
|
||||
config.log(f"工作沟通推送失败: {e}", "ERROR")
|
||||
return {"success": False, "message": f"工作沟通推送失败: {e}", "doc_id": ""}
|
||||
|
||||
|
||||
def push_messages(messages):
|
||||
"""逐条推送工作沟通(messages 结构同告知书模块产出的 OA 推送数据)。
|
||||
messages 每条含 {receivers, subject, content, attachment_paths, category}。
|
||||
返回 {success, message, doc_id, results}。"""
|
||||
results = []
|
||||
for i, msg in enumerate(messages or [], 1):
|
||||
r = _send_wrapped(
|
||||
receiver_keywords=msg.get("receivers", []),
|
||||
subject=msg.get("subject", ""),
|
||||
content=msg.get("content", ""),
|
||||
attachment_paths=msg.get("attachment_paths", ""),
|
||||
creator_id=msg.get("creator_id", ""),
|
||||
category=msg.get("category", "工作安排"))
|
||||
results.append(r)
|
||||
config.log(f"[{i}/{len(messages or [])}] {r.get('message')}")
|
||||
ok = sum(1 for r in results if r.get("success"))
|
||||
return {
|
||||
"success": ok == len(results),
|
||||
"message": f"共推送 {len(results)} 条,成功 {ok} 条",
|
||||
"doc_id": ",".join(r.get("doc_id", "") for r in results if r.get("doc_id")),
|
||||
"results": results,
|
||||
}
|
||||
@@ -0,0 +1,285 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0008 重庆社保增减员导入名单制作(generate_add.py / generate_stop.py 移植)。
|
||||
|
||||
- make_add_lists():按参保类型(转移参保 / 新参保)分组生成《XX增员导入名单.xls》,
|
||||
分别输出到 转移参保-增员 / 新参保-增员 子目录(xlrd 读取 + xlutils 复制模板保留下拉字典);
|
||||
日期规则:首次参加工作日期=本月1号、个人身份=24.工人、工伤参保时间=当日、其余参保时间=本月1号。
|
||||
- make_stop_lists():按参保单位生成《XX减员导入名单.xls》到 停保-减员 子目录;
|
||||
减少时间=离职日期(当月)否则=当天、减少原因=在职人员主动解除劳动合同、
|
||||
五个险种减少标志=1 减少、失业原因=3 劳动者自愿辞职。
|
||||
"""
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from ..data import source_reader
|
||||
|
||||
|
||||
# ==================== 翻译映射 ====================
|
||||
def _translate_education(val):
|
||||
if val is None:
|
||||
return '90.其他'
|
||||
try:
|
||||
import pandas as pd
|
||||
if pd.isna(val):
|
||||
return '90.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return config.EDU_MAP.get(str(val).strip(), '90.其他')
|
||||
|
||||
|
||||
def _translate_nation(val):
|
||||
if val is None:
|
||||
return '99.其他'
|
||||
try:
|
||||
import pandas as pd
|
||||
if pd.isna(val):
|
||||
return '99.其他'
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return config.NATION_MAP.get(str(val).strip(), '99.其他')
|
||||
|
||||
|
||||
def _translate_residence(val):
|
||||
if val is None:
|
||||
return ''
|
||||
try:
|
||||
import pandas as pd
|
||||
if pd.isna(val):
|
||||
return ''
|
||||
except (TypeError, ValueError):
|
||||
pass
|
||||
return config.RESIDENCE_MAP.get(str(val).strip(), '')
|
||||
|
||||
|
||||
# ==================== 增员名单制作 ====================
|
||||
def _write_template_add(template_file, output_path, unit_no, unit_name, records):
|
||||
"""复制《增员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。
|
||||
|
||||
xlrd 读取(formatting_info 保留样式)+ xlutils.copy 复制,保留 Sheet2 下拉字典;
|
||||
B1=社保号,D1=参保单位全称;数据从模板第4行起,按 TPL_COLS_ADD 顺序写入 B~U 列;
|
||||
日期列以 yyyy/m/d 文本写入(工伤=当日,其余已填本月1日);多余示例行清空。
|
||||
"""
|
||||
import xlrd
|
||||
from xlutils.copy import copy as xl_copy
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1 社保号
|
||||
ws.write(0, 3, unit_name) # D1 参保单位全称
|
||||
for i, rec in enumerate(records):
|
||||
r = config.TPL_DATA_START_ROW - 1 + i # 0-based:模板第4行 → index 3
|
||||
for c, col in enumerate(config.TPL_COLS_ADD):
|
||||
val = rec.get(col)
|
||||
if col in config.DATE_COLS_ADD and val is not None:
|
||||
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}")
|
||||
else:
|
||||
ws.write(r, c + 1, config._clean_value(val))
|
||||
for r in range(config.TPL_DATA_START_ROW - 1 + len(records), orig_rows):
|
||||
for c in range(1, len(config.TPL_COLS_ADD) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
def _find_template_add():
|
||||
"""定位《增员模版.xls》(社保增减名单制作/模板 下,优先精确名,其次按 *增员模版*.xls)。"""
|
||||
from glob import glob
|
||||
tpl_dir = config.roster_template_dir()
|
||||
exact = os.path.join(tpl_dir, config.TEMPLATE_ADD)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
candidates = glob(os.path.join(tpl_dir, "*增员模版*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {tpl_dir} 下未找到《{config.TEMPLATE_ADD}》,请先准备增员导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def _add_output_dir(operation_type):
|
||||
"""按参保类型取输出目录(社保增减名单制作/新参保-增员 或 转移参保-增员)。"""
|
||||
sub = {"新参保": config.OUTPUT_DIR_ADD_NEW,
|
||||
"转移参保": config.OUTPUT_DIR_ADD_TRANS}.get(operation_type)
|
||||
if not sub:
|
||||
raise ValueError(f"未知参保类型:{operation_type}(可选:{'/'.join(config.ADD_TYPES)})")
|
||||
out_dir = config.roster_output_dir(sub)
|
||||
os.makedirs(out_dir, exist_ok=True)
|
||||
return out_dir
|
||||
|
||||
|
||||
def process_add_members(operation_type):
|
||||
"""生成增员导入名单(operation_type: '新参保' 或 '转移参保')。返回生成的份数。"""
|
||||
sub, source_file, _sheet, _ = source_reader.load_records(
|
||||
"add", operation_type=operation_type, status_filter="empty")
|
||||
config.log(f"源表:{os.path.basename(source_file)}")
|
||||
if sub.empty:
|
||||
config.log(f"没有找到【{operation_type}】的数据({config.TARGET_REGION}区域,办理状态为空)")
|
||||
return 0
|
||||
|
||||
today, first_day = datetime.now(), datetime.now().replace(day=1)
|
||||
config.log(f"今日日期:{today:%Y-%m-%d};本月1日:{first_day:%Y-%m-%d}"
|
||||
f"(首次参加/养老/失业/医疗/生育参保时间);工伤参保时间=当日")
|
||||
|
||||
template_file = _find_template_add()
|
||||
output_dir = _add_output_dir(operation_type)
|
||||
config.log(f"输出目录:{output_dir}")
|
||||
n_files = 0
|
||||
for store_name, group in sub.groupby(config.COLUMN_MAP_ADD['单位名称']):
|
||||
config.log(f" 正在处理:{store_name},共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[config.COLUMN_MAP_ADD['社保号']]
|
||||
unit_full_name = first_row[config.COLUMN_MAP_ADD['参保单位全称']]
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
rec = {
|
||||
'证件号码': config._to_text(row[config.COLUMN_MAP_ADD['证件号码']]),
|
||||
'姓名': row[config.COLUMN_MAP_ADD['姓名']],
|
||||
'民族': _translate_nation(row[config.COLUMN_MAP_ADD['民族']]),
|
||||
'首次参加工作日期': first_day,
|
||||
'月基本工资额': config._clean_value(row[config.COLUMN_MAP_ADD['月基本工资额']]),
|
||||
'工种': config.DEFAULT_VALUES_ADD['工种'],
|
||||
'个人身份': config.DEFAULT_VALUES_ADD['个人身份'],
|
||||
'户口性质': _translate_residence(row[config.COLUMN_MAP_ADD['户口性质']]),
|
||||
'联系电话': config._to_text(row[config.COLUMN_MAP_ADD['联系电话']]),
|
||||
'文化程度': _translate_education(row[config.COLUMN_MAP_ADD['文化程度']]),
|
||||
'养老保险参保时间': first_day,
|
||||
'失业保险参保时间': first_day,
|
||||
'医疗保险参保时间': first_day,
|
||||
'工伤保险参保时间': today,
|
||||
'生育保险参保时间': first_day,
|
||||
'证件类型': config.DEFAULT_VALUES_ADD['证件类型'],
|
||||
'国籍': config.DEFAULT_VALUES_ADD['国籍'],
|
||||
'备注': config.DEFAULT_VALUES_ADD['备注'],
|
||||
'专职技能': config.DEFAULT_VALUES_ADD['专职技能'],
|
||||
'技能等级': config.DEFAULT_VALUES_ADD['技能等级'],
|
||||
}
|
||||
records.append(rec)
|
||||
output_path = os.path.join(output_dir,
|
||||
f"{config._safe_name(store_name)}增员导入名单.xls")
|
||||
_write_template_add(template_file, output_path, unit_no, unit_full_name, records)
|
||||
config.log(f" 已生成:{output_path}")
|
||||
n_files += 1
|
||||
config.log(f"所有【{operation_type}】导入名单生成完成!")
|
||||
return n_files
|
||||
|
||||
|
||||
def make_add_lists():
|
||||
"""增员名单制作:依次生成 转移参保 / 新参保 两类名单。返回 (总份数, 结果明细)。"""
|
||||
total, detail = 0, {}
|
||||
for op_type in config.ADD_TYPES:
|
||||
n = process_add_members(op_type)
|
||||
total += n
|
||||
detail[op_type] = n
|
||||
return total, detail
|
||||
|
||||
|
||||
# ==================== 减员名单制作 ====================
|
||||
def _write_template_stop(template_file, output_path, unit_no, unit_full_name, records):
|
||||
"""复制《减员模版.xls》写入 B1/D1 及 B4 起数据,另存为 output_path。"""
|
||||
import xlrd
|
||||
from xlutils.copy import copy as xl_copy
|
||||
rb = xlrd.open_workbook(template_file, formatting_info=True)
|
||||
orig_rows = rb.sheet_by_index(0).nrows
|
||||
wb = xl_copy(rb)
|
||||
ws = wb.get_sheet(0) # 批量导入
|
||||
ws.write(0, 1, unit_no) # B1 单位社保号
|
||||
ws.write(0, 3, unit_full_name) # D1 单位全称
|
||||
for i, rec in enumerate(records):
|
||||
r = config.TPL_DATA_START_ROW - 1 + i
|
||||
for c, col in enumerate(config.TPL_COLS_STOP):
|
||||
val = rec.get(col)
|
||||
if col in config.DATE_COLS_STOP and val is not None:
|
||||
ws.write(r, c + 1, f"{val.year}/{val.month}/{val.day}")
|
||||
else:
|
||||
ws.write(r, c + 1, config._clean_value(val))
|
||||
for r in range(config.TPL_DATA_START_ROW - 1 + len(records), orig_rows):
|
||||
for c in range(1, len(config.TPL_COLS_STOP) + 1):
|
||||
ws.write(r, c, "")
|
||||
os.makedirs(os.path.dirname(output_path), exist_ok=True)
|
||||
wb.save(output_path)
|
||||
|
||||
|
||||
def _find_template_stop():
|
||||
"""定位《减员模版.xls》(社保增减名单制作/模板 下,优先精确名,其次按 *减员模版*.xls)。"""
|
||||
from glob import glob
|
||||
tpl_dir = config.roster_template_dir()
|
||||
exact = os.path.join(tpl_dir, config.TEMPLATE_STOP)
|
||||
if os.path.isfile(exact):
|
||||
return exact
|
||||
candidates = glob(os.path.join(tpl_dir, "*减员模版*.xls"))
|
||||
if not candidates:
|
||||
raise FileNotFoundError(
|
||||
f"在 {tpl_dir} 下未找到《{config.TEMPLATE_STOP}》,请先准备停保导入模板。")
|
||||
return max(candidates, key=os.path.getmtime)
|
||||
|
||||
|
||||
def _resolve_reduce_time(raw, today):
|
||||
"""减少时间取值规则:离职日期为当月日期 → 减少时间=离职日期;否则=当天。"""
|
||||
try:
|
||||
import pandas as pd
|
||||
dt = pd.to_datetime(raw, errors='coerce')
|
||||
except (TypeError, ValueError):
|
||||
dt = None
|
||||
if dt is not None and getattr(dt, 'year', None) == today.year and dt.month == today.month:
|
||||
return dt, True
|
||||
return today, False
|
||||
|
||||
|
||||
def process_stop_members():
|
||||
"""生成停保导入名单。返回生成的份数。"""
|
||||
sub, source_file, _sheet, _ = source_reader.load_records(
|
||||
"stop", status_filter="empty")
|
||||
config.log(f"源表:{os.path.basename(source_file)}")
|
||||
if sub.empty:
|
||||
config.log(f"没有筛选到数据(类型 ∈ {'/'.join(config.STOP_TYPES)} ∩ "
|
||||
f"区域={config.TARGET_REGION} ∩ 办理停保为空)")
|
||||
return 0
|
||||
|
||||
today = datetime.now()
|
||||
config.log(f"制作日期:{today:%Y-%m-%d}")
|
||||
template_file = _find_template_stop()
|
||||
output_dir = config.roster_output_dir(config.OUTPUT_DIR_STOP)
|
||||
os.makedirs(output_dir, exist_ok=True)
|
||||
config.log(f"输出目录:{output_dir}")
|
||||
n_files, n_leave_date = 0, 0
|
||||
for group_key, group in sub.groupby(config.COLUMN_MAP_STOP['单位名称']):
|
||||
config.log(f" 正在处理:单位【{group_key}】,共 {len(group)} 人")
|
||||
first_row = group.iloc[0]
|
||||
unit_no = first_row[config.COLUMN_MAP_STOP['单位社保号']]
|
||||
unit_full_name = first_row[config.COLUMN_MAP_STOP['单位全称']]
|
||||
records = []
|
||||
for _, row in group.iterrows():
|
||||
reduce_time, from_leave = _resolve_reduce_time(
|
||||
row[config.STOP_LEAVE_DATE_COL], today)
|
||||
if from_leave:
|
||||
n_leave_date += 1
|
||||
rec = {
|
||||
'个人编号': config._clean_value(row[config.COLUMN_MAP_STOP['个人编号']]),
|
||||
'证件号码': config._clean_value(row[config.COLUMN_MAP_STOP['证件号码']]),
|
||||
'姓名': config._clean_value(row[config.COLUMN_MAP_STOP['姓名']]),
|
||||
'减少时间': reduce_time,
|
||||
'减少原因': config.DEFAULT_VALUES_STOP['减少原因'],
|
||||
'养老保险减少标志': config.DEFAULT_VALUES_STOP['养老保险减少标志'],
|
||||
'失业保险减少标志': config.DEFAULT_VALUES_STOP['失业保险减少标志'],
|
||||
'医疗保险减少标志': config.DEFAULT_VALUES_STOP['医疗保险减少标志'],
|
||||
'工伤保险减少标志': config.DEFAULT_VALUES_STOP['工伤保险减少标志'],
|
||||
'生育保险减少标志': config.DEFAULT_VALUES_STOP['生育保险减少标志'],
|
||||
'失业原因': config.DEFAULT_VALUES_STOP['失业原因'],
|
||||
}
|
||||
records.append(rec)
|
||||
output_path = os.path.join(output_dir,
|
||||
f"{config._safe_name(group_key)}减员导入名单.xls")
|
||||
_write_template_stop(template_file, output_path, unit_no, unit_full_name, records)
|
||||
config.log(f" 已生成:{output_path}")
|
||||
n_files += 1
|
||||
config.log(f"所有停保导入名单生成完成!共 {len(sub[config.COLUMN_MAP_STOP['单位名称']].unique())} 个单位")
|
||||
config.log(f"减少时间取值:{n_leave_date} 人取离职日期,"
|
||||
f"{len(sub) - n_leave_date} 人取当天({today:%Y-%m-%d})")
|
||||
return n_files
|
||||
|
||||
|
||||
def make_stop_lists():
|
||||
"""减员名单制作。返回 (份数, 结果明细)。"""
|
||||
n = process_stop_members()
|
||||
return n, {"停保-减员": n}
|
||||
@@ -0,0 +1,729 @@
|
||||
# -*- 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,失败人员不会落账,下次运行会重复申报)
|
||||
config.log(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_names = {
|
||||
"新参保": config.OUTPUT_DIR_ADD_NEW,
|
||||
"转移参保": config.OUTPUT_DIR_ADD_TRANS,
|
||||
}
|
||||
self.file_suffix = "增员导入名单.xls"
|
||||
self.fail_status = "参保失败"
|
||||
self.close_tip = False
|
||||
self.operation_type = config.WEB_ADD_TYPES
|
||||
else:
|
||||
self.business_item = "城保参保单位人员减少"
|
||||
self.import_dir_names = {}
|
||||
self.file_suffix = "减员导入名单.xls"
|
||||
self.fail_status = "停保失败"
|
||||
self.close_tip = True
|
||||
self.operation_type = None
|
||||
self.import_dir_name = config.OUTPUT_DIR_STOP if kind != 'add' else config.OUTPUT_DIR_ADD_NEW
|
||||
self.writeback = Writeback(kind)
|
||||
|
||||
def _import_dir(self, op_type):
|
||||
"""按参保类型取名单产出子目录(增员);减员固定「停保-减员」。"""
|
||||
if self.kind == 'add':
|
||||
return self.import_dir_names.get(op_type, config.OUTPUT_DIR_ADD_NEW)
|
||||
return self.import_dir_name
|
||||
|
||||
# ---------------- 预检 ----------------
|
||||
def precheck(self, units, accounts):
|
||||
"""预检:核对每个(类型+单位)的导入文件与账号。返回待办列表。"""
|
||||
tasks, errors = [], []
|
||||
config.log("\n========== 预检 ==========")
|
||||
for op_type, unit, count in units:
|
||||
import_dir = config.roster_output_dir(self._import_dir(op_type))
|
||||
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(op_type)}\\{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列平台密码为空)")
|
||||
tag = f"{unit}({op_type or '停保'},{count}人)"
|
||||
if problems:
|
||||
errors.append(f"[{unit} {op_type or ''}] " + ";".join(problems))
|
||||
config.log(f" ✗ {tag}:{';'.join(problems)}")
|
||||
else:
|
||||
tasks.append({"type": op_type, "unit": unit, "count": count, "file": file_path,
|
||||
"username": acc["username"], "password": acc["password"]})
|
||||
config.log(f" ✓ {tag} 账号={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']}"
|
||||
f"({task.get('type') or '停保'},{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('type') or ''}):{r.get('message', '')}")
|
||||
return {"success": not fail, "message": f"成功{len(ok)}/失败{len(fail)}",
|
||||
"total": len(results), "done": len(ok)}
|
||||
@@ -0,0 +1,483 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""重庆人社网上服务大厅(政务平台)法人登录模块 —— XQ0014 专用(不共享登录态)。
|
||||
|
||||
每个参保单位一套账号(统一社会信用代码/用户名 + 密码),登录一次办一家的业务。
|
||||
不做 cookies 缓存:政务平台 cookies 极易失效,缓存无意义;统一每次现场真登录
|
||||
(浏览器走完整 SSO 流程 + ddddocr 识别图形验证码)。
|
||||
|
||||
登录流程:
|
||||
1. 打开办事大厅页面 → 等待登录入口出现;
|
||||
2. 点击「登录」→ 跳转新 tab 到 SSO(authcq.cqdcg.com:1443/sso/login);
|
||||
3. 切换「法人用户」tab;
|
||||
4. 输入账号(统一社会信用代码或政务平台用户名)+ 密码;
|
||||
5. 元素截图截取图形验证码(base64 内嵌 PNG)→ ddddocr 识别 → 输入验证码;
|
||||
6. 点击「登 录」→ 等待跳回办事大厅域名即成功;
|
||||
7. 识别失败自动刷新验证码重试(验证码 5 次/轮 × 流程 3 轮)。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
import random
|
||||
import base64
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
APPLY_URL = 'https://ggfw.rlsbj.cq.gov.cn/onlinehall/nethall/pc/cqzhrs/arrondi/ApplyOnline'
|
||||
SSO_KEYWORD = 'authcq.cqdcg.com:1443/sso/login'
|
||||
HOME_KEYWORD = 'ggfw.rlsbj.cq.gov.cn'
|
||||
WORK_KEYWORD = 'onlineoffice/index' # 登录成功后新开的工作台 tab
|
||||
|
||||
RETRY_MAX = 5 # 验证码最大重试次数(每轮)
|
||||
FLOW_RETRY = 3 # 整个登录流程最大轮数
|
||||
TIMEOUT = 10 # 元素等待超时(秒)
|
||||
HEADLESS = False
|
||||
HUMAN_DELAY = (0.4, 1.2) # 操作间随机延时区间(秒),模拟人工降低脚本特征
|
||||
|
||||
|
||||
def _captcha_debug_dir():
|
||||
"""验证码调试图片目录(仅调试模式开启时落盘)。"""
|
||||
return os.path.join(config.CKPT_DIR, 'debug_captcha')
|
||||
|
||||
|
||||
# ================== 验证码识别(元素截图 + ddddocr) ==================
|
||||
def _recognize_captcha(img_bytes):
|
||||
"""ddddocr 识别图形验证码,返回文本。懒加载避免无关场景的导入开销。"""
|
||||
import ddddocr
|
||||
ocr = ddddocr.DdddOcr(show_ad=False)
|
||||
return ocr.classification(img_bytes).strip()
|
||||
|
||||
|
||||
def _dump_debug_captcha(img_bytes, text):
|
||||
"""可选:落盘验证码调试图片(仅调试模式开启时),便于分析识别失败样本。"""
|
||||
if not config.is_debug():
|
||||
return
|
||||
try:
|
||||
d = _captcha_debug_dir()
|
||||
os.makedirs(d, exist_ok=True)
|
||||
path = os.path.join(d, f"captcha_{int(time.time() * 1000)}_{text or 'unknown'}.png")
|
||||
with open(path, 'wb') as f:
|
||||
f.write(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"保存调试图片失败:{e}", "WARN")
|
||||
|
||||
|
||||
def _find_input(tab, selectors):
|
||||
"""按候选选择器顺序查找输入框。"""
|
||||
for sel in selectors:
|
||||
ele = tab.ele(sel, timeout=2)
|
||||
if ele:
|
||||
return ele
|
||||
return None
|
||||
|
||||
|
||||
def _find_captcha(tab):
|
||||
"""定位验证码图片 + 输入框。
|
||||
|
||||
从验证码输入框的容器往上找(DOM 结构:div.normalCode > span包input + img.code),
|
||||
避免命中页面其它 base64 图标(实测:img[src^=data:image] 会抓到 icon)。
|
||||
"""
|
||||
code_input = tab.ele('css:input[placeholder*="图形验证码"]', timeout=TIMEOUT)
|
||||
img = None
|
||||
if code_input:
|
||||
holder = code_input.parent(2) # div.normalCode 容器
|
||||
if holder:
|
||||
img = holder.ele('tag:img', timeout=1)
|
||||
if img is None:
|
||||
img = tab.ele('css:.ant-tabs-tabpane-active img[src^="data:image"]', timeout=2)
|
||||
return img, code_input
|
||||
|
||||
|
||||
def _read_img_bytes(img):
|
||||
"""验证码图转 bytes:优先直接解码 base64 src(像素无损、无 DPR 缩放),失败退回元素截图。"""
|
||||
try:
|
||||
src = img.attr('src') or ''
|
||||
if 'base64,' in src:
|
||||
return base64.b64decode(src.split('base64,', 1)[1])
|
||||
except Exception:
|
||||
pass
|
||||
return img.get_screenshot(as_bytes='png')
|
||||
|
||||
|
||||
# ================== 登录主流程 ==================
|
||||
def _human_pause(a=None, b=None):
|
||||
"""操作间随机延时,模拟人工节奏。"""
|
||||
lo, hi = HUMAN_DELAY if (a is None or b is None) else (a, b)
|
||||
time.sleep(random.uniform(lo, hi))
|
||||
|
||||
|
||||
def _dismiss_notice(page):
|
||||
"""关闭首页/工作台弹窗(「温馨提示」我知道了、授权提示同意等),避免遮挡操作。"""
|
||||
candidates = [
|
||||
'tag:button@@text()=我知道了',
|
||||
'tag:button@@text()=知道了',
|
||||
'tag:button@@text()=同意',
|
||||
'tag:button@@text()=确定',
|
||||
]
|
||||
for _ in range(3):
|
||||
btn = None
|
||||
for sel in candidates:
|
||||
try:
|
||||
btn = page.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
btn = None
|
||||
if btn:
|
||||
break
|
||||
if not btn:
|
||||
return
|
||||
try:
|
||||
btn.click()
|
||||
config.log(f"已关闭弹窗(点击:{btn.text.strip()})")
|
||||
time.sleep(0.5)
|
||||
except Exception:
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def _sso_form_ready(t):
|
||||
"""判断某 tab 是否已是渲染完成的 SSO 登录页:URL 在 SSO 且「法人用户」tab 已出现。
|
||||
注意用 text()= 精确匹配——text(): 模糊匹配会命中包含该文字的外层容器 div。"""
|
||||
try:
|
||||
if SSO_KEYWORD not in t.url:
|
||||
return False
|
||||
return bool(t.ele('tag:div@@text()=法人用户', timeout=0.5))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _wait_sso_ready(tab):
|
||||
"""等 SSO 登录页彻底稳定(URL 不再跳变 + 表单已渲染),再开始操作。"""
|
||||
last_url = None
|
||||
for _ in range(60): # 最多等 30 秒
|
||||
try:
|
||||
url = tab.url
|
||||
except Exception:
|
||||
return False
|
||||
stable = (url == last_url)
|
||||
last_url = url
|
||||
if _sso_form_ready(tab) and stable:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
time.sleep(1.5) # 再缓冲,确保 React 渲染完成
|
||||
return True
|
||||
|
||||
|
||||
def _is_work_tab(t):
|
||||
"""是否登录完成的工作台页(onlineoffice/index)。
|
||||
必须 origin 前缀匹配 + 路径含 onlineoffice/index——跳转链中间页的 redirectUrl 参数也含
|
||||
ggfw/onlinehall 字样,用包含匹配会误判。"""
|
||||
try:
|
||||
u = (t.url or '').strip()
|
||||
except Exception:
|
||||
return False
|
||||
return u.startswith('https://' + HOME_KEYWORD) and WORK_KEYWORD in u
|
||||
|
||||
|
||||
def _open_sso_tab(page):
|
||||
"""点击首页「登录」,等待新 tab 打开、跳转链结束且登录表单渲染完成后返回。
|
||||
返回 (tab, already_logged):
|
||||
already_logged=False → SSO 登录页(需填表)
|
||||
already_logged=True → SSO 会话有效直接跳回大厅(登录成功,无需填表)"""
|
||||
_dismiss_notice(page)
|
||||
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
login_link = page.ele('tag:a@@text():登录', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
config.log("未找到登录入口(可能残留上一账号登录态),清除 cookies 后重试", "WARN")
|
||||
try:
|
||||
page.clear_cache(cookies=True)
|
||||
except Exception:
|
||||
try:
|
||||
page.run_js("document.cookie.split(';').forEach(c=>{"
|
||||
"document.cookie=c.trim().split('=')[0]+"
|
||||
"'=;expires=Thu, 01 Jan 1970 00:00:00 GMT;path=/'});")
|
||||
except Exception:
|
||||
pass
|
||||
page.get(APPLY_URL)
|
||||
time.sleep(2)
|
||||
login_link = page.ele('css:[class*="loginBox"] a', timeout=TIMEOUT) \
|
||||
or page.ele('tag:a@@text():登录', timeout=TIMEOUT)
|
||||
if not login_link:
|
||||
config.log("找不到登录入口(首页可能已是登录态)", "WARN")
|
||||
return None, False
|
||||
before_ids = set(page.tab_ids)
|
||||
login_link.click()
|
||||
tab = None
|
||||
for _ in range(90): # 最多等 45 秒
|
||||
time.sleep(0.5)
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids]:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
except Exception:
|
||||
continue
|
||||
if _is_work_tab(t):
|
||||
config.log(f"SSO 会话有效,已直接登录:{t.url}")
|
||||
_close_extra_tabs(page, before_ids, t)
|
||||
_dismiss_notice(t)
|
||||
return t, True
|
||||
if _sso_form_ready(t):
|
||||
tab = t
|
||||
break
|
||||
if tab:
|
||||
break
|
||||
if tab is None:
|
||||
if _sso_form_ready(page):
|
||||
return page, False
|
||||
config.log("点击登录后未检测到就绪的 SSO 登录页", "WARN")
|
||||
return None, False
|
||||
_close_extra_tabs(page, before_ids, tab)
|
||||
return tab, False
|
||||
|
||||
|
||||
def _close_extra_tabs(page, before_ids, keep_tab):
|
||||
"""关掉一次「点登录」产生的多余新开 tab(中转页等),保持会话干净。"""
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids and i != keep_tab.tab_id]:
|
||||
try:
|
||||
page.get_tab(tid).close()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _try_login_once(tab, page, username, password, retry_index):
|
||||
"""在 SSO tab 内完成一次填表 + 验证码 + 提交。返回 True 表示登录成功。"""
|
||||
_wait_sso_ready(tab)
|
||||
legal_tab = tab.ele('tag:div@@text()=法人用户', timeout=TIMEOUT)
|
||||
if legal_tab:
|
||||
legal_tab.click()
|
||||
_human_pause(0.3, 0.8)
|
||||
for _ in range(3):
|
||||
active = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=2)
|
||||
if active and active.text.strip() == '法人用户':
|
||||
break
|
||||
if legal_tab:
|
||||
try:
|
||||
legal_tab.click()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
|
||||
# 账号(统一社会信用代码)+ 密码
|
||||
user_input = _find_input(tab, [
|
||||
'css:input[placeholder*="统一社会信用代码"]',
|
||||
'css:input[placeholder*="社会信用代码"]',
|
||||
'css:#identifier',
|
||||
])
|
||||
if not user_input:
|
||||
config.log("找不到账号输入框", "ERROR")
|
||||
return False
|
||||
user_input.clear()
|
||||
user_input.input(username)
|
||||
_human_pause()
|
||||
|
||||
pwd_input = _find_input(tab, ['css:#password', 'css:input[type="password"]'])
|
||||
if not pwd_input:
|
||||
config.log("找不到密码输入框", "ERROR")
|
||||
return False
|
||||
pwd_input.clear()
|
||||
pwd_input.input(password)
|
||||
_human_pause()
|
||||
|
||||
for attempt in range(RETRY_MAX):
|
||||
config.log(f"--- 第 {retry_index}-{attempt + 1} 次验证码识别 ---")
|
||||
img, code_input = _find_captcha(tab)
|
||||
if not img or not code_input:
|
||||
config.log("找不到验证码图片或输入框", "ERROR")
|
||||
return False
|
||||
img_bytes = _read_img_bytes(img)
|
||||
if not img_bytes:
|
||||
config.log("验证码图数据为空", "WARN")
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
code = _recognize_captcha(img_bytes)
|
||||
except Exception as e:
|
||||
config.log(f"ddddocr 识别异常:{e}", "ERROR")
|
||||
return False
|
||||
config.log(f" 识别结果:{code!r}")
|
||||
if not code:
|
||||
_refresh_captcha(tab, img)
|
||||
continue
|
||||
code = code.upper() # 页面显示为大写,按大写提交
|
||||
_dump_debug_captcha(img_bytes, code)
|
||||
code_input.clear()
|
||||
code_input.input(code)
|
||||
_human_pause(0.3, 0.9)
|
||||
|
||||
btn = tab.ele('css:button[type="submit"]', timeout=TIMEOUT) \
|
||||
or tab.ele('tag:button@@text():登录', timeout=TIMEOUT)
|
||||
if not btn:
|
||||
config.log("找不到登录提交按钮", "ERROR")
|
||||
return False
|
||||
_human_pause(0.2, 0.6)
|
||||
btn.click()
|
||||
|
||||
ok, work_tab = _wait_login_result(tab, page)
|
||||
if ok:
|
||||
_try_login_once.work_tab = work_tab # 供 _do_login 保存会话
|
||||
return True
|
||||
_refresh_captcha(tab, img)
|
||||
return False
|
||||
|
||||
|
||||
def _wait_login_result(tab, page):
|
||||
"""提交后轮询判定登录结果。返回 (ok, work_tab)。"""
|
||||
before_ids = set(page.tab_ids)
|
||||
for _ in range(30): # 最多等 15 秒
|
||||
time.sleep(0.5)
|
||||
for tid in [i for i in page.tab_ids if i not in before_ids]:
|
||||
try:
|
||||
t = page.get_tab(tid)
|
||||
except Exception:
|
||||
continue
|
||||
if _is_work_tab(t):
|
||||
config.log(f"登录成功(新开工作台 tab):{t.url}")
|
||||
_close_extra_tabs(page, before_ids, t)
|
||||
_dismiss_notice(t)
|
||||
return True, t
|
||||
try:
|
||||
url = (tab.url or '').strip()
|
||||
except Exception:
|
||||
url = ''
|
||||
if url.startswith('https://' + HOME_KEYWORD) and SSO_KEYWORD not in url and WORK_KEYWORD in url:
|
||||
config.log(f"登录成功,已跳转:{url}")
|
||||
_dismiss_notice(tab)
|
||||
return True, tab
|
||||
try:
|
||||
err = tab.ele('css:.ant-message-error', timeout=0.5)
|
||||
if err:
|
||||
config.log(f"登录失败提示:{err.text}")
|
||||
return False, None
|
||||
except Exception:
|
||||
pass
|
||||
config.log("等待登录结果超时", "WARN")
|
||||
return False, None
|
||||
|
||||
|
||||
def _refresh_captcha(tab, img):
|
||||
"""点击验证码图片刷新,校验 base64 src 是否真的变化(连续点 2 次)。"""
|
||||
try:
|
||||
old = img.attr('src') or ''
|
||||
except Exception:
|
||||
old = ''
|
||||
for _ in range(2):
|
||||
try:
|
||||
img.click()
|
||||
except Exception:
|
||||
try:
|
||||
img.click(by_js=True)
|
||||
except Exception:
|
||||
pass
|
||||
for _p in range(10):
|
||||
time.sleep(0.3)
|
||||
try:
|
||||
new = img.attr('src') or ''
|
||||
except Exception:
|
||||
new = old
|
||||
if new and new != old:
|
||||
return True
|
||||
config.log("警告:验证码图片刷新后未变化", "WARN")
|
||||
return False
|
||||
|
||||
|
||||
LAST_SESSION = {'page': None, 'tab': None} # 登录成功后保留的浏览器会话(供后续网页操作使用)
|
||||
|
||||
|
||||
def _teardown(page):
|
||||
"""清 cookies/本地存储后关浏览器(账号切换彻底隔离,避免残留登录态)。"""
|
||||
if page is None:
|
||||
return
|
||||
try:
|
||||
page.clear_cache(cookies=True, local_storage=True, session_storage=True)
|
||||
except Exception:
|
||||
try:
|
||||
page.clear_cache()
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def close_session():
|
||||
"""清 cookies 并关闭当前保留的登录会话(每个账号业务办完后必须调用)。"""
|
||||
_teardown(LAST_SESSION['page'])
|
||||
LAST_SESSION['page'] = None
|
||||
LAST_SESSION['tab'] = None
|
||||
|
||||
|
||||
def _do_login(username, password):
|
||||
"""打开浏览器现场完成登录(含图形验证码)。不做任何 cookies 缓存。
|
||||
成功保留浏览器会话(工作台 tab 供后续导入操作),失败关闭浏览器。
|
||||
返回 (ok, work_tab)。"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
close_session() # 账号切换隔离
|
||||
co = ChromiumOptions()
|
||||
if HEADLESS:
|
||||
co.headless()
|
||||
co.auto_port(True) # 每次启动独立端口+独立临时用户目录,账号间 cookies 天然隔离
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
page = ChromiumPage(co)
|
||||
work_tab_holder = {'tab': None}
|
||||
|
||||
def _finish(ok):
|
||||
if ok:
|
||||
LAST_SESSION['page'] = page
|
||||
LAST_SESSION['tab'] = work_tab_holder['tab']
|
||||
return True, work_tab_holder['tab']
|
||||
_teardown(page)
|
||||
return False, None
|
||||
|
||||
try:
|
||||
page.get(APPLY_URL)
|
||||
_human_pause(1.0, 2.5)
|
||||
tab = None
|
||||
for retry in range(FLOW_RETRY):
|
||||
try:
|
||||
_dismiss_notice(page)
|
||||
if tab is not None:
|
||||
try:
|
||||
if SSO_KEYWORD not in tab.url:
|
||||
tab = None
|
||||
except Exception:
|
||||
tab = None
|
||||
if tab is None:
|
||||
tab, already = _open_sso_tab(page)
|
||||
if tab is None:
|
||||
config.log(f"进入 SSO 登录页失败(第 {retry + 1}/{FLOW_RETRY} 轮)", "WARN")
|
||||
time.sleep(2)
|
||||
continue
|
||||
if already:
|
||||
work_tab_holder['tab'] = tab
|
||||
return _finish(True)
|
||||
if _try_login_once(tab, page, username, password, retry + 1):
|
||||
work_tab_holder['tab'] = getattr(_try_login_once, 'work_tab', None) or tab
|
||||
return _finish(True)
|
||||
try:
|
||||
tab.refresh()
|
||||
time.sleep(2)
|
||||
except Exception:
|
||||
pass
|
||||
except Exception as e:
|
||||
config.log(f"第 {retry + 1}/{FLOW_RETRY} 轮流程异常(将重试):{e}", "WARN")
|
||||
time.sleep(1)
|
||||
config.log("登录失败(验证码识别未通过或流程异常)", "ERROR")
|
||||
return _finish(False)
|
||||
except Exception:
|
||||
_teardown(page)
|
||||
raise
|
||||
|
||||
|
||||
def ensure_login(username, password):
|
||||
"""以指定账号现场登录政务平台(无缓存,每次真登录)。
|
||||
返回 JSON 安全 dict:{success, username, message}"""
|
||||
username = (username or '').strip()
|
||||
password = (password or '').strip()
|
||||
if not (username and password):
|
||||
return {"success": False, "username": username,
|
||||
"message": "登录账号/密码缺失(台账未取到账号密码)"}
|
||||
ok, _work_tab = _do_login(username, password)
|
||||
if ok:
|
||||
return {"success": True, "username": username, "message": "登录成功"}
|
||||
return {"success": False, "username": username,
|
||||
"message": "登录失败(验证码识别未通过或流程异常)"}
|
||||
@@ -0,0 +1,661 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""重庆社保系统增减员办理(核查-回盘)—— check_review.py / check_review_stop.py 移植。
|
||||
|
||||
申报提交后平台审核存在滞后,本模块对源名单中「办理状态/办理停保=待审核」的人员所在
|
||||
参保单位,逐个登录重庆人社政务平台核查审核结论并下载回盘表:
|
||||
|
||||
统一引擎 ReviewEngine(kind):
|
||||
- kind='add':增员核查,回写「办理状态」列(参保成功/参保失败);
|
||||
审核通过人员的个人编号由回盘表核对得出(五项参保状态全「参保缴费」→ 备注个人编号)
|
||||
- kind='stop':减员核查,回写「办理停保」列(停保成功/停保失败);
|
||||
审核通过人员的个人编号/减少时间由明细接口直取(aac001/aad030),回盘表仅留档
|
||||
|
||||
流程(每参保单位):登录 → 进业务页(减员先关「提示信息」弹窗)→ 等单位信息 →
|
||||
左侧「已申报查询」→ 读第一条状态,非「已办结」跳过 → 「查看」监听 queryYsbWs04orWs01
|
||||
接口 → 页内 XHR 重放翻页取全量 → 按证件号匹配回写 → 回盘打印下载(增员核对/减员留档)。
|
||||
400系统错误:先记录,全部核查完后统一清空状态回待办。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import json
|
||||
import time
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
from urllib.parse import urlparse, parse_qsl, urlencode
|
||||
|
||||
from .. import config
|
||||
from ..data import source_reader
|
||||
from ..data.writeback import Writeback
|
||||
from . import web_login
|
||||
from .web_import import (_shot, _click_any, _dismiss_popups,
|
||||
_open_business_page, _close_tip_modal)
|
||||
|
||||
|
||||
# ==================== 减员特有:新手引导 / 温馨提示 ====================
|
||||
def _dismiss_guide(tab):
|
||||
"""关闭新手引导浮层(点「跳过全部」,无则点「下一步」翻完)。"""
|
||||
for _ in range(4):
|
||||
hit = False
|
||||
for sel in ('text=跳过全部', 'text=下一步'):
|
||||
try:
|
||||
e = tab.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
e = None
|
||||
if not e:
|
||||
continue
|
||||
try:
|
||||
if e.states.has_rect:
|
||||
e.click()
|
||||
hit = True
|
||||
time.sleep(0.6)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if not hit:
|
||||
return
|
||||
|
||||
|
||||
def _dismiss_warm_tip(tab):
|
||||
"""关「温馨提示」弹窗(如:统一社会信用代码,调用单位信息接口失败!)。返回是否处理过。"""
|
||||
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:
|
||||
btn = p.ele('css:.ant-modal-footer button', timeout=1)
|
||||
if btn:
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
time.sleep(0.6)
|
||||
return True
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
return False
|
||||
|
||||
|
||||
def _reopen_biz(page, business_item):
|
||||
"""统一自愈入口:重走业务入口——打开业务页 → 关「提示信息」→ 跳新手引导 → 关残留弹窗。"""
|
||||
tab = _open_business_page(page, web_login.LAST_SESSION['tab'], business_item)
|
||||
_close_tip_modal(tab)
|
||||
_dismiss_guide(tab)
|
||||
_dismiss_popups(tab)
|
||||
return tab
|
||||
|
||||
|
||||
# ==================== 核查网页操作(增/减共用,少量分支) ====================
|
||||
def _open_query_menu(tab):
|
||||
"""业务页左侧菜单点「已申报查询」,等记录表(表头含 当前状态/操作)出现。"""
|
||||
_dismiss_guide(tab) # 新手引导浮层会吞菜单点击
|
||||
_click_any(tab, [f'tag:li@@text()={config.MENU_QUERY}', f'text={config.MENU_QUERY}'],
|
||||
f'左侧菜单「{config.MENU_QUERY}」')
|
||||
_dismiss_popups(tab)
|
||||
deadline = time.time() + 15
|
||||
while time.time() < deadline:
|
||||
for tb in tab.eles('tag:table'):
|
||||
try:
|
||||
ths = [th.text.strip() for th in tb.eles('tag:th')]
|
||||
except Exception:
|
||||
continue
|
||||
if '当前状态' in ths and '操作' in ths:
|
||||
return tb
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError(f"点击「{config.MENU_QUERY}」后未出现申报记录表")
|
||||
|
||||
|
||||
def _read_first_row(table):
|
||||
"""读申报记录表第一条:返回 (当前状态, 查看按钮元素)。无记录返回 (None, None)。"""
|
||||
row = table.ele('css:tbody tr.ant-table-row', timeout=3) \
|
||||
or table.ele('css:tbody tr', timeout=1)
|
||||
if row is None:
|
||||
return None, None
|
||||
ths = [th.text.strip() for th in table.eles('tag:th')]
|
||||
i_status = ths.index('当前状态')
|
||||
tds = [td.text.strip() for td in row.eles('tag:td')]
|
||||
status = tds[i_status] if len(tds) > i_status else ''
|
||||
view = None
|
||||
for sel in ('tag:a@@text()=查看', 'tag:span@@text()=查看', 'text=查看'):
|
||||
try:
|
||||
view = row.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
view = None
|
||||
if view:
|
||||
break
|
||||
return status, view
|
||||
|
||||
|
||||
def _capture_query_url(page, tab, view):
|
||||
"""点「查看」并监听明细查询接口,返回请求 URL。"""
|
||||
before = set(page.tab_ids)
|
||||
tab.listen.start(config.API_KEYWORD)
|
||||
new_tabs = []
|
||||
packet = None
|
||||
try:
|
||||
try:
|
||||
view.click()
|
||||
except Exception:
|
||||
view.click(by_js=True)
|
||||
deadline = time.time() + 25
|
||||
while time.time() < deadline and packet is None:
|
||||
for tid in [i for i in page.tab_ids if i not in before and i not in new_tabs]:
|
||||
new_tabs.append(tid)
|
||||
try:
|
||||
page.get_tab(tid).listen.start(config.API_KEYWORD)
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
packet = tab.listen.wait(count=1, timeout=2)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet is None:
|
||||
for tid in new_tabs:
|
||||
try:
|
||||
packet = page.get_tab(tid).listen.wait(count=1, timeout=0.5)
|
||||
except Exception:
|
||||
packet = None
|
||||
if packet:
|
||||
break
|
||||
finally:
|
||||
for t in [tab] + [page.get_tab(tid) for tid in new_tabs if tid in page.tab_ids]:
|
||||
try:
|
||||
t.listen.stop()
|
||||
except Exception:
|
||||
pass
|
||||
if not packet:
|
||||
raise RuntimeError("点击查看后未监听到明细查询接口(queryYsbWs04orWs01)")
|
||||
url = packet.request.url
|
||||
config.log(f" 已捕获明细接口:{url[:100]}...")
|
||||
return url
|
||||
|
||||
|
||||
def _fetch_via_xhr(tab, url):
|
||||
"""页内同步 XHR GET(自带登录态 cookies),返回响应文本。"""
|
||||
js = ("const xhr=new XMLHttpRequest();"
|
||||
"xhr.open('GET',arguments[0],false);"
|
||||
"xhr.setRequestHeader('Accept','application/json, text/javascript');"
|
||||
"xhr.send();return xhr.responseText;")
|
||||
return tab.run_js(js, url)
|
||||
|
||||
|
||||
def _wait_unit_loaded(tab, unit_name, timeout=40):
|
||||
"""等业务页单位信息加载完成:轮询 getAab001 接口直到返回本单位数据。
|
||||
接口轮询失败但页面已出现单位名时也视为加载成功。期间弹「温馨提示」→ 返回 None
|
||||
由调用方统一重走业务入口自愈。返回 data[0] / {} / None。"""
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
if _dismiss_warm_tip(tab):
|
||||
config.log(" 单位信息接口调用失败(温馨提示),关闭后重走业务入口", "WARN")
|
||||
return None
|
||||
try:
|
||||
raw = _fetch_via_xhr(tab, config.API_UNIT_INFO)
|
||||
data = (json.loads(raw).get('data') or [None])[0]
|
||||
if data and data.get('aab001'):
|
||||
config.log(f" 单位信息已加载:{data.get('aab004')}(aab001={data.get('aab001')})")
|
||||
return data
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
if tab.ele(f'text:{unit_name}', timeout=0.5):
|
||||
config.log(f" 页面已显示单位「{unit_name}」,视为加载完成")
|
||||
return {}
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return None
|
||||
|
||||
|
||||
def _replay_query_all(tab, captured_url):
|
||||
"""用捕获的请求参数重放接口翻页,取全量明细行。
|
||||
返回 (results, unit_full);results 字段取 aac003/aac002/aae110s/aae111,
|
||||
另取 aac001=个人编号、aad030=减少时间(减员审核通过备注回写用)。"""
|
||||
parsed = urlparse(captured_url)
|
||||
base_params = [(k, v) for k, v in parse_qsl(parsed.query, keep_blank_values=True)
|
||||
if k != 'pageIndex']
|
||||
root = f"{parsed.scheme}://{parsed.netloc}{parsed.path}"
|
||||
rows, total = [], None
|
||||
for idx in range(config.MAX_PAGES):
|
||||
params = base_params + [('pageIndex', json.dumps(
|
||||
{"pageIndex": idx, "pageSize": config.PAGE_SIZE}, separators=(',', ':')))]
|
||||
full = f"{root}?{urlencode(params)}"
|
||||
raw = _fetch_via_xhr(tab, full)
|
||||
if not raw:
|
||||
raise RuntimeError(f"接口重放第 {idx + 1} 页返回空")
|
||||
payload = json.loads(raw)
|
||||
data = payload.get('data') or {}
|
||||
items = data.get('data') or []
|
||||
if total is None:
|
||||
total = data.get('total')
|
||||
rows.extend(items)
|
||||
config.log(f" 接口重放第 {idx + 1} 页:取到 {len(items)} 条(累计 {len(rows)}/{total})")
|
||||
if not items or (total is not None and len(rows) >= total):
|
||||
break
|
||||
results = []
|
||||
for it in rows:
|
||||
results.append({
|
||||
"name": str(it.get('aac003') or '').strip(),
|
||||
"cid": config._norm_id(it.get('aac002')),
|
||||
"conclusion": str(it.get('aae110s') or '').strip(),
|
||||
"opinion": str(it.get('aae111') or '').strip(),
|
||||
"pid": str(it.get('aac001') or '').strip(),
|
||||
"stop_date": str(it.get('aad030') or '').strip(),
|
||||
})
|
||||
unit_full = ""
|
||||
for it in rows:
|
||||
v = str(it.get('aab004') or '').strip()
|
||||
if v:
|
||||
unit_full = v
|
||||
break
|
||||
return results, unit_full
|
||||
|
||||
|
||||
# ==================== 结论回写 ====================
|
||||
def _build_writeback(engine, results, task_cids, unit_name):
|
||||
"""按回写规则处理明细,返回 (status_map, remark_map, redo400_list, log_lines)。
|
||||
只处理本单位「待审核」人员(证件号码精确匹配)。
|
||||
400系统错误不立即清状态:先记录,运行结束后统一清空状态回待办。"""
|
||||
status_map, remark_map, redo400, logs = {}, {}, [], []
|
||||
for r in results:
|
||||
if not r['cid'] or r['cid'] not in task_cids:
|
||||
continue
|
||||
concl, opinion = r['conclusion'], r['opinion']
|
||||
line = f" {r['name']}({r['cid']}):{concl}"
|
||||
if concl == '审核通过':
|
||||
status_map[r['cid']] = engine.pass_status
|
||||
if engine.kind == 'stop':
|
||||
# 减员:备注直接取接口个人编号+减少时间(不依赖回盘表核对)
|
||||
info = ";".join(x for x in (
|
||||
f"个人编号:{r['pid']}" if r['pid'] else "",
|
||||
f"减少时间:{r['stop_date']}" if r['stop_date'] else "") if x)
|
||||
remark_map[r['cid']] = info or engine.pass_status
|
||||
line += f" → {engine.status_label}={engine.pass_status},备注追加:{info[:60]}"
|
||||
else:
|
||||
# 增员:个人编号由回盘表核对后追加(_do_huipan)
|
||||
line += f" → {engine.status_label}={engine.pass_status}"
|
||||
elif concl == '不通过':
|
||||
if config.ERR_400_KEYWORD in opinion and config.RUN_400_CLEAR:
|
||||
redo400.append({"cid": r['cid'], "name": r['name'], "unit": unit_name})
|
||||
line += " → 400系统错误,已记录(结束后统一清状态回待办重新办理)"
|
||||
elif config.ERR_400_KEYWORD in opinion:
|
||||
# 400错误但清状态开关未开:兜底按不通过处理,避免明细被静默丢弃
|
||||
status_map[r['cid']] = engine.fail_status
|
||||
remark_map[r['cid']] = opinion or '400系统错误'
|
||||
line += (f" → 400系统错误且清状态开关未开,{engine.status_label}={engine.fail_status},"
|
||||
f"备注追加:{opinion[:60]}")
|
||||
else:
|
||||
status_map[r['cid']] = engine.fail_status
|
||||
remark_map[r['cid']] = opinion or '审核不通过'
|
||||
line += f" → {engine.status_label}={engine.fail_status},备注追加:{opinion[:60]}"
|
||||
else:
|
||||
line += " → 非终态结论,跳过"
|
||||
logs.append(line)
|
||||
return status_map, remark_map, redo400, logs
|
||||
|
||||
|
||||
# ==================== 回盘打印下载 ====================
|
||||
def _clean_cell(v):
|
||||
"""单元格值转干净字符串:浮点整数去掉 .0,其余去首尾空白。"""
|
||||
if v is None:
|
||||
return ""
|
||||
if isinstance(v, float) and v.is_integer():
|
||||
return str(int(v))
|
||||
return str(v).strip()
|
||||
|
||||
|
||||
def _find_huipan_btn(tab, wait):
|
||||
"""找内容区可见的「回盘打印」提交按钮(只认 button/a,排除左侧菜单 li>span)。"""
|
||||
deadline = time.time() + wait
|
||||
while time.time() < deadline:
|
||||
for sel in ('tag:button@@text()=回盘打印', 'tag:a@@text()=回盘打印'):
|
||||
try:
|
||||
cand = tab.ele(sel, timeout=1)
|
||||
except Exception:
|
||||
cand = None
|
||||
if cand:
|
||||
try:
|
||||
if cand.states.has_rect:
|
||||
return cand
|
||||
except Exception:
|
||||
return cand
|
||||
time.sleep(0.5)
|
||||
return None
|
||||
|
||||
|
||||
def _dump_download_debug(tab, tag):
|
||||
"""回盘打印失败时自动保存现场(截图+HTML 到插件缓存 _debug/),便于对齐真实页面结构。"""
|
||||
try:
|
||||
dbg = Path(config.CKPT_DIR) / "_debug"
|
||||
dbg.mkdir(parents=True, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
tab.get_screenshot(path=str(dbg), name=f"huipan_{tag}_{ts}.png")
|
||||
(dbg / f"huipan_{tag}_{ts}.html").write_text(tab.html, encoding='utf-8')
|
||||
config.log(f" 已保存现场:{dbg / f'huipan_{tag}_{ts}.png'}(含同名 html)")
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def _download_huipan(page, biz_tab, unit, business_item, save_dir):
|
||||
"""左侧菜单「回盘打印」→ 页内「回盘打印」按钮,等下载完成后重命名为规范文件名。
|
||||
点「查看」后左侧菜单不可见,直接跳菜单页进入(重开业务页兜底);返回保存的文件 Path。"""
|
||||
save_dir = Path(save_dir)
|
||||
save_dir.mkdir(parents=True, exist_ok=True)
|
||||
target = save_dir / f"{config.REPLAY_PREFIX}_{unit}_{datetime.now():%Y%m%d}.xlsx"
|
||||
menu_sel = ['tag:li@@text()=回盘打印', 'text=回盘打印']
|
||||
btn = None
|
||||
for name, goto in (("菜单页", config.MENU_PAGE_URL), ("重开业务页", "__REOPEN__")):
|
||||
try:
|
||||
if goto == "__REOPEN__":
|
||||
biz_tab = _reopen_biz(page, business_item)
|
||||
else:
|
||||
config.log(f" 直跳{name}进回盘打印...")
|
||||
biz_tab.get(goto)
|
||||
time.sleep(2)
|
||||
_dismiss_warm_tip(biz_tab)
|
||||
_dismiss_guide(biz_tab)
|
||||
_dismiss_popups(biz_tab)
|
||||
_click_any(biz_tab, menu_sel, f'左侧菜单「回盘打印」({name})')
|
||||
btn = _find_huipan_btn(biz_tab, 8)
|
||||
if btn:
|
||||
break
|
||||
config.log(f" ({name})菜单已点但回盘打印内容未出现,换下一种方式")
|
||||
except Exception as e:
|
||||
config.log(f" ({name})方式失败:{e}")
|
||||
if btn is None:
|
||||
_dump_download_debug(biz_tab, 'nobutton')
|
||||
raise RuntimeError("直跳菜单页/重开业务页均未进入回盘打印页(已保存现场)")
|
||||
|
||||
biz_tab.set.download_path(str(save_dir))
|
||||
before = {f.name for f in save_dir.iterdir() if f.is_file()}
|
||||
try:
|
||||
btn.click()
|
||||
except Exception:
|
||||
btn.click(by_js=True)
|
||||
|
||||
# 轮询等下载:新文件出现且大小连续2秒稳定(最多90秒)
|
||||
new_file, last_size, stable = None, -1, 0
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
time.sleep(1)
|
||||
files = [f for f in save_dir.iterdir() if f.is_file() and f.name not in before
|
||||
and f.suffix.lower() not in ('.crdownload', '.tmp')]
|
||||
if not files:
|
||||
stable, last_size = 0, -1
|
||||
continue
|
||||
f = max(files, key=lambda x: x.stat().st_mtime)
|
||||
size = f.stat().st_size
|
||||
if size > 0 and size == last_size:
|
||||
stable += 1
|
||||
if stable >= 2:
|
||||
new_file = f
|
||||
break
|
||||
else:
|
||||
stable = 0
|
||||
last_size = size
|
||||
if new_file is None:
|
||||
_dump_download_debug(biz_tab, 'nodownload')
|
||||
raise RuntimeError("点击回盘打印后90秒内未检测到新下载文件(已保存现场)")
|
||||
os.replace(new_file, target)
|
||||
return target
|
||||
|
||||
|
||||
def _verify_huipan(filepath, task_cids):
|
||||
"""读回盘表(表头在第2行),按身份证号核对五项参保状态,生成备注回写内容。
|
||||
同人多条记录:取参保缴费数量最多的那条。返回 (remark_map, logs)。"""
|
||||
import pandas as pd
|
||||
df = pd.read_excel(filepath, header=1)
|
||||
df.columns = [str(c).strip() for c in df.columns]
|
||||
need = ['个人编号', '身份证号'] + config.INS_STATUSES
|
||||
missing = [c for c in need if c not in df.columns]
|
||||
if missing:
|
||||
raise RuntimeError(f"回盘表缺少列:{missing}")
|
||||
remarks, logs = {}, []
|
||||
for cid in task_cids:
|
||||
rows = df[df['身份证号'].map(
|
||||
lambda v: config._id_hit(config._norm_id(_clean_cell(v)), [cid]))]
|
||||
if rows.empty:
|
||||
remarks[cid] = "未查询到回盘记录"
|
||||
logs.append(f" 证件{cid}:回盘表中未找到记录 → 备注追加「未查询到回盘记录」")
|
||||
continue
|
||||
best_row, best_ok = None, -1
|
||||
for _, row in rows.iterrows():
|
||||
ok = sum(1 for c in config.INS_STATUSES if _clean_cell(row[c]) == config.INS_OK)
|
||||
if ok > best_ok:
|
||||
best_row, best_ok = row, ok
|
||||
target = best_row
|
||||
bh = _clean_cell(target['个人编号'])
|
||||
if best_ok == len(config.INS_STATUSES):
|
||||
remarks[cid] = f"个人编号:{bh}"
|
||||
logs.append(f" 证件{cid}:五项均参保缴费,个人编号 {bh} → 备注追加")
|
||||
else:
|
||||
bad = [f"{c}:{_clean_cell(target[c])}"
|
||||
for c in config.INS_STATUSES if _clean_cell(target[c]) != config.INS_OK]
|
||||
remarks[cid] = f"个人编号:{bh};" + "、".join(bad)
|
||||
logs.append(f" 证件{cid}:参保状态异常 → {';'.join(bad)}(个人编号 {bh})→ 备注追加")
|
||||
return remarks, logs
|
||||
|
||||
|
||||
# ==================== 统一核查引擎 ====================
|
||||
class ReviewEngine:
|
||||
"""按 kind(add/stop)配置的增/减员核查回盘引擎。"""
|
||||
|
||||
def __init__(self, kind):
|
||||
self.kind = kind
|
||||
if kind == 'add':
|
||||
self.business_item = "城保参保单位人员增加"
|
||||
self.pass_status = "参保成功"
|
||||
self.fail_status = "参保失败"
|
||||
self.status_label = "办理状态"
|
||||
self.operation_type = config.WEB_ADD_TYPES
|
||||
else:
|
||||
self.business_item = "城保参保单位人员减少"
|
||||
self.pass_status = "停保成功"
|
||||
self.fail_status = "停保失败"
|
||||
self.status_label = config.STOP_PROCESSED_COL
|
||||
self.operation_type = None
|
||||
self.writeback = Writeback(kind)
|
||||
# 回盘子目录:减员固定「停保-减员」;增员按参保类型分(新参保-增员 / 转移参保-增员)
|
||||
self._huipan_subs = {"新参保": config.OUTPUT_DIR_ADD_NEW,
|
||||
"转移参保": config.OUTPUT_DIR_ADD_TRANS}
|
||||
|
||||
# ---------------- 单个单位完整核查 ----------------
|
||||
def do_unit_check(self, task):
|
||||
"""登录后的完整核查流程。返回结果 dict(JSON 安全)。"""
|
||||
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, "checked": 0, "passed": 0, "failed": 0,
|
||||
"redo400": [], "skipped": False}
|
||||
try:
|
||||
_shot(work_tab, "c1_workbench")
|
||||
biz_tab = _open_business_page(page, work_tab, self.business_item)
|
||||
_close_tip_modal(biz_tab) # 减员特有;增员无该弹窗,调用无害
|
||||
_dismiss_popups(biz_tab)
|
||||
# 关键:必须等单位信息接口(getAab001)返回本单位,否则后续查询拿不到数据。
|
||||
# 接口偶发失败会弹「温馨提示」,统一重走业务入口自愈,最多 3 次
|
||||
unit_info = None
|
||||
for attempt in range(1, 4):
|
||||
unit_info = _wait_unit_loaded(biz_tab, task['unit'])
|
||||
if unit_info is not None:
|
||||
break
|
||||
config.log(f" 单位信息未加载(第 {attempt} 次),重走业务入口...")
|
||||
if attempt < 3:
|
||||
biz_tab = _reopen_biz(page, self.business_item)
|
||||
if unit_info is None:
|
||||
res.update(success=True, skipped=True,
|
||||
message="单位信息未加载(getAab001无数据),跳过")
|
||||
return res
|
||||
unit_full = str(unit_info.get('aab004') or '').strip()
|
||||
fail_cids = set()
|
||||
_shot(biz_tab, "c2_biz_page")
|
||||
|
||||
table = _open_query_menu(biz_tab)
|
||||
_shot(biz_tab, "c3_query_list")
|
||||
status, view = _read_first_row(table)
|
||||
if not status:
|
||||
res.update(success=True, skipped=True, message="已申报查询无记录,跳过")
|
||||
elif status != config.DONE_STATUS:
|
||||
res.update(success=True, skipped=True,
|
||||
message=f"第一条状态「{status}」非{config.DONE_STATUS},跳过")
|
||||
else:
|
||||
config.log(f" 第一条状态:{status},点击查看读取审核结论")
|
||||
url = _capture_query_url(page, biz_tab, view)
|
||||
results, detail_full = _replay_query_all(biz_tab, url)
|
||||
unit_full = unit_full or detail_full
|
||||
_shot(biz_tab, "c4_detail_fetched")
|
||||
if not results:
|
||||
res.update(success=True, message="明细接口返回 0 条,跳过")
|
||||
else:
|
||||
status_map, remark_map, redo400, logs = _build_writeback(
|
||||
self, results, task['cids'], task['unit'])
|
||||
fail_cids = {cid for cid, st in status_map.items() if st == self.fail_status}
|
||||
for line in logs:
|
||||
config.log(line)
|
||||
if status_map or remark_map:
|
||||
self.writeback.writeback_source(status_map, remark_map)
|
||||
n_match = len([r for r in results if r['cid'] in task['cids']])
|
||||
n_pass = len([v for v in status_map.values() if v == self.pass_status])
|
||||
n_fail = len([v for v in status_map.values() if v == self.fail_status])
|
||||
res.update(
|
||||
success=True, checked=n_match, passed=n_pass, failed=n_fail,
|
||||
redo400=redo400,
|
||||
message=(f"核查{n_match}条,通过{n_pass} 失败{n_fail} "
|
||||
f"400系统错误{len(redo400)}(结束后统一清状态)"))
|
||||
|
||||
# 回盘打印:每个账号核查完都下载回盘表(增员核对参保状态,减员留档)
|
||||
try:
|
||||
name_for_file = (unit_full or task['unit']).strip()
|
||||
if unit_full and unit_full != task['unit']:
|
||||
config.log(f" 使用平台单位全称命名:{unit_full}")
|
||||
config.log(" 开始回盘打印下载...")
|
||||
sub = (self._huipan_subs.get(task.get('type'), config.OUTPUT_DIR_ADD_NEW)
|
||||
if self.kind == 'add' else config.OUTPUT_DIR_STOP)
|
||||
save_dir = Path(config.replay_dir(sub))
|
||||
hp_file = _download_huipan(page, biz_tab, name_for_file,
|
||||
self.business_item, save_dir)
|
||||
config.log(f" 回盘文件已保存:{hp_file}")
|
||||
if self.kind == 'add':
|
||||
self._verify_add_huipan(hp_file, task['cids'], fail_cids, res)
|
||||
else:
|
||||
res["huipan"] = f"回盘已下载留档:{hp_file.name}"
|
||||
except Exception as e:
|
||||
res["huipan"] = f"回盘打印失败:{e}"
|
||||
config.log(f" 回盘打印失败:{e}")
|
||||
return res
|
||||
except Exception as e:
|
||||
res["message"] = f"核查异常:{e}"
|
||||
return res
|
||||
|
||||
def _verify_add_huipan(self, hp_file, task_cids, fail_cids, res):
|
||||
"""增员回盘核对:五项参保状态 + 个人编号备注追加。"""
|
||||
hp_remarks, hp_logs = _verify_huipan(hp_file, task_cids)
|
||||
for line in hp_logs:
|
||||
config.log(line)
|
||||
for cid in fail_cids:
|
||||
if hp_remarks.get(cid, "").strip() == "未查询到回盘记录":
|
||||
hp_remarks.pop(cid)
|
||||
config.log(f" 证件{cid}:审核不通过无回盘记录,跳过未查询备注")
|
||||
for cid in list(hp_remarks):
|
||||
old = self.writeback._pending_remark.get(cid)
|
||||
if old:
|
||||
hp_remarks[cid] = f"{old}\n{hp_remarks[cid]}"
|
||||
if hp_remarks:
|
||||
self.writeback.writeback_source({}, hp_remarks)
|
||||
res["huipan"] = f"回盘已下载,核对回写 {len(hp_remarks)} 人"
|
||||
|
||||
# ---------------- 逐单位登录 + 核查 ----------------
|
||||
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']}"
|
||||
f"({task['count']}人待审核)==========")
|
||||
acc = accounts.get(task['unit'])
|
||||
if len(tasks) > 1:
|
||||
config.progress(span_start + int((span_end - span_start) * (i - 1) / len(tasks)))
|
||||
try:
|
||||
login_res = web_login.ensure_login(acc["username"], acc["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_unit_check(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)):
|
||||
"""主流程:恢复缓存 → 读待审核名单 → 取号 → 预检 → 逐单位登录核查 → 统一回写。"""
|
||||
recovered_ids = self.writeback.load_ckpt()
|
||||
tasks, source_file, source_sheet = source_reader.load_check_tasks(
|
||||
self.kind, status_filter=config.CHECK_STATUS, 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 tasks:
|
||||
return {"success": True, "message": "无待核查数据", "total": 0, "done": 0}
|
||||
|
||||
accounts = source_reader.load_accounts([t['unit'] for t in tasks])
|
||||
errors = []
|
||||
for t in tasks:
|
||||
acc = accounts.get(t['unit'])
|
||||
if acc is None:
|
||||
errors.append(f"[{t['unit']}] 台账未匹配")
|
||||
elif not acc['username'] or not acc['password']:
|
||||
errors.append(f"[{t['unit']}] 账号或密码缺失")
|
||||
if errors:
|
||||
config.log("\n预检未通过:")
|
||||
for e in errors:
|
||||
config.log(f" - {e}")
|
||||
return {"success": False, "message": "预检未通过,详见日志",
|
||||
"total": len(tasks), "done": 0}
|
||||
|
||||
limit = config.get_run_limit()
|
||||
todo = tasks[:limit]
|
||||
results = self.process_units(todo, accounts, progress_span)
|
||||
|
||||
# 400系统错误:核查时只记录,全部单位核查完后统一清空状态回待办(重新走名单制作+办理)
|
||||
redo_all = [p for r in results for p in (r.get("redo400") or [])]
|
||||
if redo_all:
|
||||
self.writeback.writeback_source({p['cid']: "" for p in redo_all}, {})
|
||||
config.log(f"\n400系统错误共 {len(redo_all)} 人,已统一清空状态回待办,"
|
||||
f"请重新执行名单制作后办理:")
|
||||
for p in redo_all:
|
||||
config.log(f" - {p['name']}({p['cid']}){p['unit']}")
|
||||
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"]]
|
||||
skip = [r for r in ok if r.get("skipped")]
|
||||
config.log(f"\n========== 汇总 ==========")
|
||||
config.log(f"核查完成 {len(ok) - len(skip)} 家,跳过(未办结/无记录){len(skip)} 家,"
|
||||
f"失败 {len(fail)} 家")
|
||||
for r in fail:
|
||||
config.log(f" ✗ {r['unit']}:{r.get('message', '')}")
|
||||
return {"success": not fail,
|
||||
"message": f"完成{len(ok) - len(skip)}/跳过{len(skip)}/失败{len(fail)}",
|
||||
"total": len(results), "done": len(ok) - len(skip)}
|
||||
@@ -0,0 +1,75 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0008",
|
||||
"name": "重庆社保增减员办理",
|
||||
"version": "1.0.5",
|
||||
"description": "重庆社保增减员全流程(XQ0008 名单制作 + XQ0014 系统办理/核查回盘 + XQ0015/XQ0016 告知书制作下发):目录预检、增/减员名单制作、增/减员系统办理、增/减员核查回盘、告知书制作与 OA 推送八阶段可选串行。逐参保单位读取台账账号登录重庆人社政务平台(法人用户+图形验证码识别)完成导入申报、审核结论核查与回盘表核对,回写源名单办理状态/办理停保及备注;生成三类告知书并构造 OA 工作沟通推送,全程 JSON 缓存防崩溃、结束统一落盘。",
|
||||
"category": "社保",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0008"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"base_dir": {
|
||||
"type": "string",
|
||||
"title": "资料根目录",
|
||||
"default": "D:\\资料\\人资\\重庆社保增减员办理",
|
||||
"description": "统一目录:源名单/台账/增员减员模版/花名册/告知书模板/名单产出与回盘表"
|
||||
},
|
||||
"ledger_dir": {
|
||||
"type": "string",
|
||||
"title": "台账目录",
|
||||
"default": "",
|
||||
"description": "留空=同资料根目录(社保户头管理台账)"
|
||||
},
|
||||
"phases": {
|
||||
"type": "array",
|
||||
"title": "执行阶段(可多选)",
|
||||
"items": {
|
||||
"type": "string",
|
||||
"enum": ["dir_check", "add_list", "stop_list", "add_import", "stop_import", "add_review", "stop_review", "notice"]
|
||||
},
|
||||
"default": ["dir_check", "add_list", "stop_list", "add_import", "stop_import", "add_review", "stop_review", "notice"],
|
||||
"description": "多选按顺序串行;留空=全部八阶段(目录预检/名单制作/系统办理/核查回盘/告知书制作)"
|
||||
},
|
||||
"run_limit": {
|
||||
"type": "integer",
|
||||
"title": "每次限制单位数",
|
||||
"default": 0,
|
||||
"description": "0=不限制,一次跑完全部;>0 只处理前 N 个单位(已办/已回写自动跳过)"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试模式",
|
||||
"default": false,
|
||||
"description": "开启后保存页面截图与验证码调试图(定位问题用,日常关闭)"
|
||||
},
|
||||
"notice_branch": {
|
||||
"type": "string",
|
||||
"title": "告知书分支",
|
||||
"default": "all",
|
||||
"enum": ["all", "新参保", "转移参保"],
|
||||
"description": "all=全部(新参保+转移参保);新参保=参保+参保异常;转移参保=社保转移"
|
||||
},
|
||||
"notice_push_oa": {
|
||||
"type": "boolean",
|
||||
"title": "自动推 OA 工作沟通",
|
||||
"default": false,
|
||||
"description": "生成告知书后自动推 OA(需先在工作台登录 OA);关闭则只落盘 oa_messages.json"
|
||||
},
|
||||
"notice_test_mode": {
|
||||
"type": "boolean",
|
||||
"title": "测试接收人模式",
|
||||
"default": false,
|
||||
"description": "开启后 OA 推送接收人统一为测试接收人(正式推送请关闭)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
pandas
|
||||
openpyxl
|
||||
xlrd
|
||||
xlwt
|
||||
xlutils
|
||||
DrissionPage
|
||||
ddddocr
|
||||
python-dotenv
|
||||
python-docx
|
||||
pywin32
|
||||
requests
|
||||
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
@@ -0,0 +1,13 @@
|
||||
<!DOCTYPE html>
|
||||
<html lang="zh-CN">
|
||||
<head>
|
||||
<meta charset="UTF-8" />
|
||||
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
|
||||
<title>重庆社保增减员办理</title>
|
||||
<script type="module" crossorigin src="/pui/xq0008/assets/index-BBdqrctM.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0008/assets/index-BabdCiHB.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,92 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0009 门店上月请休假异常人员名单梳理 插件入口。
|
||||
|
||||
流程编排(由影刀版 absence_analysis.py 移植,登录态改由底座注入,插件不做自动补登):
|
||||
1) 会话校验:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
|
||||
2) 花名册:字段指定路径,或自动导出到输出目录(员工花名册.xlsx,15 分钟 TTL 缓存复用);
|
||||
3) 收银会话(技师考勤源,统计月/当前月 >= 2026-09):插件字段提供账号密码时自动接口登录,
|
||||
凭据错误中止运行;未提供凭据且无有效缓存登录态时告警降级仅用 HR 数据;
|
||||
4) 统计月考勤报表(实时)→ 报表「休息/旷工」+ 收银技师覆盖 + 全集团整天请假并入缺勤判定;
|
||||
5) 返岗判定:统计月已结束时补拉当前月考勤(技师走收银出勤日集合);
|
||||
6) 计算月末往前连续未出勤 >= 5 天人员(跨月追溯逐月重估),导出 20 列 Excel 名单。
|
||||
|
||||
运行上下文:底座注入 HR 会话与 userId(config 全局钩子),platform = hr,uses_month = True
|
||||
(前端页眉月份选择器经 payload.ref_month 注入)。
|
||||
"""
|
||||
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
|
||||
|
||||
from . import config
|
||||
from .report.absence_report import build_absence_report, resolve_month
|
||||
|
||||
|
||||
class AbsenceAnalysisPlugin(ScenePlugin):
|
||||
"""门店上月请休假异常人员名单梳理(需求 XQ0009)。"""
|
||||
|
||||
id = "xq0009"
|
||||
name = "门店上月请休假异常人员名单梳理"
|
||||
version = "1.0.3"
|
||||
description = ("梳理上月请休假异常人员:月末往前连续未出勤 >= 5 天(休息/旷工/整天请假计入,"
|
||||
"跨月往前追溯至返岗前一日)。技师考勤自 2026-09 起取收银系统数据,"
|
||||
"非技师走 HR 考勤统计报表 + 请假流程,输出 20 列 Excel 名单。")
|
||||
platform = "hr"
|
||||
uses_month = True
|
||||
capabilities = ["xq0009"]
|
||||
permissions = {"platforms": ["hr"]}
|
||||
fields = {
|
||||
"ref_month": {
|
||||
"type": "string", "title": "统计月份", "default": "",
|
||||
"description": "留空=上月;格式 YYYY-MM",
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string", "title": "输出目录",
|
||||
"default": r"D:\资料\人资\请休假异常",
|
||||
"description": "名单 Excel 与自动导出花名册的输出目录",
|
||||
},
|
||||
"roster_path": {
|
||||
"type": "string", "title": "花名册文件路径", "default": "",
|
||||
"description": "留空=自动导出到输出目录/员工花名册.xlsx(15 分钟内复用缓存)",
|
||||
},
|
||||
"cashier_username": {
|
||||
"type": "string", "title": "收银系统账号", "default": "",
|
||||
"description": "技师考勤数据源(2026-09 起技师考勤在收银系统);"
|
||||
"留空=复用缓存登录态,无缓存时降级仅用 HR 数据(技师名单可能缺失)",
|
||||
},
|
||||
"cashier_password": {
|
||||
"type": "string", "title": "收银系统密码", "format": "password", "default": "",
|
||||
"description": "配套密码;提供凭据后登录失败将中止运行(防止静默缺技师数据出错名单)",
|
||||
},
|
||||
}
|
||||
|
||||
def run(self, fields: dict, ctx):
|
||||
# ---- 注入运行上下文:日志 / HR 会话 / userId ----
|
||||
config.set_log(ctx.log)
|
||||
config.set_session(ctx.get_session("hr"))
|
||||
config.set_user_id(ctx.get_user_id("hr"))
|
||||
|
||||
ref_month = (fields.get("ref_month") or fields.get("month") or "").strip()
|
||||
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
|
||||
roster_path = (fields.get("roster_path") or "").strip()
|
||||
cashier_username = (fields.get("cashier_username") or "").strip()
|
||||
cashier_password = fields.get("cashier_password") or ""
|
||||
|
||||
_, _, month_str = resolve_month(ref_month)
|
||||
ctx.log(f"===== 门店上月请休假异常名单梳理启动:统计月 {month_str},"
|
||||
f"输出目录 {save_dir} =====", "INFO")
|
||||
ctx.progress(3)
|
||||
|
||||
# ---- 主流程(会话校验 → 花名册 → 收银 → 统计月/当前月数据 → 分析 → 导出) ----
|
||||
result = build_absence_report(
|
||||
save_dir=save_dir, roster_path=roster_path, ref_month=ref_month,
|
||||
cashier_username=cashier_username, cashier_password=cashier_password,
|
||||
progress=ctx.progress,
|
||||
)
|
||||
|
||||
summary = ("请休假异常名单梳理完成(统计 {b} ~ {e}):连续未出勤 >= {days} 天共 {n} 人。"
|
||||
"文件:{path}").format(b=result["begin"], e=result["end"],
|
||||
days=config.MIN_CONSECUTIVE_DAYS,
|
||||
n=result["count"], path=result["path"])
|
||||
return {"summary": summary, "detail": {"名单人数": result["count"]},
|
||||
"path": result["path"], "ym": result["month"]}
|
||||
|
||||
|
||||
PLUGINS.append(AbsenceAnalysisPlugin())
|
||||
@@ -0,0 +1,184 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0009 门店上月请休假异常人员名单梳理 插件 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
所有业务模块统一经 config.logger 输出日志、config.require_session()/require_user_id() 取登录态。
|
||||
HR 登录态由底座注入(hr 平台),插件不做自动补登,失效时提示「请重新登录」。
|
||||
收银系统(技师考勤源)底座无平台支持,由插件 data/cashier_api.py 自包含实现纯接口登录。
|
||||
"""
|
||||
import os
|
||||
|
||||
# ==================== 共享目录(与影刀版同路径) ====================
|
||||
_APP_DATA_DIR = os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
|
||||
|
||||
# ==================== HR 系统 ====================
|
||||
HR_BASE_URL = "https://hr.37du.co"
|
||||
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
|
||||
LEAVE_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 考勤统计报表(逐日出勤) ----------
|
||||
# 分页查询「考勤统计报表」,每人一行含 v_1~v_最后一天(当月逐日出勤状态),返回 JSON
|
||||
MONTH_ATT_REPORT_URL = f"{HR_BASE_URL}/RedseaPlatform/pt/report/excel/detail/getPageAjax.mc"
|
||||
MONTH_ATT_REPORT_ID = "f880c52a619446e0b74e3820b898d53b"
|
||||
# 集团根组织 struId(struId / belongUnitStruId / ds1.struId / ds2.stru_id 共用)
|
||||
COMPANY_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
|
||||
# 报表接口单页最大支持 1000 条(全集团一次拉取减少翻页请求)
|
||||
REPORT_PAGE_SIZE = 1000
|
||||
|
||||
# 项目级重试(AGENTS.md):瞬时故障最多重试 3 次,三次仍失败后再记录错误日志
|
||||
MAX_REQUEST_RETRY = 3
|
||||
|
||||
# ==================== 名单输出配置 ====================
|
||||
# 默认保存目录
|
||||
DEFAULT_SAVE_DIR = r"D:\资料\人资\请休假异常"
|
||||
|
||||
# 连续未出勤天数阈值:>= 该天数纳入名单
|
||||
MIN_CONSECUTIVE_DAYS = 5
|
||||
|
||||
# 跨月追溯「逐月重估」:每往前推一个月,仍在追溯人数 >= TRACE_SINGLE_MAX 时用「整月全量缓存」
|
||||
# (每月报表+请假各拉一次,多人共用),否则切「按工号单人查询」(少人数长缺勤,如产假/长期病假,
|
||||
# 逐人回溯到上班日)。追溯人数逐月递减,早期月份批量、人少了自动切单人,减少全量拉取。不设月份上限。
|
||||
TRACE_SINGLE_MAX = 10
|
||||
|
||||
# 名单输出列(含备注列):部门维度为花名册 所属单位/所属部门/一级~五级部门,并补充离职时间
|
||||
COLUMNS = [
|
||||
"序号", "所属单位", "所属部门", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
"37工号", "姓名", "联系电话", "岗位",
|
||||
"技师工号", "参保类型", "入职时间", "离职时间",
|
||||
"请休假起始日期", "请休假结束日期", "请休假天数",
|
||||
"备注",
|
||||
]
|
||||
|
||||
# 未归岗占位文案(情况 A 且无任何请假流程)
|
||||
NOT_BACK_TEXT = "未归岗,时间待定"
|
||||
|
||||
# 请假记录状态(bpm_status):001=申请中;002=已备案(生效);003=已撤销;004=销假中;
|
||||
# 005=已销假;006=撤销加班;007=销差;008=已审批未备案。
|
||||
# 整天请假缺勤判定与「仍在请假中」判定均只认 002 已备案记录:撤销(003)/已销假(005)/申请中(001)
|
||||
# 的假单在考勤报表里不体现,若也计入会把实际正常上班的人误放进名单。
|
||||
ACTIVE_LEAVE_STATUS = "002"
|
||||
|
||||
# 当前月「返岗」判定用:报表单元格命中任一请假类片段即视为「未到公司」。
|
||||
# 休息/旷工 单独精确匹配(保持统计月口径:半天「上班旷工/下班旷工」不算整天缺席)。
|
||||
NOT_ATTEND_FRAGMENTS = (
|
||||
"事假", "病假", "产假", "调休假", "年度福利假", "特别福利假", "小时特假",
|
||||
)
|
||||
|
||||
# ==================== 收银系统技师考勤 ====================
|
||||
# 背景:HR 系统从 2026-09 起不再有技师考勤数据(技师考勤迁移到收银系统),需求9 需两个系统联动:
|
||||
# - 技师:未出勤日集合来自收银技师月度考勤接口(旷工/请假/休息 逐日显式标记);
|
||||
# - 非技师:仍走 HR 考勤统计报表 + 请假流程。
|
||||
# 时间边界:2026-09 是技师数据迁移分界——
|
||||
# - 统计月 / 当前月 >= 2026-09 时,技师未出勤/返岗判定走收银(HR 该月起无技师数据);
|
||||
# - 统计月早于 2026-09,以及跨月追溯的历史月(2026-09 之前),一律走 HR 原逻辑。
|
||||
CASHIER_MIGRATE_MONTH = "2026-09" # HR 技师数据迁移到收银的起始月
|
||||
# 收银登录态(Access-Token/Refresh-Token 请求头,不走 cookie)与影刀「37du收银登录(接口版)」
|
||||
# 共用同一落盘文件,登录态互通复用。
|
||||
CASHIER_TOKEN_FILE = os.path.join(SESSIONS_DIR, 'cashier_tokens.json')
|
||||
CASHIER_API_BASE = "https://api.37du.cashier.37du.co"
|
||||
CASHIER_LOGIN_URL = f"{CASHIER_API_BASE}/sys/user/login"
|
||||
CASHIER_VALIDATE_URL = f"{CASHIER_API_BASE}/sys/user/get/info"
|
||||
CASHIER_STORE_LIST_URL = f"{CASHIER_API_BASE}/store/manager/connect/list"
|
||||
CASHIER_ATT_URL = f"{CASHIER_API_BASE}/store/manager/techAttendanceMonthlyReport/month"
|
||||
CASHIER_STORE_CACHE = os.path.join(_APP_DATA_DIR, 'data', 'cashier_stores.json')
|
||||
CASHIER_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
|
||||
"Chrome/120.0.0.0 Safari/537.36")
|
||||
# 与浏览器 SPA 同源请求头(防服务端后续加 Origin/Referer 校验)
|
||||
CASHIER_ORIGIN = 'https://admin.37du.cashier.37du.co'
|
||||
# 收银登录整轮重试(项目级重试机制)
|
||||
CASHIER_LOGIN_ROUND_MAX = 3
|
||||
CASHIER_TIMEOUT = 15
|
||||
# 收银逐日 un_duty_type 首个 code → 需求9 未出勤类别(其余非空 code 一律归为请假)
|
||||
# code:2=正休(休息)、6=旷工;7=假别7/特殊事假、3=假别3、5=病假、1=事假、4=长假、9/10=假别9/10(请假)
|
||||
CASHIER_UN_DUTY_CAT = {6: "旷工", 2: "休息"}
|
||||
|
||||
# ==================== 接口数据懒缓存 ====================
|
||||
# 统计月(上月)始终实时调接口;跨月追溯往前的历史月走缓存旁路:
|
||||
# 每次先查本地缓存,没有才调接口,调完按「月 / 月+工号」落盘,下次直接复用;
|
||||
# 缓存以 月/工号 为键互不影响,如需强制刷新删除对应缓存文件即可。
|
||||
CACHE_DIR = os.path.join(_APP_DATA_DIR, "absence_cache")
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_session = None
|
||||
_user_id = ""
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def log(msg, level="INFO"):
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f"[{level}] {msg}")
|
||||
|
||||
|
||||
class _ModuleLogger:
|
||||
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
|
||||
|
||||
@staticmethod
|
||||
def debug(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "DEBUG")
|
||||
|
||||
@staticmethod
|
||||
def info(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "INFO")
|
||||
|
||||
@staticmethod
|
||||
def warning(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "WARN")
|
||||
|
||||
@staticmethod
|
||||
def error(msg, *args):
|
||||
if args:
|
||||
msg = msg % args
|
||||
log(msg, "ERROR")
|
||||
|
||||
|
||||
logger = _ModuleLogger()
|
||||
|
||||
|
||||
def set_session(session):
|
||||
global _session
|
||||
_session = session
|
||||
|
||||
|
||||
def get_session():
|
||||
return _session
|
||||
|
||||
|
||||
def require_session():
|
||||
"""取插件运行期注入的 HR session(缺失抛错,提示先在插件界面登录 HR)。"""
|
||||
if _session is None:
|
||||
raise RuntimeError("未注入 HR 登录态,请先在插件界面完成 HR 登录")
|
||||
return _session
|
||||
|
||||
|
||||
def set_user_id(uid):
|
||||
global _user_id
|
||||
_user_id = str(uid or "")
|
||||
|
||||
|
||||
def get_user_id():
|
||||
return _user_id
|
||||
|
||||
|
||||
def require_user_id():
|
||||
uid = _user_id
|
||||
if not uid:
|
||||
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
|
||||
return uid
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0009 插件 - 数据层:HR 接口 / 花名册导出 / 收银系统技师考勤。"""
|
||||
@@ -0,0 +1,428 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0009 插件 - 收银系统技师考勤(自包含实现,底座无收银平台登录支持)。
|
||||
|
||||
由 workflows/.../absence_analysis.py 内联收银逻辑 + workflows/share/cashier_login_api.py
|
||||
(接口版登录)移植,职责:
|
||||
1. 纯接口登录(MD5 -> POST /sys/user/login -> 校验 token -> 落盘),登录态与影刀
|
||||
「37du收银登录(接口版)」共用同一 token 文件,互通复用;
|
||||
2. 门店列表(带本地缓存文件)与技师月度考勤逐门店拉取;
|
||||
3. 模块级运行时 state(month_status 未出勤映射 / month_on 出勤日集合)供 logic 层查询。
|
||||
|
||||
插件化改造点:
|
||||
- 凭据由插件界面字段传入(不再读 .env):提供凭据且缓存失效时自动登录,
|
||||
凭据错误直接 RuntimeError 中止(用户显式配置凭据却静默缺技师数据会产生错误名单);
|
||||
未提供凭据且无有效缓存登录态时返回 False,调用方告警降级仅用 HR 数据。
|
||||
- 日志统一转发到 config.logger。
|
||||
"""
|
||||
import calendar
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import date
|
||||
|
||||
import requests
|
||||
|
||||
from ..config import (
|
||||
logger, MAX_REQUEST_RETRY,
|
||||
CASHIER_TOKEN_FILE, CASHIER_MIGRATE_MONTH,
|
||||
CASHIER_LOGIN_URL, CASHIER_VALIDATE_URL,
|
||||
CASHIER_STORE_LIST_URL, CASHIER_ATT_URL, CASHIER_STORE_CACHE, CACHE_DIR,
|
||||
CASHIER_UA, CASHIER_ORIGIN, CASHIER_LOGIN_ROUND_MAX, CASHIER_TIMEOUT,
|
||||
CASHIER_UN_DUTY_CAT,
|
||||
)
|
||||
|
||||
# 收银扩展运行时状态:
|
||||
# session 收银 requests 会话(ensure_session 成功后构建)
|
||||
# month_status 收银未出勤映射缓存 {month_key: {工号: {日期: 类别}}}
|
||||
# month_on 收银出勤日缓存 {month_key: {工号: {日期}}}(当前月返岗判定用)
|
||||
state = {"session": None, "month_status": {}, "month_on": {}}
|
||||
|
||||
|
||||
# ==================== Token 持久化(与影刀接口版登录格式一致) ====================
|
||||
def _load_tokens():
|
||||
if not os.path.exists(CASHIER_TOKEN_FILE):
|
||||
return None
|
||||
try:
|
||||
with open(CASHIER_TOKEN_FILE, encoding='utf-8') as f:
|
||||
tokens = json.load(f)
|
||||
return tokens or None
|
||||
except Exception as e:
|
||||
logger.warning("收银 token 文件读取失败:%s(%s)", CASHIER_TOKEN_FILE, e)
|
||||
return None
|
||||
|
||||
|
||||
def _save_tokens(token, refresh_token):
|
||||
"""落盘 {"access": ..., "refresh": ...},与影刀登录指令结构一致。"""
|
||||
os.makedirs(os.path.dirname(CASHIER_TOKEN_FILE), exist_ok=True)
|
||||
with open(CASHIER_TOKEN_FILE, 'w', encoding='utf-8') as f:
|
||||
json.dump({"access": token, "refresh": refresh_token or ""},
|
||||
f, ensure_ascii=False, indent=2)
|
||||
logger.info("已保存收银 Access-Token/Refresh-Token 到 %s", CASHIER_TOKEN_FILE)
|
||||
|
||||
|
||||
# ==================== Token 有效性校验 ====================
|
||||
def _is_cashier_session_valid(tokens=None):
|
||||
"""API 轻量校验收银 Access-Token:请求校验接口,HTTP 200 且 code==200 视为有效。
|
||||
|
||||
tokens 缺省时从共享 token 文件读取(复用缓存场景);传入时直接校验该 token
|
||||
(登录后落盘前使用)。
|
||||
"""
|
||||
try:
|
||||
if tokens is None:
|
||||
tokens = _load_tokens()
|
||||
if not tokens or not tokens.get("access"):
|
||||
return False
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": CASHIER_UA,
|
||||
"Access-Token": tokens["access"],
|
||||
"Refresh-Token": tokens.get("refresh", ""),
|
||||
"Origin": CASHIER_ORIGIN,
|
||||
"Referer": CASHIER_ORIGIN + '/',
|
||||
})
|
||||
resp = session.get(CASHIER_VALIDATE_URL,
|
||||
params={"_t": str(int(time.time() * 1000))},
|
||||
timeout=CASHIER_TIMEOUT)
|
||||
if resp.status_code != 200:
|
||||
logger.debug("收银 Token 校验状态码异常:%s", resp.status_code)
|
||||
return False
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
return False
|
||||
return isinstance(data, dict) and data.get("code") == 200
|
||||
except Exception as e:
|
||||
logger.warning("校验收银 Token 异常:%s", e)
|
||||
return False
|
||||
|
||||
|
||||
# ==================== 纯接口登录 ====================
|
||||
def _login_headers():
|
||||
return {
|
||||
"User-Agent": CASHIER_UA,
|
||||
"Content-Type": "application/json",
|
||||
"Origin": CASHIER_ORIGIN,
|
||||
"Referer": CASHIER_ORIGIN + '/login',
|
||||
"Accept": "application/json, text/plain, */*",
|
||||
}
|
||||
|
||||
|
||||
def do_login_api(username, password):
|
||||
"""完整接口登录:MD5 加密 -> POST /sys/user/login -> 校验 token -> 落盘。
|
||||
|
||||
返回 (ok, message)。凭据错误等被拒类响应重试无意义直接返回失败;
|
||||
网络类异常按轮重试(最多 CASHIER_LOGIN_ROUND_MAX 轮,项目级重试机制)。
|
||||
"""
|
||||
md5_password = hashlib.md5(password.encode('utf-8')).hexdigest()
|
||||
for rnd in range(1, CASHIER_LOGIN_ROUND_MAX + 1):
|
||||
logger.info("--- 第 %d 轮收银登录(接口版) ---", rnd)
|
||||
try:
|
||||
resp = requests.post(
|
||||
CASHIER_LOGIN_URL,
|
||||
json={"account": username, "password": md5_password,
|
||||
"response_token": "", "mode": "none"},
|
||||
params={"_t": str(int(time.time() * 1000))},
|
||||
headers=_login_headers(), timeout=CASHIER_TIMEOUT)
|
||||
except Exception as e:
|
||||
logger.warning("提交收银登录异常:%s", e)
|
||||
time.sleep(1)
|
||||
continue
|
||||
if resp.status_code != 200:
|
||||
logger.warning("收银登录接口状态码异常:%s", resp.status_code)
|
||||
time.sleep(1)
|
||||
continue
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
logger.warning("收银登录响应非 JSON")
|
||||
time.sleep(1)
|
||||
continue
|
||||
if not (isinstance(data, dict) and data.get("code") == 200):
|
||||
msg = data.get("msg") if isinstance(data, dict) else str(resp.text[:200])
|
||||
return False, f"登录被拒绝(账号或密码错误?):{msg}"
|
||||
payload = data.get("data") or {}
|
||||
token = payload.get("token") or ""
|
||||
refresh_token = payload.get("refresh_token") or ""
|
||||
if not token:
|
||||
return False, "登录接口未返回 Access-Token"
|
||||
# 落盘前先校验本次登录拿到的 token 真实可用
|
||||
if _is_cashier_session_valid(tokens={"access": token, "refresh": refresh_token}):
|
||||
_save_tokens(token, refresh_token)
|
||||
return True, "登录成功"
|
||||
logger.warning("收银登录接口返回成功但 token 校验未通过")
|
||||
time.sleep(1)
|
||||
return False, "登录失败(重试耗尽或接口异常)"
|
||||
|
||||
|
||||
def _build_session():
|
||||
"""读共享收银 token 构造 requests 会话(认证头 Access-Token/Refresh-Token,不走 cookie)。"""
|
||||
if not os.path.exists(CASHIER_TOKEN_FILE):
|
||||
raise RuntimeError("未找到收银系统登录态 tokens,请先完成收银登录后再重试。")
|
||||
with open(CASHIER_TOKEN_FILE, encoding='utf-8') as f:
|
||||
tokens = json.load(f)
|
||||
access = tokens.get("access") or tokens.get("Access-Token") or ""
|
||||
if not access:
|
||||
raise RuntimeError("收银系统登录态 tokens 缺少 access token,请重新完成收银登录。")
|
||||
s = requests.Session()
|
||||
s.headers.update({
|
||||
"User-Agent": CASHIER_UA,
|
||||
"Access-Token": access,
|
||||
"Refresh-Token": tokens.get("refresh") or tokens.get("Refresh-Token") or "",
|
||||
})
|
||||
return s
|
||||
|
||||
|
||||
def ensure_session(username, password):
|
||||
"""确保收银系统登录态可用,返回 True/False 表示是否有可用会话。
|
||||
|
||||
优先复用共享 token 文件的缓存登录态;失效且插件界面提供了账号密码时走接口登录,
|
||||
凭据错误抛 RuntimeError 中止运行;未提供凭据时返回 False(调用方告警降级仅用 HR)。
|
||||
"""
|
||||
if _is_cashier_session_valid():
|
||||
state["session"] = _build_session()
|
||||
logger.info("复用缓存收银登录态:%s", CASHIER_TOKEN_FILE)
|
||||
return True
|
||||
username = (username or "").strip()
|
||||
password = (password or "").strip()
|
||||
if not username or not password:
|
||||
logger.warning("收银系统登录态缺失且未提供技师考勤账号,"
|
||||
"本次降级仅用 HR 数据(技师考勤可能缺失,名单口径不完整)")
|
||||
return False
|
||||
ok, msg = do_login_api(username, password)
|
||||
if not ok:
|
||||
raise RuntimeError(f"收银系统登录失败:{msg}")
|
||||
state["session"] = _build_session()
|
||||
logger.info("收银系统登录成功")
|
||||
return True
|
||||
|
||||
|
||||
def has_session():
|
||||
"""收银会话是否已初始化(调用方据此决定技师数据是否走收银)。"""
|
||||
return state.get("session") is not None
|
||||
|
||||
|
||||
# ==================== 收银接口请求 ====================
|
||||
def _cashier_request(session, method, url, params=None, payload=None):
|
||||
"""收银接口请求(项目级重试 3 次;401/非 JSON 视为登录失效直接报错)。"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_REQUEST_RETRY + 1):
|
||||
try:
|
||||
kwargs = {"timeout": 30}
|
||||
if params:
|
||||
kwargs["params"] = params
|
||||
if payload is not None:
|
||||
kwargs["json"] = payload
|
||||
resp = session.request(method, url, **kwargs)
|
||||
if resp.status_code == 401:
|
||||
raise RuntimeError("收银登录态已失效(HTTP 401),请更新收银账号后重试。")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"收银接口状态码异常:HTTP {resp.status_code}")
|
||||
text = resp.text
|
||||
if not text.lstrip().startswith(("{", "[")):
|
||||
raise RuntimeError("收银登录态已失效(接口未返回 JSON),请重新完成收银登录。")
|
||||
return resp.json()
|
||||
except RuntimeError:
|
||||
raise
|
||||
except Exception as e:
|
||||
last_exc = e
|
||||
if attempt >= MAX_REQUEST_RETRY:
|
||||
break
|
||||
logger.warning("收银接口请求第 %d 次失败(%s),重试", attempt, e)
|
||||
time.sleep(2.0 * attempt)
|
||||
raise last_exc
|
||||
|
||||
|
||||
# ==================== 门店列表 ====================
|
||||
def cashier_store_list(session):
|
||||
"""收银门店列表(带缓存文件复用,避免每次重复拉取)。"""
|
||||
if os.path.exists(CASHIER_STORE_CACHE):
|
||||
try:
|
||||
with open(CASHIER_STORE_CACHE, encoding='utf-8') as f:
|
||||
cached = json.load(f)
|
||||
stores = cached.get("stores") or []
|
||||
if stores:
|
||||
return stores
|
||||
except Exception:
|
||||
pass
|
||||
data = _cashier_request(session, "GET", CASHIER_STORE_LIST_URL,
|
||||
params={"_t": str(int(time.time() * 1000))})
|
||||
stores = data.get("data") or []
|
||||
if not stores:
|
||||
raise RuntimeError("收银门店列表接口未返回任何门店")
|
||||
try:
|
||||
os.makedirs(os.path.dirname(CASHIER_STORE_CACHE), exist_ok=True)
|
||||
with open(CASHIER_STORE_CACHE, 'w', encoding='utf-8') as f:
|
||||
json.dump({"updated_at": time.strftime("%Y-%m-%d %H:%M:%S"), "stores": stores},
|
||||
f, ensure_ascii=False, indent=2)
|
||||
except Exception as e:
|
||||
logger.warning("收银门店缓存写入失败:%s", e)
|
||||
return stores
|
||||
|
||||
|
||||
# ==================== 技师月度考勤 ====================
|
||||
def _month_range(month_str):
|
||||
"""月份 "YYYY-MM"/"YYYYMM" → (当月1日, 当月最后日)。"""
|
||||
s = str(month_str).replace("-", "")
|
||||
year, mon = int(s[:4]), int(s[4:6])
|
||||
last_day = calendar.monthrange(year, mon)[1]
|
||||
return date(year, mon, 1), date(year, mon, last_day)
|
||||
|
||||
|
||||
def _cashier_day_cat(det):
|
||||
"""收银逐日明细 → 需求9 未出勤类别(旷工/请假/休息);正常出勤返回 None。
|
||||
|
||||
以 un_duty_type 首个 code 为准(6=旷工、2=正休,其余非空=请假);display_text 兜底。
|
||||
"""
|
||||
un = det.get("un_duty_type")
|
||||
if isinstance(un, list) and un:
|
||||
cat = CASHIER_UN_DUTY_CAT.get(un[0])
|
||||
return cat if cat else "请假"
|
||||
txt = "".join(det.get("display_text") or [])
|
||||
if "旷工" in txt:
|
||||
return "旷工"
|
||||
if "正休" in txt:
|
||||
return "休息"
|
||||
if txt and txt != "正常":
|
||||
return "请假"
|
||||
return None
|
||||
|
||||
|
||||
def is_cashier_month(month_str):
|
||||
"""月份是否落在技师数据迁移月(2026-09)及以后——该月技师考勤需同时取收银数据。
|
||||
|
||||
兼容 "YYYY-MM" 与 "YYYYMM" 两种入参。
|
||||
"""
|
||||
try:
|
||||
ym = int(str(month_str).replace("-", "")[:6])
|
||||
return ym >= int(CASHIER_MIGRATE_MONTH.replace("-", ""))
|
||||
except Exception:
|
||||
return False
|
||||
|
||||
|
||||
def _dump_tech(result, on_map):
|
||||
"""把 date 键的内存结构转为 JSON 可存结构(date.isoformat 作键/元素)。"""
|
||||
return {
|
||||
"status": {code: {d.isoformat(): cat for d, cat in dm.items()}
|
||||
for code, dm in result.items()},
|
||||
"on": {code: sorted(d.isoformat() for d in ds) for code, ds in on_map.items()},
|
||||
}
|
||||
|
||||
|
||||
def _load_tech(data):
|
||||
"""_dump_tech 的逆操作:日期转回 date,出勤日集合转回 set(坏行忽略)。"""
|
||||
status = {}
|
||||
for code, dm in (data.get("status") or {}).items():
|
||||
daymap = {}
|
||||
for ds, cat in dm.items():
|
||||
try:
|
||||
daymap[date.fromisoformat(ds)] = cat
|
||||
except Exception:
|
||||
continue
|
||||
if daymap:
|
||||
status[code] = daymap
|
||||
on_map = {}
|
||||
for code, days in (data.get("on") or {}).items():
|
||||
on_days = set()
|
||||
for ds in days or []:
|
||||
try:
|
||||
on_days.add(date.fromisoformat(ds))
|
||||
except Exception:
|
||||
continue
|
||||
if on_days:
|
||||
on_map[code] = on_days
|
||||
return status, on_map
|
||||
|
||||
|
||||
def _read_tech_cache(path):
|
||||
"""读历史月收银技师缓存;不存在/损坏返回 None。"""
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
status, on_map = _load_tech(data)
|
||||
return {"status": status, "on": on_map}
|
||||
except Exception as e:
|
||||
logger.warning("收银技师缓存读取失败,忽略:%s(%s)", path, e)
|
||||
return None
|
||||
|
||||
|
||||
def _write_tech_cache(path, result, on_map):
|
||||
"""历史月收银技师结果落盘(失败仅告警,不影响主流程)。"""
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(_dump_tech(result, on_map), f, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
logger.warning("收银技师缓存写入失败,忽略:%s(%s)", path, e)
|
||||
|
||||
|
||||
def cashier_tech_status(month_key):
|
||||
"""拉取某月全部门店收银技师考勤 → 未出勤映射 {工号: {日期: 类别}}(模块内缓存)。
|
||||
|
||||
同时把该月各技师「出勤日集合」写入 state["month_on"][month_key][工号],
|
||||
供当前月返岗判定使用。未初始化收银会话时返回空 dict(调用方降级仅用 HR 数据)。
|
||||
|
||||
注意:仅统计月 / 当前月(>= CASHIER_MIGRATE_MONTH)才调用本函数;跨月追溯的历史月
|
||||
(2026-09 之前)技师数据仍在 HR,走 logic 层 HR 原逻辑。
|
||||
完整结束的历史月(早于当前月)结果落盘 absence_cache/cashier_{YYYYMM}.json,
|
||||
下次回溯直接读盘,不再逐门店重拉;统计月/当前月始终实时(数据仍在变化)。
|
||||
"""
|
||||
session = state.get("session")
|
||||
if session is None:
|
||||
return {}
|
||||
if month_key in state["month_status"]:
|
||||
return state["month_status"][month_key]
|
||||
|
||||
disk_path = None
|
||||
if month_key < date.today().strftime("%Y-%m"): # 完整结束的历史月:数据不再变化
|
||||
disk_path = os.path.join(CACHE_DIR, f"cashier_{month_key.replace('-', '')}.json")
|
||||
cached = _read_tech_cache(disk_path)
|
||||
if cached is not None:
|
||||
state["month_status"][month_key] = cached["status"]
|
||||
state["month_on"][month_key] = cached["on"]
|
||||
logger.info("命中收银技师考勤缓存:%s(%d 名技师)",
|
||||
os.path.basename(disk_path), len(cached["status"]))
|
||||
return state["month_status"][month_key]
|
||||
|
||||
year, month = int(month_key[:4]), int(month_key[5:7])
|
||||
mb, me = _month_range(month_key)
|
||||
stores = cashier_store_list(session)
|
||||
result, on_map = {}, {}
|
||||
for store in stores:
|
||||
store_id = store.get("store_id")
|
||||
try:
|
||||
data = _cashier_request(
|
||||
session, "POST", CASHIER_ATT_URL,
|
||||
payload={"store_id": store_id, "year": year, "month": month}).get("data") or []
|
||||
except Exception as e:
|
||||
logger.warning("收银门店 %s(%s) 考勤拉取失败:%s", store_id, store.get("store_name"), e)
|
||||
continue
|
||||
time.sleep(0.3) # 门店间限速,避免被接口限流
|
||||
for t in data:
|
||||
code = str(t.get("tech_base_code") or "").strip()
|
||||
if not code:
|
||||
continue
|
||||
daymap, on_days = {}, set()
|
||||
for det in (t.get("monthly_detail") or []):
|
||||
day = det.get("day")
|
||||
if not isinstance(day, int) or not (mb.day <= day <= me.day):
|
||||
continue
|
||||
d = date(year, month, day)
|
||||
cat = _cashier_day_cat(det)
|
||||
if cat:
|
||||
daymap[d] = cat
|
||||
else:
|
||||
on_days.add(d) # 正常出勤日
|
||||
if daymap:
|
||||
result[code] = daymap
|
||||
if on_days:
|
||||
on_map[code] = on_days
|
||||
state["month_status"][month_key] = result
|
||||
state["month_on"][month_key] = on_map
|
||||
if disk_path and result:
|
||||
_write_tech_cache(disk_path, result, on_map)
|
||||
logger.info("收银技师考勤 %s:%d 家门店、%d 名技师进入未出勤映射、%d 名有出勤日",
|
||||
month_key, len(stores), len(result), len(on_map))
|
||||
return result
|
||||
@@ -0,0 +1,269 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0009 插件 - HR 接口(考勤统计报表 / 请假记录)与按月懒缓存。
|
||||
|
||||
由 workflows/.../absence_analysis.py 内联 HR 逻辑移植:
|
||||
- 会话改由底座注入(config 全局钩子),删除自动补登逻辑——登录态失效直接抛
|
||||
HRSessionExpiredError,由调用方转为「请重新登录 HR」明确提示(插件开发规范 §7);
|
||||
- 请求带项目级重试(最多 3 次,4xx 不重试);
|
||||
- 历史月接口数据按月落盘懒缓存(跨月追溯复用),统计月/当前月始终实时。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
from ..config import (
|
||||
logger, CACHE_DIR, MAX_REQUEST_RETRY,
|
||||
HR_BASE_URL, GET_CUR_USER_INFO_URL, LEAVE_URL, PAGE_MAX_SIZE,
|
||||
MONTH_ATT_REPORT_URL, MONTH_ATT_REPORT_ID, COMPANY_STRU_ID, REPORT_PAGE_SIZE,
|
||||
)
|
||||
|
||||
|
||||
class HRSessionExpiredError(Exception):
|
||||
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
|
||||
|
||||
|
||||
def _request_with_retry(session, method, url, params, timeout, label):
|
||||
"""带项目级重试的 HTTP 请求:连接/超时/5xx 等瞬时故障最多重试 MAX_REQUEST_RETRY 次。
|
||||
|
||||
4xx 业务类错误(401/403 等)重试无意义,直接抛出;三次仍失败后抛出最后一次异常。
|
||||
"""
|
||||
last_exc = None
|
||||
for attempt in range(1, MAX_REQUEST_RETRY + 1):
|
||||
try:
|
||||
resp = session.request(method.upper(), url, data=params, timeout=timeout)
|
||||
resp.raise_for_status()
|
||||
return resp
|
||||
except requests.HTTPError as e:
|
||||
if e.response is not None and e.response.status_code < 500:
|
||||
raise # 4xx 不重试
|
||||
last_exc = e
|
||||
except (requests.ConnectionError, requests.Timeout) as e:
|
||||
last_exc = e
|
||||
if attempt < MAX_REQUEST_RETRY:
|
||||
delay = 2 ** (attempt - 1) # 1s / 2s / 4s 指数退避
|
||||
logger.warning("%s 第 %d 次请求失败(%s),%d 秒后重试", label, attempt, last_exc, delay)
|
||||
time.sleep(delay)
|
||||
logger.error("%s 请求重试 %d 次仍失败:%s", label, MAX_REQUEST_RETRY, last_exc)
|
||||
raise last_exc
|
||||
|
||||
|
||||
def hr_request_json(session, method, url, params, label, timeout=20):
|
||||
"""POST/GET 请求(带项目级重试)并校验返回 JSON;失效抛 HRSessionExpiredError。"""
|
||||
resp = _request_with_retry(session, method, url, params, timeout, label)
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith(("{", "[")):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON),请重新登录 HR 后再重试")
|
||||
return resp.json()
|
||||
|
||||
|
||||
def validate_session(session):
|
||||
"""调用 getCurUserInfo 校验登录态有效性,返回 userId;失效抛 HRSessionExpiredError。"""
|
||||
info = hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
|
||||
user_id = info.get("userId", "")
|
||||
if not user_id:
|
||||
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
|
||||
logger.info("HR 会话校验通过,user_id=%s", user_id)
|
||||
return user_id
|
||||
|
||||
|
||||
# ==================== 考勤统计报表 ====================
|
||||
def fetch_attendance_stat_page(session, user_id, month, page_no=1, page_size=REPORT_PAGE_SIZE,
|
||||
stru_id=COMPANY_STRU_ID, base_code=""):
|
||||
"""请求单页「考勤统计报表」数据。
|
||||
|
||||
返回 datas 一条记录 = 一个员工在查询月的逐日出勤,动态列 key 形如 v_1~v_最后一天,
|
||||
值为该日状态(休息/旷工/迟到/漏打卡/早退等)。
|
||||
"""
|
||||
params = {
|
||||
"reportId": MONTH_ATT_REPORT_ID,
|
||||
"struId": stru_id,
|
||||
"start": (page_no - 1) * page_size,
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
"ds1.userId": user_id,
|
||||
"ds1.struId": stru_id,
|
||||
"ds1.month": month,
|
||||
"ds2.stru_id": stru_id,
|
||||
"ds3.month": "#ds1.month#",
|
||||
"orgTypeCode": "1",
|
||||
"rootId": "cq37du",
|
||||
"showSetField": "1",
|
||||
"menuName": "考勤统计报表",
|
||||
"treePermitType": "permit",
|
||||
"struTreeCode": "cq37du",
|
||||
"belongUnitStruId": stru_id,
|
||||
"isVirtual": "0",
|
||||
"isHistory": "undefined",
|
||||
"useSealTreeData": "0",
|
||||
"orgAlias": "集团",
|
||||
"commonQuery": "[]",
|
||||
"ds1.base_code": base_code,
|
||||
}
|
||||
url = f"{MONTH_ATT_REPORT_URL}?reportsId={MONTH_ATT_REPORT_ID}"
|
||||
return hr_request_json(session, "POST", url, params, "考勤统计报表")
|
||||
|
||||
|
||||
def fetch_all_attendance_stat(session, user_id, month, stru_id=COMPANY_STRU_ID, base_code=""):
|
||||
"""分页抓取某月「考勤统计报表」明细(每人一行,含 v_1~v_最后一天)。
|
||||
|
||||
base_code 非空时仅查该员工(跨月追溯单人查询)。
|
||||
某页请求失败(state != 1)直接抛异常终止,绝不返回部分数据(避免导出缺人名单)。
|
||||
"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
data = fetch_attendance_stat_page(session, user_id, month, page_no,
|
||||
REPORT_PAGE_SIZE, stru_id, base_code)
|
||||
if data.get("state") != "1":
|
||||
raise RuntimeError(f"考勤统计报表第 {page_no} 页请求失败:{data.get('meg')}")
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("考勤统计报表无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("考勤统计报表已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 请假记录 ====================
|
||||
def fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
|
||||
"""请求单页请假记录数据。"""
|
||||
params = {
|
||||
"STRU_TREE_CODE": treecode,
|
||||
"user_id": user_id,
|
||||
"begin_date": "",
|
||||
"end_date": "",
|
||||
"sqlId": "select_kqLeave_record",
|
||||
"commonQuery": "",
|
||||
"commonQueryStr": "",
|
||||
"post_no": "",
|
||||
"source": "",
|
||||
"person_status": "",
|
||||
"staff_id": "",
|
||||
"staffNames": "",
|
||||
"post_type": "1",
|
||||
"processing_reason": "",
|
||||
"processing_date": "",
|
||||
"start_operat_time": "",
|
||||
"end_operat_time": "",
|
||||
"orgAlias": "",
|
||||
"dept_ids": "",
|
||||
"base_code": base_code,
|
||||
"staff_name": "",
|
||||
"start_time": start_time,
|
||||
"end_time": end_time,
|
||||
"start": str((page_no - 1) * page_size),
|
||||
"sortType": "desc",
|
||||
"sortName": "operat_time",
|
||||
"pageNo": page_no,
|
||||
"pageSize": page_size,
|
||||
}
|
||||
return hr_request_json(session, "POST", LEAVE_URL, params, "请假查询")
|
||||
|
||||
|
||||
def fetch_all_leave(session, user_id, base_code, start_time, end_time, treecode="cq37du"):
|
||||
"""分页抓取指定工号、日期范围内的全部请假记录。
|
||||
|
||||
某页请求失败(state != 1)直接抛异常终止,绝不返回部分数据(避免漏掉仍在休假的假单)。
|
||||
"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
data = fetch_leave_page(session, user_id, base_code, start_time, end_time,
|
||||
treecode, page_no, PAGE_MAX_SIZE)
|
||||
if data.get("state") != "1":
|
||||
raise RuntimeError(f"请假查询第 {page_no} 页请求失败:{data.get('meg')}")
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("请假查询无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("请假查询已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
# ==================== 接口数据懒缓存(按月落盘,命中不重复请求接口) ====================
|
||||
def _cache_path(kind, month_key, code=""):
|
||||
"""构造缓存文件路径。kind ∈ {att, leave};month_key 为 "YYYYMM";code 空表示全量。"""
|
||||
fname = f"{kind}_{month_key}" + (f"_{code}" if code else "")
|
||||
return os.path.join(CACHE_DIR, fname + ".json")
|
||||
|
||||
|
||||
def _read_cache(path):
|
||||
"""读取缓存列表;不存在/损坏返回 None。"""
|
||||
if not os.path.exists(path):
|
||||
return None
|
||||
try:
|
||||
with open(path, encoding="utf-8") as f:
|
||||
data = json.load(f)
|
||||
return data if isinstance(data, list) else None
|
||||
except Exception as e:
|
||||
logger.warning("缓存读取失败,忽略:%s(%s)", path, e)
|
||||
return None
|
||||
|
||||
|
||||
def _write_cache(path, records):
|
||||
"""把接口返回的 datas 列表写入缓存(失败仅告警,不影响主流程)。"""
|
||||
try:
|
||||
os.makedirs(os.path.dirname(path), exist_ok=True)
|
||||
with open(path, "w", encoding="utf-8") as f:
|
||||
json.dump(records, f, ensure_ascii=False)
|
||||
except Exception as e:
|
||||
logger.warning("缓存写入失败,忽略:%s(%s)", path, e)
|
||||
|
||||
|
||||
def cached_attendance(session, user_id, month_key, base_code=""):
|
||||
"""按月缓存整月考勤统计报表:先查缓存,未命中才调接口并落盘,下次直接复用。
|
||||
|
||||
month_key:月份 "YYYYMM";base_code 非空时为该员工单人报表(跨月追溯单人模式)。
|
||||
"""
|
||||
path = _cache_path("att", month_key, base_code)
|
||||
cached = _read_cache(path)
|
||||
if cached is not None:
|
||||
logger.info("命中考勤报表缓存:%s(%d 条)", os.path.basename(path), len(cached))
|
||||
return cached
|
||||
records = fetch_all_attendance_stat(session, user_id, month_key, base_code=base_code)
|
||||
_write_cache(path, records)
|
||||
return records
|
||||
|
||||
|
||||
def cached_leave(session, user_id, base_code, month_str):
|
||||
"""按月缓存整月请假记录:先查缓存,未命中才调接口并落盘,下次直接复用。
|
||||
|
||||
month_str:月份 "YYYY-MM";base_code 空为全集团,非空为该员工(跨月追溯单人模式)。
|
||||
"""
|
||||
month_key = month_str.replace("-", "")
|
||||
path = _cache_path("leave", month_key, base_code)
|
||||
cached = _read_cache(path)
|
||||
if cached is not None:
|
||||
logger.info("命中请假记录缓存:%s(%d 条)", os.path.basename(path), len(cached))
|
||||
return cached
|
||||
from datetime import date, timedelta
|
||||
|
||||
def month_range(m):
|
||||
import calendar
|
||||
s = str(m).replace("-", "")
|
||||
year, mon = int(s[:4]), int(s[4:6])
|
||||
last_day = calendar.monthrange(year, mon)[1]
|
||||
return date(year, mon, 1), date(year, mon, last_day)
|
||||
|
||||
mb, me = month_range(month_str)
|
||||
records = fetch_all_leave(session, user_id, base_code,
|
||||
mb.strftime("%Y-%m-%d"), me.strftime("%Y-%m-%d"))
|
||||
_write_cache(path, records)
|
||||
return records
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user