refactor: 重构多插件 UI 与配置结构,新增抖音/新美大平台核对插件
- 新增 XQ0042 抖音平台核对、XQ0041 新美大平台核对插件的 UI 源码与打包脚本 - 重构续签电子签、服务岗转正不通过电子签等插件的版本与配置 - 删除旧版考勤异常处理、微盟数据导出等冗余插件文件 - 修复出勤积分更新插件的 OPM 推送判断逻辑 - 优化壳子插件页面的 iframe 滚动条样式
This commit is contained in:
@@ -19,6 +19,9 @@
|
||||
读取工作簿「积分导入」「积分删除」→ OPM 登录校验 → multipart 上传
|
||||
(`/operation/point/list/importAttendance`、`.../importAttendanceDel`)。
|
||||
推送前界面会二次确认;不使用单独的试运行开关——只想看名单时只开第一步,两张表就在工作簿里。
|
||||
上传失败最多重传一次:先判会话是否还有效(有效则原会话直接重传,不白做重登),
|
||||
拿到登录页 / 401 才重登;OPM 偶发返回非 JSON(HTML / 空响应)时,日志会带出
|
||||
HTTP 状态、content-type 与响应体片段,重传若提示「已存在 / 未生成出勤积分」即判定首传已生效。
|
||||
|
||||
只推送不更新时,自动取目录中最新修改的工作簿(或界面「指定工作簿」),不新建批次。
|
||||
仅更新不推送时,不做任何 OPM 网络请求(无需填写 OPM 账号)。
|
||||
|
||||
@@ -78,7 +78,7 @@ class Xq0033Plugin(ScenePlugin):
|
||||
|
||||
id = "xq0033"
|
||||
name = "门店管理及服务岗出勤积分更新"
|
||||
version = "1.0.7"
|
||||
version = "1.0.9"
|
||||
description = (
|
||||
"拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,"
|
||||
"自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,"
|
||||
@@ -326,19 +326,29 @@ class Xq0033Plugin(ScenePlugin):
|
||||
groups.setdefault(r[2].date(), []).append(r)
|
||||
if len(groups) > 1:
|
||||
ctx.log(f"{label} 共 {len(rows)} 行,按积分日期分 {len(groups)} 批上传", "INFO")
|
||||
parts, failed = [], []
|
||||
parts, failed, retried, existed = [], [], 0, 0
|
||||
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)} 行")
|
||||
item = f"{d:%m-%d} {len(chunk)} 行"
|
||||
if res.get("first_error"):
|
||||
retried += 1
|
||||
item += "(重试后确认)"
|
||||
elif res.get("kind") == "benign":
|
||||
# 服务端提示已存在/无需处理:这批此前已导入过,不是本次新写入
|
||||
existed += 1
|
||||
item += "(已存在)"
|
||||
parts.append(item)
|
||||
else:
|
||||
failed.append(f"{d:%m-%d}({res['message']})")
|
||||
results[label] = {
|
||||
"success": not failed,
|
||||
"message": ("分批成功:" + "、".join(parts)) if not failed
|
||||
else "失败批次:" + ";".join(failed),
|
||||
}
|
||||
msg = ("分批成功:" + "、".join(parts)) if not failed \
|
||||
else "失败批次:" + ";".join(failed)
|
||||
if not failed and retried:
|
||||
msg += f";其中 {retried} 批首传响应异常,已由重传结果确认"
|
||||
if not failed and existed:
|
||||
msg += f";其中 {existed} 批服务端提示已存在(此前已导入,本次未新增)"
|
||||
results[label] = {"success": not failed, "message": msg}
|
||||
else:
|
||||
results[label] = self._upload_once(client, ctx, label, rows, kind)
|
||||
res = results[label]
|
||||
@@ -348,18 +358,37 @@ class Xq0033Plugin(ScenePlugin):
|
||||
|
||||
@staticmethod
|
||||
def _upload_once(client, ctx, label, rows, kind):
|
||||
"""单批上传;失败时重登会话再试一次(大请求超时后 OPM 常会重置会话返回 HTML)。"""
|
||||
"""单批上传,失败最多重传一次。
|
||||
|
||||
OPM 偶发返回非 JSON(HTML 登录页 / 空响应),此时无法确认是否已写入:
|
||||
- 会话仍有效 → 原会话直接重传,不白做一次重登;
|
||||
- 会话失效(拿到登录页 / 401) → 重登后重传;
|
||||
- 重传若提示「已存在/未生成出勤积分」→ 判定首传其实已生效,如实记录而不是报失败。
|
||||
"""
|
||||
url = client.import_url if kind == "import" else client.delete_url
|
||||
res = client.upload(url, build_kaoqin_bytes(rows), f"{label}.xlsx")
|
||||
payload = build_kaoqin_bytes(rows)
|
||||
res = client.upload(url, payload, 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")
|
||||
|
||||
need_relogin = res.get("kind") == "notfound" or not client.is_session_valid()
|
||||
ctx.log(f"{label} 第 1 次上传未确认成功:{res['message']}"
|
||||
f"(会话{'已失效,重登后重试' if need_relogin else '仍有效,直接重试'})", "WARN")
|
||||
if need_relogin:
|
||||
try:
|
||||
client.session = None
|
||||
client.ensure_session()
|
||||
except Exception as e:
|
||||
return {"success": False, "message": f"{res['message']};重登失败:{e}"}
|
||||
|
||||
res2 = client.upload(url, payload, f"{label}.xlsx")
|
||||
if res2["success"]:
|
||||
if res2.get("kind") == "benign":
|
||||
res2["message"] = (f"首传响应异常({res['message']}),重传提示已存在 → "
|
||||
f"判定首传已生效:{res2['message']}")
|
||||
res2["first_error"] = res["message"]
|
||||
return res2
|
||||
return {"success": False, "message": f"首传:{res['message']};重传:{res2['message']}"}
|
||||
|
||||
|
||||
PLUGINS.append(Xq0033Plugin())
|
||||
|
||||
@@ -70,6 +70,8 @@ OPM_DELETE_PATH = "/operation/point/list/importAttendanceDel"
|
||||
OPM_TIMEOUT = 120
|
||||
# 服务端对「重复/无内容可删」的良性响应关键词:目标状态已达成,不算失败
|
||||
OPM_BENIGN_MSGS = ("不能重复添加", "未生成出勤积分", "已存在")
|
||||
# 同一条 message 里出现这些词说明确有行处理失败:不能因含良性关键词就整体判成功
|
||||
OPM_FATAL_MSGS = ("失败", "异常", "错误", "不存在", "格式不正确", "解析")
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
|
||||
@@ -94,6 +94,36 @@ def build_kaoqin_bytes(rows):
|
||||
return buf.getvalue()
|
||||
|
||||
|
||||
# ==================== 响应诊断 ====================
|
||||
def _body_text(resp, limit=300):
|
||||
"""取响应体文本片段(诊断「响应非 JSON」到底返回了什么)。"""
|
||||
body = resp.content or b""
|
||||
if not body:
|
||||
return ""
|
||||
txt = None
|
||||
for enc in ("utf-8", "gbk"):
|
||||
try:
|
||||
txt = body.decode(enc)
|
||||
break
|
||||
except UnicodeDecodeError:
|
||||
continue
|
||||
if txt is None:
|
||||
txt = body.decode("utf-8", "replace")
|
||||
txt = " ".join(txt.split())
|
||||
return txt[:limit] + ("…" if len(txt) > limit else "")
|
||||
|
||||
|
||||
def _looks_like_login_page(txt):
|
||||
low = (txt or "").lower()
|
||||
return "<html" in low or "<!doctype" in low or ("<form" in low and "password" in low)
|
||||
|
||||
|
||||
def _fmt_msg(msg, limit=500):
|
||||
"""服务端 message 多为多行逐行提示,压成单行,保留更多内容。"""
|
||||
txt = ";".join(x.strip() for x in str(msg or "").splitlines() if x.strip())
|
||||
return txt[:limit] + ("…" if len(txt) > limit else "")
|
||||
|
||||
|
||||
# ==================== 客户端 ====================
|
||||
class OPMClient:
|
||||
"""OPM 登录 + 考勤积分上传(积分导入 / 积分删除)。"""
|
||||
@@ -115,6 +145,13 @@ class OPMClient:
|
||||
s.get(self.login_url, timeout=TIMEOUT)
|
||||
return s
|
||||
|
||||
def _warm_up(self, session):
|
||||
"""对齐浏览器上下文:正式上传都在「积分列表」页发起,登录后先 GET 一次该页。"""
|
||||
try:
|
||||
session.get(self.base_url + "/point/list", timeout=TIMEOUT)
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
def is_session_valid(self, session=None):
|
||||
session = session or self.session
|
||||
if session is None:
|
||||
@@ -168,6 +205,7 @@ class OPMClient:
|
||||
raise OPMLoginError(f"OPM 登录被拒绝(账号或密码错误?):{msg}")
|
||||
if self.is_session_valid(session):
|
||||
self.session = session
|
||||
self._warm_up(session)
|
||||
config.logger.info("OPM 登录成功")
|
||||
return session
|
||||
last_msg = "登录接口返回成功但会话校验未通过"
|
||||
@@ -180,21 +218,50 @@ class OPMClient:
|
||||
return self.login()
|
||||
|
||||
def upload(self, url, file_bytes, filename):
|
||||
"""上传单个文件,返回 {success, message, kind}。
|
||||
|
||||
kind 用于上层判断该不该重登/重传:
|
||||
ok 服务端明确成功
|
||||
benign 服务端提示「已存在/未生成出勤积分」等,目标状态已达成(算成功)
|
||||
notfound 会话失效(拿到登录页/HTML),必须重登后再试
|
||||
unknown 响应非 JSON 或空响应,无法确认结果,需重传确认
|
||||
http HTTP 非 200
|
||||
error 服务端明确失败
|
||||
"""
|
||||
try:
|
||||
resp = self.session.post(
|
||||
url, files={"file": (filename, file_bytes, FILE_MIME)},
|
||||
headers={"Referer": self.base_url + "/point/list"}, timeout=config.OPM_TIMEOUT)
|
||||
except Exception as e:
|
||||
return {"success": False, "message": f"上传异常:{e}"}
|
||||
return {"success": False, "kind": "error", "message": f"上传异常:{e}"}
|
||||
if resp.status_code != 200:
|
||||
return {"success": False, "message": f"HTTP {resp.status_code}"}
|
||||
snippet = _body_text(resp, 200)
|
||||
msg = f"HTTP {resp.status_code}" + (f"({snippet})" if snippet else "")
|
||||
return {"success": False,
|
||||
"kind": "notfound" if resp.status_code in (401, 403) else "http",
|
||||
"message": msg}
|
||||
try:
|
||||
data = resp.json()
|
||||
except Exception:
|
||||
return {"success": False, "message": "响应非 JSON"}
|
||||
snippet = _body_text(resp)
|
||||
if not snippet:
|
||||
return {"success": False, "kind": "unknown",
|
||||
"message": "响应为空(HTTP 200 无内容)"}
|
||||
kind = "notfound" if _looks_like_login_page(snippet) else "unknown"
|
||||
ctype = resp.headers.get("content-type", "")
|
||||
return {"success": False, "kind": kind,
|
||||
"message": f"响应非 JSON(HTTP 200,{ctype or '无 content-type'}):{snippet}"}
|
||||
if not isinstance(data, dict):
|
||||
return {"success": False, "kind": "unknown",
|
||||
"message": f"响应格式异常:{_body_text(resp, 150)}"}
|
||||
ok = data.get("status") is True or data.get("code") == "S0"
|
||||
msg = data.get("message") or ""
|
||||
if not ok and any(k in msg for k in config.OPM_BENIGN_MSGS):
|
||||
return {"success": True,
|
||||
"message": f"部分已存在/无需处理(目标状态已达成):{msg[:200]}"}
|
||||
return {"success": bool(ok), "message": msg or ("" if ok else "导入失败")}
|
||||
msg = _fmt_msg(data.get("message"))
|
||||
if ok:
|
||||
return {"success": True, "kind": "ok", "message": msg}
|
||||
if msg and any(k in msg for k in config.OPM_BENIGN_MSGS):
|
||||
# 逐行提示里既有「已存在/未生成」又有「失败/不存在」等硬错误时不能算成功
|
||||
if not any(k in msg for k in config.OPM_FATAL_MSGS):
|
||||
return {"success": True, "kind": "benign",
|
||||
"message": f"部分已存在/无需处理(目标状态已达成):{msg}"}
|
||||
return {"success": False, "kind": "error",
|
||||
"message": msg or "导入失败(服务端未返回原因)"}
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0033",
|
||||
"name": "门店管理及服务岗出勤积分更新",
|
||||
"version": "1.0.7",
|
||||
"version": "1.0.9",
|
||||
"description": "拉取 HR 当月考勤统计报表并按 A 列公式圈人,滚动今日/前一日快照做逐日差值,自动更新积分工作簿(考勤统计报表 / 当月再入职名单 / 积分导入 / 积分删除,COM 全量重算),可选将积分导入与删除表推送至 OPM 平台。",
|
||||
"category": "考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -48,7 +48,7 @@ class _LogWriter:
|
||||
class Xq0034Plugin(ScenePlugin):
|
||||
id = "xq0034"
|
||||
name = "续签电子签"
|
||||
version = "1.0.18"
|
||||
version = "1.0.19"
|
||||
description = ("XQ0034 续签电子签:AI表格【续签名单到期跟进-月更新】驱动——否续签回填、"
|
||||
"是续签手机号校验后 HR 生效中合同属性页「续签合同」提交推送电子签并回填,"
|
||||
"HR 会话由壳子注入")
|
||||
|
||||
@@ -442,11 +442,12 @@ def renew_contract(session, ai, dry_run):
|
||||
# 「合同/协议到期日」须与【生效中合同】截止日期完全一致;不一致(含
|
||||
# AI 表未填)说明两边数据错位(旧合同已被替换/到期日填错),不发起
|
||||
# 续签,报异常转人工核对(该异常推送钉钉通知)。
|
||||
ai["_alert"] = True
|
||||
if old_expire is None:
|
||||
ai["_alert"] = True
|
||||
return "异常", ("AI表「合同/协议到期日」为空,无法核对生效中合同截止日期,"
|
||||
"不发起续签,请人工补充后重跑")
|
||||
if a_end != old_expire:
|
||||
ai["_alert"] = True
|
||||
return "异常", (f"AI表合同/协议到期日({old_expire})与生效中合同截止日期"
|
||||
f"({a_end or '?'})不一致,不发起续签,请人工核对")
|
||||
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0034",
|
||||
"name": "续签电子签",
|
||||
"version": "1.0.18",
|
||||
"version": "1.0.19",
|
||||
"description": "XQ0034 续签电子签:钉钉AI表格【续签名单到期跟进-月更新】驱动——「是否续签=否」回填人资是否推送=否;「是否续签=是」前置默认补全(电子签接收电话为空取花名册号码回填、期望推送日期为空默认当天回填)后完整发起续签:校验电话与花名册一致(不一致且合法自动修正HR联系方式),发起前核对 AI 表「合同/协议到期日」与【生效中合同】截止日期,不一致或未填=异常不发起并推送钉钉通知,一致则在 HR【合同台账-生效中合同】属性页「续签合同」提交推送电子签(新合同信息直接取AI表字段,电子签模板按员工+签署单位实时查询,为空不提交转人工),成功回填人资是否推送=是+推送时间;核验:待生效+生效中联合取最新合同,时间与AI表续签期一致且签署记录is_initiate_sign=2已完成签署才回填完成签署=是(1已发起/3已撤销均不算);通知块格式与加班审批一致,推送成功/核验完成数量/核验未完成数量/失败/合同到期日异常;HR 会话由壳子注入",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -52,7 +52,7 @@ class _LogWriter:
|
||||
class Xq0035Plugin(ScenePlugin):
|
||||
id = "xq0035"
|
||||
name = "服务岗转正不通过电子签"
|
||||
version = "1.0.2"
|
||||
version = "1.0.9"
|
||||
description = ("XQ0035 服务岗转正不通过电子签(离职+入职):①变更试用期主流程 "
|
||||
"②新签合同 ③签署生效复核,AI表格驱动、断点续跑,单步执行错峰定时")
|
||||
platform = "hr"
|
||||
|
||||
@@ -1294,6 +1294,13 @@ def _build_processed_msg(stage, rec, base_code, target_end_date):
|
||||
"跳过发起调动解除,请人工核查生效情况。")
|
||||
|
||||
|
||||
def _effective_reaches_target(proc_rec, target_end_date):
|
||||
"""已生效变更记录的新试用期结束日期是否已达到脚本目标(>= 目标日)。"""
|
||||
eff = _to_date((proc_rec or {}).get("hr_staff_probation.new_period_end_date"))
|
||||
tgt = _to_date(target_end_date)
|
||||
return bool(eff and tgt and eff >= tgt)
|
||||
|
||||
|
||||
# ==================== 钉钉 AI表格:名单读取 + 处理后回写 ====================
|
||||
_aitable_tok = {"at": "", "exp": 0.0}
|
||||
|
||||
@@ -1584,9 +1591,12 @@ def process_one(session, task):
|
||||
已发起 -> 跳过发起环节,离职推送时间取实际发起日期(create_time),而非本次操作日期。
|
||||
无生效中合同 = 调动解除(电子签)已走完生效,电子签链(发起/完善信息/CA签署)视为完成,
|
||||
直接进入变更试用期(测试号场景:电子签已走完、无生效中合同)。
|
||||
电子签(调动解除/CA 签署)发起失败:仅记 flow_error 异常,变更试用期仍继续(实测不依赖电子签)。
|
||||
交叉验证:处理前核查三个变更 Tab,命中(已被他人操作到任意环节)则 status=跳过,
|
||||
不发起点调动解除,仅提示人工核查,all_done=False 不回填 AI表格。
|
||||
电子签(调动解除/CA 签署)发起失败:仅记 flow_error 异常,变更试用期仍继续(实测不依赖电子签),
|
||||
但 all_done 恒为 False -> 不回填 AI 表格(判失败、入异常表+钉钉),下次运行自动续跑。
|
||||
交叉验证:处理前核查三个变更 Tab:
|
||||
待确认/待生效命中 -> status=跳过,不发起调动解除,仅提示人工核查,all_done=False 不回填 AI表格;
|
||||
已生效且新到期日已达目标、但生效中合同仍在(离职电子签未发起)-> 变更/确认视为已完成,
|
||||
跳过变更与确认,继续补做调动解除(离职电子签),跑通后照常回填 AI表格。
|
||||
"""
|
||||
base_code = str(task["base_code"]).strip()
|
||||
new_period_date = task.get("new_period_date") or FIXED_NEW_PERIOD_MONTHS
|
||||
@@ -1653,17 +1663,33 @@ def process_one(session, task):
|
||||
logger.info("【%s】未达龄(性别 %s,生日 %s,序列 %s),继续流程", base_code,
|
||||
"男" if str(r_sex) == "1" else "女", r_birth, seq_name or "未知")
|
||||
|
||||
# 1) 交叉验证:流程可能已被他人操作到任意环节,命中则跳过发起调动解除,提示人工核查
|
||||
# 1) 交叉验证:流程可能已被他人操作到任意环节
|
||||
# - 待确认/待生效:半途被他人操作,跳过并提示人工核查
|
||||
# - 已生效但生效中合同仍在(离职电子签未发起):变更/确认视为已完成,
|
||||
# 不重复提交变更,继续补做调动解除(离职电子签),跑通后照常回填台账
|
||||
stage, proc_rec = check_processed_stage(session, base_code)
|
||||
contract = query_active_contract(session, base_code)
|
||||
skip_change = False
|
||||
if stage is not None:
|
||||
result["status"] = "跳过"
|
||||
result["message"] = _build_processed_msg(stage, proc_rec, base_code, new_period_end_date)
|
||||
logger.warning("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
if (stage == "done" and contract and contract.get("contract_id")
|
||||
and _effective_reaches_target(proc_rec, new_period_end_date)):
|
||||
result["stages"]["change"] = True
|
||||
result["stages"]["confirm"] = True
|
||||
skip_change = True
|
||||
logger.warning("【%s】交叉验证:试用期变更已生效(新到期 %s,操作人 %s,%s),"
|
||||
"但生效中合同仍在(离职电子签未发起)——跳过变更/确认,只补做调动解除",
|
||||
base_code,
|
||||
(proc_rec or {}).get("hr_staff_probation.new_period_end_date"),
|
||||
(proc_rec or {}).get("hr_staff_probation.operator_name"),
|
||||
(proc_rec or {}).get("hr_staff_probation.operate_time"))
|
||||
else:
|
||||
result["status"] = "跳过"
|
||||
result["message"] = _build_processed_msg(stage, proc_rec, base_code, new_period_end_date)
|
||||
logger.warning("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
|
||||
# 1) 调动解除(电子签):查生效合同 -> 断点续跑检测 -> 防重校验 -> 发起《(改签)离职电子签流程》
|
||||
logger.info("【%s】1/5 查询【生效中合同】并处理调动解除(电子签)……", base_code)
|
||||
contract = query_active_contract(session, base_code)
|
||||
logger.info("【%s】1/5 处理调动解除(电子签)……", base_code)
|
||||
if not contract or not contract.get("contract_id"):
|
||||
# 无生效中合同 = 调动解除(电子签)已走完生效(离职解除已生效)
|
||||
# -> 电子签链(发起/完善信息/CA签署)视为已完成,直接进入变更试用期
|
||||
@@ -1756,64 +1782,77 @@ def process_one(session, task):
|
||||
result["staff_name"] = staff.get("hr_staff_base.staff_name") or ""
|
||||
logger.info("【%s】命中员工:%s(base_id=%s)", base_code, result["staff_name"], base_id)
|
||||
|
||||
# 3) 提交变更试用期
|
||||
logger.info("【%s】3/5 提交变更试用期(类型=%s(%s),新试用期=%s 月,结束=%s)……",
|
||||
base_code, corr_name, correction_type, new_period_date, new_period_end_date)
|
||||
save_resp = change_trial_period(session, base_id, correction_type,
|
||||
new_period_date, new_period_end_date,
|
||||
trial_row=staff)
|
||||
if save_resp.get("state") != "1":
|
||||
meg = save_resp.get("meg") or ""
|
||||
if "已经存在子页面" in meg:
|
||||
# 幂等:该员工已有待确认记录(重复运行/断点续跑),视为已提交,继续确认
|
||||
logger.info("【%s】变更已提交过(待确认记录已存在),继续后续环节", base_code)
|
||||
else:
|
||||
result["message"] = f"提交变更试用期失败:{meg or save_resp}"
|
||||
if skip_change:
|
||||
# 变更/确认此前已生效(交叉验证命中),本次只补做调动解除,不重复提交
|
||||
logger.info("【%s】3~5/5 试用期变更此前已生效(新到期 %s),跳过变更与确认",
|
||||
base_code, new_period_end_date)
|
||||
else:
|
||||
# 3) 提交变更试用期
|
||||
logger.info("【%s】3/5 提交变更试用期(类型=%s(%s),新试用期=%s 月,结束=%s)……",
|
||||
base_code, corr_name, correction_type, new_period_date, new_period_end_date)
|
||||
save_resp = change_trial_period(session, base_id, correction_type,
|
||||
new_period_date, new_period_end_date,
|
||||
trial_row=staff)
|
||||
if save_resp.get("state") != "1":
|
||||
meg = save_resp.get("meg") or ""
|
||||
if "已经存在子页面" in meg:
|
||||
# 幂等:该员工已有待确认记录(重复运行/断点续跑),视为已提交,继续确认
|
||||
logger.info("【%s】变更已提交过(待确认记录已存在),继续后续环节", base_code)
|
||||
else:
|
||||
result["message"] = f"提交变更试用期失败:{meg or save_resp}"
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
result["stages"]["change"] = True
|
||||
|
||||
# 4) 定位待确认记录(变更提交后进入「变更/转正待确认」)
|
||||
# ⚠️ 服务端落库存在延迟:提交成功后立即查询可能查不到(实测),需重试等待
|
||||
logger.info("【%s】4/5 查询「变更/转正待确认」……", base_code)
|
||||
pending = None
|
||||
for attempt in range(1, 6):
|
||||
pending = query_pending(session, base_code)
|
||||
if pending:
|
||||
break
|
||||
logger.info("【%s】第 %d 次未查到待确认记录,服务端落库可能延迟,5 秒后重试",
|
||||
base_code, attempt)
|
||||
time.sleep(5)
|
||||
if not pending:
|
||||
result["message"] = "变更已提交,但未在「变更/转正待确认」中找到记录,需人工检查"
|
||||
logger.warning("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
management_id = pending.get("hr_staff_probation.management_id")
|
||||
logger.info("【%s】待确认记录 management_id=%s", base_code, management_id)
|
||||
|
||||
# 5) 确认
|
||||
logger.info("【%s】5/5 执行确认……", base_code)
|
||||
confirm_resp = confirm_pending(session, management_id)
|
||||
if confirm_resp.get("state") != "1":
|
||||
result["message"] = f"确认失败:{confirm_resp.get('meg') or confirm_resp}"
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
result["stages"]["change"] = True
|
||||
result["stages"]["confirm"] = True
|
||||
|
||||
# 4) 定位待确认记录(变更提交后进入「变更/转正待确认」)
|
||||
# ⚠️ 服务端落库存在延迟:提交成功后立即查询可能查不到(实测),需重试等待
|
||||
logger.info("【%s】4/5 查询「变更/转正待确认」……", base_code)
|
||||
pending = None
|
||||
for attempt in range(1, 6):
|
||||
pending = query_pending(session, base_code)
|
||||
if pending:
|
||||
break
|
||||
logger.info("【%s】第 %d 次未查到待确认记录,服务端落库可能延迟,5 秒后重试",
|
||||
base_code, attempt)
|
||||
time.sleep(5)
|
||||
if not pending:
|
||||
result["message"] = "变更已提交,但未在「变更/转正待确认」中找到记录,需人工检查"
|
||||
logger.warning("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
management_id = pending.get("hr_staff_probation.management_id")
|
||||
logger.info("【%s】待确认记录 management_id=%s", base_code, management_id)
|
||||
|
||||
# 5) 确认
|
||||
logger.info("【%s】5/5 执行确认……", base_code)
|
||||
confirm_resp = confirm_pending(session, management_id)
|
||||
if confirm_resp.get("state") != "1":
|
||||
result["message"] = f"确认失败:{confirm_resp.get('meg') or confirm_resp}"
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
result["stages"]["confirm"] = True
|
||||
result["all_done"] = all(result["stages"].values())
|
||||
change_desc = (f"试用期变更此前已生效(结束 {new_period_end_date}),本次跳过变更/确认"
|
||||
if skip_change else
|
||||
f"试用期已变更({corr_name},{new_period_date} 月,结束 {new_period_end_date})并确认生效")
|
||||
# 离职电子签(CA)未发起成功 = 整条未完成:all_done=False 不回填台账,下次运行续跑(防漏单)
|
||||
result["all_done"] = all(result["stages"].values()) and not result["flow_error"]
|
||||
|
||||
if result["flow_error"]:
|
||||
# 电子签(调动解除/CA 签署)发起失败但变更+确认已完成:
|
||||
# 异常已记录(异常表+钉钉),回填由 main() 按 all_done 决定
|
||||
result["status"] = "成功" if result["all_done"] else "失败"
|
||||
result["message"] = (f"{result['staff_name']} 试用期已变更({corr_name},"
|
||||
f"{new_period_date} 月,结束 {new_period_end_date})并确认生效;"
|
||||
f"⚠️ 电子签异常需人工处理:{result['flow_error']}")
|
||||
# 电子签(调动解除/CA 签署)发起失败:异常已记录(异常表+钉钉),
|
||||
# all_done 恒为 False → 不回填 AI 表格,保留待处理状态供下次重试
|
||||
result["status"] = "失败"
|
||||
result["message"] = (f"{result['staff_name']} {change_desc};"
|
||||
f"⚠️ 离职电子签发起失败需人工处理(台账未回填,下次运行续跑):"
|
||||
f"{result['flow_error']}")
|
||||
logger.error("【%s】%s", base_code, result["message"])
|
||||
return result
|
||||
|
||||
result["status"] = "成功"
|
||||
result["message"] = (f"{result['staff_name']} 调动解除(电子签)已发起,"
|
||||
f"试用期已变更({corr_name},{new_period_date} 月,结束 {new_period_end_date})并确认生效")
|
||||
if skip_change:
|
||||
result["message"] = (f"{result['staff_name']} 调动解除(电子签)已补发起,"
|
||||
f"试用期变更此前已生效(结束 {new_period_end_date}),本次跳过变更/确认")
|
||||
else:
|
||||
result["message"] = (f"{result['staff_name']} 调动解除(电子签)已发起,{change_desc}")
|
||||
logger.info("【%s】✅ %s", base_code, result["message"])
|
||||
return result
|
||||
except LoginRequiredError as e:
|
||||
|
||||
@@ -2,7 +2,7 @@
|
||||
"schema_version": 1,
|
||||
"id": "xq0035",
|
||||
"name": "服务岗转正不通过电子签",
|
||||
"version": "1.0.7",
|
||||
"version": "1.0.9",
|
||||
"description": "XQ0035 服务岗转正不通过电子签(离职+入职):按步骤执行 ①变更试用期主流程(调动解除电子签+完善信息+发起离职电子签+变更试用期+确认生效+回填AI表格)②新签合同(超龄用工协议/劳动合同+回填新合同推送日期)③签署生效复核(回填签署跟进);AI表格驱动、断点续跑,HR 会话由壳子注入",
|
||||
"category": "人事考勤",
|
||||
"icon": "",
|
||||
|
||||
@@ -0,0 +1,229 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0041 新美大平台核对 —— webhost 场景插件入口。
|
||||
|
||||
执行过程由 action 决定(UI 的两个开关派生):
|
||||
action='download' → 只下载:登录经营宝,按勾选下载打款记录 / 团购收益明细 / 预订收益明细;
|
||||
action='reconcile' → 只核对:**不开浏览器**,直接用本机最新的台账与收益明细并入台账、
|
||||
更新核对统计(适合数据已下载、只想重算的场景);
|
||||
action='all' → 下载后再核对(默认)。
|
||||
|
||||
签名说明:平台接口的签名参数由页面自身的前端组件生成,插件只在页面上下文发起请求,
|
||||
不涉及任何签名算法。
|
||||
"""
|
||||
import os
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import browser, meituan_login, payment_download, profit_download
|
||||
from .logic import merge_ledger, stat_links
|
||||
|
||||
|
||||
def _parse_day(s):
|
||||
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||
try:
|
||||
return datetime.strptime(str(s).strip(), fmt).date()
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_pair(raw_from, raw_to):
|
||||
"""解析一组日期:都空=昨天~今天;只给一端=单日;起止颠倒自动换序。"""
|
||||
d1 = _parse_day(raw_from) if raw_from else None
|
||||
d2 = _parse_day(raw_to) if raw_to else None
|
||||
if d1 is None and d2 is None:
|
||||
return ((date.today() - timedelta(days=1)).isoformat(), date.today().isoformat())
|
||||
if d1 is None:
|
||||
d1 = d2
|
||||
if d2 is None:
|
||||
d2 = d1
|
||||
if d2 < d1:
|
||||
d1, d2 = d2, d1
|
||||
return d1.isoformat(), d2.isoformat()
|
||||
|
||||
|
||||
def _resolve_action(fields):
|
||||
"""决定本次做什么:download / reconcile / all。
|
||||
|
||||
UI 会直接给 action;老配置(无 action)按开关推导,缺省视为全流程。
|
||||
"""
|
||||
action = str(fields.get('action') or '').strip().lower()
|
||||
if action in ('download', 'reconcile', 'all'):
|
||||
return action
|
||||
do_download = fields.get('do_download')
|
||||
do_reconcile = fields.get('do_reconcile')
|
||||
do_download = True if do_download is None else bool(do_download)
|
||||
do_reconcile = True if do_reconcile is None else bool(do_reconcile)
|
||||
if do_download and do_reconcile:
|
||||
return 'all'
|
||||
if do_download:
|
||||
return 'download'
|
||||
if do_reconcile:
|
||||
return 'reconcile'
|
||||
return ''
|
||||
|
||||
|
||||
class Xq0041Plugin(ScenePlugin):
|
||||
id = 'xq0041'
|
||||
name = '新美大平台核对'
|
||||
version = '1.1.2'
|
||||
description = ('美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、'
|
||||
'预订收益明细,把新产生的收益按验券时间并入月份台账,'
|
||||
'并给核对统计表补当天的团购统计表链接')
|
||||
platform = '' # 插件自带登录(经营宝 SSO + 选商家),不用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ['xq0041']
|
||||
permissions = {'platforms': []}
|
||||
# 与 plugin.json.fields 一致(ui=true,前端按此渲染表单)
|
||||
fields = {
|
||||
'action': {'type': 'string', 'title': '执行过程', 'default': 'all',
|
||||
'enum': ['all', 'download', 'reconcile']},
|
||||
'do_download': {'type': 'boolean', 'title': '下载数据', 'default': True},
|
||||
'do_reconcile': {'type': 'boolean', 'title': '更新核对', 'default': True},
|
||||
'pay_enabled': {'type': 'boolean', 'title': '下载打款记录', 'default': True},
|
||||
'pay_date_from': {'type': 'string', 'title': '打款记录-开始日期', 'default': ''},
|
||||
'pay_date_to': {'type': 'string', 'title': '打款记录-结束日期', 'default': ''},
|
||||
'profit_group': {'type': 'boolean', 'title': '下载团购收益明细', 'default': True},
|
||||
'profit_booking': {'type': 'boolean', 'title': '下载预订收益明细', 'default': True},
|
||||
'profit_date_from': {'type': 'string', 'title': '收益明细-开始日期', 'default': ''},
|
||||
'profit_date_to': {'type': 'string', 'title': '收益明细-结束日期', 'default': ''},
|
||||
'run_merge': {'type': 'boolean', 'title': '并入台账', 'default': True},
|
||||
'run_links': {'type': 'boolean', 'title': '更新核对统计', 'default': True},
|
||||
'dry_run': {'type': 'boolean', 'title': '只核对不写入', 'default': False},
|
||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx):
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_debug(fields.get('debug_mode'))
|
||||
|
||||
# ---------- 参数 ----------
|
||||
action = _resolve_action(fields)
|
||||
if not action:
|
||||
raise RuntimeError('请至少选择一个执行过程(下载数据 / 更新核对)')
|
||||
do_download = action in ('all', 'download')
|
||||
do_reconcile = action in ('all', 'reconcile')
|
||||
|
||||
codes = []
|
||||
if fields.get('profit_group', True):
|
||||
codes.append(1)
|
||||
if fields.get('profit_booking', True):
|
||||
codes.append(11)
|
||||
pay_on = bool(fields.get('pay_enabled', True))
|
||||
|
||||
dry_run = bool(fields.get('dry_run'))
|
||||
run_merge = bool(fields.get('run_merge', True))
|
||||
run_links = bool(fields.get('run_links', True))
|
||||
save_dir = str(fields.get('save_dir') or config.WORK_DIR).strip().strip('"') or config.WORK_DIR
|
||||
|
||||
if do_download and not pay_on and not codes:
|
||||
raise RuntimeError('请至少勾选一项要下载的内容(打款记录 / 团购 / 预订)')
|
||||
|
||||
# 并入台账依赖团购收益明细(台账只收团购口径)
|
||||
if do_reconcile and run_merge and not codes and do_download:
|
||||
config.log('未勾选团购收益明细,本次跳过「并入台账」', 'WARN')
|
||||
run_merge = False
|
||||
|
||||
pay_from, pay_to = _resolve_pair(fields.get('pay_date_from'), fields.get('pay_date_to'))
|
||||
profit_from, profit_to = _resolve_pair(fields.get('profit_date_from'),
|
||||
fields.get('profit_date_to'))
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
|
||||
plan = []
|
||||
if do_download:
|
||||
if pay_on:
|
||||
plan.append(f'打款记录 {pay_from}~{pay_to}')
|
||||
if codes:
|
||||
name = '/'.join(n for c, n in ((1, '团购'), (11, '预订')) if c in codes)
|
||||
plan.append(f'{name}收益明细 {profit_from}~{profit_to}')
|
||||
if do_reconcile:
|
||||
plan.append('并入台账' if run_merge else '')
|
||||
plan.append('更新核对统计' if run_links else '')
|
||||
plan = [p for p in plan if p]
|
||||
config.log(('本次执行:' + ';'.join(plan) if plan else '本次没有可执行的动作')
|
||||
+ (f';目录 {save_dir}' if do_download else '')
|
||||
+ ('(只核对不写入)' if dry_run else ''))
|
||||
|
||||
detail = {'action': action, 'pay': None, 'profit': None, 'merge': None, 'links': None}
|
||||
files = []
|
||||
|
||||
# ---------- 1~3:登录 + 下载 ----------
|
||||
if do_download:
|
||||
ctx.progress(2)
|
||||
page = browser.open_page()
|
||||
try:
|
||||
ok, msg = meituan_login.ensure_login(page)
|
||||
config.log(msg)
|
||||
if not ok:
|
||||
raise RuntimeError(f'登录失败:{msg}')
|
||||
ctx.progress(20 if do_reconcile else 30)
|
||||
|
||||
if pay_on:
|
||||
r1 = payment_download.download(page, pay_from, pay_to, save_dir, dry_run)
|
||||
if not r1.get('ok'):
|
||||
raise RuntimeError(f'打款记录下载失败:{r1.get("message")}')
|
||||
config.log(r1.get('message') or '')
|
||||
if r1.get('path'):
|
||||
files.append(r1['path'])
|
||||
detail['pay'] = r1
|
||||
ctx.progress(45 if do_reconcile else 65)
|
||||
|
||||
if codes:
|
||||
r2 = profit_download.download(page, profit_from, profit_to, save_dir,
|
||||
codes, dry_run)
|
||||
if not r2.get('ok'):
|
||||
raise RuntimeError(f'收益明细下载失败:{r2.get("message")}')
|
||||
config.log(r2.get('message') or '')
|
||||
files.extend(r2.get('paths') or [])
|
||||
detail['profit'] = r2
|
||||
ctx.progress(60 if do_reconcile else 95)
|
||||
finally:
|
||||
browser.close_page(page)
|
||||
|
||||
# ---------- 4~5:并入台账 + 更新核对(不依赖浏览器) ----------
|
||||
if do_reconcile:
|
||||
ctx.progress(65 if do_download else 10)
|
||||
if run_merge:
|
||||
m = merge_ledger.run(dry_run=dry_run)
|
||||
config.log(m.get('message') or '')
|
||||
detail['merge'] = m
|
||||
if not m.get('ok'):
|
||||
raise RuntimeError(f'并入台账失败:{m.get("message")}')
|
||||
ctx.progress(85 if do_download else 60)
|
||||
|
||||
if run_links:
|
||||
# 纯核对时让后端按本机最新明细文件的日期推断(跟随实际数据);
|
||||
# 有下载则用本次的收益明细区间。
|
||||
link_from, link_to = (profit_from, profit_to) if do_download else (None, None)
|
||||
s = stat_links.run(link_from, link_to, dry_run=dry_run)
|
||||
config.log(s.get('message') or '')
|
||||
detail['links'] = s
|
||||
if not s.get('ok'):
|
||||
config.log(f'更新核对统计失败:{s.get("message")}', 'WARN')
|
||||
|
||||
ctx.progress(100)
|
||||
|
||||
# ---------- 汇总 ----------
|
||||
parts = []
|
||||
if files:
|
||||
parts.append(f'下载 {len(files)} 个文件')
|
||||
if detail['merge'] and detail['merge'].get('appended'):
|
||||
parts.append(f'台账并入 {detail["merge"]["appended"]} 行')
|
||||
if detail['links'] and detail['links'].get('rows'):
|
||||
parts.append(f'核对统计更新 {len(detail["links"]["rows"])} 行')
|
||||
if not parts:
|
||||
parts.append('执行完成')
|
||||
if dry_run:
|
||||
parts.insert(0, '[只核对不写入]')
|
||||
return {
|
||||
'summary': ';'.join(parts),
|
||||
'detail': detail,
|
||||
'path': files[0] if files else '',
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(Xq0041Plugin())
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
|
||||
|
||||
输出 dist-plugin/xq0041_v<版本>.zip,zip 根含 plugin.json。
|
||||
排除:ui-src、__pycache__、debug、.sessions、本脚本、*.pyc。
|
||||
|
||||
用法(仓库根下执行):
|
||||
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0041 新美大平台核对\\_pack.py"
|
||||
"""
|
||||
import json
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,181 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0041 新美大平台核对 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
各业务模块统一经 config.log() / config.progress() 输出,由 run() 启动时注入 ctx。
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
|
||||
# ==================== 平台:美团经营宝 ====================
|
||||
HOME_URL = 'https://ecom.meituan.com/'
|
||||
|
||||
# 登录成功的落地页:经营宝按商家类型分流(kdb → ecom.meituan.com/meishi,
|
||||
# dp → e.dianping.com/app/...)。命中任一即已登录。
|
||||
BACKEND_HINTS = (
|
||||
'ecom.meituan.com/meishi',
|
||||
'e.dianping.com/app/',
|
||||
'e.dianping.com/meishi/',
|
||||
)
|
||||
LOGIN_PAGE_HINT = 'bizaccount/login.html'
|
||||
BIZ_CHOICE_HINT = 'bizaccount/biz-choice.html'
|
||||
PASSPORT_HINTS = (
|
||||
'passport.meituan.com', 'epassport.meituan.com', 'unifiedlogin', 'ssologin',
|
||||
'passport.dianping.com', 'account.dianping.com/login', 'e.dianping.com/login',
|
||||
)
|
||||
|
||||
# ==================== 打款记录(h5 账单页,iframe 内 smartBill 接口) ====================
|
||||
PAYMENT_PAGE_URL = (
|
||||
'https://e.dianping.com/app/merchant-platform/02a5e2f40d5d4b0'
|
||||
'?iUrl=Ly9oNS5kaWFucGluZy5jb20vL2FwcC9tZXJjaGFudC1iaWxsLXN0YXRpYy9pbmRleC5odG1sIy9wYXltZW50cmVjb3Jk')
|
||||
PAYMENT_LIST_API = 'https://e.dianping.com/gw/smartBill/paymentlist'
|
||||
PAYMENT_DOWNLOAD_API = 'https://e.dianping.com/gw/smartBill/paymentdownload'
|
||||
PAYMENT_HISTORY_API = 'https://e.dianping.com/gw/smartBill/paymenthistory'
|
||||
PAYMENT_FILE_TYPE = 6 # 6 = 打款记录
|
||||
PAYMENT_NAME_KEY = '打款记录'
|
||||
|
||||
# ==================== 收益明细(PC 商户中心 downloadManagement 接口) ====================
|
||||
PROFIT_PAGE_URL = 'https://e.dianping.com/finance/web/payment/download/list'
|
||||
SHOP_API = 'https://e.dianping.com/smartBill/queryAllShopIds'
|
||||
PRODUCT_API = 'https://e.dianping.com/finance/ajax/downloadManagement/productCodeList'
|
||||
PROFIT_REQUEST_API = 'https://e.dianping.com/finance/ajax/downloadManagement/request'
|
||||
PROFIT_LIST_API = 'https://e.dianping.com/finance/ajax/downloadManagement/list'
|
||||
PROFIT_LINK_API = 'https://e.dianping.com/finance/ajax/downloadManagement/downloadLink'
|
||||
PROFIT_FILE_TYPE = 201 # 201 = 收益明细
|
||||
|
||||
# ==================== 台账 ====================
|
||||
WORK_DIR = r'D:\资料\财务\新美大平台核对' # 账单 + 台账统一目录
|
||||
LEDGER_GLOB = '新美大到账统计*.xlsx'
|
||||
LEDGER_SHEET = '金色印象--新美大导出(收)'
|
||||
STAT_SHEET = '新美大核对统计'
|
||||
TIME_COL = '验券/退款/调整时间'
|
||||
DETAIL_GLOB = '团购收益明细_*.xlsx'
|
||||
HEADER_ROW = 2
|
||||
DATA_START_ROW = 3
|
||||
|
||||
# 「新美大核对统计」V/W 列的外部工作簿(与台账历史 62 条链接一致)
|
||||
SHARE_ROOT = r'\\caiwu01\共享文件夹\1111\TG'
|
||||
LINK_BOOK = '马敏团购总表'
|
||||
LINK_SHEET = '资金组取数'
|
||||
|
||||
# ==================== 运行参数 ====================
|
||||
LOGIN_WAIT = 600 # 等待人工登录(含选商家)超时
|
||||
BACKEND_STABLE = 20 # 后台页连续稳定秒数(/meishi 未登录也会停留约 20s 再跳)
|
||||
SETTLE_WAIT = 8 # 登录成功后等首屏请求结束再抓 cookie
|
||||
POLL_SECONDS = 2
|
||||
RECORD_SECONDS = 120 # 账单生成后轮询记录的最长时间
|
||||
REUSE_MAX_AGE_MIN = 10 # 账单复用时效:记录生成时间距今 ≤ N 分钟才复用
|
||||
RETRY_MAX = 3
|
||||
HEADLESS = False # 人工登录必须可见浏览器
|
||||
|
||||
# ==================== 共享路径 ====================
|
||||
def _app_data_dir():
|
||||
return os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
|
||||
|
||||
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
||||
COOKIE_FILE = os.path.join(SESSIONS_DIR, 'meituan_cookies.json')
|
||||
COOKIE_HEADER_FILE = os.path.join(SESSIONS_DIR, 'meituan_cookies_header.txt')
|
||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'meituan_tokens.json')
|
||||
META_FILE = os.path.join(SESSIONS_DIR, 'meituan_session_meta.json')
|
||||
|
||||
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留,不占用日常 Chrome 配置。"""
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0041')
|
||||
|
||||
|
||||
# ==================== 浏览器窗口(全屏 + 置顶) ====================
|
||||
def apply_window_mode(page):
|
||||
"""把浏览器窗口设为全屏并置顶。
|
||||
|
||||
登录需要人工操作(账号密码 / 短信 / 扫码 / 选商家),窗口被其它窗口遮挡或最小化时
|
||||
用户容易漏看;置顶保证它一直在最前面。失败仅告警,不影响流程。
|
||||
"""
|
||||
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
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def set_debug(on):
|
||||
global _debug
|
||||
_debug = bool(on)
|
||||
|
||||
|
||||
def debug_enabled():
|
||||
return _debug
|
||||
|
||||
|
||||
def log(msg, level='INFO'):
|
||||
text = f'[{time.strftime("%H:%M:%S")}] {msg}'
|
||||
if level == 'DEBUG' and not _debug:
|
||||
return
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f'[{level}] {text}')
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""数据层:登录态、打款记录与收益明细的下载。"""
|
||||
@@ -0,0 +1,133 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""浏览器:一次运行共用一个可见浏览器(登录 + 三张表下载都复用它,避免反复开关)。
|
||||
|
||||
独立固定用户目录 %LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0041,
|
||||
登录态跨次保留,不占用用户日常 Chrome 配置。
|
||||
"""
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def open_page():
|
||||
co = ChromiumOptions()
|
||||
if config.HEADLESS:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
profile = config.get_browser_profile_dir()
|
||||
import os
|
||||
os.makedirs(profile, exist_ok=True)
|
||||
co.set_user_data_path(profile)
|
||||
config.log(f'浏览器用户目录:{profile}', 'DEBUG')
|
||||
page = ChromiumPage(co)
|
||||
if not config.HEADLESS:
|
||||
# 登录要人工操作(账密/短信/扫码/选商家),全屏 + 置顶避免被其它窗口挡住
|
||||
config.apply_window_mode(page)
|
||||
return page
|
||||
|
||||
|
||||
def close_page(page):
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
|
||||
def xhr(page, method, url, payload=None):
|
||||
"""页面上下文同步 XHR:mtgsig/yodaReady 由页面上的 Yoda(H5guard) SDK 自动补。
|
||||
|
||||
返回 (status:int, text:str)。
|
||||
"""
|
||||
import json as _json
|
||||
body_js = 'null'
|
||||
headers_js = ''
|
||||
if payload is not None:
|
||||
body_js = 'JSON.stringify(' + _json.dumps(payload, ensure_ascii=False) + ')'
|
||||
headers_js = "x.setRequestHeader('Content-Type','application/json');"
|
||||
js = '''
|
||||
try {
|
||||
var x = new XMLHttpRequest();
|
||||
x.open('%s', '%s', false);
|
||||
x.withCredentials = true;
|
||||
%s
|
||||
x.send(%s);
|
||||
return x.status + '||' + String(x.responseText || '');
|
||||
} catch (e) {
|
||||
return 'ERR||' + e;
|
||||
}
|
||||
''' % (method.upper(), url, headers_js, body_js)
|
||||
raw = page.run_js(js)
|
||||
if not raw or '||' not in str(raw):
|
||||
return 0, f'返回值异常:{str(raw)[:200]}'
|
||||
status, _, text = str(raw).partition('||')
|
||||
try:
|
||||
return int(status), text
|
||||
except Exception:
|
||||
return 0, text
|
||||
|
||||
|
||||
def api_json(page, method, url, payload=None):
|
||||
import json as _json
|
||||
status, text = xhr(page, method, url, payload)
|
||||
name = url.split('/')[-1].split('?')[0]
|
||||
if status != 200:
|
||||
config.log(f'{name} 请求失败:status={status} {text[:200]}', 'WARN')
|
||||
return None
|
||||
try:
|
||||
return _json.loads(text)
|
||||
except Exception as e:
|
||||
config.log(f'{name} 返回非 JSON:{e} | {text[:200]}', 'WARN')
|
||||
return None
|
||||
|
||||
|
||||
def download_file(link, save_path):
|
||||
"""S3 预签名 URL 直下(无需 Cookie / mtgsig)。返回字节数,失败 0。"""
|
||||
import os
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
headers = {
|
||||
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'),
|
||||
'Accept': '*/*',
|
||||
}
|
||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
resp = requests.get(link, headers=headers, timeout=300, stream=True)
|
||||
if resp.status_code != 200:
|
||||
config.log(f'下载失败:HTTP {resp.status_code}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
continue
|
||||
tmp = save_path + '.part'
|
||||
with open(tmp, 'wb') as f:
|
||||
for chunk in resp.iter_content(128 * 1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
os.replace(tmp, save_path)
|
||||
size = os.path.getsize(save_path)
|
||||
if size < 1024:
|
||||
config.log(f'文件异常小({size} 字节),重试 {attempt}/{config.RETRY_MAX}', 'WARN')
|
||||
time.sleep(2)
|
||||
continue
|
||||
return size
|
||||
except Exception as e:
|
||||
config.log(f'下载异常:{e}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
return 0
|
||||
|
||||
|
||||
def read_xlsx_summary(path):
|
||||
"""读 sheet 名/行列数,确认文件有效。"""
|
||||
try:
|
||||
from openpyxl import load_workbook
|
||||
wb = load_workbook(path, read_only=True, data_only=True)
|
||||
ws = wb.worksheets[0]
|
||||
info = {'sheet': ws.title, 'rows': ws.max_row, 'cols': ws.max_column}
|
||||
wb.close()
|
||||
return info
|
||||
except Exception as e:
|
||||
return {'error': str(e)}
|
||||
@@ -0,0 +1,199 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""美团经营宝登录态:打开官方页面 → 人工登录(含选商家)→ 检测完成 → 落盘 cookies/票据。
|
||||
|
||||
为什么不用 requests 校验:经营宝所有业务接口带 mtgsig 动态签名(页面 H5guard 秒级生成),
|
||||
requests 复刻必然 403。登录态有效性只由浏览器判定,取数也一律在页面上下文发请求。
|
||||
|
||||
实测登录链路(2026-10):
|
||||
ecom.meituan.com → 外壳,未登录也先进这里
|
||||
ecom.meituan.com/meishi → 前端异步鉴权,约 20s 后才跳走,不可当已登录
|
||||
.../bizaccount/login.html → 真·未登录
|
||||
.../bizaccount/biz-choice.html → 账号已登录、待选商家
|
||||
e.dianping.com/app/... → 选完商家进后台(登录完成,dp 商家)
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def classify(url):
|
||||
"""页面状态:login / biz_choice / backend / other。"""
|
||||
low = (url or '').strip().lower()
|
||||
if not low.startswith('http'):
|
||||
return 'other'
|
||||
if config.LOGIN_PAGE_HINT in low or any(h in low for h in config.PASSPORT_HINTS):
|
||||
return 'login'
|
||||
if config.BIZ_CHOICE_HINT in low:
|
||||
return 'biz_choice'
|
||||
if any(h in low for h in config.BACKEND_HINTS):
|
||||
return 'backend'
|
||||
return 'other'
|
||||
|
||||
|
||||
def _cookies(page):
|
||||
try:
|
||||
return page.cookies(all_domains=True) or []
|
||||
except Exception as e:
|
||||
config.log(f'读取 Cookies 失败:{e}', 'WARN')
|
||||
return []
|
||||
|
||||
|
||||
def _platform_cookie_header(cookies):
|
||||
skip = ('passport', 'certificates', 'report', 'lx', 'dreport')
|
||||
pairs = [f'{c.get("name")}={c.get("value")}' for c in cookies
|
||||
if c.get('name')
|
||||
and any(d in (c.get('domain') or '') for d in ('meituan.com', 'dianping.com'))
|
||||
and not any(s in (c.get('domain') or '') for s in skip)]
|
||||
return '; '.join(pairs) if pairs else None
|
||||
|
||||
|
||||
def _read_storage(page):
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const dump = (store) => {
|
||||
const data = {};
|
||||
for (let i = 0; i < store.length; i++) {
|
||||
const k = store.key(i);
|
||||
const v = store.getItem(k);
|
||||
if (v && v.length < 100000) data[k] = v;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
return JSON.stringify({
|
||||
localStorage: dump(window.localStorage),
|
||||
sessionStorage: dump(window.sessionStorage),
|
||||
});
|
||||
''')
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception as e:
|
||||
config.log(f'读取 storage 失败(不影响 Cookies):{e}', 'WARN')
|
||||
return {}
|
||||
|
||||
|
||||
def _save_login_state(page):
|
||||
cookies = _cookies(page)
|
||||
_ensure_dir(config.SESSIONS_DIR)
|
||||
if cookies:
|
||||
_atomic_write(config.COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
config.log(f'已保存 {len(cookies)} 个 Cookies → {config.COOKIE_FILE}')
|
||||
else:
|
||||
config.log('未取到任何 Cookies(登录态可能未生效)', 'WARN')
|
||||
|
||||
header = _platform_cookie_header(cookies)
|
||||
if header:
|
||||
_atomic_write(config.COOKIE_HEADER_FILE, header)
|
||||
|
||||
storage = _read_storage(page)
|
||||
ls, ss = (storage.get('localStorage') or {}), (storage.get('sessionStorage') or {})
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps({
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'localStorage': ls,
|
||||
'sessionStorage': ss,
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
domains = {}
|
||||
for c in cookies:
|
||||
d = c.get('domain') or '(空)'
|
||||
domains[d] = domains.get(d, 0) + 1
|
||||
summary = {
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'title': (getattr(page, 'title', '') or ''),
|
||||
'cookie_count': len(cookies),
|
||||
'cookie_domains': domains,
|
||||
'cookie_names': sorted({c.get('name') for c in cookies if c.get('name')}),
|
||||
'storage_keys': {'localStorage': sorted(ls.keys()), 'sessionStorage': sorted(ss.keys())},
|
||||
}
|
||||
_atomic_write(config.META_FILE, json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
config.log(f'登录态已落盘:{len(cookies)} 个 Cookie,'
|
||||
f'localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项')
|
||||
|
||||
|
||||
def _wait_backend(page):
|
||||
"""等人工完成「登录 + 选商家」。返回 True/False。"""
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
last_url, last_state = None, None
|
||||
backend_since = None
|
||||
login_hint_at = biz_hint_at = 0.0
|
||||
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
url = page.url or ''
|
||||
except Exception:
|
||||
url = ''
|
||||
state = classify(url)
|
||||
|
||||
if url != last_url:
|
||||
last_url = url
|
||||
config.log(f'页面状态 = {state} | {url}', 'DEBUG')
|
||||
|
||||
if state != last_state:
|
||||
last_state = state
|
||||
if state == 'login' and time.time() - login_hint_at > 30:
|
||||
login_hint_at = time.time()
|
||||
config.log('请在浏览器窗口内完成登录(账号密码 / 短信验证码 / 扫码均可)')
|
||||
elif state == 'biz_choice' and time.time() - biz_hint_at > 30:
|
||||
biz_hint_at = time.time()
|
||||
config.log('账号已登录,请在页面上选择要进入的商家(脚本不自动选,避免进错店)')
|
||||
|
||||
if state == 'backend':
|
||||
if backend_since is None:
|
||||
backend_since = time.time()
|
||||
config.log(f'已进入商家后台,等待 {config.BACKEND_STABLE}s 确认不会再被踢回登录页…')
|
||||
elif time.time() - backend_since >= config.BACKEND_STABLE:
|
||||
return True
|
||||
else:
|
||||
if backend_since is not None:
|
||||
config.log('又回到登录/选商家页,重新计时', 'WARN')
|
||||
backend_since = None
|
||||
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
return False
|
||||
|
||||
|
||||
def ensure_login(page):
|
||||
"""确保 page 已进入商家后台;必要时停在前台等人工登录。"""
|
||||
config.log(f'打开经营宝:{config.HOME_URL}')
|
||||
page.get(config.HOME_URL)
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
# 复用一个短窗口:profile 里残留会话能直接进后台就不用打扰
|
||||
reuse_end = time.time() + config.BACKEND_STABLE + 10
|
||||
while time.time() < reuse_end:
|
||||
state = classify(page.url)
|
||||
if state == 'backend':
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
_save_login_state(page)
|
||||
return True, '复用缓存登录态'
|
||||
if state in ('login', 'biz_choice'):
|
||||
break
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
config.log(f'需要人工登录,最多等待 {config.LOGIN_WAIT} 秒…')
|
||||
if not _wait_backend(page):
|
||||
cookies = _cookies(page)
|
||||
config.log('当前 Cookie:' + ', '.join(sorted({c.get('name') for c in cookies if c.get('name')})),
|
||||
'WARN')
|
||||
return False, '登录超时(未进入商家后台)'
|
||||
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
if classify(page.url) != 'backend':
|
||||
return False, '登录态未稳定(落盘前离开后台)'
|
||||
_save_login_state(page)
|
||||
return True, '登录成功'
|
||||
@@ -0,0 +1,159 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""打款记录下载(h5 账单页,iframe 内 smartBill 三个接口)。
|
||||
|
||||
链路(实测):
|
||||
① 查询 POST /gw/smartBill/paymentlist body{payTime,productCodeList,payStatusList,shopList,pageIndex,pageSize}
|
||||
② 生成 POST /gw/smartBill/paymentdownload body 同上 + downloadFileType=6
|
||||
③ 记录 GET /gw/smartBill/paymenthistory?pageIndex=0&pageSize=20&downloadFileType=6
|
||||
(必须带 downloadFileType + 分页参数,缺了返回 code=500)
|
||||
④ 下载 记录里的 downloadLink(mss-shon 预签名 URL,requests 直下)
|
||||
|
||||
①②③ 在 iframe 上下文发 XHR,mtgsig 由页面 SDK 自动补。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from . import browser
|
||||
|
||||
|
||||
def _find_frame(page, timeout=30):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
for f in page.get_frames():
|
||||
try:
|
||||
if 'merchant-bill' in (f.url or ''):
|
||||
return f
|
||||
except Exception:
|
||||
continue
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(1)
|
||||
return None
|
||||
|
||||
|
||||
def _history_items(frame):
|
||||
url = (f'{config.PAYMENT_HISTORY_API}?pageIndex=0&pageSize=20'
|
||||
f'&downloadFileType={config.PAYMENT_FILE_TYPE}')
|
||||
data = browser.api_json(frame, 'GET', url) or {}
|
||||
return (data.get('data') or {}).get('details') or []
|
||||
|
||||
|
||||
def _throttle_seconds(msg):
|
||||
import re
|
||||
m = re.search(r'(\d+)\s*秒', msg or '')
|
||||
return int(m.group(1)) if m else 0
|
||||
|
||||
|
||||
def _age_minutes(add_time):
|
||||
try:
|
||||
dt = datetime.strptime(str(add_time).strip(), '%Y-%m-%d %H:%M:%S')
|
||||
return (datetime.now() - dt).total_seconds() / 60.0
|
||||
except Exception:
|
||||
return 1e9
|
||||
|
||||
|
||||
def download(page, d_from, d_to, save_dir, dry_run=False):
|
||||
"""下载指定日期区间的打款记录。返回 {ok, path, rows, message}。"""
|
||||
tag = d_from.replace('-', '') if d_from == d_to else \
|
||||
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
||||
match_key = d_from
|
||||
|
||||
config.log(f'打开打款记录页:{config.PAYMENT_PAGE_URL}', 'DEBUG')
|
||||
page.get(config.PAYMENT_PAGE_URL)
|
||||
frame = _find_frame(page)
|
||||
if not frame:
|
||||
return {'ok': False, 'message': '未找到账单 iframe(登录态可能已失效)'}
|
||||
config.log(f'账单 iframe:{frame.url}', 'DEBUG')
|
||||
|
||||
# ① 先查询(页面同款顺序:查询出数据后下载按钮才可用)
|
||||
query = {
|
||||
'payTime': f'{d_from},{d_to}',
|
||||
'productCodeList': [], 'payStatusList': [], 'shopList': [],
|
||||
'pageIndex': 0, 'pageSize': 10,
|
||||
}
|
||||
q = browser.api_json(frame, 'POST', config.PAYMENT_LIST_API, query)
|
||||
if q is None:
|
||||
return {'ok': False, 'message': '打款记录查询失败'}
|
||||
qdata = q.get('data') or {}
|
||||
total = qdata.get('totalCount')
|
||||
details = qdata.get('details') or []
|
||||
config.log(f'查询 {d_from}~{d_to}:totalCount={total}')
|
||||
if details:
|
||||
s = details[0]
|
||||
config.log(f' 首条 {s.get("payTime")} | {s.get("productCodeName")} | '
|
||||
f'{s.get("amount")} | {s.get("payStatusName")}')
|
||||
if not total:
|
||||
return {'ok': False, 'message': f'{d_from}~{d_to} 没有打款记录'}
|
||||
|
||||
# ② 已有记录时效内复用
|
||||
before = _history_items(frame)
|
||||
before_ids = {it.get('id') for it in before}
|
||||
target = None
|
||||
cands = [it for it in before
|
||||
if match_key in (it.get('timeInterval') or '') and it.get('downloadLink')]
|
||||
fresh = [it for it in cands if _age_minutes(it.get('addTime')) <= config.REUSE_MAX_AGE_MIN]
|
||||
if fresh and not dry_run:
|
||||
target = fresh[0]
|
||||
config.log(f'复用 {_age_minutes(target.get("addTime")):.0f} 分钟前的同区间记录'
|
||||
f'(阈值 {config.REUSE_MAX_AGE_MIN} 分钟),不重复生成')
|
||||
elif cands:
|
||||
config.log('同区间记录已过期,重新生成以取最新数据')
|
||||
|
||||
# ③ 生成 + 轮询
|
||||
if not target and not dry_run:
|
||||
payload = dict(query)
|
||||
payload.pop('pageIndex', None)
|
||||
payload.pop('pageSize', None)
|
||||
payload['downloadFileType'] = config.PAYMENT_FILE_TYPE
|
||||
config.log(f'提交账单生成:{json.dumps(payload, ensure_ascii=False)}')
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
resp = browser.api_json(frame, 'POST', config.PAYMENT_DOWNLOAD_API, payload)
|
||||
if resp and resp.get('code') == 200:
|
||||
config.log('生成任务已受理')
|
||||
break
|
||||
msg = (resp or {}).get('message') or '无响应'
|
||||
wait = _throttle_seconds(msg)
|
||||
if wait and attempt < config.RETRY_MAX:
|
||||
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试({attempt}/{config.RETRY_MAX})',
|
||||
'WARN')
|
||||
time.sleep(wait + 3)
|
||||
continue
|
||||
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
|
||||
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
while time.time() < deadline:
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
items = _history_items(frame)
|
||||
for it in items:
|
||||
if it.get('id') in before_ids:
|
||||
continue
|
||||
if match_key not in (it.get('timeInterval') or ''):
|
||||
continue
|
||||
target = it
|
||||
break
|
||||
if target:
|
||||
break
|
||||
config.log(' 等待账单生成…')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'message': f'[演练] 将生成并下载打款记录 {d_from}~{d_to}', 'rows': total}
|
||||
|
||||
if not target:
|
||||
return {'ok': False, 'message': f'{config.RECORD_SECONDS}s 内未拿到可下载记录'}
|
||||
|
||||
link = target.get('downloadLink')
|
||||
if not link:
|
||||
return {'ok': False, 'message': '记录里没有 downloadLink(可能仍在生成)'}
|
||||
|
||||
path = os.path.join(save_dir, f'{config.PAYMENT_NAME_KEY}_{tag}.xlsx')
|
||||
config.log(f'下载 → {path}')
|
||||
size = browser.download_file(link, path)
|
||||
if not size:
|
||||
return {'ok': False, 'message': '打款记录下载失败'}
|
||||
info = browser.read_xlsx_summary(path)
|
||||
config.log(f'完成:{os.path.basename(path)}({size / 1024:.0f} KB){info}')
|
||||
return {'ok': True, 'path': path, 'rows': info.get('rows'), 'message': '打款记录已下载'}
|
||||
@@ -0,0 +1,189 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""收益明细下载(PC 商户中心 downloadManagement 一套接口)。
|
||||
|
||||
链路(实测):
|
||||
① 门店 GET /smartBill/queryAllShopIds → data.availableShopIds(0=全部)
|
||||
② 类型 GET /finance/ajax/downloadManagement/productCodeList → [{1,团购},{11,预订}]
|
||||
③ 生成 POST /finance/ajax/downloadManagement/request
|
||||
body{beginDate,endDate,productCodeList,shopIdList,downloadFileType:201}
|
||||
(一次生成团购+预订两个文件,约 30~40 秒内限流一次)
|
||||
④ 记录 GET /finance/ajax/downloadManagement/list?pageSize=20&pageNum=1&beginDate&endDate
|
||||
⑤ 链接 GET /finance/ajax/downloadManagement/downloadLink?id=<记录id>(记录里 downloadLink 为空时)
|
||||
⑥ 下载 mss-shon 预签名 URL(requests 直下)
|
||||
|
||||
复用策略:按业务类型分组取最新一条,**任一类型缺失或过期就整体重新生成**,
|
||||
避免出现「只拿到团购、预订缺失」的半套数据。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
from .. import config
|
||||
from . import browser
|
||||
|
||||
|
||||
def _throttle_seconds(msg):
|
||||
import re
|
||||
m = re.search(r'(\d+)\s*秒', msg or '')
|
||||
return int(m.group(1)) if m else 0
|
||||
|
||||
|
||||
def _age_minutes(add_time):
|
||||
try:
|
||||
dt = datetime.strptime(str(add_time).strip(), '%Y-%m-%d %H:%M:%S')
|
||||
return (datetime.now() - dt).total_seconds() / 60.0
|
||||
except Exception:
|
||||
return 1e9
|
||||
|
||||
|
||||
def _history(page, day_from, day_to):
|
||||
url = f'{config.PROFIT_LIST_API}?pageSize=20&pageNum=1&beginDate={day_from}&endDate={day_to}'
|
||||
data = browser.api_json(page, 'GET', url) or {}
|
||||
return data.get('data') or []
|
||||
|
||||
|
||||
def _expect_names(codes):
|
||||
"""勾选的业务类型 → 预期产出的明细名称。"""
|
||||
names = []
|
||||
if 1 in codes:
|
||||
names.append('团购收益明细')
|
||||
if 11 in codes:
|
||||
names.append('预订收益明细')
|
||||
return names
|
||||
|
||||
|
||||
def download(page, d_from, d_to, save_dir, codes=None, dry_run=False):
|
||||
"""下载指定业务类型的收益明细。codes:1=团购、11=预订;None=两者都要。
|
||||
|
||||
返回 {ok, paths, message}。
|
||||
"""
|
||||
tag = d_from.replace('-', '') if d_from == d_to else \
|
||||
f'{d_from.replace("-", "")}_{d_to.replace("-", "")}'
|
||||
|
||||
config.log(f'打开收益明细页:{config.PROFIT_PAGE_URL}', 'DEBUG')
|
||||
page.get(config.PROFIT_PAGE_URL)
|
||||
time.sleep(4)
|
||||
|
||||
# ① 门店 / 业务类型
|
||||
shop_data = browser.api_json(page, 'GET', config.SHOP_API) or {}
|
||||
shop_ids = ((shop_data.get('data') or {}).get('availableShopIds')) or []
|
||||
if not shop_ids:
|
||||
config.log('未取到门店列表,回退 [0](全部)', 'WARN')
|
||||
shop_ids = [0]
|
||||
prod_data = browser.api_json(page, 'GET', config.PRODUCT_API) or {}
|
||||
products = prod_data.get('data') or []
|
||||
all_codes = [p.get('productCode') for p in products if p.get('productCode')] or [1, 11]
|
||||
# 只保留勾选的类型;未指定则全要
|
||||
want = [c for c in (codes or all_codes) if c in all_codes] or all_codes
|
||||
expect = _expect_names(want)
|
||||
config.log(f'门店 {len(shop_ids)} 个;本次下载类型:{json.dumps(products, ensure_ascii=False)}'
|
||||
f' → {expect}')
|
||||
|
||||
# ② 已有记录:按类型完整性 + 时效判断
|
||||
from datetime import date, timedelta
|
||||
list_from = (date.today() - timedelta(days=30)).isoformat()
|
||||
list_to = date.today().isoformat()
|
||||
before = _history(page, list_from, list_to)
|
||||
|
||||
targets = []
|
||||
groups = {}
|
||||
for it in before:
|
||||
if d_from not in (it.get('timeInterval') or ''):
|
||||
continue
|
||||
if it.get('downloadStatus') != 2:
|
||||
continue
|
||||
key = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||
groups.setdefault(key, []).append(it)
|
||||
newest = {k: max(v, key=lambda x: str(x.get('addTime') or '')) for k, v in groups.items()}
|
||||
newest = {k: v for k, v in newest.items() if k in expect} # 只看勾选的类型
|
||||
ages = {k: _age_minutes(v.get('addTime')) for k, v in newest.items()}
|
||||
stale = [k for k, a in ages.items() if a > config.REUSE_MAX_AGE_MIN]
|
||||
if all(name in newest for name in expect) and not stale:
|
||||
targets = list(newest.values())
|
||||
config.log('同区间记录齐全且新鲜,直接复用:' +
|
||||
', '.join(f'{k}({ages[k]:.0f}分钟前)' for k in newest))
|
||||
elif newest:
|
||||
config.log(f'已有记录不完整或过期({len(newest)}/{len(expect)} 类,'
|
||||
f'过期:{",".join(stale) or "无"}),重新生成以取最新数据')
|
||||
|
||||
# ③ 生成
|
||||
if not targets and not dry_run:
|
||||
payload = {
|
||||
'beginDate': d_from,
|
||||
'endDate': d_to,
|
||||
'productCodeList': want,
|
||||
'shopIdList': shop_ids,
|
||||
'downloadFileType': config.PROFIT_FILE_TYPE,
|
||||
}
|
||||
config.log(f'提交生成:{d_from}~{d_to},类型 {want},门店 {len(shop_ids)} 个')
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
resp = browser.api_json(page, 'POST', config.PROFIT_REQUEST_API, payload)
|
||||
if resp and resp.get('code') == 200:
|
||||
config.log('生成任务已受理')
|
||||
break
|
||||
msg = (resp or {}).get('message') or '无响应'
|
||||
wait = _throttle_seconds(msg)
|
||||
if wait and attempt < config.RETRY_MAX:
|
||||
config.log(f'触发限流:{msg} → 等待 {wait + 3}s 后重试({attempt}/{config.RETRY_MAX})',
|
||||
'WARN')
|
||||
time.sleep(wait + 3)
|
||||
continue
|
||||
return {'ok': False, 'message': f'生成任务提交失败:{msg}'}
|
||||
|
||||
before_ids = {it.get('id') for it in before}
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
while time.time() < deadline:
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
items = _history(page, list_from, list_to)
|
||||
hits = [it for it in items
|
||||
if it.get('id') not in before_ids and d_from in (it.get('timeInterval') or '')]
|
||||
ready = [it for it in hits if it.get('downloadStatus') == 2]
|
||||
pending = [it for it in hits if it.get('downloadStatus') != 2]
|
||||
if ready:
|
||||
targets = ready
|
||||
if not pending:
|
||||
break
|
||||
config.log(' 已就绪 %d 条,仍有 %d 条生成中(%s)…' % (
|
||||
len(ready), len(pending),
|
||||
', '.join(str(it.get('productCodeName')) for it in pending)))
|
||||
else:
|
||||
config.log(' 等待生成…')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'message': f'[演练] 将生成并下载收益明细 {d_from}~{d_to}', 'paths': []}
|
||||
|
||||
if not targets:
|
||||
return {'ok': False, 'message': f'未拿到可下载的收益明细({config.RECORD_SECONDS}s 内未完成)'}
|
||||
|
||||
# ④ 逐个下载(同类型去重取最新)
|
||||
uniq = {}
|
||||
for it in targets:
|
||||
key = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||
if expect and key not in expect:
|
||||
continue
|
||||
uniq.setdefault(key, it)
|
||||
|
||||
paths = []
|
||||
for it in uniq.values():
|
||||
name = it.get('productCodeName') or it.get('fileName') or '收益明细'
|
||||
link = it.get('downloadLink') or ''
|
||||
if not link:
|
||||
ld = browser.api_json(page, 'GET', f'{config.PROFIT_LINK_API}?id={it.get("id")}') or {}
|
||||
link = ((ld.get('data') or {}).get('downloadLink')) or ''
|
||||
if not link:
|
||||
config.log(f'{name} 未取到 downloadLink,跳过', 'WARN')
|
||||
continue
|
||||
path = os.path.join(save_dir, f'{name}_{tag}.xlsx')
|
||||
config.log(f'下载 {name} → {path}')
|
||||
size = browser.download_file(link, path)
|
||||
if not size:
|
||||
config.log(f'{name} 下载失败', 'ERROR')
|
||||
continue
|
||||
info = browser.read_xlsx_summary(path)
|
||||
config.log(f' {name} 完成:{size / 1024:.0f} KB | {info}')
|
||||
paths.append(path)
|
||||
|
||||
if not paths:
|
||||
return {'ok': False, 'message': '收益明细全部下载失败'}
|
||||
return {'ok': True, 'paths': paths, 'message': f'收益明细已下载 {len(paths)} 个文件'}
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""逻辑层:台账增量合并、核对统计 V/W 外部链接。"""
|
||||
@@ -0,0 +1,449 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""台账增量合并:把收益明细里比台账更新的行追加到「金色印象--新美大导出(收)」。
|
||||
|
||||
规则(业务口径):
|
||||
1. 找最新月份的台账(新美大到账统计YYYY.M月新.xlsx,排除备份文件);
|
||||
2. 取该 sheet「验券/退款/调整时间」列的最大时间;
|
||||
3. 明细里该列 < 最大时间的行剔除,其余按表头对齐追加;
|
||||
4. 从**真实数据末行**的下一行开始写(max_row 被尾部公式空行撑大,不能直接用);
|
||||
5. 台账第 32 列之后(AF~AP)全是公式 —— 几十万行不可能人工下拉,必须由脚本生成:
|
||||
模板行里内联公式直接按行号平移;共享公式(<f t="shared" si="N"/>)先按 si
|
||||
找到同列主定义,再从定义行平移到新行。效果与手工下拉完全一致。
|
||||
|
||||
写入方式:只改目标 sheet 的 XML(清掉尾部空行、在 </sheetData> 前插入新行、更新 dimension),
|
||||
其余部件逐字节拷贝 —— 台账含 5 个透视表 + 62 个外部链接,openpyxl 全量保存会丢透视表,
|
||||
且 645MB 的 sheet 也吃不下内存。
|
||||
"""
|
||||
import glob
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import date, datetime
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .. import config
|
||||
|
||||
_NS_MAIN = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
_NS_REL = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
||||
_NS_PKGREL = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
||||
_MONTH_RE = re.compile(r'(\d{4})[.\-年](\d{1,2})\s*月')
|
||||
_CELL_RE = re.compile(rb'<c r="([A-Z]+)(\d+)"([^>]*?)>(.*?)</c>', re.S)
|
||||
_F_RE = re.compile(rb'<f([^>]*?)(?:/>|>(.*?)</f>)', re.S)
|
||||
|
||||
|
||||
# ==================== 通用小工具 ====================
|
||||
def _to_dt(v):
|
||||
if v is None:
|
||||
return None
|
||||
if isinstance(v, datetime):
|
||||
return v
|
||||
if isinstance(v, date):
|
||||
return datetime(v.year, v.month, v.day)
|
||||
s = str(v).strip()
|
||||
if not s:
|
||||
return None
|
||||
for fmt in ('%Y-%m-%d %H:%M:%S', '%Y-%m-%d %H:%M', '%Y-%m-%d',
|
||||
'%Y/%m/%d %H:%M:%S', '%Y/%m/%d'):
|
||||
try:
|
||||
return datetime.strptime(s, fmt)
|
||||
except ValueError:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _month_key(path):
|
||||
m = _MONTH_RE.search(os.path.basename(path))
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (0, 0)
|
||||
|
||||
|
||||
def _pick_latest(pattern, by_month=True):
|
||||
"""排除备份文件(`_备份20261027_155650.xlsx` 同样匹配 glob,曾误当成台账)。"""
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
|
||||
if '备份' not in os.path.basename(p) and not p.endswith('.rebuild.tmp')]
|
||||
if not files:
|
||||
return None
|
||||
if by_month:
|
||||
files.sort(key=lambda p: (_month_key(p), os.path.getmtime(p)))
|
||||
else:
|
||||
files.sort(key=os.path.getmtime)
|
||||
return files[-1]
|
||||
|
||||
|
||||
def _header_index(header):
|
||||
out = {}
|
||||
for i, v in enumerate(header):
|
||||
if v is None:
|
||||
continue
|
||||
name = str(v).strip()
|
||||
if name and name not in out:
|
||||
out[name] = i
|
||||
return out
|
||||
|
||||
|
||||
def _col_letter(n):
|
||||
s = ''
|
||||
while n > 0:
|
||||
n, r = divmod(n - 1, 26)
|
||||
s = chr(65 + r) + s
|
||||
return s
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _xml_text(v):
|
||||
return (str(v).replace('&', '&').replace('<', '<')
|
||||
.replace('>', '>').replace('"', '"'))
|
||||
|
||||
|
||||
def _cell_xml(col, row, value, style=None):
|
||||
letter = _col_letter(col) if isinstance(col, int) else col
|
||||
ref = f'{letter}{row}'
|
||||
s_attr = f' s="{style}"' if style else ''
|
||||
if value is None:
|
||||
return ''
|
||||
if isinstance(value, bool):
|
||||
return f'<c r="{ref}"{s_attr} t="b"><v>{1 if value else 0}</v></c>'
|
||||
if isinstance(value, (int, float)):
|
||||
num = repr(round(float(value), 12)) if isinstance(value, float) else str(value)
|
||||
return f'<c r="{ref}"{s_attr}><v>{num}</v></c>'
|
||||
text = str(value)
|
||||
if text == '':
|
||||
return ''
|
||||
return f'<c r="{ref}"{s_attr} t="inlineStr"><is><t xml:space="preserve">{_xml_text(text)}</t></is></c>'
|
||||
|
||||
|
||||
# ==================== 公式:模板行 + 共享公式 ====================
|
||||
def _parse_shared_defs(chunk):
|
||||
"""共享公式主定义 {si: (定义行, 公式原文)}。
|
||||
|
||||
Excel 把连续行的同款公式存成一组共享公式:只有主定义带公式文本,
|
||||
其余单元格是自闭合的 <f t="shared" si="N"/>。要下拉必须先按 si 找到定义。
|
||||
"""
|
||||
out = {}
|
||||
for m in _CELL_RE.finditer(chunk):
|
||||
row, inner = int(m.group(2)), m.group(4)
|
||||
fm = _F_RE.search(inner)
|
||||
if not fm or b't="shared"' not in fm.group(1):
|
||||
continue
|
||||
text = (fm.group(2) or b'').decode('utf-8', 'replace')
|
||||
if not text.strip():
|
||||
continue
|
||||
sm = re.search(rb'si="(\d+)"', fm.group(1))
|
||||
if sm:
|
||||
out[sm.group(1).decode()] = (row, text)
|
||||
return out
|
||||
|
||||
|
||||
def _parse_template_row(xml_bytes, row_no):
|
||||
"""模板行 {列字母: {'s': 样式, 'f': 内联公式, 'si': 共享公式组号}}。"""
|
||||
text = xml_bytes.decode('utf-8', 'replace')
|
||||
out = {}
|
||||
for m in re.finditer(r'<c r="([A-Z]+)' + str(row_no) + r'"([^>]*?)(/>|>(.*?)</c>)', text, re.S):
|
||||
col, attrs, inner = m.group(1), m.group(2), m.group(4) or ''
|
||||
sm = re.search(r'\bs="(\d+)"', attrs)
|
||||
fm = re.search(r'<f([^>]*?)(?:/>|>(.*?)</f>)', inner, re.S)
|
||||
f_text = si = None
|
||||
if fm:
|
||||
f_text = (fm.group(2) or None)
|
||||
if 't="shared"' in fm.group(1):
|
||||
sim = re.search(r'si="(\d+)"', fm.group(1))
|
||||
si = sim.group(1) if sim else None
|
||||
out[col] = {'s': sm.group(1) if sm else None, 'f': f_text, 'si': si}
|
||||
return out
|
||||
|
||||
|
||||
def _shift_formula(formula, from_row, to_row):
|
||||
"""把公式里的相对行号从 from_row 平移到 to_row($ 锁定的行号不动)。"""
|
||||
if not formula or from_row == to_row:
|
||||
return formula
|
||||
delta = to_row - from_row
|
||||
|
||||
def repl(m):
|
||||
col, lock, row = m.group(1), m.group(2), m.group(3)
|
||||
if lock == '$':
|
||||
return m.group(0)
|
||||
return f'{col}{int(row) + delta}'
|
||||
|
||||
return re.sub(r'(?<![A-Za-z0-9_])([A-Z]{1,3})(\$?)(\d+)', repl, formula)
|
||||
|
||||
|
||||
def _rows_xml(rows, start_row, col_map, tpl=None, tpl_row=None, shared=None):
|
||||
"""构造新行 XML:A~AE 填值,AF~AP 逐行下拉公式(内联公式 + 共享公式)。"""
|
||||
tpl = tpl or {}
|
||||
shared = shared or {}
|
||||
parts = []
|
||||
for i, row in enumerate(rows):
|
||||
r = start_row + i
|
||||
cells = []
|
||||
for didx, lcol in col_map:
|
||||
if didx < len(row):
|
||||
letter = _col_letter(lcol)
|
||||
c = _cell_xml(letter, r, row[didx], (tpl.get(letter) or {}).get('s'))
|
||||
if c:
|
||||
cells.append((lcol, c))
|
||||
for letter, info in tpl.items():
|
||||
cnum = _col_num(letter)
|
||||
if cnum <= 31:
|
||||
continue
|
||||
formula = None
|
||||
if info.get('f'):
|
||||
formula = _shift_formula(info['f'], tpl_row or start_row, r)
|
||||
elif info.get('si') and info['si'] in shared:
|
||||
def_row, text = shared[info['si']]
|
||||
formula = _shift_formula(text, def_row, r)
|
||||
if not formula:
|
||||
continue
|
||||
s_attr = f' s="{info["s"]}"' if info.get('s') else ''
|
||||
cells.append((cnum, f'<c r="{letter}{r}"{s_attr}><f>{formula}</f></c>'))
|
||||
if not cells:
|
||||
continue
|
||||
cells.sort(key=lambda x: x[0])
|
||||
parts.append(f'<row r="{r}">{"".join(c for _, c in cells)}</row>')
|
||||
return ''.join(parts).encode('utf-8')
|
||||
|
||||
|
||||
# ==================== 原生 XML 写入 ====================
|
||||
def _sheet_xml_path(zf, sheet_name):
|
||||
import xml.etree.ElementTree as ET
|
||||
root = ET.fromstring(zf.read('xl/workbook.xml'))
|
||||
rid = None
|
||||
for s in root.iter(f'{_NS_MAIN}sheet'):
|
||||
if s.get('name') == sheet_name:
|
||||
rid = s.get(f'{_NS_REL}id')
|
||||
break
|
||||
if not rid:
|
||||
return None
|
||||
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
|
||||
for rel in rels.iter(f'{_NS_PKGREL}Relationship'):
|
||||
if rel.get('Id') == rid:
|
||||
t = (rel.get('Target') or '').lstrip('/')
|
||||
return t if t.startswith('xl/') else 'xl/' + t
|
||||
return None
|
||||
|
||||
|
||||
def _append_rows_native(path, sheet_name, rows, start_row, col_map, new_max_row,
|
||||
skip_from_row=None, tpl_row=None):
|
||||
"""流式重写目标 sheet:先丢弃尾部空公式行,再在 </sheetData> 前插入带公式的新行。"""
|
||||
tmp = path + '.rebuild.tmp'
|
||||
marker = b'</sheetData>'
|
||||
skip_tag = f'<row r="{skip_from_row}"'.encode() if skip_from_row else None
|
||||
tpl_tag = f'<row r="{tpl_row}"'.encode() if tpl_row else None
|
||||
tpl = None
|
||||
shared_defs = {}
|
||||
cache = {'payload': None}
|
||||
|
||||
def _payload():
|
||||
if cache['payload'] is None:
|
||||
cache['payload'] = _rows_xml(rows, start_row, col_map,
|
||||
tpl=tpl, tpl_row=tpl_row, shared=shared_defs)
|
||||
return cache['payload']
|
||||
|
||||
inserted = False
|
||||
dim_done = False
|
||||
|
||||
with zipfile.ZipFile(path, 'r') as src:
|
||||
sheet_path = _sheet_xml_path(src, sheet_name)
|
||||
if not sheet_path:
|
||||
raise RuntimeError(f'workbook 里找不到 sheet「{sheet_name}」')
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in src.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
with src.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
if info.filename != sheet_path:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
continue
|
||||
|
||||
mode = 'skip' if skip_tag else 'plain'
|
||||
buf = b''
|
||||
while True:
|
||||
chunk = fin.read(4 << 20)
|
||||
if not chunk:
|
||||
if buf:
|
||||
fout.write(buf)
|
||||
break
|
||||
buf += chunk
|
||||
if not dim_done:
|
||||
buf = re.sub(
|
||||
rb'(<dimension ref="[A-Z]+\d+:[A-Z]+)\d+(")',
|
||||
lambda m: m.group(1) + str(new_max_row).encode() + m.group(2),
|
||||
buf, count=1)
|
||||
dim_done = True
|
||||
|
||||
# 模板行在尾部空行之前,只出现一次;就近拿共享公式主定义
|
||||
if tpl is None and tpl_tag:
|
||||
i = buf.find(tpl_tag)
|
||||
if i >= 0:
|
||||
j = buf.find(b'</row>', i)
|
||||
if j >= 0:
|
||||
shared_defs.update(_parse_shared_defs(buf[:i]))
|
||||
tpl = _parse_template_row(buf[i:j + 6], tpl_row)
|
||||
fcols = [c for c, v in tpl.items()
|
||||
if v.get('f') or v.get('si')]
|
||||
config.log(f'模板行 {tpl_row}:{len(tpl)} 个单元格,'
|
||||
f'计算列 {fcols or "无"},'
|
||||
f'计算规则 {len(shared_defs)} 组', 'DEBUG')
|
||||
|
||||
if mode == 'plain':
|
||||
idx = buf.find(marker)
|
||||
if idx == -1:
|
||||
keep = 64
|
||||
fout.write(buf[:-keep])
|
||||
buf = buf[-keep:]
|
||||
continue
|
||||
fout.write(buf[:idx])
|
||||
fout.write(_payload())
|
||||
fout.write(buf[idx:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
|
||||
if mode == 'skip':
|
||||
i_skip = buf.find(skip_tag)
|
||||
i_mark = buf.find(marker)
|
||||
if i_mark >= 0 and (i_skip < 0 or i_mark < i_skip):
|
||||
fout.write(buf[:i_mark])
|
||||
fout.write(_payload())
|
||||
fout.write(buf[i_mark:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
if i_skip < 0:
|
||||
keep = max(len(skip_tag), len(marker), 512 * 1024)
|
||||
fout.write(buf[:-keep])
|
||||
buf = buf[-keep:]
|
||||
continue
|
||||
fout.write(buf[:i_skip])
|
||||
buf = buf[i_skip:]
|
||||
mode = 'drop'
|
||||
|
||||
idx = buf.find(marker)
|
||||
if idx < 0:
|
||||
buf = buf[-len(marker):]
|
||||
continue
|
||||
fout.write(_payload())
|
||||
fout.write(buf[idx:])
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
inserted = True
|
||||
break
|
||||
if not inserted:
|
||||
try:
|
||||
os.remove(tmp)
|
||||
except Exception:
|
||||
pass
|
||||
raise RuntimeError('sheet xml 里没找到 </sheetData>,未做任何修改')
|
||||
os.replace(tmp, path)
|
||||
return len(_payload())
|
||||
|
||||
|
||||
def run(dry_run=False):
|
||||
"""执行合并。返回 {ok, appended, start_row, end_row, ledger, message}。"""
|
||||
if not os.path.isdir(config.WORK_DIR):
|
||||
return {'ok': False, 'message': f'目录不存在:{config.WORK_DIR}'}
|
||||
|
||||
ledger = _pick_latest(config.LEDGER_GLOB, by_month=True)
|
||||
if not ledger:
|
||||
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
|
||||
config.log(f'台账:{os.path.basename(ledger)}({_month_key(ledger)})')
|
||||
|
||||
detail = _pick_latest(config.DETAIL_GLOB, by_month=False)
|
||||
if not detail:
|
||||
return {'ok': False, 'message': f'未找到收益明细:{config.DETAIL_GLOB}'}
|
||||
config.log(f'明细:{os.path.basename(detail)}')
|
||||
|
||||
t0 = time.time()
|
||||
wb = load_workbook(ledger, read_only=True, data_only=True)
|
||||
if config.LEDGER_SHEET not in wb.sheetnames:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账缺少 sheet「{config.LEDGER_SHEET}」'}
|
||||
ws = wb[config.LEDGER_SHEET]
|
||||
total_row = ws.max_row
|
||||
it = ws.iter_rows(values_only=True)
|
||||
next(it)
|
||||
lhead = _header_index(next(it))
|
||||
if config.TIME_COL not in lhead:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账表头缺少「{config.TIME_COL}」'}
|
||||
li = lhead[config.TIME_COL]
|
||||
|
||||
ledger_max = None
|
||||
ledger_rows = 0
|
||||
key_cols = [lhead[c] for c in ('账户名称', '订单号', '券号', config.TIME_COL) if c in lhead]
|
||||
last_data_row = config.HEADER_ROW
|
||||
for i, row in enumerate(it, start=config.DATA_START_ROW):
|
||||
if row is None:
|
||||
continue
|
||||
if key_cols and any(c < len(row) and row[c] not in (None, '') for c in key_cols):
|
||||
last_data_row = i
|
||||
if len(row) <= li:
|
||||
continue
|
||||
dt = _to_dt(row[li])
|
||||
if dt is None:
|
||||
continue
|
||||
ledger_rows += 1
|
||||
if ledger_max is None or dt > ledger_max:
|
||||
ledger_max = dt
|
||||
wb.close()
|
||||
if ledger_max is None:
|
||||
return {'ok': False, 'message': '台账该列没有有效时间'}
|
||||
config.log(f'台账有效行 {ledger_rows},最大时间 {ledger_max},真实末行 {last_data_row}'
|
||||
f'(max_row={total_row},尾部 {total_row - last_data_row} 行是公式撑出的空行)')
|
||||
|
||||
wb2 = load_workbook(detail, read_only=True, data_only=True)
|
||||
ws2 = wb2.worksheets[0]
|
||||
it2 = ws2.iter_rows(values_only=True)
|
||||
next(it2)
|
||||
dhead = _header_index(next(it2))
|
||||
if config.TIME_COL not in dhead:
|
||||
wb2.close()
|
||||
return {'ok': False, 'message': f'明细表头缺少「{config.TIME_COL}」'}
|
||||
di = dhead[config.TIME_COL]
|
||||
|
||||
keep, total, skip_old = [], 0, 0
|
||||
for row in it2:
|
||||
if row is None:
|
||||
continue
|
||||
total += 1
|
||||
dt = _to_dt(row[di]) if len(row) > di else None
|
||||
if dt is None or dt < ledger_max:
|
||||
skip_old += 1
|
||||
continue
|
||||
keep.append(row)
|
||||
wb2.close()
|
||||
config.log(f'明细 {total} 行:保留 {len(keep)},剔除 {skip_old}(耗时 {time.time() - t0:.1f}s)')
|
||||
|
||||
if not keep:
|
||||
return {'ok': True, 'appended': 0, 'message': '明细里没有比台账更新的记录'}
|
||||
|
||||
start_row = last_data_row + 1
|
||||
new_max_row = start_row + len(keep) - 1
|
||||
col_map = [(didx, lhead[name] + 1) for name, didx in dhead.items() if name in lhead]
|
||||
config.log(f'并入范围:台账第 {start_row} ~ {new_max_row} 行')
|
||||
|
||||
if dry_run:
|
||||
return {'ok': True, 'appended': 0, 'start_row': start_row, 'end_row': new_max_row,
|
||||
'ledger': ledger, 'message': f'[演练] 将追加 {len(keep)} 行'}
|
||||
|
||||
bak = os.path.join(
|
||||
config.WORK_DIR,
|
||||
f'{os.path.splitext(os.path.basename(ledger))[0]}_备份{time.strftime("%Y%m%d_%H%M%S")}.xlsx')
|
||||
shutil.copy2(ledger, bak)
|
||||
config.log(f'已备份 → {os.path.basename(bak)}')
|
||||
|
||||
t1 = time.time()
|
||||
size = _append_rows_native(ledger, config.LEDGER_SHEET, keep, start_row, col_map,
|
||||
new_max_row, skip_from_row=start_row, tpl_row=last_data_row)
|
||||
config.log(f'并入完成:{len(keep)} 行,耗时 {time.time() - t1:.1f}s(数据量 {size / 1024:.0f} KB)')
|
||||
return {'ok': True, 'appended': len(keep), 'start_row': start_row, 'end_row': new_max_row,
|
||||
'ledger': ledger, 'message': f'已并入 {len(keep)} 行到台账'}
|
||||
@@ -0,0 +1,282 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""「新美大核对统计」按日期补 V/W 列外部链接公式。
|
||||
|
||||
业务口径(从台账既有 62 条链接反推):
|
||||
V = =[N]资金组取数!$B$5 (应收岗-团购统计表-昨日遗留)
|
||||
W = =[N]资金组取数!$B$6 (应收岗-团购统计表-本日遗留)
|
||||
外部文件:file:///\\\\caiwu01\\共享文件夹\\1111\\TG\\{YYYY}年{M}月\\{M}.{D}\\马敏团购总表{M}.{D}.xlsx
|
||||
|
||||
实现:能复用的链接按 target 匹配复用,缺的新增 externalLinkNN.xml + rels +
|
||||
workbook.xml 的 externalReferences + workbook.xml.rels + Content_Types 声明;
|
||||
目标 sheet 只改对应行的 V/W 单元格,其余部件原样拷贝。
|
||||
"""
|
||||
import os
|
||||
import re
|
||||
import shutil
|
||||
import time
|
||||
import zipfile
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from openpyxl import load_workbook
|
||||
|
||||
from .. import config
|
||||
|
||||
_EXTLINK_TPL = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
'<externalLink xmlns="http://schemas.openxmlformats.org/spreadsheetml/2006/main"'
|
||||
' xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">'
|
||||
'<externalBook r:id="rId1"><sheetNames><sheetName val="%s"/></sheetNames>'
|
||||
'<sheetDataSet><sheetData sheetId="0"/></sheetDataSet></externalBook></externalLink>'
|
||||
)
|
||||
_EXTLINK_RELS_TPL = (
|
||||
'<?xml version="1.0" encoding="UTF-8" standalone="yes"?>\r\n'
|
||||
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006/relationships">'
|
||||
'<Relationship Id="rId1" Type="http://schemas.openxmlformats.org/officeDocument/2006/'
|
||||
'relationships/externalLinkPath" Target="%s" TargetMode="External"/></Relationships>'
|
||||
)
|
||||
_CELL_RE = re.compile(r'<c r="([A-Z]+)(\d+)"([^>]*?)(?:/>|>(.*?)</c>)', re.S)
|
||||
|
||||
|
||||
def _pick_latest(pattern):
|
||||
import glob
|
||||
files = [p for p in glob.glob(os.path.join(config.WORK_DIR, pattern))
|
||||
if '备份' not in os.path.basename(p)]
|
||||
if not files:
|
||||
return None
|
||||
files.sort(key=os.path.getmtime)
|
||||
return files[-1]
|
||||
|
||||
|
||||
def _target_path(d):
|
||||
return os.path.join(config.SHARE_ROOT, f'{d.year}年{d.month}月', f'{d.month}.{d.day}',
|
||||
f'{config.LINK_BOOK}{d.month}.{d.day}.xlsx')
|
||||
|
||||
|
||||
def _file_uri(path):
|
||||
"""与既有 rels 一致:file:///\\\\caiwu01\\共享文件夹\\...(XML 属性里反斜杠不转义)。"""
|
||||
return 'file:///' + path
|
||||
|
||||
|
||||
def _sheet_xml_path(zf, sheet_name):
|
||||
import xml.etree.ElementTree as ET
|
||||
main = '{http://schemas.openxmlformats.org/spreadsheetml/2006/main}'
|
||||
rel = '{http://schemas.openxmlformats.org/officeDocument/2006/relationships}'
|
||||
pkg = '{http://schemas.openxmlformats.org/package/2006/relationships}'
|
||||
root = ET.fromstring(zf.read('xl/workbook.xml'))
|
||||
rid = None
|
||||
for s in root.iter(f'{main}sheet'):
|
||||
if s.get('name') == sheet_name:
|
||||
rid = s.get(f'{rel}id')
|
||||
break
|
||||
if not rid:
|
||||
return None
|
||||
rels = ET.fromstring(zf.read('xl/_rels/workbook.xml.rels'))
|
||||
for r in rels.iter(f'{pkg}Relationship'):
|
||||
if r.get('Id') == rid:
|
||||
t = (r.get('Target') or '').lstrip('/')
|
||||
return t if t.startswith('xl/') else 'xl/' + t
|
||||
return None
|
||||
|
||||
|
||||
def _col_num(letters):
|
||||
n = 0
|
||||
for ch in letters:
|
||||
n = n * 26 + (ord(ch) - 64)
|
||||
return n
|
||||
|
||||
|
||||
def _set_row_cells(row_xml, row_no, cells):
|
||||
keep = []
|
||||
style_default = None
|
||||
for m in _CELL_RE.finditer(row_xml):
|
||||
col = m.group(1)
|
||||
sm = re.search(r'\bs="(\d+)"', m.group(3))
|
||||
if style_default is None and sm:
|
||||
style_default = sm.group(1)
|
||||
if col in cells:
|
||||
continue
|
||||
keep.append((_col_num(col), m.group(0)))
|
||||
for col, (formula, style) in cells.items():
|
||||
s = style or style_default
|
||||
s_attr = f' s="{s}"' if s else ''
|
||||
keep.append((_col_num(col), f'<c r="{col}{row_no}"{s_attr}><f>{formula}</f></c>'))
|
||||
keep.sort(key=lambda x: x[0])
|
||||
attrs = re.match(r'<row([^>]*)>', row_xml)
|
||||
head = f'<row{attrs.group(1)}>' if attrs else f'<row r="{row_no}">'
|
||||
return f'{head}{"".join(c for _, c in keep)}</row>'
|
||||
|
||||
|
||||
def _norm_uri(uri):
|
||||
"""外部链接目标归一化:`file:///\\\\caiwu01\\共享...` → `\\\\caiwu01\\共享...`(小写)。
|
||||
|
||||
比对方是本地路径,不带 file:/// 前缀;不归一会永远匹配不上,
|
||||
导致每次运行都新增一条重复的外部链接。
|
||||
"""
|
||||
u = (uri or '').strip()
|
||||
if u.lower().startswith('file:///'):
|
||||
u = u[len('file:///'):]
|
||||
return u.replace('\\\\', '\\').lower()
|
||||
|
||||
|
||||
def _parse_links(zf):
|
||||
mapping, max_n = {}, 0
|
||||
for name in zf.namelist():
|
||||
m = re.match(r'xl/externalLinks/_rels/externalLink(\d+)\.xml\.rels$', name)
|
||||
if not m:
|
||||
continue
|
||||
n = int(m.group(1))
|
||||
max_n = max(max_n, n)
|
||||
txt = zf.read(name).decode('utf-8', 'replace')
|
||||
tm = re.search(r'Target="([^"]+)"', txt)
|
||||
if tm:
|
||||
mapping.setdefault(_norm_uri(tm.group(1)), n) # 同路径多条时保留最早那条
|
||||
return mapping, max_n
|
||||
|
||||
|
||||
def run(d_from=None, d_to=None, dry_run=False):
|
||||
"""按日期区间补 V/W。d_from/d_to 为空则取最新「团购收益明细_YYYYMMDD_YYYYMMDD.xlsx」的日期。"""
|
||||
ledger = _pick_latest(config.LEDGER_GLOB)
|
||||
if not ledger:
|
||||
return {'ok': False, 'message': f'未找到台账:{config.LEDGER_GLOB}'}
|
||||
config.log(f'台账:{os.path.basename(ledger)}')
|
||||
|
||||
if not d_from:
|
||||
detail = _pick_latest(config.DETAIL_GLOB)
|
||||
if detail:
|
||||
m = re.search(r'(\d{8})_(\d{8})', os.path.basename(detail)) or \
|
||||
re.search(r'(\d{8})', os.path.basename(detail))
|
||||
if m:
|
||||
d_from = m.group(1)
|
||||
d_to = m.group(2) if m.lastindex and m.lastindex >= 2 else m.group(1)
|
||||
if not d_from:
|
||||
today = date.today()
|
||||
d_from = (today - timedelta(days=1)).isoformat()
|
||||
d_to = today.isoformat()
|
||||
|
||||
d1 = datetime.strptime(d_from.replace('-', '')[:8], '%Y%m%d').date()
|
||||
d2 = datetime.strptime(str(d_to).replace('-', '')[:8], '%Y%m%d').date()
|
||||
config.log(f'日期区间:{d1} ~ {d2}')
|
||||
|
||||
wb = load_workbook(ledger, read_only=True, data_only=False)
|
||||
if config.STAT_SHEET not in wb.sheetnames:
|
||||
wb.close()
|
||||
return {'ok': False, 'message': f'台账缺少 sheet「{config.STAT_SHEET}」'}
|
||||
ws = wb[config.STAT_SHEET]
|
||||
date_rows = {}
|
||||
for i, row in enumerate(ws.iter_rows(min_col=1, max_col=1, values_only=True), start=1):
|
||||
v = row[0]
|
||||
if isinstance(v, datetime):
|
||||
date_rows[v.date()] = i
|
||||
elif isinstance(v, date):
|
||||
date_rows[v] = i
|
||||
wb.close()
|
||||
|
||||
days, day = [], d1
|
||||
while day <= d2:
|
||||
days.append(day)
|
||||
day += timedelta(days=1)
|
||||
skipped = [d for d in days if d not in date_rows]
|
||||
if skipped:
|
||||
config.log(f'核对统计表里没有这些日期行,跳过:{[str(d) for d in skipped]}', 'WARN')
|
||||
days = [d for d in days if d in date_rows]
|
||||
if not days:
|
||||
return {'ok': False, 'message': '没有可处理的日期行'}
|
||||
|
||||
zf = zipfile.ZipFile(ledger)
|
||||
link_map, max_link = _parse_links(zf)
|
||||
config.log(f'既有外部链接 {len(link_map)} 条,最大序号 {max_link}')
|
||||
|
||||
plan, need_new = [], []
|
||||
for d in days:
|
||||
path = _target_path(d)
|
||||
if _norm_uri(path) in link_map:
|
||||
plan.append((d, date_rows[d], link_map[_norm_uri(path)], path, '复用'))
|
||||
else:
|
||||
idx = max_link + len(need_new) + 1
|
||||
need_new.append((idx, path, _file_uri(path)))
|
||||
plan.append((d, date_rows[d], idx, path, '新增'))
|
||||
|
||||
for d, row_no, idx, path, mode in plan:
|
||||
config.log(f' {d} → 第{row_no}行 [{idx}]({mode}){path}')
|
||||
|
||||
if dry_run:
|
||||
zf.close()
|
||||
return {'ok': True, 'rows': [p[1] for p in plan],
|
||||
'message': f'[演练] {len(plan)} 行将更新 V/W,需新增 {len(need_new)} 条外部链接'}
|
||||
|
||||
if not os.path.isdir(config.SHARE_ROOT):
|
||||
config.log(f'共享盘当前不可达({config.SHARE_ROOT}),公式照写,'
|
||||
f'恢复后打开 Excel 点「更新链接」即可取值', 'WARN')
|
||||
|
||||
sheet_path = _sheet_xml_path(zf, config.STAT_SHEET)
|
||||
if not sheet_path:
|
||||
zf.close()
|
||||
return {'ok': False, 'message': f'找不到「{config.STAT_SHEET}」的 xml'}
|
||||
sheet_xml = zf.read(sheet_path).decode('utf-8')
|
||||
wb_xml = zf.read('xl/workbook.xml').decode('utf-8')
|
||||
wb_rels = zf.read('xl/_rels/workbook.xml.rels').decode('utf-8')
|
||||
ct_xml = zf.read('[Content_Types].xml').decode('utf-8')
|
||||
|
||||
for d, row_no, idx, path, mode in plan:
|
||||
m = re.search(r'<row r="' + str(row_no) + r'"[^>]*>.*?</row>', sheet_xml, re.S)
|
||||
if not m:
|
||||
config.log(f'第 {row_no} 行 XML 未找到,跳过', 'WARN')
|
||||
continue
|
||||
# 注意:XML 的 <f> 里放公式正文,不带 Excel 界面上的前导 '='
|
||||
new_row = _set_row_cells(m.group(0), row_no, {
|
||||
'V': (f'[{idx}]{config.LINK_SHEET}!$B$5', None),
|
||||
'W': (f'[{idx}]{config.LINK_SHEET}!$B$6', None),
|
||||
})
|
||||
sheet_xml = sheet_xml[:m.start()] + new_row + sheet_xml[m.end():]
|
||||
config.log(f'{d} 行已补上团购统计表取数链接')
|
||||
|
||||
for idx, path, uri in need_new:
|
||||
rid_num = max(int(x) for x in re.findall(r'Id="rId(\d+)"', wb_rels)) + 1
|
||||
rid = f'rId{rid_num}'
|
||||
wb_rels = wb_rels.replace(
|
||||
'</Relationships>',
|
||||
f'<Relationship Id="{rid}" Type="http://schemas.openxmlformats.org/'
|
||||
f'officeDocument/2006/relationships/externalLink" '
|
||||
f'Target="externalLinks/externalLink{idx}.xml"/></Relationships>')
|
||||
wb_xml = wb_xml.replace('</externalReferences>',
|
||||
f'<externalReference r:id="{rid}"/></externalReferences>')
|
||||
ct_xml = ct_xml.replace(
|
||||
'</Types>',
|
||||
f'<Override PartName="/xl/externalLinks/externalLink{idx}.xml" '
|
||||
f'ContentType="application/vnd.openxmlformats-officedocument.'
|
||||
f'spreadsheetml.externalLink+xml"/></Types>')
|
||||
|
||||
tmp = ledger + '.rebuild.tmp'
|
||||
replace = {
|
||||
sheet_path: sheet_xml.encode('utf-8'),
|
||||
'xl/workbook.xml': wb_xml.encode('utf-8'),
|
||||
'xl/_rels/workbook.xml.rels': wb_rels.encode('utf-8'),
|
||||
'[Content_Types].xml': ct_xml.encode('utf-8'),
|
||||
}
|
||||
new_files = {}
|
||||
for idx, path, uri in need_new:
|
||||
new_files[f'xl/externalLinks/externalLink{idx}.xml'] = \
|
||||
(_EXTLINK_TPL % config.LINK_SHEET).encode('utf-8')
|
||||
new_files[f'xl/externalLinks/_rels/externalLink{idx}.xml.rels'] = \
|
||||
(_EXTLINK_RELS_TPL % uri).encode('utf-8')
|
||||
|
||||
with zipfile.ZipFile(tmp, 'w', zipfile.ZIP_DEFLATED, allowZip64=True) as dst:
|
||||
for info in zf.infolist():
|
||||
if info.is_dir():
|
||||
continue
|
||||
zi = zipfile.ZipInfo(info.filename, date_time=info.date_time)
|
||||
zi.compress_type = zipfile.ZIP_DEFLATED
|
||||
zi.external_attr = info.external_attr
|
||||
if info.filename in replace:
|
||||
dst.writestr(zi, replace.pop(info.filename))
|
||||
else:
|
||||
with zf.open(info) as fin, dst.open(zi, 'w', force_zip64=True) as fout:
|
||||
shutil.copyfileobj(fin, fout, 4 << 20)
|
||||
for name, data in list(replace.items()) + list(new_files.items()):
|
||||
dst.writestr(name, data)
|
||||
zf.close()
|
||||
os.replace(tmp, ledger)
|
||||
|
||||
config.log(f'完成:{len(plan)} 行更新 V/W,新增外部链接 {len(need_new)} 条')
|
||||
return {'ok': True, 'rows': [p[1] for p in plan], 'new_links': len(need_new),
|
||||
'message': f'核对统计 V/W 已更新 {len(plan)} 行'}
|
||||
@@ -0,0 +1,108 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0041",
|
||||
"name": "新美大平台核对",
|
||||
"version": "1.1.2",
|
||||
"description": "美团经营宝账单自动下载与台账核对:按需下载打款记录、团购收益明细、预订收益明细,把新产生的收益按验券时间并入月份台账,并给核对统计表补当天的团购统计表链接。登录一次后可长期复用。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"runTimeoutSeconds": 0,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0041"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"action": {
|
||||
"type": "string",
|
||||
"title": "执行过程",
|
||||
"default": "all",
|
||||
"enum": ["all", "download", "reconcile"],
|
||||
"description": "all=下载后核对;download=只下载;reconcile=只核对(不下载)"
|
||||
},
|
||||
"do_download": {
|
||||
"type": "boolean",
|
||||
"title": "下载数据",
|
||||
"default": true,
|
||||
"description": "登录经营宝,把账单下载到本机目录"
|
||||
},
|
||||
"do_reconcile": {
|
||||
"type": "boolean",
|
||||
"title": "更新核对",
|
||||
"default": true,
|
||||
"description": "读本机最新的台账与收益明细,并入台账并更新核对统计,不重新下载"
|
||||
},
|
||||
"pay_enabled": {
|
||||
"type": "boolean",
|
||||
"title": "下载打款记录",
|
||||
"default": true,
|
||||
"description": "平台打款到门店的明细(打款金额、到账银行卡、打款状态、账单周期)"
|
||||
},
|
||||
"pay_date_from": {
|
||||
"type": "string",
|
||||
"title": "打款记录-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"pay_date_to": {
|
||||
"type": "string",
|
||||
"title": "打款记录-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"profit_group": {
|
||||
"type": "boolean",
|
||||
"title": "下载团购收益明细",
|
||||
"default": true,
|
||||
"description": "团购业务的收益明细(券号/订单号、结算价、总收入、技术服务费、渠道佣金)"
|
||||
},
|
||||
"profit_booking": {
|
||||
"type": "boolean",
|
||||
"title": "下载预订收益明细",
|
||||
"default": true,
|
||||
"description": "预订业务的收益明细(无预订业务时为空表)"
|
||||
},
|
||||
"profit_date_from": {
|
||||
"type": "string",
|
||||
"title": "收益明细-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"profit_date_to": {
|
||||
"type": "string",
|
||||
"title": "收益明细-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"run_merge": {
|
||||
"type": "boolean",
|
||||
"title": "并入台账",
|
||||
"default": true,
|
||||
"description": "把收益明细里晚于台账最新一笔的记录追加到台账(需勾选团购收益明细)"
|
||||
},
|
||||
"run_links": {
|
||||
"type": "boolean",
|
||||
"title": "更新核对统计",
|
||||
"default": true,
|
||||
"description": "给核对统计表对应日期的行补上当天团购统计表的取数链接"
|
||||
},
|
||||
"dry_run": {
|
||||
"type": "boolean",
|
||||
"title": "只核对不写入",
|
||||
"default": false,
|
||||
"description": "只输出将要并入的行数与将更新的日期,不改动台账"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "输出完整调试日志(默认关闭)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
+3
-3
@@ -1,3 +1,3 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
openpyxl>=3.1
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
openpyxl>=3.1
|
||||
@@ -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>新美大平台核对</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": "xq0041-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,246 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 内联提示 -->
|
||||
<div v-if="notice" class="notice" :class="'is-' + notice.type">
|
||||
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '!') }}</span>
|
||||
<span>{{ notice.text }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 执行配置(头部含方案工具:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<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">
|
||||
<rect x="5" y="4" width="14" height="17" rx="2" />
|
||||
<path d="M9 4V3h6v1" />
|
||||
<path d="m9 13 2 2 4-4" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
|
||||
<i />{{ lastSavedAt ? '已保存 ' + lastSavedAt : '尚未保存' }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
placeholder="当前配置(自动保存)" @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">
|
||||
<!-- 01 下载内容 -->
|
||||
<section v-show="form.do_download" class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">01</span>
|
||||
<span class="sec-name">下载内容</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="打款记录">
|
||||
<el-switch v-model="form.pay_enabled" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="团购收益明细">
|
||||
<el-switch v-model="form.profit_group" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="预订收益明细">
|
||||
<el-switch v-model="form.profit_booking" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid grid-date">
|
||||
<el-form-item label="打款记录 日期">
|
||||
<el-date-picker v-model="payRange" type="daterange" value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
|
||||
:disabled="running || !form.pay_enabled" />
|
||||
</el-form-item>
|
||||
<el-form-item label="收益明细 日期">
|
||||
<el-date-picker v-model="profitRange" type="daterange" value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
|
||||
:disabled="running || !profitOn" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
打款记录:平台打款到门店的明细;收益明细:每笔券号/订单号、结算价、总收入、技术服务费、营销费用、渠道佣金。<br>
|
||||
默认昨天到今天;今天的账单次日才齐,需完整数据请选到昨天。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 02 执行过程 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">执行过程</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="下载数据">
|
||||
<el-switch v-model="form.do_download" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="更新核对">
|
||||
<el-switch v-model="form.do_reconcile" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
下载数据:登录经营宝,把账单下载到本机目录。<br>
|
||||
更新核对:读本机最新的台账与收益明细,把新记录并入台账并更新核对统计,不重新下载。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="start">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button :disabled="running" @click="restoreLastFields">恢复上次参数</el-button>
|
||||
<el-button :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<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>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
// 默认日期区间:昨天 ~ 今天
|
||||
function defaultRange() {
|
||||
const today = new Date()
|
||||
const y = new Date(today.getTime() - 86400000)
|
||||
const fmt = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
||||
return [fmt(y), fmt(today)]
|
||||
}
|
||||
|
||||
const DEFAULTS = () => ({
|
||||
do_download: true,
|
||||
do_reconcile: true,
|
||||
pay_enabled: true,
|
||||
pay_date_from: '',
|
||||
pay_date_to: '',
|
||||
profit_group: true,
|
||||
profit_booking: true,
|
||||
profit_date_from: '',
|
||||
profit_date_to: '',
|
||||
})
|
||||
|
||||
const {
|
||||
form, loaded, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.do_download && !form.do_reconcile) {
|
||||
ElMessage.warning('请至少勾选一个执行过程(下载数据 / 更新核对)')
|
||||
return false
|
||||
}
|
||||
if (form.do_download && !form.pay_enabled && !form.profit_group && !form.profit_booking) {
|
||||
ElMessage.warning('请至少勾选一项要下载的内容(打款记录 / 团购 / 预订)')
|
||||
return false
|
||||
}
|
||||
const pairs = [
|
||||
['打款记录', form.pay_date_from, form.pay_date_to],
|
||||
['收益明细', form.profit_date_from, form.profit_date_to],
|
||||
]
|
||||
for (const [label, f, t] of pairs) {
|
||||
const a = (f || '').trim()
|
||||
const b = (t || '').trim()
|
||||
if (a && b && a > b) {
|
||||
ElMessage.warning(`${label}的开始日期不能晚于结束日期`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
},
|
||||
buildPayload(f) {
|
||||
const t = (v) => (v || '').trim()
|
||||
const action = f.do_download && f.do_reconcile ? 'all' : (f.do_download ? 'download' : 'reconcile')
|
||||
return {
|
||||
action,
|
||||
pay_enabled: !!f.pay_enabled,
|
||||
pay_date_from: t(f.pay_date_from),
|
||||
pay_date_to: t(f.pay_date_to),
|
||||
profit_group: !!f.profit_group,
|
||||
profit_booking: !!f.profit_booking,
|
||||
profit_date_from: t(f.profit_date_from),
|
||||
profit_date_to: t(f.profit_date_to),
|
||||
// 核对就是完整流程:并入台账 + 更新核对统计,不做演练
|
||||
run_merge: true,
|
||||
run_links: true,
|
||||
dry_run: false,
|
||||
debug_mode: false,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
function start() {
|
||||
run()
|
||||
}
|
||||
|
||||
const profitOn = computed(() => form.profit_group || form.profit_booking)
|
||||
|
||||
// 日期范围选择器 ↔ 两个字段(plugin.json 仍以 *_date_from/to 为契约,定时任务兼容)
|
||||
function makeRange(getFrom, getTo, setFrom, setTo) {
|
||||
return computed({
|
||||
get: () => {
|
||||
const a = getFrom()
|
||||
const b = getTo()
|
||||
return (a || b) ? [a || null, b || null] : null
|
||||
},
|
||||
set: (v) => {
|
||||
setFrom((v && v[0]) || '')
|
||||
setTo((v && v[1]) || '')
|
||||
},
|
||||
})
|
||||
}
|
||||
|
||||
const payRange = makeRange(
|
||||
() => form.pay_date_from, () => form.pay_date_to,
|
||||
(v) => { form.pay_date_from = v }, (v) => { form.pay_date_to = v },
|
||||
)
|
||||
const profitRange = makeRange(
|
||||
() => form.profit_date_from, () => form.profit_date_to,
|
||||
(v) => { form.profit_date_from = v }, (v) => { form.profit_date_to = v },
|
||||
)
|
||||
|
||||
// 配置加载完成后:日期为空则带出「昨天~今天」
|
||||
watch(loaded, (v) => {
|
||||
if (!v) return
|
||||
const [from, to] = defaultRange()
|
||||
if (!form.pay_date_from && !form.pay_date_to) {
|
||||
form.pay_date_from = from
|
||||
form.pay_date_to = to
|
||||
}
|
||||
if (!form.profit_date_from && !form.profit_date_to) {
|
||||
form.profit_date_from = from
|
||||
form.profit_date_to = to
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
@@ -0,0 +1 @@
|
||||
export const PLUGIN_ID = 'xq0041'
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
// 注意顺序:style.css 必须在 element-plus 之后引入,才能覆盖 --el-* 变量映射到壳子 token
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus).mount('#app')
|
||||
@@ -0,0 +1,523 @@
|
||||
/* ============================================================
|
||||
插件 UI 基础样式(规范 v2)
|
||||
- 上半部分:壳子 design token 子集(权威源 desktop/electron-shell/design-app/styles.css)
|
||||
- 中间:Element Plus 变量映射到壳子 token(iframe 内与壳子同一套皮肤)
|
||||
- 下半部分:标准版式骨架(panel / sec / grid / actions),与其它插件保持一致
|
||||
规则:插件内只用 var(--xxx),不写字面色值。
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* ---- 底色与卡面 ---- */
|
||||
--canvas: #F2F4F8;
|
||||
--surface: #FFFFFF;
|
||||
--field: #F5F6FA;
|
||||
--subtle: #F7F8FC;
|
||||
|
||||
/* ---- 描边 ---- */
|
||||
--line: #E8EAF1;
|
||||
--line-soft: #F0F2F7;
|
||||
--line-btn: #E3E6EF;
|
||||
|
||||
/* ---- 文字四阶 ---- */
|
||||
--t1: #12141B;
|
||||
--t2: #3C4250;
|
||||
--t3: #6E7686;
|
||||
--t4: #A3AAB8;
|
||||
--t5: #C6CBD6;
|
||||
|
||||
/* ---- 主色(靛蓝) ---- */
|
||||
--brand: #4F5AE8;
|
||||
--brand-ink: #3D47D4;
|
||||
--brand-soft: #EEF0FE;
|
||||
--brand-hover: #4550E0;
|
||||
|
||||
/* ---- 语义色 ---- */
|
||||
--good: #0E9F76;
|
||||
--good-soft: #EBF7F2;
|
||||
--good-line: #D3EDE3;
|
||||
--warn: #D98218;
|
||||
--warn-soft: #FDF3E4;
|
||||
--danger: #E5484D;
|
||||
--danger-soft: #FDEDED;
|
||||
--danger-line: #F6D7D8;
|
||||
|
||||
/* ---- 圆角 ---- */
|
||||
--r-field: 9px;
|
||||
--r-btn: 10px;
|
||||
--r-sub: 12px;
|
||||
--r-card: 14px;
|
||||
--r-pill: 999px;
|
||||
|
||||
/* ---- 阴影 ---- */
|
||||
--sh-card: 0 2px 8px rgba(18, 20, 31, .05);
|
||||
--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);
|
||||
--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);
|
||||
|
||||
/* ---- 字体 ---- */
|
||||
--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;
|
||||
--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
|
||||
/* ---- 间距 ---- */
|
||||
--space-1: 4px;
|
||||
--space-1-5: 6px;
|
||||
--space-2: 8px;
|
||||
--space-2-5: 10px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
Element Plus → 壳子 token 映射
|
||||
============================================================ */
|
||||
:root {
|
||||
--el-color-primary: var(--brand);
|
||||
--el-color-primary-light-3: #7A83EE;
|
||||
--el-color-primary-light-5: #A6ACF4;
|
||||
--el-color-primary-light-7: #C9CDF9;
|
||||
--el-color-primary-light-8: #DDE0FB;
|
||||
--el-color-primary-light-9: var(--brand-soft);
|
||||
--el-color-primary-dark-2: var(--brand-ink);
|
||||
|
||||
--el-color-success: var(--good);
|
||||
--el-color-success-light-9: var(--good-soft);
|
||||
--el-color-warning: var(--warn);
|
||||
--el-color-warning-light-9: var(--warn-soft);
|
||||
--el-color-danger: var(--danger);
|
||||
--el-color-danger-light-9: var(--danger-soft);
|
||||
--el-color-error: var(--danger);
|
||||
|
||||
--el-text-color-primary: var(--t1);
|
||||
--el-text-color-regular: var(--t2);
|
||||
--el-text-color-secondary: var(--t3);
|
||||
--el-text-color-placeholder: var(--t4);
|
||||
|
||||
--el-border-color: var(--line);
|
||||
--el-border-color-light: var(--line);
|
||||
--el-border-color-lighter: var(--line-soft);
|
||||
--el-border-color-extra-light: var(--line-soft);
|
||||
--el-fill-color-blank: var(--surface);
|
||||
--el-fill-color-light: var(--field);
|
||||
--el-bg-color: var(--surface);
|
||||
|
||||
--el-border-radius-base: var(--r-field);
|
||||
--el-border-radius-small: var(--r-field);
|
||||
--el-font-family: var(--f-cn);
|
||||
--el-font-size-base: 12.5px;
|
||||
--el-box-shadow-light: var(--sh-card);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
基础重置
|
||||
============================================================ */
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--surface);
|
||||
color: var(--t1);
|
||||
font-family: var(--f-cn);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#app {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
页面骨架(与其它插件一致:panel + sec 分区 + grid 栅格 + actions)
|
||||
============================================================ */
|
||||
.page {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
/* 壳子 iframe 外层已有 padding,这里再留一层,避免内容贴着 iframe 边缘 */
|
||||
padding: 8px 16px 24px;
|
||||
}
|
||||
|
||||
/* ---------- 工具条:方案下拉 + 存为方案 + 删除 + 已保存胶囊 ---------- */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.toolbar .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ---------- 主容器:无边框平铺,外框由壳子 iframe 提供 ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.panel .el-card__header {
|
||||
padding: 4px 0 16px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.panel .el-card__body {
|
||||
padding: 16px 0 4px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部:标题 + 方案工具条 ---------- */
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.title-ico {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: var(--r-btn);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.title-txt {
|
||||
font: 600 13.5px/1.25 var(--f-cn);
|
||||
color: var(--t1);
|
||||
}
|
||||
|
||||
.title-sub {
|
||||
font-size: 11.5px;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 10px;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--good-soft);
|
||||
border: 1px solid var(--good-line);
|
||||
color: var(--good);
|
||||
font-size: 11.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.saved i {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: var(--good);
|
||||
}
|
||||
|
||||
/* 尚无保存记录:占位,保持卡片头右侧元素对齐 */
|
||||
.saved.is-idle {
|
||||
background: var(--subtle);
|
||||
border-color: var(--line);
|
||||
color: var(--t4);
|
||||
}
|
||||
|
||||
.saved.is-idle i {
|
||||
background: var(--t5);
|
||||
}
|
||||
|
||||
/* ---------- 分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.sec-badge {
|
||||
width: 23px;
|
||||
height: 23px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font: 600 11px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sec-name {
|
||||
font: 600 13px/1.3 var(--f-cn);
|
||||
color: var(--t1);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--line-soft), transparent);
|
||||
}
|
||||
|
||||
/* ---------- 栅格 ---------- */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
gap: 0 18px;
|
||||
}
|
||||
|
||||
/* ---------- 开关栅格:每格 = 名称 + 开关(规范 §5.2 / §7) ---------- */
|
||||
.grid-switch {
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
}
|
||||
|
||||
/* 日期区间与开关行之间留出呼吸 */
|
||||
.grid-date {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.grid .el-form-item__label {
|
||||
padding-bottom: 6px !important;
|
||||
font-weight: 500;
|
||||
color: var(--t2);
|
||||
}
|
||||
|
||||
/* 栅格里的控件统一撑满 */
|
||||
.grid .el-input,
|
||||
.grid .el-select,
|
||||
.grid .el-date-editor {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
/* ---------- 提示 ---------- */
|
||||
.tip {
|
||||
margin-top: var(--space-2);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.65;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.tip b {
|
||||
color: var(--t2);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- 内联提示条(替代顶部大横幅) ---------- */
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--r-field);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--subtle);
|
||||
font-size: 12px;
|
||||
color: var(--t2);
|
||||
}
|
||||
|
||||
.notice .n-ico {
|
||||
flex: 0 0 auto;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.notice.is-warn {
|
||||
background: var(--warn-soft);
|
||||
border-color: rgba(217, 130, 24, .24);
|
||||
color: #8A5B0E;
|
||||
}
|
||||
|
||||
.notice.is-error {
|
||||
background: var(--danger-soft);
|
||||
border-color: var(--danger-line);
|
||||
color: #CC3B40;
|
||||
}
|
||||
|
||||
.notice.is-ok {
|
||||
background: var(--good-soft);
|
||||
border-color: var(--good-line);
|
||||
color: var(--good);
|
||||
}
|
||||
|
||||
/* ---------- 执行摘要(操作区上方一行低调说明) ---------- */
|
||||
.plan {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-2);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.plan .p-tag {
|
||||
flex: 0 0 auto;
|
||||
font-weight: 600;
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
|
||||
.plan .p-text {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.plan.is-empty .p-text {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
border-top: 1px dashed var(--line);
|
||||
padding-top: 18px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.actions .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* 底部通用操作(恢复参数/保存/恢复默认),不重复画分隔线 */
|
||||
.actions--foot {
|
||||
border-top: none;
|
||||
padding-top: 0;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
height: 34px;
|
||||
border: none;
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
font: 600 12.5px/18px var(--f-cn);
|
||||
letter-spacing: 1px;
|
||||
box-shadow: var(--sh-brand);
|
||||
transition: background .15s, box-shadow .15s, transform .06s;
|
||||
}
|
||||
|
||||
.btn-run:hover {
|
||||
background: var(--brand-hover);
|
||||
}
|
||||
|
||||
.btn-run:active {
|
||||
transform: translateY(1px);
|
||||
box-shadow: var(--sh-brand-sm);
|
||||
}
|
||||
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态:进度条 + 一行说明 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: var(--r-sub);
|
||||
background: var(--brand-soft);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.status-bar .el-progress-bar__outer {
|
||||
background: rgba(79, 89, 232, .14);
|
||||
}
|
||||
|
||||
.status-bar .el-progress-bar__inner {
|
||||
background: var(--brand);
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
flex: 1;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.status-pct {
|
||||
font: 600 13px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ---------- 运行态一行文字(进度由壳子 RunIndicator 展示) ---------- */
|
||||
.runline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
font-size: 12px;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.runline .pct {
|
||||
font: 600 12px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
|
||||
.pulse {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--brand);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--brand-soft);
|
||||
}
|
||||
70% {
|
||||
box-shadow: 0 0 0 7px transparent;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
|
||||
//
|
||||
// 与 v1 的差异(适配当前壳子):
|
||||
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
|
||||
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
|
||||
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
|
||||
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
|
||||
// 不能再当成普通失败提示。
|
||||
//
|
||||
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
|
||||
// 执行状态机(执行/强停/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 Object.assign(new Error(msg), { code: res.status, status: res.status })
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
|
||||
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
const saveScheme = (name, fields) => j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
const deleteScheme = (cfgId) =>
|
||||
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||
const startRun = (fields) => j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
const getRun = (runId) => j(`/api/runs/${runId}`)
|
||||
const stopRun = (runId) => 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))
|
||||
|
||||
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
|
||||
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
|
||||
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
|
||||
function readSavedAt() {
|
||||
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
|
||||
}
|
||||
function writeSavedAt(v) {
|
||||
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
|
||||
}
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
|
||||
// (空数组可能是有意配置,如「留空=不筛选」)
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
|
||||
const lastSavedAt = ref(readSavedAt())
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
|
||||
const notify = (type, text) => { notice.value = type ? { type, text } : null }
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
|
||||
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes()
|
||||
})
|
||||
|
||||
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 })
|
||||
writeSavedAt(lastSavedAt.value)
|
||||
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) : {})
|
||||
notify(null)
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
|
||||
async function restoreLastFields() {
|
||||
try {
|
||||
const r = await loadLastFields()
|
||||
const fields = r.fields || {}
|
||||
if (!Object.keys(fields).length) {
|
||||
ElMessage.info('暂无上次执行参数')
|
||||
return
|
||||
}
|
||||
mergeSaved(form, fields)
|
||||
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('恢复上次参数失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 多配置方案 ----------
|
||||
const schemes = ref([])
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
|
||||
async function run(action) {
|
||||
if (running.value) return
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
} catch (_) {
|
||||
notify('error', '登录态未就绪,请稍后重试')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (validate && !validate(action)) return
|
||||
await saveNow(false)
|
||||
notify(null)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
try {
|
||||
const payload = buildPayload ? buildPayload(form) : clone(form)
|
||||
if (action) payload.action = action
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) {
|
||||
needLogin.value = true
|
||||
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
|
||||
} else if (e.code === 409) {
|
||||
// 壳子「入队确认」里用户点了取消
|
||||
notify('warn', '已取消加入执行队列,本次没有启动')
|
||||
} else {
|
||||
notify('error', '启动执行失败:' + 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
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
|
||||
if (summary) notify('ok', summary)
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
notify('error', '执行失败:' + err)
|
||||
}
|
||||
|
||||
return {
|
||||
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子托管在 /pui/xq0041/ 下,构建产物输出到插件包 ui/ 目录。
|
||||
// dev 端口 5182(5180/5181 已被 xq0002/xq0047 占用),代理到本机壳子 8799。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0041/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5182,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
File diff suppressed because one or more lines are too long
+1
-1
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/xq0041/assets/index-D_F9Lnim.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0041/assets/index-ficKgg0s.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -0,0 +1,147 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0042 抖音平台核对 —— webhost 场景插件入口。
|
||||
|
||||
当前阶段:登录态获取 + 两类数据自动导出。
|
||||
打开抖音来客 → 人工登录(含验证码/滑块,浏览器里一次性完成,之后复用登录态)
|
||||
→ 按日期区间导出「核销明细」(履约管理订单列表)与「提现记录」(财务导出记录)
|
||||
→ 轮询生成状态 → 下载到本机目录(默认 D:\\资料\\财务\\抖音平台核对)。
|
||||
导出前查该类导出记录,超过保留阈值(界面可配,默认核销 60 / 提现 25)就删最早的。
|
||||
|
||||
接口签名(a_bogus / msToken)由页面 SDK 注入,插件只在页面上下文发请求,不逆向签名。
|
||||
|
||||
待补:并入台账 + 更新核对统计(口径确认后按 xq0041 的分层补齐)。
|
||||
"""
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
from webhost.backend.plugins.base import PLUGINS, ScenePlugin
|
||||
|
||||
from . import config
|
||||
from .data import browser, douyin_export, douyin_login
|
||||
|
||||
|
||||
def _parse_day(s):
|
||||
for fmt in ('%Y-%m-%d', '%Y/%m/%d', '%Y%m%d'):
|
||||
try:
|
||||
return datetime.strptime(str(s).strip(), fmt).date()
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def _resolve_pair(raw_from, raw_to):
|
||||
"""解析日期区间:都空=昨天~今天;只给一端=单日;起止颠倒自动换序。"""
|
||||
d1 = _parse_day(raw_from) if raw_from else None
|
||||
d2 = _parse_day(raw_to) if raw_to else None
|
||||
if d1 is None and d2 is None:
|
||||
return ((date.today() - timedelta(days=1)).isoformat(), date.today().isoformat())
|
||||
if d1 is None:
|
||||
d1 = d2
|
||||
if d2 is None:
|
||||
d2 = d1
|
||||
if d2 < d1:
|
||||
d1, d2 = d2, d1
|
||||
return d1.isoformat(), d2.isoformat()
|
||||
|
||||
|
||||
def _limit(raw, default):
|
||||
"""导出记录保留阈值:非法/过小则回退默认值。"""
|
||||
try:
|
||||
val = int(str(raw).strip())
|
||||
except (TypeError, ValueError):
|
||||
return default
|
||||
return val if val >= config.RECORD_LIMIT_MIN else default
|
||||
|
||||
|
||||
class Xq0042Plugin(ScenePlugin):
|
||||
id = 'xq0042'
|
||||
name = '抖音平台核对'
|
||||
version = '0.6.2'
|
||||
description = ('抖音来客数据自动导出:登录后按日期区间导出核销明细、提现记录,'
|
||||
'轮询生成完成后下载到本机目录;导出记录超阈值自动删最早的')
|
||||
platform = '' # 插件自带登录(抖音来客 SSO),不用底座共享登录态
|
||||
uses_month = False
|
||||
capabilities = ['xq0042']
|
||||
permissions = {'platforms': []}
|
||||
fields = {
|
||||
'date_from': {'type': 'string', 'title': '核销时间-开始日期', 'default': ''},
|
||||
'date_to': {'type': 'string', 'title': '核销时间-结束日期', 'default': ''},
|
||||
'withdraw_from': {'type': 'string', 'title': '提现时间-开始日期', 'default': ''},
|
||||
'withdraw_to': {'type': 'string', 'title': '提现时间-结束日期', 'default': ''},
|
||||
'export_verify': {'type': 'boolean', 'title': '导出核销明细', 'default': True},
|
||||
'export_withdraw': {'type': 'boolean', 'title': '导出提现记录', 'default': True},
|
||||
'record_limit_verify': {'type': 'integer', 'title': '核销明细-导出记录保留条数',
|
||||
'default': config.RECORD_LIMIT_VERIFY},
|
||||
'record_limit_withdraw': {'type': 'integer', 'title': '提现记录-导出记录保留条数',
|
||||
'default': config.RECORD_LIMIT_WITHDRAW},
|
||||
'save_dir': {'type': 'string', 'title': '保存目录', 'default': ''},
|
||||
'force_login': {'type': 'boolean', 'title': '强制重新登录', 'default': False},
|
||||
'debug_mode': {'type': 'boolean', 'title': '调试日志', 'default': False},
|
||||
}
|
||||
|
||||
def run(self, fields, ctx):
|
||||
fields = fields or {}
|
||||
config.set_log(ctx.log)
|
||||
config.set_progress(ctx.progress)
|
||||
config.set_debug(fields.get('debug_mode'))
|
||||
|
||||
v_from, v_to = _resolve_pair(fields.get('date_from'), fields.get('date_to'))
|
||||
w_from, w_to = _resolve_pair(fields.get('withdraw_from'), fields.get('withdraw_to'))
|
||||
save_dir = (str(fields.get('save_dir') or '').strip().strip('"')
|
||||
or config.WORK_DIR)
|
||||
force = bool(fields.get('force_login'))
|
||||
do_verify = fields.get('export_verify', True) is not False
|
||||
do_withdraw = fields.get('export_withdraw', True) is not False
|
||||
if not do_verify and not do_withdraw:
|
||||
raise RuntimeError('请至少勾选一项导出内容(核销明细 / 提现记录)')
|
||||
limit_verify = _limit(fields.get('record_limit_verify'), config.RECORD_LIMIT_VERIFY)
|
||||
limit_withdraw = _limit(fields.get('record_limit_withdraw'), config.RECORD_LIMIT_WITHDRAW)
|
||||
|
||||
kinds = [k for k, on in (('核销明细', do_verify), ('提现记录', do_withdraw)) if on]
|
||||
ranges = []
|
||||
if do_verify:
|
||||
ranges.append(f'核销 {v_from} ~ {v_to}')
|
||||
if do_withdraw:
|
||||
ranges.append(f'提现 {w_from} ~ {w_to}')
|
||||
config.log(f'本次执行:导出{"、".join(kinds)}({";".join(ranges)})→ {save_dir}'
|
||||
+ ('(强制重新登录)' if force else ''))
|
||||
config.log(f'导出记录保留条数:核销明细 {limit_verify}、提现记录 {limit_withdraw}')
|
||||
config.progress(5)
|
||||
|
||||
page = browser.open_page()
|
||||
results = {}
|
||||
try:
|
||||
ok, msg = douyin_login.ensure_login(page, force=force)
|
||||
config.log(msg)
|
||||
if not ok:
|
||||
raise RuntimeError(f'登录失败:{msg}')
|
||||
config.progress(30)
|
||||
|
||||
if do_verify:
|
||||
results['核销明细'] = douyin_export.run(page, v_from, v_to, save_dir,
|
||||
limit_verify)
|
||||
config.progress(65)
|
||||
if do_withdraw:
|
||||
results['提现记录'] = douyin_export.run_withdraw(page, w_from, w_to,
|
||||
save_dir, limit_withdraw)
|
||||
config.progress(95)
|
||||
finally:
|
||||
browser.close_page(page)
|
||||
|
||||
failed = {k: v.get('message') for k, v in results.items() if not v.get('ok')}
|
||||
ok_parts = [v.get('message') for v in results.values() if v.get('ok')]
|
||||
path = next((v.get('path') for v in results.values() if v.get('ok')), '')
|
||||
if failed:
|
||||
detail = ';'.join(f'{k}失败:{m}' for k, m in failed.items())
|
||||
raise RuntimeError(('已完成:' + ';'.join(ok_parts) + '。' if ok_parts else '')
|
||||
+ detail)
|
||||
config.progress(100)
|
||||
return {
|
||||
'summary': f'{";".join(ranges)}:' + ';'.join(ok_parts),
|
||||
'detail': {'date_from': v_from, 'date_to': v_to,
|
||||
'withdraw_from': w_from, 'withdraw_to': w_to,
|
||||
'login': msg, 'results': results},
|
||||
'path': path,
|
||||
}
|
||||
|
||||
|
||||
PLUGINS.append(Xq0042Plugin())
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""发布打包辅助(开发工具,`_` 前缀运行时不会被插件扫描加载)。
|
||||
|
||||
输出 dist-plugin/xq0042_v<版本>.zip,zip 根含 plugin.json。
|
||||
排除:ui-src、__pycache__、debug、.sessions、本脚本、*.pyc。
|
||||
|
||||
用法(仓库根下执行):
|
||||
.venv\\Scripts\\python.exe "plugins\\XQ0001-0100\\XQ0042 抖音平台核对\\_pack.py"
|
||||
"""
|
||||
import json
|
||||
import zipfile
|
||||
from pathlib import Path
|
||||
|
||||
_HERE = Path(__file__).resolve().parent
|
||||
_OUT_DIR = _HERE.parents[2] / "dist-plugin"
|
||||
_EXCLUDE_DIRS = {"ui-src", "__pycache__", "debug", ".sessions"}
|
||||
_EXCLUDE_FILES = {"_pack.py"}
|
||||
|
||||
|
||||
def main():
|
||||
manifest = json.loads((_HERE / "plugin.json").read_text(encoding="utf-8"))
|
||||
pid, ver = manifest["id"], manifest["version"]
|
||||
_OUT_DIR.mkdir(exist_ok=True)
|
||||
out = _OUT_DIR / f"{pid}_v{ver}.zip"
|
||||
with zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as zf:
|
||||
for p in sorted(_HERE.rglob("*")):
|
||||
rel = p.relative_to(_HERE)
|
||||
if set(rel.parts) & _EXCLUDE_DIRS or p.name in _EXCLUDE_FILES or p.suffix == ".pyc":
|
||||
continue
|
||||
if p.is_file():
|
||||
zf.write(p, str(rel))
|
||||
print(f"已打包: {out}({out.stat().st_size / 1024:.0f} KB)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,199 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0042 抖音平台核对 - 配置常量与全局钩子。
|
||||
|
||||
插件自包含:只依赖标准库 / 第三方库 / 底座注入的 RunContext。
|
||||
各业务模块统一经 config.log() / config.progress() 输出,由 run() 启动时注入 ctx。
|
||||
|
||||
当前阶段只做「登录态获取与验证」(抖音来客)。
|
||||
2026-10-28 实测:
|
||||
登录页 https://life.douyin.com/p/login
|
||||
首页 https://life.douyin.com/p/home[?groupid=...]
|
||||
会话票据种在 .life.douyin.com:sessionid_ls / sessionid_ss_ls / sid_tt_ls / sid_guard_ls
|
||||
"""
|
||||
import os
|
||||
import time
|
||||
|
||||
# ==================== 平台:抖音来客 ====================
|
||||
HOME_URL = 'https://life.douyin.com/p/home'
|
||||
LOGIN_URL = 'https://life.douyin.com/p/login'
|
||||
|
||||
BACKEND_HOST = 'life.douyin.com' # 来客后台主域
|
||||
LOGIN_PAGE_HINTS = ('/p/login', 'login') # 登录页路径(同域下的排除项)
|
||||
PASSPORT_HINTS = ( # 统一登录/账号域
|
||||
'sso.douyin.com', 'passport.douyin.com', 'open.douyin.com',
|
||||
'douyin.com/login', 'account.douyin.com',
|
||||
)
|
||||
|
||||
# 登录票据 Cookie:名字带分区后缀 `_ls`(老版本/无分区时是裸名),按前缀匹配
|
||||
SESSION_COOKIE_PREFIXES = ('sessionid', 'sid_tt', 'sid_guard', 'sid_ucp')
|
||||
|
||||
# 票据候选(子串匹配,仅用于日志摘要)与埋点排除项
|
||||
TICKET_KEY_HINTS = ('session', 'sid', 'token', 'ticket', 'userid', 'user_id')
|
||||
IGNORE_KEY_HINTS = (
|
||||
'ttwid', 'mstoken', 'csrf', '_ga', '_gid', '__ac', 's_v_web_id', 'tt_scid',
|
||||
'monitor', 'abtest', 'odin', 'store-region', 'passport_csrf',
|
||||
)
|
||||
|
||||
# ==================== 核销明细导出(履约管理 → 导出工具) ====================
|
||||
# 实测 2026-10-28:导出工具弹窗「核销明细」提交的就是这个接口,
|
||||
# 返回 downloadStruct(download_id + status=1 生成中),完成后在「导出记录」里出现。
|
||||
ORDER_URL = ('https://life.douyin.com/p/liteapp/fulfillment-admin/order-list'
|
||||
'?admin_industry=45&groupid=1732612560882691')
|
||||
ORDER_GROUP_ID = '1732612560882691' # 当前账号(URL 里取不到时的兜底)
|
||||
ROOT_LIFE_ACCOUNT_ID = '7044832462517569568' # 主账号 ID(localStorage 解析失败时的兜底)
|
||||
VERIFY_EXPORT_API = ('https://life.douyin.com/life/trade_view/v1/management/verify/query/'
|
||||
'download_verify_record_list')
|
||||
DOWNLOAD_LIST_API = 'https://life.douyin.com/life/settle/v1/download/list/'
|
||||
DOWNLOAD_TYPE = 10031001 # 导出记录页(财务 → 导出记录)
|
||||
VERIFY_VIEW_TYPE = 'common_view_verify_record'
|
||||
VERIFY_SHOW_REASON = 'catering_comprehensive_coupon'
|
||||
# 商品类型过滤(与页面默认一致:团购券/次卡等全部可核销类型)
|
||||
VERIFY_PRODUCT_OPTIONS = ['1', '11', '15', '2601', '26', '130011', '2201', '1801', '1802',
|
||||
'1803', '1804', '2901', '1501', '2801', '100112', '110301', '1502']
|
||||
RECORD_SECONDS = 180 # 导出任务生成超时(秒)
|
||||
RECORD_POLL = 10 # 轮询生成状态的间隔(秒)
|
||||
|
||||
# ==================== 提现记录(余额提现记录)导出 ====================
|
||||
# 实测 2026-10-28:财务 → 导出记录(/p/fulfillsettle/export_records/16)点「导出」,
|
||||
# 走的是 GET withdraw/capital/download_records_list,时间参数为秒级时间戳;
|
||||
# 记录列表 download_type=16,文件名形如「资金账户交易提现记录_起_止.xlsx」。
|
||||
WITHDRAW_URL = ('https://life.douyin.com/p/fulfillsettle/export_records/16'
|
||||
'?groupid=1732612560882691')
|
||||
WITHDRAW_EXPORT_API = ('https://life.douyin.com/life/settle/v1/withdraw/capital/'
|
||||
'download_records_list/')
|
||||
WITHDRAW_DOWNLOAD_TYPE = 16 # 余额提现记录
|
||||
WITHDRAW_FUND_ACCOUNT_TYPE = 6 # 资金账户类型(页面默认)
|
||||
DELETE_API = 'https://life.douyin.com/life/settle/v1/download/delete/'
|
||||
|
||||
# 平台限制:提现记录类导出最多 30 条,满了再发起会返回
|
||||
# 224000002「最多仅支持30个待下载文件,请删除部分历史文件后重试」。
|
||||
# 因此每次导出前先查列表:记录数超过「保留阈值」就删最早的、只留最新 N 条。
|
||||
# 阈值可在插件界面手动改(record_limit_verify / record_limit_withdraw)。
|
||||
RECORD_LIMIT_VERIFY = 60 # 核销明细:该类列表暂未遇到 30 条限制,先记 60
|
||||
RECORD_LIMIT_WITHDRAW = 25 # 提现记录:平台 30 条硬上限,留 5 条余量
|
||||
RECORD_LIMIT_CODE = 224000002 # 「最多仅支持30个待下载文件」的业务错误码
|
||||
RECORD_LIMIT_MIN = 5 # 阈值下限:防止误填过小导致批量删记录
|
||||
|
||||
# 删除导出记录要限流:连续删除间隔随机抖动,单次运行设上限,避免被平台风控判定异常
|
||||
DELETE_MIN_INTERVAL = 1.0 # 两条删除之间的最短间隔(秒)
|
||||
DELETE_MAX_INTERVAL = 2.0 # 最长间隔(秒),实际取值在两者之间随机
|
||||
DELETE_MAX_PER_RUN = 20 # 单次运行最多删几条,超出部分留到下次运行
|
||||
|
||||
# ==================== 输出目录 ====================
|
||||
WORK_DIR = r'D:\资料\财务\抖音平台核对' # 核销明细 + 台账统一目录
|
||||
|
||||
# ==================== 运行参数 ====================
|
||||
LOGIN_WAIT = 600 # 等待人工登录(含验证码/滑块)超时
|
||||
BACKEND_STABLE = 15 # 后台页连续稳定秒数(登录后有短暂回跳登录页的现象)
|
||||
SETTLE_WAIT = 8 # 登录成功后等首屏请求结束再抓 cookie
|
||||
POLL_SECONDS = 2
|
||||
RETRY_MAX = 3
|
||||
HEADLESS = False # 人工登录必须可见浏览器
|
||||
|
||||
# ==================== 共享路径 ====================
|
||||
def _app_data_dir():
|
||||
return os.path.join(
|
||||
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
|
||||
'37duAutomation')
|
||||
|
||||
|
||||
SESSIONS_DIR = os.path.join(_app_data_dir(), '.sessions')
|
||||
COOKIE_FILE = os.path.join(SESSIONS_DIR, 'douyin_cookies.json')
|
||||
COOKIE_HEADER_FILE = os.path.join(SESSIONS_DIR, 'douyin_cookies_header.txt')
|
||||
TOKEN_FILE = os.path.join(SESSIONS_DIR, 'douyin_tokens.json')
|
||||
META_FILE = os.path.join(SESSIONS_DIR, 'douyin_session_meta.json')
|
||||
|
||||
|
||||
def get_browser_profile_dir():
|
||||
"""独立固定浏览器用户目录:登录态跨次保留,不占用日常 Chrome 配置。"""
|
||||
return os.path.join(_app_data_dir(), 'browser_sessions', 'xq0042')
|
||||
|
||||
|
||||
# ==================== 浏览器窗口(全屏 + 置顶) ====================
|
||||
def apply_window_mode(page):
|
||||
"""把浏览器窗口设为全屏并置顶(登录要人工操作,避免被其它窗口挡住)。"""
|
||||
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
|
||||
|
||||
|
||||
# ==================== 全局钩子(run() 启动时注入) ====================
|
||||
_log = None
|
||||
_progress = None
|
||||
_debug = False
|
||||
|
||||
|
||||
def set_log(fn):
|
||||
global _log
|
||||
_log = fn
|
||||
|
||||
|
||||
def set_progress(fn):
|
||||
global _progress
|
||||
_progress = fn
|
||||
|
||||
|
||||
def set_debug(on):
|
||||
global _debug
|
||||
_debug = bool(on)
|
||||
|
||||
|
||||
def debug_enabled():
|
||||
return _debug
|
||||
|
||||
|
||||
def log(msg, level='INFO'):
|
||||
text = f'[{time.strftime("%H:%M:%S")}] {msg}'
|
||||
if level == 'DEBUG' and not _debug:
|
||||
return
|
||||
if _log:
|
||||
_log(str(msg), level)
|
||||
else:
|
||||
print(f'[{level}] {text}')
|
||||
|
||||
|
||||
def progress(pct):
|
||||
if _progress:
|
||||
try:
|
||||
_progress(int(pct))
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,2 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""xq0042 抖音平台核对 - 数据层。"""
|
||||
@@ -0,0 +1,36 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""浏览器:一次运行共用一个可见浏览器(登录 + 后续取数都复用它,避免反复开关)。
|
||||
|
||||
独立固定用户目录 %LOCALAPPDATA%\\37duAutomation\\browser_sessions\\xq0042,
|
||||
登录态跨次保留,不占用用户日常 Chrome 配置。
|
||||
"""
|
||||
import os
|
||||
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def open_page():
|
||||
co = ChromiumOptions()
|
||||
if config.HEADLESS:
|
||||
co.headless()
|
||||
co.set_argument('--start-maximized')
|
||||
co.set_pref('credentials_enable_service', False)
|
||||
co.set_pref('profile.password_manager_enabled', False)
|
||||
profile = config.get_browser_profile_dir()
|
||||
os.makedirs(profile, exist_ok=True)
|
||||
co.set_user_data_path(profile)
|
||||
config.log(f'浏览器用户目录:{profile}', 'DEBUG')
|
||||
page = ChromiumPage(co)
|
||||
if not config.HEADLESS:
|
||||
# 登录要人工操作(账密/短信/扫码/滑块),全屏 + 置顶避免被其它窗口挡住
|
||||
config.apply_window_mode(page)
|
||||
return page
|
||||
|
||||
|
||||
def close_page(page):
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
@@ -0,0 +1,403 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""导出模块:核销明细 + 提现记录(余额提现记录)。
|
||||
|
||||
实测(2026-10-28):
|
||||
|
||||
核销明细(履约管理订单列表 → 导出工具)
|
||||
创建:POST /life/trade_view/v1/management/verify/query/download_verify_record_list
|
||||
body.condition.query_conditions = [商品类型 product_option, 核销时间 verify_time(秒级)]
|
||||
→ data.downloadStruct{download_id, file_name, status=1}
|
||||
轮询:GET /life/settle/v1/download/list/?download_type=10031001
|
||||
|
||||
提现记录(财务 → 导出记录 /p/fulfillsettle/export_records/16)
|
||||
创建:GET /life/settle/v1/withdraw/capital/download_records_list/?start_date=&end_date=
|
||||
轮询:GET /life/settle/v1/download/list/?download_type=16
|
||||
→ download_infos[] 里 status=2 表示生成完成,file_url 为预签名地址
|
||||
|
||||
公共约束
|
||||
平台同类导出记录最多 30 条,满了创建会返回 224000002;
|
||||
因此导出前先查列表,超限就删最早的(POST /life/settle/v1/download/delete/)。
|
||||
下载:file_url 直接 requests 取(带签名,不需要 Cookie)。
|
||||
|
||||
签名参数(a_bogus / msToken)由页面 SDK 注入,所以请求都在页面上下文里发。
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import random
|
||||
import time
|
||||
|
||||
import requests
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _xhr(page, method, url, payload=None):
|
||||
"""页面上下文同步 XHR,返回 (status, text)。"""
|
||||
body_js = 'null'
|
||||
headers_js = ''
|
||||
if payload is not None:
|
||||
body_js = 'JSON.stringify(' + json.dumps(payload, ensure_ascii=False) + ')'
|
||||
headers_js = "x.setRequestHeader('Content-Type','application/json');"
|
||||
js = '''
|
||||
try {
|
||||
var x = new XMLHttpRequest();
|
||||
x.open('%s', '%s', false);
|
||||
x.withCredentials = true;
|
||||
%s
|
||||
x.send(%s);
|
||||
return x.status + '||' + String(x.responseText || '');
|
||||
} catch (e) {
|
||||
return 'ERR||' + e;
|
||||
}
|
||||
''' % (method.upper(), url, headers_js, body_js)
|
||||
raw = page.run_js(js)
|
||||
if not raw or '||' not in str(raw):
|
||||
return 0, f'返回值异常:{str(raw)[:200]}'
|
||||
status, _, text = str(raw).partition('||')
|
||||
try:
|
||||
return int(status), text
|
||||
except Exception:
|
||||
return 0, text
|
||||
|
||||
|
||||
def _api_json(page, method, url, payload=None):
|
||||
status, text = _xhr(page, method, url, payload)
|
||||
name = url.split('/')[-1].split('?')[0]
|
||||
if status != 200:
|
||||
config.log(f'{name} 请求失败:status={status} {text[:200]}', 'WARN')
|
||||
return None
|
||||
try:
|
||||
return json.loads(text)
|
||||
except Exception as e:
|
||||
config.log(f'{name} 返回非 JSON:{e} | {text[:200]}', 'WARN')
|
||||
return None
|
||||
|
||||
|
||||
def _account_id(page):
|
||||
"""root_life_account_id:页面 localStorage 里是 {用户id: 主账号id} 的 JSON 映射,
|
||||
取映射值;读不到/解析失败用配置兜底。"""
|
||||
try:
|
||||
val = page.run_js("return localStorage.getItem('root_life_account_id') || '';")
|
||||
text = str(val or '').strip()
|
||||
if text:
|
||||
try:
|
||||
obj = json.loads(text)
|
||||
if isinstance(obj, dict) and obj:
|
||||
return str(list(obj.values())[0])
|
||||
if isinstance(obj, str) and obj:
|
||||
return obj.strip()
|
||||
except Exception:
|
||||
return text.strip('"')
|
||||
except Exception:
|
||||
pass
|
||||
return config.ROOT_LIFE_ACCOUNT_ID
|
||||
|
||||
|
||||
def _group_id(page):
|
||||
"""groupid 从当前 URL 里取(?groupid=...),取不到用配置兜底。"""
|
||||
url = page.url or ''
|
||||
if 'groupid=' in url:
|
||||
val = url.split('groupid=', 1)[1].split('&', 1)[0]
|
||||
if val.isdigit():
|
||||
return val
|
||||
return config.ORDER_GROUP_ID
|
||||
|
||||
|
||||
def _ensure_page(page, url, hint, label):
|
||||
"""切到导出所在页面(同域上下文,SDK 才会给请求签名)。"""
|
||||
target = url.replace(config.ORDER_GROUP_ID, _group_id(page))
|
||||
if hint not in (page.url or ''):
|
||||
config.log(f'打开{label}页面')
|
||||
page.get(target)
|
||||
try:
|
||||
page.wait.doc_loaded(timeout=20)
|
||||
except Exception:
|
||||
time.sleep(5)
|
||||
# SPA 首屏文档加载完之后前端才注入签名 SDK,留一点时间再发业务请求
|
||||
time.sleep(2)
|
||||
return target
|
||||
|
||||
|
||||
def _ensure_order_page(page):
|
||||
return _ensure_page(page, config.ORDER_URL,
|
||||
'fulfillment-admin/order-list', '履约管理订单列表')
|
||||
|
||||
|
||||
def _ensure_withdraw_page(page):
|
||||
return _ensure_page(page, config.WITHDRAW_URL,
|
||||
'fulfillsettle/export_records', '提现记录')
|
||||
|
||||
|
||||
def _list_records(page, download_type):
|
||||
"""查某类导出记录列表(新的在前)。"""
|
||||
aid = _account_id(page)
|
||||
url = (f'{config.DOWNLOAD_LIST_API}?download_type={download_type}'
|
||||
+ (f'&root_life_account_id={aid}' if aid else ''))
|
||||
data = _api_json(page, 'GET', url)
|
||||
return ((data or {}).get('download_infos') or [])
|
||||
|
||||
|
||||
def _delete_record(page, download_id):
|
||||
"""删除单条导出记录。"""
|
||||
aid = _account_id(page)
|
||||
url = config.DELETE_API + (f'?root_life_account_id={aid}' if aid else '')
|
||||
data = _api_json(page, 'POST', url, {'download_id': str(download_id)})
|
||||
base = ((data or {}).get('BaseResp') or {})
|
||||
return data is not None and base.get('StatusCode', -1) == 0
|
||||
|
||||
|
||||
def _delete_oldest(page, download_type, count, infos=None):
|
||||
"""删掉最早的 count 条导出记录(按 generate_start_time 升序)。返回删除条数。
|
||||
|
||||
限流:两条之间随机间隔 DELETE_MIN_INTERVAL ~ DELETE_MAX_INTERVAL 秒,
|
||||
单次运行最多删 DELETE_MAX_PER_RUN 条,避免短时间连续删除触发风控。
|
||||
"""
|
||||
if count <= 0:
|
||||
return 0
|
||||
limit = config.DELETE_MAX_PER_RUN
|
||||
if count > limit:
|
||||
config.log(f'本次只删最早的 {limit} 条(单次上限),其余留到下次运行', 'WARN')
|
||||
count = limit
|
||||
if infos is None:
|
||||
infos = _list_records(page, download_type)
|
||||
if not infos:
|
||||
return 0
|
||||
oldest_first = sorted(infos, key=lambda x: int(x.get('generate_start_time') or 0))[:int(count)]
|
||||
removed = 0
|
||||
for idx, rec in enumerate(oldest_first):
|
||||
did = rec.get('download_id')
|
||||
if not did:
|
||||
continue
|
||||
if idx or removed:
|
||||
pause = random.uniform(config.DELETE_MIN_INTERVAL, config.DELETE_MAX_INTERVAL)
|
||||
config.log(f'限流等待 {pause:.1f}s 再删下一条', 'DEBUG')
|
||||
time.sleep(pause)
|
||||
name = rec.get('file_name') or ''
|
||||
if _delete_record(page, did):
|
||||
removed += 1
|
||||
config.log(f'删除最早导出记录:{name}({did})')
|
||||
else:
|
||||
config.log(f'删除导出记录失败:{name}({did})', 'WARN')
|
||||
return removed
|
||||
|
||||
|
||||
def _ensure_capacity(page, download_type, limit):
|
||||
"""记录数超过保留阈值时,删最早的、只保留最新 limit 条。返回删除条数。"""
|
||||
infos = _list_records(page, download_type)
|
||||
total = len(infos)
|
||||
if total <= limit:
|
||||
config.log(f'导出记录 {total} 条(保留阈值 {limit}),无需清理', 'DEBUG')
|
||||
return 0
|
||||
config.log(f'导出记录 {total} 条,超过保留阈值 {limit},删除最早的 {total - limit} 条')
|
||||
return _delete_oldest(page, download_type, total - limit, infos)
|
||||
|
||||
|
||||
def _create_export(page, start_ts, end_ts):
|
||||
"""发起核销明细导出,返回 downloadStruct(含 download_id / file_name)。"""
|
||||
aid = _account_id(page)
|
||||
url = config.VERIFY_EXPORT_API + (f'?root_life_account_id={aid}' if aid else '')
|
||||
payload = {
|
||||
'condition': {
|
||||
'query_type': 101,
|
||||
'query_conditions': [
|
||||
{'column_name': 'product_option',
|
||||
'params': list(config.VERIFY_PRODUCT_OPTIONS), 'query_type': 9},
|
||||
{'column_name': 'verify_time',
|
||||
'params': [str(int(start_ts)), str(int(end_ts))], 'query_type': 12},
|
||||
],
|
||||
},
|
||||
'is_app': False,
|
||||
'show_reason': config.VERIFY_SHOW_REASON,
|
||||
'view_type': config.VERIFY_VIEW_TYPE,
|
||||
'download_field_option': 1,
|
||||
'permission_common_param': {},
|
||||
}
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
data = _api_json(page, 'POST', url, payload)
|
||||
if data is None:
|
||||
config.log(f'发起导出异常({attempt}/{config.RETRY_MAX}),重试', 'WARN')
|
||||
time.sleep(3)
|
||||
continue
|
||||
base = (data.get('BaseResp') or {})
|
||||
struct = ((data.get('data') or {}).get('downloadStruct') or {})
|
||||
code = base.get('StatusCode')
|
||||
if code == 0 and struct.get('download_id'):
|
||||
return struct
|
||||
if code == config.RECORD_LIMIT_CODE:
|
||||
config.log('导出记录已达平台上限,删最早 5 条后重试', 'WARN')
|
||||
_delete_oldest(page, config.DOWNLOAD_TYPE, 5)
|
||||
continue
|
||||
# 业务错误重试不会变好(如鉴权失败),直接返回,避免重复创建导出任务
|
||||
config.log(f'发起导出失败:{base.get("StatusMessage") or data}', 'WARN')
|
||||
return None
|
||||
return None
|
||||
|
||||
|
||||
def _create_withdraw(page, start_ts, end_ts):
|
||||
"""发起提现记录导出,返回 (ok, 说明)。"""
|
||||
aid = _account_id(page)
|
||||
url = (f'{config.WITHDRAW_EXPORT_API}?life_account_id_list='
|
||||
f'&start_date={int(start_ts)}&end_date={int(end_ts)}&status_array='
|
||||
f'&fund_account_type_list={config.WITHDRAW_FUND_ACCOUNT_TYPE}'
|
||||
+ (f'&root_life_account_id={aid}' if aid else ''))
|
||||
msg = ''
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
data = _api_json(page, 'GET', url)
|
||||
if data is None:
|
||||
config.log(f'发起提现记录导出异常({attempt}/{config.RETRY_MAX}),重试', 'WARN')
|
||||
time.sleep(3)
|
||||
continue
|
||||
code = data.get('status_code')
|
||||
base = (data.get('BaseResp') or {})
|
||||
if code == 0:
|
||||
return True, 'ok'
|
||||
msg = data.get('status_msg') or base.get('StatusMessage') or str(data)
|
||||
if code == config.RECORD_LIMIT_CODE:
|
||||
config.log('导出记录已达平台上限,删最早 5 条后重试', 'WARN')
|
||||
_delete_oldest(page, config.WITHDRAW_DOWNLOAD_TYPE, 5)
|
||||
continue
|
||||
# 业务错误重试不会变好,直接返回,避免重复创建导出任务
|
||||
return False, msg
|
||||
return False, msg or '网络异常,未拿到导出响应'
|
||||
|
||||
|
||||
def _wait_record(page, download_type, match):
|
||||
"""轮询导出记录,等 status=2(生成完成)后返回记录;match(rec) 用来认本次任务。"""
|
||||
deadline = time.time() + config.RECORD_SECONDS
|
||||
last_status = None
|
||||
while time.time() < deadline:
|
||||
infos = _list_records(page, download_type)
|
||||
hit = next((x for x in infos if match(x)), None)
|
||||
if hit:
|
||||
status = hit.get('status')
|
||||
if status != last_status:
|
||||
last_status = status
|
||||
config.log(f'导出任务状态={status}({hit.get("file_name")})')
|
||||
if status == 2 and hit.get('file_url'):
|
||||
return hit
|
||||
if status not in (1, 2):
|
||||
config.log(f'导出任务异常:{hit}', 'WARN')
|
||||
return None
|
||||
else:
|
||||
config.log('导出记录里还没出现本次任务,继续等…', 'DEBUG')
|
||||
time.sleep(config.RECORD_POLL)
|
||||
config.log(f'等待导出生成超时({config.RECORD_SECONDS}s)', 'WARN')
|
||||
return None
|
||||
|
||||
|
||||
def _download(file_url, save_path):
|
||||
"""预签名地址直下,返回字节数(失败 0)。"""
|
||||
headers = {
|
||||
'User-Agent': ('Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 '
|
||||
'(KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36'),
|
||||
'Accept': '*/*',
|
||||
}
|
||||
os.makedirs(os.path.dirname(save_path), exist_ok=True)
|
||||
for attempt in range(1, config.RETRY_MAX + 1):
|
||||
try:
|
||||
resp = requests.get(file_url, headers=headers, timeout=300, stream=True)
|
||||
if resp.status_code != 200:
|
||||
config.log(f'下载失败:HTTP {resp.status_code}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
continue
|
||||
tmp = save_path + '.part'
|
||||
with open(tmp, 'wb') as f:
|
||||
for chunk in resp.iter_content(128 * 1024):
|
||||
if chunk:
|
||||
f.write(chunk)
|
||||
os.replace(tmp, save_path)
|
||||
size = os.path.getsize(save_path)
|
||||
if size < 1024:
|
||||
config.log(f'文件异常小({size} 字节),重试 {attempt}/{config.RETRY_MAX}', 'WARN')
|
||||
try:
|
||||
os.remove(save_path)
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(2)
|
||||
continue
|
||||
return size
|
||||
except Exception as e:
|
||||
config.log(f'下载异常:{e}({attempt}/{config.RETRY_MAX})', 'WARN')
|
||||
time.sleep(2)
|
||||
return 0
|
||||
|
||||
|
||||
def _day_bounds(date_from, date_to):
|
||||
"""自然日区间 → 秒级时间戳(00:00:00 ~ 23:59:59)。"""
|
||||
start_ts = int(time.mktime(time.strptime(date_from + ' 00:00:00', '%Y-%m-%d %H:%M:%S')))
|
||||
end_ts = int(time.mktime(time.strptime(date_to + ' 23:59:59', '%Y-%m-%d %H:%M:%S')))
|
||||
return start_ts, end_ts
|
||||
|
||||
|
||||
def _save_record(record, save_dir, default_name, label):
|
||||
"""把生成好的记录下载落盘,返回统一结果 dict。"""
|
||||
download_id = str(record.get('download_id') or '')
|
||||
file_name = record.get('file_name') or default_name
|
||||
safe_name = str(file_name).replace('/', '_').replace('\\', '_')
|
||||
save_path = os.path.join(save_dir, safe_name)
|
||||
size = _download(record.get('file_url'), save_path)
|
||||
if not size:
|
||||
return {'ok': False, 'message': f'{label}文件下载失败', 'path': '',
|
||||
'download_id': download_id, 'file_name': safe_name}
|
||||
config.log(f'已下载:{save_path}({size / 1024:.0f} KB)')
|
||||
return {'ok': True, 'message': f'{label}已导出:{safe_name}', 'path': save_path,
|
||||
'download_id': download_id, 'file_name': safe_name, 'size': size}
|
||||
|
||||
|
||||
def run(page, date_from, date_to, save_dir=None, record_limit=None):
|
||||
"""导出指定「核销时间」区间的核销明细并下载。
|
||||
|
||||
date_from/date_to:YYYY-MM-DD;核销时间按自然日取整(00:00:00 ~ 23:59:59)。
|
||||
record_limit:导出记录保留条数(超出则先删最早的),默认 config.RECORD_LIMIT_VERIFY。
|
||||
返回 {ok, message, path, download_id, file_name}
|
||||
"""
|
||||
save_dir = save_dir or config.WORK_DIR
|
||||
limit = int(record_limit or config.RECORD_LIMIT_VERIFY)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
start_ts, end_ts = _day_bounds(date_from, date_to)
|
||||
|
||||
_ensure_order_page(page)
|
||||
config.log(f'发起核销明细导出:核销时间 {date_from} ~ {date_to}')
|
||||
_ensure_capacity(page, config.DOWNLOAD_TYPE, limit)
|
||||
struct = _create_export(page, start_ts, end_ts)
|
||||
if not struct:
|
||||
return {'ok': False, 'message': '发起导出失败(接口未返回 download_id)', 'path': ''}
|
||||
download_id = str(struct.get('download_id'))
|
||||
file_name = struct.get('file_name') or f'核销明细_{date_from}_{date_to}.xlsx'
|
||||
config.log(f'导出任务已创建:download_id={download_id},文件名={file_name}')
|
||||
|
||||
record = _wait_record(page, config.DOWNLOAD_TYPE,
|
||||
lambda x: str(x.get('download_id')) == download_id)
|
||||
if not record:
|
||||
return {'ok': False, 'message': '导出任务未生成完成', 'path': '',
|
||||
'download_id': download_id, 'file_name': file_name}
|
||||
return _save_record(record, save_dir, file_name, '核销明细')
|
||||
|
||||
|
||||
def run_withdraw(page, date_from, date_to, save_dir=None, record_limit=None):
|
||||
"""导出指定区间的「提现记录」(资金账户交易提现记录)并下载。
|
||||
|
||||
该接口不回 download_id,创建后按 generate_start_time 找最新那条记录。
|
||||
record_limit:导出记录保留条数,默认 config.RECORD_LIMIT_WITHDRAW。
|
||||
"""
|
||||
save_dir = save_dir or config.WORK_DIR
|
||||
limit = int(record_limit or config.RECORD_LIMIT_WITHDRAW)
|
||||
os.makedirs(save_dir, exist_ok=True)
|
||||
start_ts, end_ts = _day_bounds(date_from, date_to)
|
||||
|
||||
_ensure_withdraw_page(page)
|
||||
config.log(f'发起提现记录导出:{date_from} ~ {date_to}')
|
||||
_ensure_capacity(page, config.WITHDRAW_DOWNLOAD_TYPE, limit)
|
||||
before = int(time.time()) - 5
|
||||
ok, msg = _create_withdraw(page, start_ts, end_ts)
|
||||
if not ok:
|
||||
return {'ok': False, 'message': f'发起提现记录导出失败:{msg}', 'path': ''}
|
||||
|
||||
record = _wait_record(page, config.WITHDRAW_DOWNLOAD_TYPE,
|
||||
lambda x: int(x.get('generate_start_time') or 0) >= before)
|
||||
if not record:
|
||||
return {'ok': False, 'message': '提现记录导出任务未生成完成', 'path': ''}
|
||||
config.log(f'导出任务已创建:download_id={record.get("download_id")},'
|
||||
f'文件名={record.get("file_name")}')
|
||||
return _save_record(record, save_dir,
|
||||
f'资金账户交易提现记录_{date_from}_{date_to}.xlsx', '提现记录')
|
||||
@@ -0,0 +1,246 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""抖音来客登录态:打开登录页 → 人工登录(含验证码/滑块/扫码)→ 检测完成 → 落盘 cookies/票据。
|
||||
|
||||
实测链路(2026-10-28):
|
||||
https://life.douyin.com/p/login 登录页(账密 / 短信验证码 / 扫码)
|
||||
sso.douyin.com / passport.douyin.com
|
||||
登录成功后跳 https://life.douyin.com/p/home?groupid=...,期间可能短暂回跳登录页
|
||||
|
||||
判定规则(三条同时满足):
|
||||
1) 当前 URL 是 life.douyin.com 的非登录页;
|
||||
2) douyin 域下存在会话票据 Cookie(sessionid* / sid_tt* / sid_guard*);
|
||||
3) 连续稳定 BACKEND_STABLE 秒,期间没有被踢回登录页。
|
||||
|
||||
落盘(%LOCALAPPDATA%\\37duAutomation\\.sessions\\douyin_*):
|
||||
douyin_cookies.json / douyin_cookies_header.txt / douyin_tokens.json / douyin_session_meta.json
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from .. import config
|
||||
|
||||
|
||||
def _ensure_dir(path):
|
||||
if path:
|
||||
os.makedirs(path, exist_ok=True)
|
||||
|
||||
|
||||
def _atomic_write(path, text):
|
||||
"""原子写:先写临时文件再整体替换,避免中断留下半截快照(半截快照必然登录失效)。"""
|
||||
_ensure_dir(os.path.dirname(path))
|
||||
tmp = f'{path}.tmp'
|
||||
with open(tmp, 'w', encoding='utf-8') as f:
|
||||
f.write(text)
|
||||
os.replace(tmp, path)
|
||||
|
||||
|
||||
def _host(url):
|
||||
try:
|
||||
return (url or '').split('://', 1)[-1].split('/', 1)[0].split('?', 1)[0].lower()
|
||||
except Exception:
|
||||
return ''
|
||||
|
||||
|
||||
def classify(url):
|
||||
"""页面状态:login(登录页/统一登录域)/ backend(来客后台)/ other。"""
|
||||
low = (url or '').strip().lower()
|
||||
if not low.startswith('http'):
|
||||
return 'other'
|
||||
if any(h in low for h in config.PASSPORT_HINTS):
|
||||
return 'login'
|
||||
host = _host(low)
|
||||
if host.endswith(config.BACKEND_HOST):
|
||||
path = low.split(host, 1)[-1]
|
||||
if any(p in path for p in config.LOGIN_PAGE_HINTS):
|
||||
return 'login'
|
||||
return 'backend'
|
||||
return 'other'
|
||||
|
||||
|
||||
def _cookies(page):
|
||||
try:
|
||||
return page.cookies(all_domains=True) or []
|
||||
except Exception as e:
|
||||
config.log(f'读取 Cookies 失败:{e}', 'WARN')
|
||||
return []
|
||||
|
||||
|
||||
def _has_session_cookie(cookies):
|
||||
"""douyin 域下是否存在登录票据 Cookie(名字带 _ls 等分区后缀,按前缀匹配)。"""
|
||||
for c in cookies:
|
||||
name = (c.get('name') or '').strip().lower()
|
||||
if name.startswith(config.SESSION_COOKIE_PREFIXES) and c.get('value') \
|
||||
and 'douyin.com' in (c.get('domain') or ''):
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
def _ticket_cookies(cookies):
|
||||
out = []
|
||||
for c in cookies:
|
||||
name = (c.get('name') or '').strip()
|
||||
low = name.lower()
|
||||
if not name or not c.get('value'):
|
||||
continue
|
||||
if any(k in low for k in config.IGNORE_KEY_HINTS):
|
||||
continue
|
||||
if any(k in low for k in config.TICKET_KEY_HINTS):
|
||||
out.append(name)
|
||||
return sorted(set(out))
|
||||
|
||||
|
||||
def _cookie_header(cookies):
|
||||
"""按浏览器原始顺序拼出 douyin 域 Cookie 头(passport/埋点域名不要)。"""
|
||||
skip = ('passport', 'sso', 'report', 'monitor', 'lx', 'dreport', 'open.douyin')
|
||||
pairs = [f'{c.get("name")}={c.get("value")}' for c in cookies
|
||||
if c.get('name')
|
||||
and 'douyin.com' in (c.get('domain') or '')
|
||||
and not any(s in (c.get('domain') or '') for s in skip)]
|
||||
return '; '.join(pairs) if pairs else None
|
||||
|
||||
|
||||
def _read_storage(page):
|
||||
try:
|
||||
raw = page.run_js('''
|
||||
const dump = (store) => {
|
||||
const data = {};
|
||||
for (let i = 0; i < store.length; i++) {
|
||||
const k = store.key(i);
|
||||
const v = store.getItem(k);
|
||||
if (v && v.length < 100000) data[k] = v;
|
||||
}
|
||||
return data;
|
||||
};
|
||||
return JSON.stringify({
|
||||
localStorage: dump(window.localStorage),
|
||||
sessionStorage: dump(window.sessionStorage),
|
||||
});
|
||||
''')
|
||||
return json.loads(raw) if raw else {}
|
||||
except Exception as e:
|
||||
config.log(f'读取 storage 失败(不影响 Cookies):{e}', 'WARN')
|
||||
return {}
|
||||
|
||||
|
||||
def _save_login_state(page):
|
||||
cookies = _cookies(page)
|
||||
_ensure_dir(config.SESSIONS_DIR)
|
||||
if cookies:
|
||||
_atomic_write(config.COOKIE_FILE, json.dumps(cookies, ensure_ascii=False, indent=2))
|
||||
config.log(f'已保存 {len(cookies)} 个 Cookies → {config.COOKIE_FILE}')
|
||||
else:
|
||||
config.log('未取到任何 Cookies(登录态可能未生效)', 'WARN')
|
||||
|
||||
header = _cookie_header(cookies)
|
||||
if header:
|
||||
_atomic_write(config.COOKIE_HEADER_FILE, header)
|
||||
config.log(f'已保存 douyin 域 Cookie 头({header.count(";") + 1} 项)')
|
||||
|
||||
storage = _read_storage(page)
|
||||
ls, ss = (storage.get('localStorage') or {}), (storage.get('sessionStorage') or {})
|
||||
_atomic_write(config.TOKEN_FILE, json.dumps({
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'localStorage': ls,
|
||||
'sessionStorage': ss,
|
||||
}, ensure_ascii=False, indent=2))
|
||||
|
||||
domains = {}
|
||||
for c in cookies:
|
||||
d = c.get('domain') or '(空)'
|
||||
domains[d] = domains.get(d, 0) + 1
|
||||
summary = {
|
||||
'saved_at': time.strftime('%Y-%m-%d %H:%M:%S'),
|
||||
'url': page.url,
|
||||
'title': (getattr(page, 'title', '') or ''),
|
||||
'cookie_count': len(cookies),
|
||||
'cookie_domains': domains,
|
||||
'has_session_cookie': _has_session_cookie(cookies),
|
||||
'ticket_cookies': _ticket_cookies(cookies),
|
||||
'cookie_names': sorted({c.get('name') for c in cookies if c.get('name')}),
|
||||
'storage_keys': {'localStorage': sorted(ls.keys()), 'sessionStorage': sorted(ss.keys())},
|
||||
}
|
||||
_atomic_write(config.META_FILE, json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
config.log(f'登录态已落盘:{len(cookies)} 个 Cookie,'
|
||||
f'localStorage {len(ls)} 项 / sessionStorage {len(ss)} 项')
|
||||
return summary
|
||||
|
||||
|
||||
def _wait_backend(page):
|
||||
"""等人工完成「登录 + 验证码」,返回 True/False。"""
|
||||
deadline = time.time() + config.LOGIN_WAIT
|
||||
last_url, last_state = None, None
|
||||
backend_since = None
|
||||
login_hint_at = 0.0
|
||||
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
url = page.url or ''
|
||||
except Exception:
|
||||
url = ''
|
||||
state = classify(url)
|
||||
|
||||
if url != last_url:
|
||||
last_url = url
|
||||
config.log(f'页面状态 = {state} | {url}', 'DEBUG')
|
||||
|
||||
if state != last_state:
|
||||
last_state = state
|
||||
if state == 'login' and time.time() - login_hint_at > 30:
|
||||
login_hint_at = time.time()
|
||||
config.log('请在浏览器窗口内完成登录'
|
||||
'(账号密码 / 短信验证码 / 扫码 / 滑块均可,脚本不碰表单)')
|
||||
|
||||
if state == 'backend' and _has_session_cookie(_cookies(page)):
|
||||
if backend_since is None:
|
||||
backend_since = time.time()
|
||||
config.log(f'已进来客后台且票据已种下,等待 {config.BACKEND_STABLE}s '
|
||||
f'确认不会再被踢回登录页…')
|
||||
elif time.time() - backend_since >= config.BACKEND_STABLE:
|
||||
return True
|
||||
else:
|
||||
if backend_since is not None:
|
||||
config.log('离开后台或票据消失,重新计时', 'WARN')
|
||||
backend_since = None
|
||||
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
return False
|
||||
|
||||
|
||||
def ensure_login(page, force=False):
|
||||
"""确保 page 已进入来客后台;必要时停在前台等人工登录。
|
||||
|
||||
force=True 跳过 profile 残留会话试探,直接等人工登录(换账号/排查问题用)。
|
||||
"""
|
||||
config.log(f'打开抖音来客:{config.HOME_URL}')
|
||||
page.get(config.HOME_URL)
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
|
||||
# 复用 profile 残留会话:能直接进后台就不用打扰用户
|
||||
if not force:
|
||||
reuse_end = time.time() + config.BACKEND_STABLE + 10
|
||||
while time.time() < reuse_end:
|
||||
state = classify(page.url)
|
||||
if state == 'backend' and _has_session_cookie(_cookies(page)):
|
||||
config.log(f'profile 残留会话有效,直接复用(URL={page.url})')
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
_save_login_state(page)
|
||||
return True, '复用缓存登录态'
|
||||
if state == 'login':
|
||||
break
|
||||
time.sleep(config.POLL_SECONDS)
|
||||
config.log('profile 无有效会话,转人工登录', 'WARN')
|
||||
|
||||
config.log(f'需要人工登录(含验证码/滑块),最多等待 {config.LOGIN_WAIT} 秒…')
|
||||
if not _wait_backend(page):
|
||||
cookies = _cookies(page)
|
||||
config.log('当前 Cookie:' +
|
||||
', '.join(sorted({c.get('name') for c in cookies if c.get('name')})), 'WARN')
|
||||
return False, '登录超时(未进入来客后台或会话票据缺失)'
|
||||
|
||||
time.sleep(config.SETTLE_WAIT)
|
||||
if classify(page.url) != 'backend':
|
||||
return False, '登录态未稳定(落盘前离开后台)'
|
||||
_save_login_state(page)
|
||||
return True, '登录成功'
|
||||
@@ -0,0 +1,89 @@
|
||||
{
|
||||
"schema_version": 1,
|
||||
"id": "xq0042",
|
||||
"name": "抖音平台核对",
|
||||
"version": "0.6.2",
|
||||
"description": "抖音来客(life.douyin.com)数据自动导出:打开官方页面人工登录(含验证码/滑块),按日期区间导出核销明细与提现记录,轮询生成完成后下载到本机目录;导出记录超过保留阈值自动删最早的(阈值可在界面改);并入台账与核对统计待补齐。",
|
||||
"category": "财务",
|
||||
"icon": "",
|
||||
"platform": "",
|
||||
"uses_month": false,
|
||||
"runTimeoutSeconds": 0,
|
||||
"ui": true,
|
||||
"capabilities": ["xq0042"],
|
||||
"permissions": {
|
||||
"platforms": []
|
||||
},
|
||||
"fields": {
|
||||
"type": "object",
|
||||
"properties": {
|
||||
"date_from": {
|
||||
"type": "string",
|
||||
"title": "核销时间-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"date_to": {
|
||||
"type": "string",
|
||||
"title": "核销时间-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"withdraw_from": {
|
||||
"type": "string",
|
||||
"title": "提现时间-开始日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=昨天"
|
||||
},
|
||||
"withdraw_to": {
|
||||
"type": "string",
|
||||
"title": "提现时间-结束日期",
|
||||
"default": "",
|
||||
"description": "YYYY-MM-DD;留空=今天"
|
||||
},
|
||||
"export_verify": {
|
||||
"type": "boolean",
|
||||
"title": "导出核销明细",
|
||||
"default": true,
|
||||
"description": "履约管理订单列表 → 核销明细(按核销时间区间)"
|
||||
},
|
||||
"export_withdraw": {
|
||||
"type": "boolean",
|
||||
"title": "导出提现记录",
|
||||
"default": true,
|
||||
"description": "财务 → 导出记录 → 余额提现记录(资金账户交易提现记录)"
|
||||
},
|
||||
"record_limit_verify": {
|
||||
"type": "integer",
|
||||
"title": "核销明细-导出记录保留条数",
|
||||
"default": 60,
|
||||
"description": "导出前查记录,超过该条数就删最早的、只留最新 N 条;核销明细暂无平台 30 条限制,默认 60"
|
||||
},
|
||||
"record_limit_withdraw": {
|
||||
"type": "integer",
|
||||
"title": "提现记录-导出记录保留条数",
|
||||
"default": 25,
|
||||
"description": "导出前查记录,超过该条数就删最早的、只留最新 N 条;平台硬上限 30,默认 25 留余量"
|
||||
},
|
||||
"save_dir": {
|
||||
"type": "string",
|
||||
"title": "保存目录",
|
||||
"default": "",
|
||||
"description": "留空=D:\\资料\\财务\\抖音平台核对"
|
||||
},
|
||||
"force_login": {
|
||||
"type": "boolean",
|
||||
"title": "强制重新登录",
|
||||
"default": false,
|
||||
"description": "忽略浏览器里残留的登录态,直接等人工重新登录(换账号/排查登录问题时用)"
|
||||
},
|
||||
"debug_mode": {
|
||||
"type": "boolean",
|
||||
"title": "调试日志",
|
||||
"default": false,
|
||||
"description": "输出完整调试日志(含页面跳转轨迹,默认关闭)"
|
||||
}
|
||||
},
|
||||
"required": []
|
||||
}
|
||||
}
|
||||
@@ -1,2 +1 @@
|
||||
DrissionPage>=4.1
|
||||
requests>=2.28
|
||||
@@ -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>抖音平台核对</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": "xq0042-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,265 @@
|
||||
<template>
|
||||
<div class="page">
|
||||
<!-- 内联提示 -->
|
||||
<div v-if="notice" class="notice" :class="'is-' + notice.type">
|
||||
<span class="n-ico">{{ notice.type === 'ok' ? '✓' : (notice.type === 'error' ? '✕' : '!') }}</span>
|
||||
<span>{{ notice.text }}</span>
|
||||
</div>
|
||||
|
||||
<!-- 执行配置(头部含方案工具:方案供「定时任务」引用,到点自动取方案最新参数) -->
|
||||
<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">
|
||||
<rect x="5" y="4" width="14" height="17" rx="2" />
|
||||
<path d="M9 4V3h6v1" />
|
||||
<path d="m9 13 2 2 4-4" />
|
||||
</svg>
|
||||
</span>
|
||||
<div class="title-txts">
|
||||
<div class="title-txt">执行配置</div>
|
||||
<div class="title-sub">参数自动保存到本机,方案供定时任务到点引用</div>
|
||||
</div>
|
||||
</div>
|
||||
<div class="head-tools">
|
||||
<span class="saved" :class="{ 'is-idle': !lastSavedAt }">
|
||||
<i />{{ lastSavedAt ? '已保存 ' + lastSavedAt : '尚未保存' }}
|
||||
</span>
|
||||
<el-select v-model="schemeSel" class="scheme-sel" size="small" :disabled="running"
|
||||
placeholder="当前配置(自动保存)" @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">
|
||||
<!-- 01 导出范围 -->
|
||||
<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="grid grid-switch">
|
||||
<el-form-item label="核销明细">
|
||||
<el-switch v-model="form.export_verify" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="提现记录">
|
||||
<el-switch v-model="form.export_withdraw" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid grid-date">
|
||||
<el-form-item label="核销明细 核销时间">
|
||||
<el-date-picker v-model="verifyRange" type="daterange" value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
|
||||
:disabled="running || !form.export_verify" />
|
||||
</el-form-item>
|
||||
<el-form-item label="提现记录 提现时间">
|
||||
<el-date-picker v-model="withdrawRange" type="daterange" value-format="YYYY-MM-DD"
|
||||
start-placeholder="开始日期" end-placeholder="结束日期" range-separator="至"
|
||||
:disabled="running || !form.export_withdraw" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid grid-date">
|
||||
<el-form-item label="保存目录">
|
||||
<el-input v-model="form.save_dir" :disabled="running"
|
||||
placeholder="留空 = D:\资料\财务\抖音平台核对" clearable />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
<b>核销明细</b>:履约管理订单列表按核销时间导出;<b>提现记录</b>:财务 → 导出记录里的
|
||||
「余额提现记录」(资金账户交易提现记录),按其提现时间导出。<br>
|
||||
两类数据分别落到保存目录(文件名由平台生成)。<br>
|
||||
默认昨天到今天;今天的核销数据当天可导,如要完整日结数据建议选到昨天。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 02 执行设置 -->
|
||||
<section class="sec">
|
||||
<div class="sec-head">
|
||||
<span class="sec-badge">02</span>
|
||||
<span class="sec-name">执行设置</span>
|
||||
<span class="sec-line" />
|
||||
</div>
|
||||
<div class="grid grid-switch">
|
||||
<el-form-item label="强制重新登录">
|
||||
<el-switch v-model="form.force_login" :disabled="running" />
|
||||
</el-form-item>
|
||||
<el-form-item label="调试日志">
|
||||
<el-switch v-model="form.debug_mode" :disabled="running" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="grid grid-date">
|
||||
<el-form-item label="核销明细-导出记录保留条数">
|
||||
<el-input-number v-model="form.record_limit_verify" :min="5" :step="5"
|
||||
:disabled="running" class="wide" />
|
||||
</el-form-item>
|
||||
<el-form-item label="提现记录-导出记录保留条数">
|
||||
<el-input-number v-model="form.record_limit_withdraw" :min="5" :step="5"
|
||||
:disabled="running" class="wide" />
|
||||
</el-form-item>
|
||||
</div>
|
||||
<div class="tip">
|
||||
登录态默认复用本机浏览器档案,仅在过期时才需要人工登录(含验证码/滑块)。<br>
|
||||
勾选<b>强制重新登录</b>会忽略残留登录态直接等人工登录,换账号或排查登录问题时用;
|
||||
<b>调试日志</b>输出页面跳转轨迹,日常保持关闭。<br>
|
||||
导出前先查该类的导出记录,<b>超过保留条数就删最早的、只留最新 N 条</b>;
|
||||
提现记录平台硬上限 30 条,默认 25 留余量。删除会限流(每条间隔 1~2 秒、单次最多 20 条)。
|
||||
</div>
|
||||
</section>
|
||||
|
||||
<!-- 操作 -->
|
||||
<div class="actions">
|
||||
<el-button type="primary" class="btn-run" :loading="running" @click="start">
|
||||
{{ running ? '执行中 ' + progress + '%' : '一键执行' }}
|
||||
</el-button>
|
||||
<el-button v-if="running" type="danger" plain :loading="stopping"
|
||||
@click="forceStop">强制停止</el-button>
|
||||
<span class="spacer" />
|
||||
<el-button :disabled="running" @click="restoreLastFields">恢复上次参数</el-button>
|
||||
<el-button :disabled="running" @click="saveNow(true)">保存配置</el-button>
|
||||
<el-button text :disabled="running" @click="resetDefaults">恢复默认</el-button>
|
||||
</div>
|
||||
</el-form>
|
||||
</el-card>
|
||||
|
||||
<!-- 运行状态 -->
|
||||
<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>
|
||||
</div>
|
||||
</template>
|
||||
|
||||
<script setup>
|
||||
import { computed, watch } from 'vue'
|
||||
import { ElMessage } from 'element-plus'
|
||||
import { usePluginUI } from './usePluginUI'
|
||||
|
||||
// 默认日期区间:昨天 ~ 今天
|
||||
function defaultRange() {
|
||||
const today = new Date()
|
||||
const y = new Date(today.getTime() - 86400000)
|
||||
const fmt = (d) => `${d.getFullYear()}-${String(d.getMonth() + 1).padStart(2, '0')}-${String(d.getDate()).padStart(2, '0')}`
|
||||
return [fmt(y), fmt(today)]
|
||||
}
|
||||
|
||||
// 默认日期区间:昨天 ~ 今天(首屏即带出,不依赖配置接口)
|
||||
const DEFAULTS = () => {
|
||||
const [from, to] = defaultRange()
|
||||
return {
|
||||
date_from: from,
|
||||
date_to: to,
|
||||
withdraw_from: from,
|
||||
withdraw_to: to,
|
||||
export_verify: true,
|
||||
export_withdraw: true,
|
||||
record_limit_verify: 60,
|
||||
record_limit_withdraw: 25,
|
||||
save_dir: '',
|
||||
force_login: false,
|
||||
debug_mode: false,
|
||||
}
|
||||
}
|
||||
|
||||
const {
|
||||
form, loaded, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
} = usePluginUI({
|
||||
defaults: DEFAULTS,
|
||||
validate() {
|
||||
if (!form.export_verify && !form.export_withdraw) {
|
||||
ElMessage.warning('请至少勾选一项要导出的内容(核销明细 / 提现记录)')
|
||||
return false
|
||||
}
|
||||
const pairs = []
|
||||
if (form.export_verify) pairs.push(['核销时间', form.date_from, form.date_to])
|
||||
if (form.export_withdraw) pairs.push(['提现时间', form.withdraw_from, form.withdraw_to])
|
||||
for (const [label, rawA, rawB] of pairs) {
|
||||
const a = (rawA || '').trim()
|
||||
const b = (rawB || '').trim()
|
||||
if (a && b && a > b) {
|
||||
ElMessage.warning(`${label}的开始日期不能晚于结束日期`)
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
},
|
||||
buildPayload(f) {
|
||||
const t = (v) => (v || '').trim()
|
||||
const n = (v, d) => {
|
||||
const x = Number(v)
|
||||
return Number.isFinite(x) && x >= 5 ? Math.floor(x) : d
|
||||
}
|
||||
return {
|
||||
date_from: t(f.date_from),
|
||||
date_to: t(f.date_to),
|
||||
withdraw_from: t(f.withdraw_from),
|
||||
withdraw_to: t(f.withdraw_to),
|
||||
export_verify: !!f.export_verify,
|
||||
export_withdraw: !!f.export_withdraw,
|
||||
record_limit_verify: n(f.record_limit_verify, 60),
|
||||
record_limit_withdraw: n(f.record_limit_withdraw, 25),
|
||||
save_dir: t(f.save_dir),
|
||||
force_login: !!f.force_login,
|
||||
debug_mode: !!f.debug_mode,
|
||||
}
|
||||
},
|
||||
})
|
||||
|
||||
function start() {
|
||||
run()
|
||||
}
|
||||
|
||||
// 日期区间选择器 ↔ 两个字段(plugin.json 以 date_from/to、withdraw_from/to 为契约)
|
||||
const verifyRange = computed({
|
||||
get: () => {
|
||||
const a = form.date_from
|
||||
const b = form.date_to
|
||||
return (a || b) ? [a || null, b || null] : null
|
||||
},
|
||||
set: (v) => {
|
||||
form.date_from = (v && v[0]) || ''
|
||||
form.date_to = (v && v[1]) || ''
|
||||
},
|
||||
})
|
||||
|
||||
const withdrawRange = computed({
|
||||
get: () => {
|
||||
const a = form.withdraw_from
|
||||
const b = form.withdraw_to
|
||||
return (a || b) ? [a || null, b || null] : null
|
||||
},
|
||||
set: (v) => {
|
||||
form.withdraw_from = (v && v[0]) || ''
|
||||
form.withdraw_to = (v && v[1]) || ''
|
||||
},
|
||||
})
|
||||
|
||||
// 配置加载完成后:日期为空则带出「昨天~今天」
|
||||
watch(loaded, (v) => {
|
||||
if (!v) return
|
||||
const [from, to] = defaultRange()
|
||||
if (!form.date_from && !form.date_to) {
|
||||
form.date_from = from
|
||||
form.date_to = to
|
||||
}
|
||||
if (!form.withdraw_from && !form.withdraw_to) {
|
||||
form.withdraw_from = from
|
||||
form.withdraw_to = to
|
||||
}
|
||||
}, { immediate: true })
|
||||
</script>
|
||||
@@ -0,0 +1 @@
|
||||
export const PLUGIN_ID = 'xq0042'
|
||||
@@ -0,0 +1,8 @@
|
||||
import { createApp } from 'vue'
|
||||
import ElementPlus from 'element-plus'
|
||||
import 'element-plus/dist/index.css'
|
||||
// 注意顺序:style.css 必须在 element-plus 之后引入,才能覆盖 --el-* 变量映射到壳子 token
|
||||
import './style.css'
|
||||
import App from './App.vue'
|
||||
|
||||
createApp(App).use(ElementPlus).mount('#app')
|
||||
@@ -0,0 +1,524 @@
|
||||
/* ============================================================
|
||||
插件 UI 基础样式(规范 v2)
|
||||
- 上半部分:壳子 design token 子集(权威源 desktop/electron-shell/design-app/styles.css)
|
||||
- 中间:Element Plus 变量映射到壳子 token(iframe 内与壳子同一套皮肤)
|
||||
- 下半部分:标准版式骨架(panel / sec / grid / actions),与其它插件保持一致
|
||||
规则:插件内只用 var(--xxx),不写字面色值。
|
||||
============================================================ */
|
||||
|
||||
:root {
|
||||
/* ---- 底色与卡面 ---- */
|
||||
--canvas: #F2F4F8;
|
||||
--surface: #FFFFFF;
|
||||
--field: #F5F6FA;
|
||||
--subtle: #F7F8FC;
|
||||
|
||||
/* ---- 描边 ---- */
|
||||
--line: #E8EAF1;
|
||||
--line-soft: #F0F2F7;
|
||||
--line-btn: #E3E6EF;
|
||||
|
||||
/* ---- 文字四阶 ---- */
|
||||
--t1: #12141B;
|
||||
--t2: #3C4250;
|
||||
--t3: #6E7686;
|
||||
--t4: #A3AAB8;
|
||||
--t5: #C6CBD6;
|
||||
|
||||
/* ---- 主色(靛蓝) ---- */
|
||||
--brand: #4F5AE8;
|
||||
--brand-ink: #3D47D4;
|
||||
--brand-soft: #EEF0FE;
|
||||
--brand-hover: #4550E0;
|
||||
|
||||
/* ---- 语义色 ---- */
|
||||
--good: #0E9F76;
|
||||
--good-soft: #EBF7F2;
|
||||
--good-line: #D3EDE3;
|
||||
--warn: #D98218;
|
||||
--warn-soft: #FDF3E4;
|
||||
--danger: #E5484D;
|
||||
--danger-soft: #FDEDED;
|
||||
--danger-line: #F6D7D8;
|
||||
|
||||
/* ---- 圆角 ---- */
|
||||
--r-field: 9px;
|
||||
--r-btn: 10px;
|
||||
--r-sub: 12px;
|
||||
--r-card: 14px;
|
||||
--r-pill: 999px;
|
||||
|
||||
/* ---- 阴影 ---- */
|
||||
--sh-card: 0 2px 8px rgba(18, 20, 31, .05);
|
||||
--sh-brand: 0 4px 12px rgba(79, 89, 232, .28);
|
||||
--sh-brand-sm: 0 2px 8px rgba(79, 89, 232, .24);
|
||||
|
||||
/* ---- 字体 ---- */
|
||||
--f-cn: "PingFang SC", "HarmonyOS Sans SC", "Microsoft YaHei", "Noto Sans SC", system-ui, -apple-system, sans-serif;
|
||||
--f-num: "Inter", "SF Pro Display", -apple-system, "Segoe UI", Roboto, Helvetica, Arial, sans-serif;
|
||||
|
||||
/* ---- 间距 ---- */
|
||||
--space-1: 4px;
|
||||
--space-1-5: 6px;
|
||||
--space-2: 8px;
|
||||
--space-2-5: 10px;
|
||||
--space-3: 12px;
|
||||
--space-4: 16px;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
Element Plus → 壳子 token 映射
|
||||
============================================================ */
|
||||
:root {
|
||||
--el-color-primary: var(--brand);
|
||||
--el-color-primary-light-3: #7A83EE;
|
||||
--el-color-primary-light-5: #A6ACF4;
|
||||
--el-color-primary-light-7: #C9CDF9;
|
||||
--el-color-primary-light-8: #DDE0FB;
|
||||
--el-color-primary-light-9: var(--brand-soft);
|
||||
--el-color-primary-dark-2: var(--brand-ink);
|
||||
|
||||
--el-color-success: var(--good);
|
||||
--el-color-success-light-9: var(--good-soft);
|
||||
--el-color-warning: var(--warn);
|
||||
--el-color-warning-light-9: var(--warn-soft);
|
||||
--el-color-danger: var(--danger);
|
||||
--el-color-danger-light-9: var(--danger-soft);
|
||||
--el-color-error: var(--danger);
|
||||
|
||||
--el-text-color-primary: var(--t1);
|
||||
--el-text-color-regular: var(--t2);
|
||||
--el-text-color-secondary: var(--t3);
|
||||
--el-text-color-placeholder: var(--t4);
|
||||
|
||||
--el-border-color: var(--line);
|
||||
--el-border-color-light: var(--line);
|
||||
--el-border-color-lighter: var(--line-soft);
|
||||
--el-border-color-extra-light: var(--line-soft);
|
||||
--el-fill-color-blank: var(--surface);
|
||||
--el-fill-color-light: var(--field);
|
||||
--el-bg-color: var(--surface);
|
||||
|
||||
--el-border-radius-base: var(--r-field);
|
||||
--el-border-radius-small: var(--r-field);
|
||||
--el-font-family: var(--f-cn);
|
||||
--el-font-size-base: 12.5px;
|
||||
--el-box-shadow-light: var(--sh-card);
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
基础重置
|
||||
============================================================ */
|
||||
* {
|
||||
box-sizing: border-box;
|
||||
}
|
||||
|
||||
html,
|
||||
body {
|
||||
margin: 0;
|
||||
padding: 0;
|
||||
background: var(--surface);
|
||||
color: var(--t1);
|
||||
font-family: var(--f-cn);
|
||||
font-size: 12.5px;
|
||||
line-height: 1.5;
|
||||
-webkit-font-smoothing: antialiased;
|
||||
}
|
||||
|
||||
#app {
|
||||
padding: 0;
|
||||
}
|
||||
|
||||
/* ============================================================
|
||||
页面骨架(与其它插件一致:panel + sec 分区 + grid 栅格 + actions)
|
||||
============================================================ */
|
||||
.page {
|
||||
width: 100%;
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: var(--space-3);
|
||||
/* 壳子 iframe 外层已有 padding,这里再留一层,避免内容贴着 iframe 边缘 */
|
||||
padding: 8px 16px 24px;
|
||||
}
|
||||
|
||||
/* ---------- 工具条:方案下拉 + 存为方案 + 删除 + 已保存胶囊 ---------- */
|
||||
.toolbar {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.toolbar .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* ---------- 主容器:无边框平铺,外框由壳子 iframe 提供 ---------- */
|
||||
.panel {
|
||||
background: transparent;
|
||||
border: none;
|
||||
box-shadow: none;
|
||||
border-radius: 0;
|
||||
}
|
||||
|
||||
.panel .el-card__header {
|
||||
padding: 4px 0 16px;
|
||||
border-bottom: 1px solid var(--line-soft);
|
||||
background: transparent;
|
||||
}
|
||||
|
||||
.panel .el-card__body {
|
||||
padding: 16px 0 4px;
|
||||
}
|
||||
|
||||
/* ---------- 卡片头部:标题 + 方案工具条 ---------- */
|
||||
.panel-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: space-between;
|
||||
gap: var(--space-3);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.panel-title {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-3);
|
||||
}
|
||||
|
||||
.title-ico {
|
||||
width: 34px;
|
||||
height: 34px;
|
||||
border-radius: var(--r-btn);
|
||||
display: flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.title-txts {
|
||||
display: flex;
|
||||
flex-direction: column;
|
||||
gap: 2px;
|
||||
}
|
||||
|
||||
.title-txt {
|
||||
font: 600 13.5px/1.25 var(--f-cn);
|
||||
color: var(--t1);
|
||||
}
|
||||
|
||||
.title-sub {
|
||||
font-size: 11.5px;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.head-tools {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
}
|
||||
|
||||
.scheme-sel {
|
||||
width: 200px;
|
||||
}
|
||||
|
||||
.saved {
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
gap: 6px;
|
||||
padding: 3px 10px;
|
||||
border-radius: var(--r-pill);
|
||||
background: var(--good-soft);
|
||||
border: 1px solid var(--good-line);
|
||||
color: var(--good);
|
||||
font-size: 11.5px;
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.saved i {
|
||||
width: 5px;
|
||||
height: 5px;
|
||||
border-radius: 50%;
|
||||
background: var(--good);
|
||||
}
|
||||
|
||||
/* 尚无保存记录:占位,保持卡片头右侧元素对齐 */
|
||||
.saved.is-idle {
|
||||
background: var(--subtle);
|
||||
border-color: var(--line);
|
||||
color: var(--t4);
|
||||
}
|
||||
|
||||
.saved.is-idle i {
|
||||
background: var(--t5);
|
||||
}
|
||||
|
||||
/* ---------- 分区 ---------- */
|
||||
.sec {
|
||||
margin-bottom: 20px;
|
||||
}
|
||||
|
||||
.sec:last-of-type {
|
||||
margin-bottom: 6px;
|
||||
}
|
||||
|
||||
.sec-head {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-bottom: 14px;
|
||||
}
|
||||
|
||||
.sec-badge {
|
||||
width: 23px;
|
||||
height: 23px;
|
||||
border-radius: 7px;
|
||||
display: inline-flex;
|
||||
align-items: center;
|
||||
justify-content: center;
|
||||
font: 600 11px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
background: var(--brand-soft);
|
||||
flex-shrink: 0;
|
||||
}
|
||||
|
||||
.sec-name {
|
||||
font: 600 13px/1.3 var(--f-cn);
|
||||
color: var(--t1);
|
||||
white-space: nowrap;
|
||||
}
|
||||
|
||||
.sec-line {
|
||||
flex: 1;
|
||||
height: 1px;
|
||||
background: linear-gradient(90deg, var(--line-soft), transparent);
|
||||
}
|
||||
|
||||
/* ---------- 栅格 ---------- */
|
||||
.grid {
|
||||
display: grid;
|
||||
grid-template-columns: repeat(auto-fit, minmax(260px, 1fr));
|
||||
gap: 0 18px;
|
||||
}
|
||||
|
||||
/* ---------- 开关栅格:每格 = 名称 + 开关(规范 §5.2 / §7) ---------- */
|
||||
.grid-switch {
|
||||
grid-template-columns: repeat(auto-fit, minmax(220px, 1fr));
|
||||
}
|
||||
|
||||
/* 日期区间与开关行之间留出呼吸 */
|
||||
.grid-date {
|
||||
margin-top: 16px;
|
||||
}
|
||||
|
||||
.grid .el-form-item {
|
||||
margin-bottom: 4px;
|
||||
}
|
||||
|
||||
.grid .el-form-item__label {
|
||||
padding-bottom: 6px !important;
|
||||
font-weight: 500;
|
||||
color: var(--t2);
|
||||
}
|
||||
|
||||
/* 栅格里的控件统一撑满 */
|
||||
.grid .el-input,
|
||||
.grid .el-select,
|
||||
.grid .el-input-number,
|
||||
.grid .el-date-editor {
|
||||
width: 100% !important;
|
||||
}
|
||||
|
||||
/* ---------- 提示 ---------- */
|
||||
.tip {
|
||||
margin-top: var(--space-2);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.65;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.tip b {
|
||||
color: var(--t2);
|
||||
font-weight: 600;
|
||||
}
|
||||
|
||||
/* ---------- 内联提示条(替代顶部大横幅) ---------- */
|
||||
.notice {
|
||||
display: flex;
|
||||
align-items: flex-start;
|
||||
gap: var(--space-2);
|
||||
padding: 10px 12px;
|
||||
border-radius: var(--r-field);
|
||||
border: 1px solid var(--line);
|
||||
background: var(--subtle);
|
||||
font-size: 12px;
|
||||
color: var(--t2);
|
||||
}
|
||||
|
||||
.notice .n-ico {
|
||||
flex: 0 0 auto;
|
||||
font-weight: 700;
|
||||
}
|
||||
|
||||
.notice.is-warn {
|
||||
background: var(--warn-soft);
|
||||
border-color: rgba(217, 130, 24, .24);
|
||||
color: #8A5B0E;
|
||||
}
|
||||
|
||||
.notice.is-error {
|
||||
background: var(--danger-soft);
|
||||
border-color: var(--danger-line);
|
||||
color: #CC3B40;
|
||||
}
|
||||
|
||||
.notice.is-ok {
|
||||
background: var(--good-soft);
|
||||
border-color: var(--good-line);
|
||||
color: var(--good);
|
||||
}
|
||||
|
||||
/* ---------- 执行摘要(操作区上方一行低调说明) ---------- */
|
||||
.plan {
|
||||
display: flex;
|
||||
align-items: baseline;
|
||||
gap: var(--space-2);
|
||||
font-size: 11.5px;
|
||||
line-height: 1.6;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.plan .p-tag {
|
||||
flex: 0 0 auto;
|
||||
font-weight: 600;
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
|
||||
.plan .p-text {
|
||||
min-width: 0;
|
||||
}
|
||||
|
||||
.plan.is-empty .p-text {
|
||||
color: var(--warn);
|
||||
}
|
||||
|
||||
/* ---------- 操作区 ---------- */
|
||||
.actions {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
flex-wrap: wrap;
|
||||
border-top: 1px dashed var(--line);
|
||||
padding-top: 18px;
|
||||
margin-top: 6px;
|
||||
}
|
||||
|
||||
.actions .spacer {
|
||||
flex: 1;
|
||||
}
|
||||
|
||||
/* 底部通用操作(恢复参数/保存/恢复默认),不重复画分隔线 */
|
||||
.actions--foot {
|
||||
border-top: none;
|
||||
padding-top: 0;
|
||||
margin-top: 0;
|
||||
}
|
||||
|
||||
.btn-run {
|
||||
min-width: 150px;
|
||||
height: 34px;
|
||||
border: none;
|
||||
border-radius: var(--r-btn);
|
||||
background: var(--brand);
|
||||
color: #fff;
|
||||
font: 600 12.5px/18px var(--f-cn);
|
||||
letter-spacing: 1px;
|
||||
box-shadow: var(--sh-brand);
|
||||
transition: background .15s, box-shadow .15s, transform .06s;
|
||||
}
|
||||
|
||||
.btn-run:hover {
|
||||
background: var(--brand-hover);
|
||||
}
|
||||
|
||||
.btn-run:active {
|
||||
transform: translateY(1px);
|
||||
box-shadow: var(--sh-brand-sm);
|
||||
}
|
||||
|
||||
.btn-run.is-loading {
|
||||
pointer-events: none;
|
||||
}
|
||||
|
||||
/* ---------- 运行状态:进度条 + 一行说明 ---------- */
|
||||
.status {
|
||||
padding: 14px 16px;
|
||||
border-radius: var(--r-sub);
|
||||
background: var(--brand-soft);
|
||||
border: 1px solid var(--line);
|
||||
}
|
||||
|
||||
.status-bar .el-progress-bar__outer {
|
||||
background: rgba(79, 89, 232, .14);
|
||||
}
|
||||
|
||||
.status-bar .el-progress-bar__inner {
|
||||
background: var(--brand);
|
||||
}
|
||||
|
||||
.status-row {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
margin-top: 8px;
|
||||
}
|
||||
|
||||
.status-txt {
|
||||
flex: 1;
|
||||
font-size: 12px;
|
||||
line-height: 1.5;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.status-pct {
|
||||
font: 600 13px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
font-variant-numeric: tabular-nums;
|
||||
}
|
||||
|
||||
/* ---------- 运行态一行文字(进度由壳子 RunIndicator 展示) ---------- */
|
||||
.runline {
|
||||
display: flex;
|
||||
align-items: center;
|
||||
gap: var(--space-2);
|
||||
font-size: 12px;
|
||||
color: var(--t3);
|
||||
}
|
||||
|
||||
.runline .pct {
|
||||
font: 600 12px/1 var(--f-num);
|
||||
color: var(--brand-ink);
|
||||
}
|
||||
|
||||
.pulse {
|
||||
width: 7px;
|
||||
height: 7px;
|
||||
border-radius: 50%;
|
||||
background: var(--brand);
|
||||
animation: pulse 1.4s ease-out infinite;
|
||||
}
|
||||
|
||||
@keyframes pulse {
|
||||
0% {
|
||||
box-shadow: 0 0 0 0 var(--brand-soft);
|
||||
}
|
||||
70% {
|
||||
box-shadow: 0 0 0 7px transparent;
|
||||
}
|
||||
100% {
|
||||
box-shadow: 0 0 0 0 transparent;
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,347 @@
|
||||
// 插件 UI 公共 kit v2(vendored 进各插件 ui-src,构建期内联,运行零外部依赖)。
|
||||
//
|
||||
// 与 v1 的差异(适配当前壳子):
|
||||
// 1. 新增 restoreLastFields():调 /api/plugins/<id>/last-fields 恢复上次执行参数(password 不落盘);
|
||||
// 2. 顶部大横幅 → 内联 notice:执行结果横幅、插件名/版本、运行 Indicator 已由壳子
|
||||
// (PageHead + 结果横幅 + RunIndicator)统一渲染,插件内不再重复;
|
||||
// 3. startRun 的 409 单独识别:壳子在 iframe fetch 上包了「入队确认」,用户取消会返回 409,
|
||||
// 不能再当成普通失败提示。
|
||||
//
|
||||
// 保留能力:本机当前配置(加载/防抖自动保存/恢复默认)、多配置方案(供定时任务按 config_id 引用)、
|
||||
// 执行状态机(执行/强停/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 Object.assign(new Error(msg), { code: res.status, status: res.status })
|
||||
}
|
||||
return res.json()
|
||||
}
|
||||
|
||||
// ---- 后端 API(同源,统一账户会话 cookie 自动携带)----
|
||||
const loadConfig = () => j(`/api/plugin-config/${PLUGIN_ID}`)
|
||||
const saveConfig = (data) => j(`/api/plugin-config/${PLUGIN_ID}`, {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify(data),
|
||||
})
|
||||
const loadLastFields = () => j(`/api/plugins/${PLUGIN_ID}/last-fields`)
|
||||
const listSchemes = () => j(`/api/plugin-configs?plugin_id=${encodeURIComponent(PLUGIN_ID)}`)
|
||||
const saveScheme = (name, fields) => j('/api/plugin-configs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, name, fields }),
|
||||
})
|
||||
const deleteScheme = (cfgId) =>
|
||||
j(`/api/plugin-configs/${encodeURIComponent(PLUGIN_ID)}/${encodeURIComponent(cfgId)}`, { method: 'DELETE' })
|
||||
const startRun = (fields) => j('/api/runs', {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
body: JSON.stringify({ plugin_id: PLUGIN_ID, fields }),
|
||||
})
|
||||
const getRun = (runId) => j(`/api/runs/${runId}`)
|
||||
const stopRun = (runId) => 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))
|
||||
|
||||
// 本机配置的「上次保存时间」:后端只存字段、不返回时间戳,
|
||||
// 这里用 localStorage 记住,刷新后仍能显示(取不到时静默)。
|
||||
const SAVED_AT_KEY = `plugin:${PLUGIN_ID}:lastSavedAt`
|
||||
function readSavedAt() {
|
||||
try { return localStorage.getItem(SAVED_AT_KEY) || '' } catch (_) { return '' }
|
||||
}
|
||||
function writeSavedAt(v) {
|
||||
try { localStorage.setItem(SAVED_AT_KEY, v) } catch (_) { /* 存储不可用时只保留内存态 */ }
|
||||
}
|
||||
|
||||
// 保存字段合并规则:标量空值(''/null/undefined)不覆盖;数组照原样应用
|
||||
// (空数组可能是有意配置,如「留空=不筛选」)
|
||||
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
|
||||
})
|
||||
}
|
||||
|
||||
export function usePluginUI(opts = {}) {
|
||||
const { defaults, validate, buildPayload } = opts
|
||||
|
||||
const form = reactive(defaults ? defaults() : {})
|
||||
const loaded = ref(false)
|
||||
const needLogin = ref(false)
|
||||
const notice = ref(null) // { type: 'warn'|'error'|'ok', text }
|
||||
const lastSavedAt = ref(readSavedAt())
|
||||
const running = ref(false)
|
||||
const progress = ref(0)
|
||||
const stopping = ref(false)
|
||||
|
||||
let ws = null
|
||||
let runId = ''
|
||||
let pollTimer = null
|
||||
let saveTimer = null
|
||||
|
||||
// 传空 type 视为清除横幅(不能留 {type:null},否则会渲染成只有"!"的空横幅)
|
||||
const notify = (type, text) => { notice.value = type ? { type, text } : null }
|
||||
|
||||
// ---------- 当前配置:加载 / 防抖自动保存 ----------
|
||||
// 登录由壳子统一处理(打开界面时会话必然就绪),这里读取失败一律静默回退默认值,
|
||||
// 不弹任何提示;真到执行时才发现会话问题,再明确告知。
|
||||
onMounted(async () => {
|
||||
try {
|
||||
const saved = await loadConfig()
|
||||
mergeSaved(form, saved)
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
}
|
||||
loaded.value = true
|
||||
refreshSchemes()
|
||||
})
|
||||
|
||||
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 })
|
||||
writeSavedAt(lastSavedAt.value)
|
||||
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) : {})
|
||||
notify(null)
|
||||
ElMessage.info('已恢复默认配置')
|
||||
}
|
||||
|
||||
// 恢复上次执行参数(壳子记录,password 类字段不落盘)
|
||||
async function restoreLastFields() {
|
||||
try {
|
||||
const r = await loadLastFields()
|
||||
const fields = r.fields || {}
|
||||
if (!Object.keys(fields).length) {
|
||||
ElMessage.info('暂无上次执行参数')
|
||||
return
|
||||
}
|
||||
mergeSaved(form, fields)
|
||||
ElMessage.success('已恢复上次执行参数' + (r.at ? `(${r.at})` : ''))
|
||||
} catch (e) {
|
||||
if (e.code === 401) needLogin.value = true
|
||||
else ElMessage.error('恢复上次参数失败:' + e.message)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 多配置方案 ----------
|
||||
const schemes = ref([])
|
||||
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)
|
||||
}
|
||||
}
|
||||
|
||||
// ---------- 执行 ----------
|
||||
// action: download(只下载)/ reconcile(只核对);不传则用 payload 里的 action
|
||||
async function run(action) {
|
||||
if (running.value) return
|
||||
if (needLogin.value) {
|
||||
try {
|
||||
await loadConfig()
|
||||
needLogin.value = false
|
||||
} catch (_) {
|
||||
notify('error', '登录态未就绪,请稍后重试')
|
||||
return
|
||||
}
|
||||
}
|
||||
if (validate && !validate(action)) return
|
||||
await saveNow(false)
|
||||
notify(null)
|
||||
running.value = true
|
||||
progress.value = 0
|
||||
try {
|
||||
const payload = buildPayload ? buildPayload(form) : clone(form)
|
||||
if (action) payload.action = action
|
||||
const r = await startRun(payload)
|
||||
runId = r.run_id
|
||||
connect()
|
||||
startPolling()
|
||||
} catch (e) {
|
||||
running.value = false
|
||||
stopPolling()
|
||||
if (e.code === 401) {
|
||||
needLogin.value = true
|
||||
notify('error', '登录态未就绪,本次没有启动,请稍后重试')
|
||||
} else if (e.code === 409) {
|
||||
// 壳子「入队确认」里用户点了取消
|
||||
notify('warn', '已取消加入执行队列,本次没有启动')
|
||||
} else {
|
||||
notify('error', '启动执行失败:' + 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
|
||||
}
|
||||
}
|
||||
|
||||
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
|
||||
// 结果横幅由壳子统一展示,插件内仅在需要时给一句简短结论
|
||||
if (summary) notify('ok', summary)
|
||||
}
|
||||
|
||||
function failed(err) {
|
||||
stopPolling()
|
||||
running.value = false
|
||||
notify('error', '执行失败:' + err)
|
||||
}
|
||||
|
||||
return {
|
||||
form, loaded, needLogin, notice, lastSavedAt, running, progress, stopping,
|
||||
saveNow, resetDefaults, restoreLastFields,
|
||||
schemes, schemeSel, schemeOptions, onSchemeChange, saveSchemeAs, removeScheme,
|
||||
run, forceStop,
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,20 @@
|
||||
import { defineConfig } from 'vite'
|
||||
import vue from '@vitejs/plugin-vue'
|
||||
|
||||
// 插件 UI 由壳子托管在 /pui/xq0042/ 下,构建产物输出到插件包 ui/ 目录。
|
||||
// dev 端口 5199(避开已占用的 5180-5185/5188/5198),代理到本机壳子 8799。
|
||||
export default defineConfig({
|
||||
plugins: [vue()],
|
||||
base: '/pui/xq0042/',
|
||||
build: {
|
||||
outDir: '../ui',
|
||||
emptyOutDir: true,
|
||||
},
|
||||
server: {
|
||||
port: 5199,
|
||||
proxy: {
|
||||
'/api': { target: 'http://127.0.0.1:8799', changeOrigin: true },
|
||||
'/ws': { target: 'ws://127.0.0.1:8799', ws: true },
|
||||
},
|
||||
},
|
||||
})
|
||||
+23
-23
File diff suppressed because one or more lines are too long
+1
-1
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/xq0042/assets/index-BUp-ZeAA.js"></script>
|
||||
<link rel="stylesheet" crossorigin href="/pui/xq0042/assets/index-D2-8mbvQ.css">
|
||||
</head>
|
||||
<body>
|
||||
<div id="app"></div>
|
||||
</body>
|
||||
</html>
|
||||
@@ -1,221 +0,0 @@
|
||||
# -*- 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())
|
||||
@@ -1,408 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 data 层:花名册导出(接口版)。"""
|
||||
@@ -1,453 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 logic 层:筛选复制 + 三阶段名额调度 + WPS/Excel 重算。"""
|
||||
@@ -1,658 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,158 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,559 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,122 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,86 +0,0 @@
|
||||
{
|
||||
"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": []
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0002 插件 report 层:在参名单更新/变更清单/备份/增减员导入输出。"""
|
||||
@@ -1,297 +0,0 @@
|
||||
# -*- 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)}
|
||||
@@ -1,120 +0,0 @@
|
||||
# -*- 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")
|
||||
@@ -1,664 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,6 +0,0 @@
|
||||
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
@@ -1,13 +0,0 @@
|
||||
<!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>
|
||||
@@ -1,195 +0,0 @@
|
||||
# -*- 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())
|
||||
@@ -1,203 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 数据层。"""
|
||||
@@ -1,356 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,124 +0,0 @@
|
||||
# -*- 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}"}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 业务规则层。"""
|
||||
@@ -1,375 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,265 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,58 +0,0 @@
|
||||
{
|
||||
"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": []
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0003 请假流程审核 插件 - 报告与推送层。"""
|
||||
@@ -1,230 +0,0 @@
|
||||
# -*- 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)}
|
||||
@@ -1,205 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,6 +0,0 @@
|
||||
requests
|
||||
DrissionPage
|
||||
rapidocr
|
||||
onnxruntime
|
||||
Pillow
|
||||
numpy
|
||||
File diff suppressed because one or more lines are too long
@@ -1,13 +0,0 @@
|
||||
<!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>
|
||||
@@ -1,207 +0,0 @@
|
||||
# -*- 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())
|
||||
@@ -1,213 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 数据层。"""
|
||||
@@ -1,348 +0,0 @@
|
||||
# -*- 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
|
||||
@@ -1,124 +0,0 @@
|
||||
# -*- 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}"}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 业务规则层。"""
|
||||
@@ -1,598 +0,0 @@
|
||||
# -*- 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,
|
||||
}
|
||||
@@ -1,64 +0,0 @@
|
||||
{
|
||||
"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": []
|
||||
}
|
||||
}
|
||||
@@ -1,2 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""XQ0004 加班流程审核 插件 - 报告与推送层。"""
|
||||
@@ -1,230 +0,0 @@
|
||||
# -*- 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)}
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user