- 调整台账导出范围为近三月、筛选时间为近4天 - 将名单表从「本月发起名单」统一改为「已发起名单」 - 新增三类人员群提醒、分页查询流程优化 - 修复单位名称匹配逻辑,新增选项集获取 - 替换COM写入为openpyxl避免时区问题
391 lines
18 KiB
Python
391 lines
18 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0037 步骤5:HR 已发起工号回写钉钉 AI 表格「改签离职电子签跟进-日更新」(新增行)。
|
||
|
||
链路最后一步,与 step2/3/4 同一作用域闸门:仅处理「待办工号列表.json」内工号
|
||
(step2 置位时登记,step4 发起后保留),字段从当天推送表「已发起名单」取。
|
||
发起成功以 HR 系统为准:
|
||
1. HR 核查:遍历运行中「改签离职电子签」流程按表单 base_code 匹配工号,
|
||
再按流程主键查签署记录,is_initiate_sign 非空非 0 即已发起
|
||
(step4 自动发起与人工在 HR 里发起同样命中);未发起/运行中流程未找到
|
||
的保留待办,不回写 AI 表、不回填、不移除;
|
||
2. HR 已发起者,候选再与名单表取交集(列表内但名单无行的打日志提示,不回写);
|
||
3. 防重按「工号+调动日期」判定:同工号可能调动多次(如陆昌立),AI 表中
|
||
同一笔调动(同调动日)已有记录才跳过;历史调动的旧行不影响本次新增;
|
||
4. 新增行:姓名/工号/调动时间/现单位名称/现岗位/现技师工号/原单位名称/
|
||
原岗位/原技师工号 + 是否已发起改签离职=是 + 发起时间=当天;
|
||
5. 检测到已发起(AI 表已有本笔调动记录,或本次回写成功)-> 回填推送表
|
||
「已发起名单」对应行「发起日期」列(AI/35,openpyxl 直写,试算模式不写);
|
||
6. 回写完成(新增成功或 AI 表已有)-> 从待办工号列表移除,列表清空即链路收尾。
|
||
|
||
字段映射注意:AI 表「现单位名称/原单位名称」是 singleSelect 且选项为会馆名
|
||
(四级部门级),取名单表「现四级部门/原四级部门」列,不是「现单位/原单位」
|
||
(事业部级名称不在选项集,写入报 invalid)。
|
||
date 字段写毫秒时间戳(XQ0035 同款口径);singleSelect 写入传选项名字符串
|
||
(读取才返回 {"name","id"} 对象)。
|
||
|
||
复用:XQ0035 step2_sign_new_contract 的钉钉 token/请求(内嵌副本);step2 待办列表/
|
||
HR 会话(底座注入);step3 名单表定位/运行中流程遍历/表单业务数据;step4 签署记录查询。
|
||
|
||
【插件版移植说明】本模块由影刀版原样移植为执行机插件 data 层(xq0037):
|
||
- XQ0035 公共函数改从本插件内嵌副本 xq35_step2_sign_new_contract 相对导入;
|
||
- print 日志由插件入口统一改道 ctx.log 推送前端。
|
||
|
||
运行方式:
|
||
业务脚本:importlib 加载调用 main(dry_run=...)
|
||
"""
|
||
import os
|
||
from datetime import datetime
|
||
|
||
import openpyxl
|
||
|
||
from .xq35_step2_sign_new_contract import ( # noqa: E402
|
||
AITABLE_BASE_ID, AITABLE_OPERATOR_UNIONID, _aitable_request)
|
||
from .step2_transfer_initiate import ( # noqa: E402
|
||
TARGET_SHEET, _hr_session, load_pending_list, remove_pending)
|
||
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"
|
||
RECORDS_LIST_URL = (f"https://api.dingtalk.com/v1.0/notable/bases/{AITABLE_BASE_ID}"
|
||
f"/sheets/{TABLE_ID}/records/list")
|
||
RECORDS_ADD_URL = (f"https://api.dingtalk.com/v1.0/notable/bases/{AITABLE_BASE_ID}"
|
||
f"/sheets/{TABLE_ID}/records")
|
||
|
||
# 名单表「已发起名单」所需列(按表头名解析,列序无关)
|
||
ROSTER_COLS = ("姓名", "工号", "调动时间",
|
||
"现二级部门", "现三级部门", "现四级部门", "现岗位", "现技师工号",
|
||
"原二级部门", "原三级部门", "原四级部门", "原岗位", "原技师工号")
|
||
|
||
FIELD_INITIATED = "是否已发起改签离职"
|
||
FIELD_INIT_TIME = "发起时间"
|
||
|
||
# 试算开关:True=试算(只打印,不写 AI 表);False=实跑写入
|
||
DRY_RUN = False
|
||
FIELD_INIT_DATE = "发起日期" # 「已发起名单」AI(35) 列(按表头名定位),已发起时回填
|
||
DATE_FMT = "yyyy/mm/dd" # 回填显示格式
|
||
|
||
|
||
def _s(v):
|
||
return str(v).strip() if v is not None else ""
|
||
|
||
|
||
def _ms_day(value):
|
||
"""datetime / 'yyyy-MM-dd…' / 毫秒时间戳(int) -> 当天 0 点毫秒;失败 None。
|
||
|
||
钉钉日期字段读取返回 int 毫秒,必须归一到同一日粒度才能做防重比对。
|
||
"""
|
||
if isinstance(value, bool):
|
||
return None
|
||
if isinstance(value, (int, float)):
|
||
d = datetime.fromtimestamp(value / 1000)
|
||
elif isinstance(value, datetime):
|
||
d = value
|
||
elif isinstance(value, str):
|
||
try:
|
||
d = datetime.strptime(value.strip()[:10], "%Y-%m-%d")
|
||
except ValueError:
|
||
return None
|
||
else:
|
||
return None
|
||
d = d.replace(hour=0, minute=0, second=0, microsecond=0)
|
||
return int(d.timestamp() * 1000)
|
||
|
||
|
||
# ---------- 数据源:待办列表 + 名单表字段 ----------
|
||
def fetch_field_choices():
|
||
"""「现/原单位名称」字段选项集(两字段选项一致,取并集兜底)。
|
||
|
||
fields 接口响应结构 {"value": [field...]},单选选项在 property.choices。
|
||
"""
|
||
url = (f"https://api.dingtalk.com/v1.0/notable/bases/{AITABLE_BASE_ID}"
|
||
f"/sheets/{TABLE_ID}/fields")
|
||
d = _aitable_request("GET", url, params={"operatorId": AITABLE_OPERATOR_UNIONID})
|
||
names = set()
|
||
for f in d.get("value") or []:
|
||
if f.get("name") in ("现单位名称", "原单位名称"):
|
||
names |= {c["name"] for c in (f.get("property") or {}).get("choices") or []
|
||
if c.get("name")}
|
||
return names
|
||
|
||
|
||
def pick_unit(row, prefix, choices):
|
||
"""单位名称候选依次 四级 -> 二级-三级 -> 二级 -> 三级,首个命中选项集者。
|
||
|
||
金色印象系四级=会馆名直接命中;石桥铺会馆直管体系选项为
|
||
「石桥铺会馆-前厅部」式路径名,由 二级-三级 拼接命中。
|
||
"""
|
||
l2 = row[f"{prefix}二级部门"]
|
||
l3 = row[f"{prefix}三级部门"]
|
||
l4 = row[f"{prefix}四级部门"]
|
||
for cand in (l4, f"{l2}-{l3}" if l2 and l3 else "", l2, l3):
|
||
if cand and cand in choices:
|
||
return cand
|
||
return ""
|
||
|
||
|
||
def load_roster_rows():
|
||
"""名单表数据行 -> {工号(str): 回写字段 + _row(行号,发起日期回填用)};
|
||
同工号多行取后一行。"""
|
||
path, header = _find_push_table()
|
||
miss = [c for c in ROSTER_COLS if c not in header]
|
||
if miss:
|
||
raise KeyError(f"{os.path.basename(path)}「{TARGET_SHEET}」缺列:{miss}")
|
||
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||
ws = wb[TARGET_SHEET]
|
||
rows = {}
|
||
for r in range(2, ws.max_row + 1):
|
||
code = _s(ws.cell(r, header["工号"]).value)
|
||
if not code:
|
||
continue
|
||
rows[code] = {
|
||
"姓名": _s(ws.cell(r, header["姓名"]).value),
|
||
"工号": code,
|
||
"调动时间": ws.cell(r, header["调动时间"]).value,
|
||
"现二级部门": _s(ws.cell(r, header["现二级部门"]).value),
|
||
"现三级部门": _s(ws.cell(r, header["现三级部门"]).value),
|
||
"现四级部门": _s(ws.cell(r, header["现四级部门"]).value),
|
||
"现岗位": _s(ws.cell(r, header["现岗位"]).value),
|
||
"现技师工号": _s(ws.cell(r, header["现技师工号"]).value),
|
||
"原二级部门": _s(ws.cell(r, header["原二级部门"]).value),
|
||
"原三级部门": _s(ws.cell(r, header["原三级部门"]).value),
|
||
"原四级部门": _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)}「{TARGET_SHEET}」共 {len(rows)} 条")
|
||
return rows
|
||
|
||
|
||
# ---------- AI 表格 ----------
|
||
def fetch_follow_records():
|
||
"""分页全量读取跟进表 -> {工号: [(record_id, 调动时间日毫秒, 发起时间日毫秒)]}。
|
||
|
||
同工号可能有多行(调动多次),防重按「工号+调动日期」判定:
|
||
同一笔调动(同工号同调动日)已回写过才跳过;跨天重跑亦幂等。
|
||
发起时间用于回填推送表「发起日期」列(历史记录可能缺失,取 None)。
|
||
"""
|
||
records, token = [], ""
|
||
for _ in range(200):
|
||
d = _aitable_request("POST", RECORDS_LIST_URL,
|
||
params={"operatorId": AITABLE_OPERATOR_UNIONID},
|
||
json_body={"maxResults": 100, "nextToken": token})
|
||
records.extend(d.get("records") or [])
|
||
if d.get("hasMore") and d.get("nextToken"):
|
||
token = d["nextToken"]
|
||
else:
|
||
break
|
||
out = {}
|
||
for rec in records:
|
||
f = rec.get("fields") or {}
|
||
code = _s(f.get("工号"))
|
||
if not code:
|
||
continue
|
||
out.setdefault(code, []).append(
|
||
(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)} 个")
|
||
return out
|
||
|
||
|
||
def append_follow_rows(items):
|
||
"""新增行(items: [fields dict]),返回新增 record id 列表。"""
|
||
d = _aitable_request("POST", RECORDS_ADD_URL,
|
||
params={"operatorId": AITABLE_OPERATOR_UNIONID},
|
||
json_body={"records": [{"fields": it} for it in items]})
|
||
return [r.get("id") for r in (d.get("records") or [])
|
||
if isinstance(r, dict)]
|
||
|
||
|
||
def backfill_init_dates(rows, items):
|
||
"""已发起回填:发起日期写入「已发起名单」对应行「发起日期」列(显示 yyyy/mm/dd)。
|
||
|
||
Args:
|
||
rows: load_roster_rows() 返回(借 _row 定位行)
|
||
items: [(工号, 发起时间日毫秒)],毫秒 None 时按当天补
|
||
Returns:
|
||
实际更新行数(单元格已是同一天则跳过,跨天重跑幂等)
|
||
|
||
openpyxl 直写保留公式(同 step2 风格),保存清公式缓存无碍
|
||
(公式保留,打开自动重算显示)。
|
||
"""
|
||
path, header = _find_push_table()
|
||
if FIELD_INIT_DATE not in header:
|
||
raise KeyError(f"{os.path.basename(path)}「{TARGET_SHEET}」缺「{FIELD_INIT_DATE}」列")
|
||
col = header[FIELD_INIT_DATE]
|
||
wb = openpyxl.load_workbook(path)
|
||
ws = wb[TARGET_SHEET]
|
||
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)
|
||
same_day = isinstance(cell.value, datetime) and cell.value.date() == d.date()
|
||
if same_day and cell.number_format == DATE_FMT:
|
||
continue
|
||
if not same_day:
|
||
cell.value = d
|
||
cell.number_format = DATE_FMT
|
||
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, choices):
|
||
"""名单行 + 发起时间 + 选项集 -> AI 表新增行 fields(空值字段不写)。
|
||
|
||
singleSelect(是否已发起改签离职/现单位名称/原单位名称)写入传选项名字符串;
|
||
单位名称经 pick_unit 匹配选项集,未命中不写该字段(留空告警)。
|
||
"""
|
||
fields = {
|
||
"姓名": row["姓名"],
|
||
"工号": row["工号"],
|
||
FIELD_INITIATED: "是",
|
||
FIELD_INIT_TIME: today_ms,
|
||
}
|
||
t = _ms_day(row["调动时间"])
|
||
if t:
|
||
fields["调动时间"] = t
|
||
u = pick_unit(row, "现", choices)
|
||
if u:
|
||
fields["现单位名称"] = u
|
||
if row["现岗位"]:
|
||
fields["现岗位"] = row["现岗位"]
|
||
if row["现技师工号"]:
|
||
fields["现技师工号"] = str(row["现技师工号"])
|
||
u = pick_unit(row, "原", choices)
|
||
if u:
|
||
fields["原单位名称"] = u
|
||
if row["原岗位"]:
|
||
fields["原岗位"] = row["原岗位"]
|
||
if row["原技师工号"]:
|
||
fields["原技师工号"] = str(row["原技师工号"])
|
||
return fields
|
||
|
||
|
||
# ---------- 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 = DRY_RUN 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,
|
||
"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()
|
||
|
||
# 发起成功以 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
|
||
|
||
choices = fetch_field_choices()
|
||
if not choices:
|
||
raise RuntimeError("未能获取「现/原单位名称」字段选项集,终止回写以免单位名称写空")
|
||
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, 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, today_ms, choices)
|
||
warn = "" if ("现单位名称" in fields and "原单位名称" in fields) \
|
||
else "(存在无匹配选项的单位名称,已留空待人工核对)"
|
||
_log(f"[回写] {code} {row['姓名']} | 现单位 {fields.get('现单位名称') or '空'} | "
|
||
f"原单位 {fields.get('原单位名称') or '空'} | 调动 {row['调动时间']}{warn}")
|
||
add_items.append(fields)
|
||
|
||
if add_items and not dry_run:
|
||
ids = append_follow_rows(add_items)
|
||
_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"[汇总] 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
|