- 修复 cashier_login.py 登录成功判定逻辑,调整 URL 条件为同时包含 SUCCESS_KEYWORD 且不在 /login 路径,避免误判 - 调整 roster_export_api.py 默认参数,新增离职状态及时间范围,更新输出路径 - 扩展 absence_analysis.py 日期范围支持 YYYYMM 格式 - 新增 transfer_roster_export_api.py 调动改签电子签导出模板字段配置 - 新增 XQ0037 调动改签离职电子签全流程步骤文件 step1~step6,涵盖台账导出筛选、待办处理、电子签发起及跟进回写等功能
239 lines
10 KiB
Python
239 lines
10 KiB
Python
# -*- coding: utf-8 -*-
|
||
"""XQ0037 步骤5:待办工号回写钉钉 AI 表格「改签离职电子签跟进-日更新」(新增行)。
|
||
|
||
链路最后一步,与 step2/3/4 同一作用域闸门:仅处理「待办工号列表.json」内工号
|
||
(step2 置位时登记,step4 发起后保留),字段从当天推送表「本月发起名单」取:
|
||
1. 候选 = 待办列表 ∩ 名单表(列表内但名单无行的打日志提示,不回写);
|
||
2. 防重按「工号+调动日期」判定:同工号可能调动多次(如陆昌立),AI 表中
|
||
同一笔调动(同调动日)已有记录才跳过;历史调动的旧行不影响本次新增;
|
||
3. 新增行:姓名/工号/调动时间/现单位名称/现岗位/现技师工号/原单位名称/
|
||
原岗位/原技师工号 + 是否已发起改签离职=是 + 发起时间=当天;
|
||
4. 回写完成(新增成功或 AI 表已有)-> 从待办工号列表移除,列表清空即链路收尾。
|
||
|
||
字段映射注意:AI 表「现单位名称/原单位名称」是 singleSelect 且选项为会馆名
|
||
(四级部门级),取名单表「现四级部门/原四级部门」列,不是「现单位/原单位」
|
||
(事业部级名称不在选项集,写入报 invalid)。
|
||
date 字段写毫秒时间戳(XQ0035 同款口径);singleSelect 写入传选项名字符串
|
||
(读取才返回 {"name","id"} 对象)。
|
||
|
||
复用:XQ0035 sign_new_contract 的钉钉 token/请求;step2 待办列表;step3 名单表定位。
|
||
依赖环境变量:根目录 .env(hr 账号配置,沿用共享指令)。
|
||
|
||
运行方式:
|
||
1. 命令行:python step5_transfer_aitable.py(默认 XQ0037_DRY_RUN=1 试算不写入,
|
||
XQ0037_DRY_RUN=0 实际写入)
|
||
2. 业务脚本:importlib 加载调用 main(dry_run=...)
|
||
"""
|
||
import os
|
||
import sys
|
||
from datetime import datetime
|
||
|
||
import openpyxl
|
||
|
||
HERE = os.path.dirname(os.path.abspath(__file__))
|
||
_XQ35 = r"d:\work\code\37duAutomation\workflows\XQ0001-0100\XQ0035 服务岗转正不通过电子签(离职+入职)"
|
||
for _p in (_XQ35, HERE):
|
||
if _p not in sys.path:
|
||
sys.path.insert(0, _p)
|
||
|
||
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
|
||
|
||
# 钉钉 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 = "发起时间"
|
||
|
||
|
||
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 load_roster_rows():
|
||
"""名单表数据行 -> {工号(str): 9 个回写字段};同工号多行取后一行。"""
|
||
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)}「本月发起名单」缺列:{miss}")
|
||
wb = openpyxl.load_workbook(path, read_only=True, data_only=True)
|
||
ws = wb["本月发起名单"]
|
||
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),
|
||
}
|
||
wb.close()
|
||
_log(f"[名单] {os.path.basename(path)}「本月发起名单」共 {len(rows)} 条")
|
||
return rows
|
||
|
||
|
||
# ---------- AI 表格 ----------
|
||
def fetch_follow_records():
|
||
"""分页全量读取跟进表 -> {工号: [(record_id, 调动时间日毫秒)]}。
|
||
|
||
同工号可能有多行(调动多次),防重按「工号+调动日期」判定:
|
||
同一笔调动(同工号同调动日)已回写过才跳过;跨天重跑亦幂等。
|
||
"""
|
||
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("调动时间"))))
|
||
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 build_fields(row, today_ms):
|
||
"""名单行 + 发起时间 -> AI 表新增行 fields(空值字段不写)。
|
||
|
||
singleSelect(是否已发起改签离职/现单位名称/原单位名称)写入传选项名字符串。
|
||
"""
|
||
fields = {
|
||
"姓名": row["姓名"],
|
||
"工号": row["工号"],
|
||
FIELD_INITIATED: "是",
|
||
FIELD_INIT_TIME: today_ms,
|
||
}
|
||
t = _ms_day(row["调动时间"])
|
||
if t:
|
||
fields["调动时间"] = t
|
||
if row["现四级部门"]:
|
||
fields["现单位名称"] = row["现四级部门"]
|
||
if row["现岗位"]:
|
||
fields["现岗位"] = row["现岗位"]
|
||
if row["现技师工号"]:
|
||
fields["现技师工号"] = str(row["现技师工号"])
|
||
if row["原四级部门"]:
|
||
fields["原单位名称"] = row["原四级部门"]
|
||
if row["原岗位"]:
|
||
fields["原岗位"] = row["原岗位"]
|
||
if row["原技师工号"]:
|
||
fields["原技师工号"] = str(row["原技师工号"])
|
||
return fields
|
||
|
||
|
||
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}
|
||
_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):
|
||
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, [])
|
||
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)
|
||
continue
|
||
fields = build_fields(row, _ms_day(datetime.now()))
|
||
_log(f"[回写] {code} {row['姓名']} | 现单位 {row['现四级部门'] or '空'} | "
|
||
f"原单位 {row['原四级部门'] or '空'} | 调动 {row['调动时间']}")
|
||
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)
|
||
elif add_items:
|
||
_log(f"[完成] 待新增 {len(add_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']}"
|
||
f"{'(试算模式)' if dry_run else ''}")
|
||
return stats
|
||
|
||
|
||
if __name__ == "__main__":
|
||
main()
|