feat(workflows): 新增HR发起状态核查及发起日期回填逻辑

新增通过HR系统运行中流程及签署记录核查改签发起状态,未发起的保留待办;新增推送表发起日期回填功能,同时优化名单表和AI表的数据结构,完善注释说明。
This commit is contained in:
2026-10-13 09:01:22 +08:00
parent 332b5b9271
commit 0b42fdab56
2 changed files with 137 additions and 23 deletions
@@ -84,9 +84,10 @@ def _find_push_table(today=None):
path = os.path.join(
PUSH_DIR, f"{today:%Y%m} {PUSH_TABLE_PREFIX}{today:%m%d}.xlsx")
if not os.path.exists(path):
cands = sorted(
(f for f in os.listdir(PUSH_DIR) if f.startswith(f"20{PUSH_TABLE_PREFIX}")),
reverse=True)
# 文件名格式 {YYYYMM} 每日推送调动改签名单{MMDD}.xlsx,按名倒序取最近
pat = re.compile(rf"20\d{{4}} {re.escape(PUSH_TABLE_PREFIX)}\d{{4}}\.xlsx")
cands = sorted((f for f in os.listdir(PUSH_DIR) if pat.fullmatch(f)),
reverse=True)
if not cands:
raise FileNotFoundError(f"{PUSH_DIR} 下找不到「{PUSH_TABLE_PREFIX}」推送表")
path = os.path.join(PUSH_DIR, cands[0])
@@ -1,14 +1,21 @@
# -*- coding: utf-8 -*-
"""XQ0037 步骤5:待办工号回写钉钉 AI 表格「改签离职电子签跟进-日更新」(新增行)。
"""XQ0037 步骤5:HR 已发起工号回写钉钉 AI 表格「改签离职电子签跟进-日更新」(新增行)。
链路最后一步,与 step2/3/4 同一作用域闸门:仅处理「待办工号列表.json」内工号
(step2 置位时登记,step4 发起后保留),字段从当天推送表「本月发起名单」取:
1. 候选 = 待办列表 ∩ 名单表(列表内但名单无行的打日志提示,不回写);
2. 防重按「工号+调动日期」判定:同工号可能调动多次(如陆昌立),AI 表中
(step2 置位时登记,step4 发起后保留),字段从当天推送表「本月发起名单」取。
发起成功以 HR 系统为准(用户澄清:AI 表只是回写结果,不是判定依据):
1. HR 核查:遍历运行中「改签离职电子签」流程按表单 base_code 匹配工号,
再按流程主键查签署记录,is_initiate_sign 非空非 0 即已发起
(step4 自动发起与人工在 HR 里发起同样命中);未发起/运行中流程未找到
的保留待办,不回写 AI 表、不回填、不移除;
2. HR 已发起者,候选再与名单表取交集(列表内但名单无行的打日志提示,不回写);
3. 防重按「工号+调动日期」判定:同工号可能调动多次(如陆昌立),AI 表中
同一笔调动(同调动日)已有记录才跳过;历史调动的旧行不影响本次新增;
3. 新增行:姓名/工号/调动时间/现单位名称/现岗位/现技师工号/原单位名称/
4. 新增行:姓名/工号/调动时间/现单位名称/现岗位/现技师工号/原单位名称/
原岗位/原技师工号 + 是否已发起改签离职=是 + 发起时间=当天;
4. 回写完成(新增成功或 AI 表已有)-> 从待办工号列表移除,列表清空即链路收尾。
5. 检测到已发起(AI 表已有本笔调动记录,或本次回写成功)-> 回填推送表
「本月发起名单」对应行「发起日期」列(openpyxl 直写,试算模式不写);
6. 回写完成(新增成功或 AI 表已有)-> 从待办工号列表移除,列表清空即链路收尾。
字段映射注意:AI 表「现单位名称/原单位名称」是 singleSelect 且选项为会馆名
(四级部门级),取名单表「现四级部门/原四级部门」列,不是「现单位/原单位」
@@ -16,7 +23,8 @@
date 字段写毫秒时间戳(XQ0035 同款口径);singleSelect 写入传选项名字符串
(读取才返回 {"name","id"} 对象)。
复用:XQ0035 sign_new_contract 的钉钉 token/请求;step2 待办列表;step3 名单表定位。
复用:XQ0035 sign_new_contract 的钉钉 token/请求;step2 待办列表/HR 会话;
step3 名单表定位/运行中流程遍历/表单业务数据;step4 签署记录查询。
依赖环境变量:根目录 .env(hr 账号配置,沿用共享指令)。
运行方式:
@@ -39,8 +47,11 @@ for _p in (_XQ35, HERE):
from sign_new_contract import ( # noqa: E402
AITABLE_BASE_ID, AITABLE_OPERATOR_UNIONID, _aitable_request)
from step2_transfer_initiate import ( # noqa: E402
load_pending_list, remove_pending)
from step3_transfer_todo import _find_push_table, _log # noqa: E402
_hr_session, load_pending_list, remove_pending)
from step3_transfer_todo import ( # noqa: E402
WORKFORM_FORM_ID, _find_push_table, _log, get_business_data,
list_running_workflows)
from step4_transfer_esign import query_sign_status # noqa: E402
# 钉钉 AI 表格:与 XQ0035 同一人资 base,目标 sheet「改签离职电子签跟进-日更新」
TABLE_ID = "ZuwepIq"
@@ -56,6 +67,7 @@ ROSTER_COLS = ("姓名", "工号", "调动时间",
FIELD_INITIATED = "是否已发起改签离职"
FIELD_INIT_TIME = "发起时间"
FIELD_INIT_DATE = "发起日期" # 「本月发起名单」值列(第38列),已发起时回填
def _s(v):
@@ -86,7 +98,8 @@ def _ms_day(value):
# ---------- 数据源:待办列表 + 名单表字段 ----------
def load_roster_rows():
"""名单表数据行 -> {工号(str): 9 个回写字段};同工号多行取后一行。"""
"""名单表数据行 -> {工号(str): 9 个回写字段 + _row(行号,发起日期回填用)};
同工号多行取后一行。"""
path, header = _find_push_table()
miss = [c for c in ROSTER_COLS if c not in header]
if miss:
@@ -108,6 +121,7 @@ def load_roster_rows():
"原四级部门": _s(ws.cell(r, header["原四级部门"]).value),
"原岗位": _s(ws.cell(r, header["原岗位"]).value),
"原技师工号": _s(ws.cell(r, header["原技师工号"]).value),
"_row": r,
}
wb.close()
_log(f"[名单] {os.path.basename(path)}「本月发起名单」共 {len(rows)} 条")
@@ -116,10 +130,11 @@ def load_roster_rows():
# ---------- AI 表格 ----------
def fetch_follow_records():
"""分页全量读取跟进表 -> {工号: [(record_id, 调动时间日毫秒)]}。
"""分页全量读取跟进表 -> {工号: [(record_id, 调动时间日毫秒, 发起时间日毫秒)]}。
同工号可能有多行(调动多次),防重按「工号+调动日期」判定:
同一笔调动(同工号同调动日)已回写过才跳过;跨天重跑亦幂等。
发起时间用于回填推送表「发起日期」列(历史记录可能缺失,取 None)。
"""
records, token = [], ""
for _ in range(200):
@@ -138,7 +153,8 @@ def fetch_follow_records():
if not code:
continue
out.setdefault(code, []).append(
(rec.get("id"), _ms_day(f.get("调动时间"))))
(rec.get("id"), _ms_day(f.get("调动时间")),
_ms_day(f.get(FIELD_INIT_TIME))))
total = sum(len(v) for v in out.values())
_log(f"[AI表格] 「改签离职电子签跟进-日更新」共 {total} 行,"
f"有效工号 {len(out)} 个")
@@ -154,6 +170,44 @@ def append_follow_rows(items):
if isinstance(r, dict)]
def backfill_init_dates(rows, items):
"""已发起回填:发起日期写入「本月发起名单」对应行「发起日期」列。
Args:
rows: load_roster_rows() 返回(借 _row 定位行)
items: [(工号, 发起时间日毫秒)],毫秒 None 时按当天补
Returns:
实际更新行数(单元格已是同一天则跳过,跨天重跑幂等)
openpyxl 直写保留公式(同 step2 风格),保存清公式缓存无碍
(step1 下次跑时 WPS 重算恢复)。
"""
path, header = _find_push_table()
if FIELD_INIT_DATE not in header:
raise KeyError(f"{os.path.basename(path)}「本月发起名单」缺「{FIELD_INIT_DATE}」列")
col = header[FIELD_INIT_DATE]
wb = openpyxl.load_workbook(path)
ws = wb["本月发起名单"]
done = 0
for code, ms in items:
row = rows.get(code)
if not row or not row.get("_row"):
continue
d = datetime.fromtimestamp((ms or _ms_day(datetime.now())) / 1000)
cell = ws.cell(row["_row"], col)
if isinstance(cell.value, datetime) and cell.value.date() == d.date():
continue
cell.value = d
done += 1
try:
wb.save(path)
except PermissionError as exc:
raise RuntimeError(
f"保存失败,文件被占用:{path}\n请先在 WPS/Excel 中关闭该文件后重试。") from exc
_log(f"[发起日期] 回填 {done} 行 -> {os.path.basename(path)}「{FIELD_INIT_DATE}」列")
return done
def build_fields(row, today_ms):
"""名单行 + 发起时间 -> AI 表新增行 fields(空值字段不写)。
@@ -183,36 +237,88 @@ def build_fields(row, today_ms):
return fields
# ---------- HR 发起状态核查(发起成功以 HR 为准,用户澄清) ----------
def check_hr_initiated(session, pending):
"""核查各待办工号电子签发起状态 -> (initiated, miss)。
遍历运行中「改签离职电子签」流程,按表单业务数据 base_code 匹配待办工号,
再按流程主键(businessKey)查签署记录:is_initiate_sign 非空非 0
(1=签署中/2=已完成)即已发起(step4 自动发起与人工发起同样命中)。
Returns:
initiated: {工号: businessKey} 已发起
miss: {工号: 原因} 未发起/运行中流程未找到 -> 保留待办
"""
flows = {}
for flow in list_running_workflows(session):
biz = get_business_data(session, flow.get("businessKey"), WORKFORM_FORM_ID)
code = str(biz.get("base_code") or "").strip()
if code in pending and code not in flows:
flows[code] = str(flow.get("businessKey") or "")
initiated, miss = {}, {}
for code in sorted(pending):
bk = flows.get(code)
if not bk:
miss[code] = "运行中改签流程未找到"
continue
st = query_sign_status(session, bk)
if str(st.get("is_initiate_sign") or "") not in ("", "0"):
initiated[code] = bk
else:
miss[code] = "HR 签署记录未发起(is_initiate_sign 空/0)"
_log(f"[HR核查] 待办 {len(pending)} 人:已发起 {len(initiated)},"
f"未发起/无流程 {len(miss)}")
return initiated, miss
def main(dry_run=None):
dry_run = (os.environ.get("XQ0037_DRY_RUN", "1") == "1"
if dry_run is None else dry_run)
pending = load_pending_list()
if not pending:
_log("[待办] 待办工号列表为空(本批次无人待办),无事可做")
return {"added": 0, "skip_exists": 0, "skip_noroster": 0}
return {"added": 0, "skip_exists": 0, "skip_noroster": 0,
"not_initiated": 0, "backfill": 0}
_log("[待办] 本批待办 {} 人:{}".format(
len(pending), "、".join(f"{c}{n}" for c, n in sorted(pending.items()))))
roster = load_roster_rows()
existing = fetch_follow_records()
add_items, done_codes = [], []
stats = {"added": 0, "skip_exists": 0, "skip_noroster": 0}
for code in sorted(pending):
# 发起成功以 HR 为准:未发起/无流程的保留待办,不回写不回填不移除
session = _hr_session()
initiated, miss = check_hr_initiated(session, pending)
stats = {"added": 0, "skip_exists": 0, "skip_noroster": 0,
"not_initiated": len(miss), "backfill": 0}
for code, reason in sorted(miss.items()):
_log(f"[跳过] {code} {pending[code]} | {reason},保留待办等下次")
if not initiated:
_log("[完成] HR 侧无人已发起,本轮不回写(试算模式仅核查)"
if dry_run else "[完成] HR 侧无人已发起,本轮不回写")
_log(f"[汇总] HR已发起=0 未发起或无流程={stats['not_initiated']} "
f"名单缺行={stats['skip_noroster']} 新增={stats['added']} "
f"已有跳过={stats['skip_exists']} 发起日期回填={stats['backfill']}"
f"{'(试算模式)' if dry_run else ''}")
return stats
add_items, done_codes, init_items = [], [], []
today_ms = _ms_day(datetime.now())
for code in sorted(initiated):
row = roster.get(code)
if row is None:
_log(f"[跳过] {code} {pending[code]} | 名单表中无该工号,无法取字段")
stats["skip_noroster"] += 1
continue
move_ms = _ms_day(row["调动时间"])
dup = next(((rid, m) for rid, m in existing.get(code, [])
dup = next(((rid, m, im) for rid, m, im in existing.get(code, [])
if m is not None and m == move_ms), None)
if dup:
_log(f"[跳过] {code} {row['姓名']} | 本笔调动({row['调动时间']})"
f"AI 表已有记录(record {dup[0]}),视为已回写")
stats["skip_exists"] += 1
done_codes.append(code)
init_items.append((code, dup[2]))
continue
fields = build_fields(row, _ms_day(datetime.now()))
fields = build_fields(row, today_ms)
_log(f"[回写] {code} {row['姓名']} | 现单位 {row['现四级部门'] or '空'} | "
f"原单位 {row['原四级部门'] or '空'} | 调动 {row['调动时间']}")
add_items.append(fields)
@@ -222,14 +328,21 @@ def main(dry_run=None):
_log(f"[完成] AI 表新增 {len(add_items)} 行(record id:{ids})")
stats["added"] = len(add_items)
done_codes.extend(f["工号"] for f in add_items)
init_items.extend((f["工号"], today_ms) for f in add_items)
elif add_items:
_log(f"[完成] 待新增 {len(add_items)} 行(试算模式,未写入)")
if init_items and not dry_run:
stats["backfill"] = backfill_init_dates(roster, init_items)
elif init_items:
_log(f"[发起日期] {len(init_items)} 人已发起,待回填(试算模式,未写入)")
if done_codes and not dry_run:
remove_pending(done_codes)
_log("[待办] 回写完成,已从待办列表移除:{}".format("、".join(done_codes)))
_log(f"[汇总] 新增={stats['added']} 已有跳过={stats['skip_exists']} "
f"名单缺行={stats['skip_noroster']}"
_log(f"[汇总] HR已发起={len(initiated)} 未发起或无流程={stats['not_initiated']} "
f"名单缺行={stats['skip_noroster']} 新增={stats['added']} "
f"已有跳过={stats['skip_exists']} 发起日期回填={stats['backfill']}"
f"{'(试算模式)' if dry_run else ''}")
return stats