docs: 批量更新项目评级文档,移除200元/400元/600元金额标注

refactor: 重构钉钉推送逻辑,移除内嵌dws命令改用全局变量传递
fix: 雇主险调度逻辑,修复名额复用与增删员同步问题
style: 优化文档表格排版与代码注释格式
This commit is contained in:
2026-09-03 13:33:52 +08:00
parent 16d59e4e69
commit 657f444041
13 changed files with 349 additions and 331 deletions
@@ -4,7 +4,14 @@
@Author: 小布丁
@CreateTime: 2026-08-13
@Description: 雇主险名额调度系统「步骤2:调度」
@Version: 1.1.0
@Version: 1.2.0
- v1.2.0:
1) 变更清单「修改」仅用于"自己的名额档次替换、不涉及其他人"(未复用他人名额
且自己的旧名额未被他人复用);涉及他人的替换输出正常两条(删除+增加)。
2) 特殊情况源员工(离职/参保减少被复用后保留占位)写入参名单时补写 N列投保日期;
增员导入文件同样包含该源员工(新增空闲方案),不漏人。
3) 增减员执行顺序:必须先执行【减员】导入,再执行【增员】导入,否则替换/修改
人员先增员会因方案冲突直接报错。
- v1.1.0:增员导入「保险方案名称」按类别追加厂区后缀(秒创/湖畔/水庄,
三十七度无后缀),与 HR 侧带后缀方案列表对齐。
@@ -639,26 +646,21 @@ def _to_date(value):
return None
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)
def _find_special_slots(final_records, in_param_df):
"""识别特殊情况:离职/参保减少名额被老员工复用,且该老员工释放的旧名额无人复用。
# 构建初始参保映射:在参名单中存在原投保方案(M列)的员工视为"原已参保"
# (不依赖R列方案处理值,避免老员工R列为空/其它值时漏掉"删除原方案"记录,
# 例如 A:20→50 与 B:50→20 交换时需输出 A删20+A增50+B删50+B增20 共4条)
(例如 曹益娟参保减少20万→老员工胡兴复用,胡兴的X档旧名额没人用)。
此时把源员工名额改为老员工旧方案(X档)保留在参名单,变更清单补一条"增加X档",
既保证 增加>=删除 平衡,又把空闲名额放回池中供下次替换使用(避免同人两条名单)。
Args:
final_records: 最终参保记录列表(每条含 证件号/投保方案/名额来源/来源员工ID)
in_param_df: 在参名单 DataFrame(J列=姓名 K列=证件号 L列=类别 M列=方案)
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]
@@ -669,11 +671,6 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
initial_employee_map[emp_id] = True
final_emp_ids = set(rec["证件号"] for rec in final_records)
# 特殊情况识别:离职/参保减少名额被老员工复用,且该老员工释放的旧名额无人复用
# (例如 曹益娟参保减少20万→老员工胡兴复用,胡兴的X档旧名额没人用)。
# 此时把源员工名额改为老员工旧方案(X档)保留在参名单,变更清单补一条"增加X档",
# 既保证 增加>=删除 平衡,又把空闲名额放回池中供下次替换使用(避免同人两条名单)。
# 槽位复用网络:来源员工ID -> 接收记录(用于链条追踪)
slot_network = {}
for _rec in final_records:
@@ -685,8 +682,6 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
# 老员工每次"删除自己旧方案"即释放一个旧名额,若该名额被下一人复用则继续,直到:
# - 接收者是全新新员工(无旧方案可删)→ 链条自然结束,增删本就平衡;
# - 末端老员工释放的旧名额无人复用 → 该旧名额即"空闲名额"(X档)。
# 此时把最初源员工的名额改为该空闲名额保留在参名单,并补一条"增加[X档]"记录:
# 既保证 增加>=删除,又把空闲名额放回池中供下次替换使用(避免同人两条名单)。
special_slots = []
for rec in final_records:
if rec.get("名额来源") not in ("离职减少", "参保减少"):
@@ -728,6 +723,43 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
"source_category": src_row.iloc[11],
"new_scheme": loose_end_scheme,
})
return special_slots
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列为空/其它值时漏掉"删除原方案"记录,
# 例如 A:20→50 与 B:50→20 交换时需输出 A删20+A增50+B删50+B增20 共4条)
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)
# 特殊情况识别(公共函数):离职/参保减少名额被老员工复用,且老员工释放的旧名额无人复用
# -> 源员工名额改为该空闲方案保留在参名单,变更清单补一条"增加X档"
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:
@@ -807,9 +839,10 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
emp_id = row_info["emp_id"]
if emp_id in kept_emp_ids:
row_data = row_info["data"]
# 特殊情况源员工:M列改为老员工释放的旧方案(X档),下次可继续做替换
# 特殊情况源员工: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]
@@ -1039,7 +1072,15 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
records.append({"op": "删除", "name": "未知", "emp_id": emp_id,
"category": "未知", "scheme": "未知"})
# 2. 增加记录;档次替换合并为一条「修改」(备注写明由xx替换为xx)
# 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:
@@ -1052,17 +1093,29 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
category = None
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]
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})
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:
records.append({"op": "增加", "name": name, "emp_id": emp_id,
"category": category, "scheme": scheme})
@@ -1165,6 +1218,11 @@ def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_s
- 减员 = 原参保记录 − 新参保记录(离职减少/参保减少被复用的、档位替换遗留的原名额)
- 增员 = 新参保记录 − 原参保记录(全新新增、复用空闲名额、档位替换后的新方案)
离职减少/参保减少名额未被使用 → 新旧记录都在 → 不减员,方便下次直接替换。
特殊情况:离职/参保减少名额被老员工复用且老员工旧名额无人复用 -> 源员工保留在
参名单并改为空闲方案,该源员工同样纳入增员(新增该方案),保证不漏人。
★执行顺序:请务必先执行【减员】导入,再执行【增员】导入!涉及替换/修改的人员
若先增员会因人员方案冲突直接报错(必须先撤下旧方案,再上新方案)。
模板结构:第1行标题、第2行表头、第3行示例说明(均保留),第4行起填数据。
- 减员:序号 | *工号/身份证 | *姓名 | *减员日期
@@ -1183,7 +1241,7 @@ def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_s
continue
orig_records[_to_text(emp_id)] = scheme
# ---------- 2. 新参保记录集合(保留的原记录 + 新增记录) ----------
# ---------- 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 = {
@@ -1192,6 +1250,11 @@ def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_s
}
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 = [
@@ -1229,17 +1292,34 @@ def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_s
continue
sub_rows.append([i, _code(emp_id), name, TODAY_DATE])
add_rows, skipped_add = [], 0
for i, rec in enumerate(final_records, start=1):
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
add_rows.append([i, _code(emp_id), name,
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)
@@ -1247,6 +1327,7 @@ def export_add_sub_import(category, biz_df, in_param_df, final_records, reused_s
logger.info("类别[%s] 增员 %d 条 / 减员 %d 条(跳过:增员 %d / 减员 %d)",
category["name"], len(add_rows), len(sub_rows), skipped_add, skipped_sub)
logger.info("执行顺序提醒:请先执行【减员】导入,再执行【增员】导入(涉及替换/修改的人员先增员会因方案冲突报错)")
# ============================================================
@@ -24,8 +24,8 @@
absence_roster_path=(可选)花名册文件路径,默认 D:\资料\人资\门店上月请休假异常人员名单梳理\员工花名册.xlsx
(由「37du花名册导出」指令导出的固定文件)
absence_push_at_all=(可选)"1" 时推送文本 @所有人(需确认群权限,默认不 @)
absence_push_record_dir=(可选)群聊推送记录目录,留空不记录(默认 D:\资料\人资\请休假异常\推送记录)
(推送目标群固定为「金色印象人行条线沟通工作群」,见 DEFAULT_PUSH_GROUP)
(导出后写入全局变量 messages,由流程拖「37du钉钉推送」指令发送;消息 dict 含 group 键
自动识别为群聊,无需配置 chat_type。推送目标群固定为「金色印象人行条线沟通工作群」,见 DEFAULT_PUSH_GROUP)
运行:
- 影刀「调用模块」:main({"save_dir": ..., "month": "2026-07", "roster_path": ...})
@@ -183,15 +183,13 @@ NOT_ATTEND_FRAGMENTS = (
# 业务脚本只读取该文件,不做浏览器导出、不加载共享模块(影刀指令拖拽机制下无法按文件路径加载)。
DEFAULT_ROSTER_PATH = r"D:\资料\人资\请休假异常\员工花名册.xlsx"
# ---------- 钉钉群聊推送配置(dws,可选) ----------
# 需求9 固定推送群:「金色印象人行条线沟通工作群」,导出后自动推送到该群,不提供覆盖。
# 推送逻辑与共享模块 yingdao/share/dingtalk_dws_push.py 同款 dws 命令,本脚本单文件自包含内联,
# 不依赖外部模块(影刀指令拖拽机制下无法按文件路径加载共享模块)。
DWS_BIN = r"C:\Users\admin\.local\bin\dws.exe" # dws 命令行工具路径
# ---------- 钉钉群聊推送配置(可选,写全局变量 messages 由「37du钉钉推送」指令发送) ----------
# 需求9 固定推送群:「金色印象人行条线沟通工作群」,导出后把推送消息写入影刀全局变量 messages,
# 由流程拖「37du钉钉推送」指令读取并实际发送。推送逻辑单一真源在共享模块
# yingdao/share/dingtalk_dws_push.py;业务脚本不 import 共享模块,只通过全局变量交接(影刀指令
# 拖拽机制下无法按文件路径加载共享模块)。消息 dict 含 group 键即自动识别为群聊,无需配置 chat_type。
DEFAULT_PUSH_GROUP = "金色印象人行条线沟通工作群" # 需求9 固定推送群名
PUSH_AT_ALL_ENV = "absence_push_at_all" # "1" 时推送文本 @所有人
PUSH_RECORD_DIR_ENV = "absence_push_record_dir" # 推送记录目录(留空=不记录)
PUSH_RECORD_DEFAULT_DIR = r"D:\资料\人资\请休假异常\推送记录"
# ---------- 接口数据懒缓存(避免重复调用接口) ----------
# 统计月(上月)始终实时调接口;跨月追溯往前的历史月走缓存旁路:
@@ -1097,92 +1095,42 @@ def _analyze(emp, month_status, session, user_id, begin, end, cur_ctx=None):
return rows
# ==================== 钉钉群聊推送(dws,可选) ====================
def _dws_run(cmd_list):
"""执行 dws 命令并返回完整 JSON(含 success/result 顶层字段)。"""
import subprocess
proc = subprocess.run(cmd_list, capture_output=True, text=True,
encoding="utf-8", errors="replace")
if proc.returncode != 0:
raise RuntimeError(f"dws 命令失败: {proc.stderr.strip()}")
raw = proc.stdout
data = json.loads(raw[raw.find("{"):])
if not data.get("success"):
raise RuntimeError(f"dws 命令未成功: {data}")
return data
# ==================== 钉钉群聊推送消息构造(写全局变量 messages,由「37du钉钉推送」指令发送) ====================
def _build_group_push_messages(save_path, month_str, count):
"""构造群聊推送消息列表(文本 + 附件 Excel),写入影刀全局变量 messages。
实际发送由流程拖「37du钉钉推送」指令完成(推送逻辑单一真源在共享模块
yingdao/share/dingtalk_dws_push.py,业务脚本不 import、不内联 dws 命令),本脚本只负责生成消息;
消息 dict 含 group 键,指令自动识别为群聊,无需配置 chat_type。
导出文件不存在时返回空列表(流程指令收到空列表则跳过发送)。
def _resolve_push_group_id(group_name):
"""按群名解析群聊 openconversation_id:模糊搜索 → 精确同名过滤 → 唯一命中才返回,歧义报错。"""
data = _dws_run([DWS_BIN, "chat", "search", "--query", group_name, "--format", "json"])
groups = data.get("result") or []
if not groups:
raise RuntimeError(f"未找到群「{group_name}」,请确认群名后重试")
exact = [g for g in groups if (g.get("name") or "").strip() == group_name]
if exact:
groups = exact
conv_ids = []
for g in groups:
for key in ("openConversationId", "conversationId", "chatId", "id"):
if g.get(key):
conv_ids.append(str(g[key]))
break
if len(conv_ids) == 1:
logger.info("命中推送群:%s", group_name)
return conv_ids[0]
hints = "\n".join(f" {g.get('name') or '未知群名'}" for g in groups)
raise RuntimeError(
f"群名「{group_name}」匹配到 {len(conv_ids)} 个候选,请使用更精确的群名:\n{hints}")
Args:
save_path: 导出名单 Excel 绝对路径
month_str: 统计月份 "YYYYMM"
count: 名单人数
def _push_to_group(save_path, month_str, count):
"""导出成功后推送名单到钉钉群(dws,文本 + 附件 Excel 一并发送)。
目标群固定为 DEFAULT_PUSH_GROUP;文件不存在时静默跳过,推送失败只记日志、不影响导出。
Returns:
群聊推送消息列表(每项为 group 推送 dict);文件不存在时返回 []。
"""
group = DEFAULT_PUSH_GROUP
if not save_path or not os.path.exists(save_path):
logger.warning("导出文件不存在,跳过群聊推送:%s", save_path)
return
logger.warning("导出文件不存在,跳过群聊推送消息构造:%s", save_path)
return []
at_all = (os.getenv(PUSH_AT_ALL_ENV) or "0").strip().lower() in ("1", "true", "yes", "y")
record_dir = (os.getenv(PUSH_RECORD_DIR_ENV) or "").strip() or PUSH_RECORD_DEFAULT_DIR
try:
conv_id = _resolve_push_group_id(group)
text = (f"【门店上月请休假异常名单】\n"
f"统计月份:{month_str[:4]}-{month_str[4:]}\n"
f"连续未出勤 ≥ {MIN_CONSECUTIVE_DAYS} 天:{count} 人")
cmd = [DWS_BIN, "chat", "message", "send", "--conversation-id", conv_id]
if at_all:
cmd += ["--at-all"]
text += "\n<@all>"
cmd += ["--content", text, "--format", "json"]
_dws_run(cmd)
_dws_run([DWS_BIN, "chat", "message", "send", "--conversation-id", conv_id,
"--msg-type", "file", "--file", save_path, "--format", "json"])
logger.info("名单已推送到群「%s」(文本 + 附件)", group)
_record_push_csv(record_dir, group, "成功", text, save_path)
except Exception as e:
logger.error("名单推送到群「%s」失败(不影响导出):%s", group, e)
def _record_push_csv(record_dir, group, result, text, file_path):
"""尽力追加一条群聊推送记录(best-effort,失败不影响推送)。"""
import csv
try:
os.makedirs(os.path.join(record_dir, datetime.now().strftime("%Y-%m-%d")), exist_ok=True)
path = os.path.join(record_dir, datetime.now().strftime("%Y-%m-%d"), "推送记录.csv")
new_file = not os.path.exists(path)
summary = (str(text or "").strip() or os.path.basename(str(file_path)))[:200]
with open(path, "a", newline="", encoding="utf-8-sig") as f:
writer = csv.DictWriter(f, fieldnames=["推送时间", "群名", "结果", "消息摘要"])
if new_file:
writer.writeheader()
writer.writerow({
"推送时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"群名": group, "结果": result, "消息摘要": summary,
})
logger.info("群聊推送记录已写入:%s(%s)", path, result)
except Exception as e:
logger.warning("群聊推送记录写入失败(不影响推送):%s", e)
# 截止日期 = 统计月最后一天(month_str 形如 "202608" → "2026-08-31")
end_date = date(int(month_str[:4]), int(month_str[4:]),
calendar.monthrange(int(month_str[:4]), int(month_str[4:]))[1]).strftime("%Y-%m-%d")
text = (f"【门店上月请休假异常名单】截止{end_date}(且最后一天处于未出勤) "
f"向前连续未出勤 ≥ {MIN_CONSECUTIVE_DAYS} 天:{count} 人")
if at_all:
text += "\n<@all>" # @所有人 需在内容中含占位符 <@all>(与共享模块约定一致)
return [{
"group": DEFAULT_PUSH_GROUP,
"content": text,
"file_path": save_path,
"title": "",
"at_all": at_all,
"at_open_ids": "",
}]
def export_excel(rows, save_dir, month_str):
@@ -1275,8 +1223,14 @@ def export_absence_list(save_dir=None, roster_path=None, month=None):
# 5. 导出
path = export_excel(rows, save_dir, month_str)
# 5.5 推送名单到钉钉群(固定推送到 DEFAULT_PUSH_GROUP,失败不影响导出)
_push_to_group(path, month_str, len(rows))
# 5.5 写入群聊推送消息到全局变量 messages,由流程拖「37du钉钉推送」指令发送
# (消息 dict 含 group 键自动识别为群聊,无需配置 chat_type)
push_msgs = _build_group_push_messages(path, month_str, len(rows))
_set_glv('messages', push_msgs)
if push_msgs:
logger.info("群聊推送消息已写入全局变量 messages(%d 条,群「%s」),"
"请拖「37du钉钉推送」指令发送",
len(push_msgs), DEFAULT_PUSH_GROUP)
logger.info("=" * 60)
logger.info("【请休假异常名单汇总】")
@@ -1293,7 +1247,8 @@ def main(args=None):
save_dir(导出目录)、month("YYYY-MM",默认上月)、roster_path(花名册文件路径,
默认取环境变量 absence_roster_path,最后为「37du花名册导出」指令固定输出路径)、
push_at_all(是否 @所有人,默认取环境变量 absence_push_at_all)。
推送目标群固定为 DEFAULT_PUSH_GROUP,不提供覆盖。
推送目标群固定为 DEFAULT_PUSH_GROUP,不提供覆盖;推送消息写入全局变量 messages,
由流程拖「37du钉钉推送」指令发送(消息 dict 含 group 键自动识别为群聊,无需配置 chat_type)。
"""
if args is None:
args = {}
+114 -90
View File
@@ -2,28 +2,27 @@
"""
@FileName: dingtalk_dws_push.py
@Description: 钉钉推送共享模块(单聊 + 群聊,文本 / 文件,基于 dws 命令行)。
供各业务脚本 import 复用,也可作为影刀自定义指令「37du钉钉单聊推送」
/「37du钉钉群聊推送」的模块源码。
供各业务脚本 import 复用,也可作为影刀自定义指令「37du钉钉推送」的模块源码
(同一入口,chat_type 参数决定单聊还是群聊)。
入口:
main(messages, record_dir='') 影刀自定义指令「37du钉钉单聊推送」调用入口。
传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址):
入口(统一 main,按消息结构自动识别单聊/群聊):
main(messages, record_dir='', chat_type='') 影刀自定义指令「37du钉钉推送」调用入口。
通道判定:chat_type 留空(默认)时按每条消息结构自动判断——dict 含 group/群名 键为群聊,
其余为单聊;显式传 'single'/'group' 时整批强制用该通道(兼容旧流程)。
chat_type='single'/单聊:传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址):
msg_type 消息类型:'text'/'文本' 或 'file'/'文件'
name 接收人姓名(文本/文件均按姓名解析 openDingTalkId;同名多人时按工号精确定位)
user_id 接收人工号(同名消歧;发文件且对方无会话时用于先建会话)
content 消息内容(msg_type=text 时必填)
file_path 文件地址(msg_type=file 时必填,本地绝对路径)
record_dir(可选):非空时每条结果写入 <record_dir>/YYYY-MM-DD/推送记录.csv,
并把记录文件路径写入影刀全局变量 push_record_path,供流程处理失败名单。
返回: {"success": bool, "message": str, "results": [...]}
main_group(messages, record_dir='') 影刀自定义指令「37du钉钉群聊推送」调用入口。
传入消息列表,每项支持 dict 或元组:
chat_type='group'/群聊:传入消息列表,每项支持 dict 或元组:
dict: {"group": 群名, "content": 文本, "file_path": 文件,
"title": 标题, "at_all": bool, "at_open_ids": "openId1,openId2"}
元组: (群名, 文本内容, 文件地址, 标题, at_all, at_open_ids),后 4 项可省略
按群名解析 openconversation_id 后发送(文本/文件可同时存在,@ 需在内容中含占位符)。
返回: {"success": bool, "message": str, "results": [...]}
record_dir(可选):非空时每条结果写入 <record_dir>/YYYY-MM-DD/推送记录.csv,
并把记录文件路径写入影刀全局变量 push_record_path,供流程处理失败名单。
逐条发送,返回: {"success": bool, "message": str, "results": [...]}
send_message(msg_type, name, user_id, content, file_path, record_dir='') # 单聊单条发送(内部/业务脚本复用)
send_group_message(group_name, content, file_path, title, at_all, at_open_ids, record_dir='') # 群聊单条发送
@@ -373,10 +372,14 @@ def send_file(open_id: str, file_path: str):
def search_group(query: str, limit: int = 20) -> list:
"""按群名搜索群聊(关键词模糊搜索),返回候选列表。
注意:dws 要求 query 使用群名连续核心词(如「项目冲刺」),勿拆成单字搜索。
dws chat search 返回结构为 result.groups(result 是字典),此处统一提取列表。
"""
data = _run_dws([DWS_BIN, "chat", "search", "--query", query,
"--limit", str(limit), "--format", "json"])
return data.get("result") or []
result = data.get("result") or {}
if isinstance(result, dict):
return result.get("groups") or []
return result or []
def _group_conv_id(group: dict) -> str:
@@ -388,32 +391,40 @@ def _group_conv_id(group: dict) -> str:
return ""
def _group_title(group: dict) -> str:
"""群搜索条目里的群名:dws chat search 返回的群名字段是 title(个别场景可能是 name)。"""
for key in ("title", "name"):
val = (group or {}).get(key)
if val:
return str(val)
return ""
def resolve_group_id(group_name: str) -> str:
"""按群名解析群聊 openconversation_id。
先模糊搜索候选,再按精确同名过滤;唯一命中即返回,多候选/无候选则报错带候选清单,
绝不自行假定第一个(与 resolve_open_id 的同名歧义处理一致)。
"""按群名精确解析群聊 openconversation_id(群名一律传全称)。
先按全称搜索,再对 title 做全等过滤:唯一命中即返回;无匹配或同名多个直接报错,
不采用模糊候选(绝不推给相近群名)。
"""
group_name = str(group_name or "").strip()
if not group_name:
raise RuntimeError("群名不能为空(请传群全称)")
groups = search_group(group_name)
if not groups:
raise RuntimeError(f"未找到群「{group_name}」,请确认群名后重试")
exact = [g for g in groups if (g.get("name") or "").strip() == group_name]
if exact:
groups = exact
candidates = [g for g in groups if _group_conv_id(g)]
if len(candidates) == 1:
g = candidates[0]
print(f"[INFO] 命中群: {g.get('name')} | openConversationId={_group_conv_id(g)}")
raise RuntimeError(f"未找到群「{group_name}」,请确认群全称后重试")
exact = [g for g in groups if _group_title(g) == group_name]
if len(exact) == 1:
g = exact[0]
print(f"[INFO] 命中群: {_group_title(g)} | openConversationId={_group_conv_id(g)}")
return _group_conv_id(g)
if not candidates:
if not exact:
hints = "\n".join(
f" {_group_title(g) or '未知群名'}" for g in groups)
raise RuntimeError(
f"群「{group_name}」搜索结果均无 openconversation_id,原始数据:{groups}")
f"未找到与「{group_name}」全等匹配的群,附近候选:\n{hints}")
hints = "\n".join(
f" {g.get('name') or '未知群名'} | {_group_conv_id(g)}" for g in candidates
)
f" {_group_title(g) or '未知群名'} | {_group_conv_id(g)}" for g in exact)
raise RuntimeError(
f"群名「{group_name}」匹配到 {len(candidates)} 个候选,请使用更精确的群名:\n{hints}"
)
f"群名「{group_name}」匹配到 {len(exact)} 个同名候选,请确认后重试:\n{hints}")
def send_group_text(conversation_id: str, text: str, title: str = "",
@@ -485,41 +496,6 @@ def send_group_message(group_name, content="", file_path="", title="",
record_dir, "", name, content, file_path)
def main_group(messages, record_dir=""):
"""影刀自定义指令「37du钉钉群聊推送」调用入口。
传入消息列表,每项支持 dict 或元组:
dict: {"group": 群名, "content": 文本, "file_path": 文件,
"title": 标题, "at_all": bool, "at_open_ids": "openId1,openId2"}
元组: (群名, 文本内容, 文件地址, 标题, at_all, at_open_ids),后 4 项可省略。
逐条发送,返回: {"success": bool, "message": str, "results": [...]}
"""
results = []
for item in messages or []:
if isinstance(item, dict):
group = item.get("group") or item.get("群名") or ""
content = item.get("content") or item.get("文本内容") or ""
file_path = item.get("file_path") or item.get("文件地址") or ""
title = item.get("title") or item.get("标题") or ""
at_all = bool(item.get("at_all") or item.get("@所有人"))
at_open_ids = item.get("at_open_ids") or item.get("@成员") or ""
else:
group = item[0] if len(item) > 0 else ""
content = item[1] if len(item) > 1 else ""
file_path = item[2] if len(item) > 2 else ""
title = item[3] if len(item) > 3 else ""
at_all = bool(item[4]) if len(item) > 4 else False
at_open_ids = item[5] if len(item) > 5 else ""
results.append(send_group_message(group, content, file_path, title,
at_all, at_open_ids, record_dir))
ok = sum(1 for r in results if r.get("success"))
_write_record_path_to_glv(record_dir)
return {
"success": ok == len(results),
"message": f"共 {len(results)} 条,成功 {ok},失败 {len(results) - ok}",
"results": results,
}
# ==================== 统一入口 ====================
def send_message(msg_type, name, user_id, content, file_path="", record_dir=""):
"""单条推送:按消息类型分发文本 / 文件。
@@ -565,34 +541,80 @@ def send_message(msg_type, name, user_id, content, file_path="", record_dir=""):
record_dir, name, user_id, content, file_path)
def main(messages, record_dir=""):
"""影刀自定义指令「37du钉钉单聊推送」调用入口。
传入消息列表,每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址),
缺省字段按空处理:
msg_type 'text'/'文本' 或 'file'/'文件'
name 接收人姓名
user_id 接收人工号
content 消息内容(文本类型必填)
file_path 文件地址(文件类型必填,可留空)
def _normalize_chat_type(chat_type: str) -> str:
"""推送通道归一化:'single'/'单聊' → 'single';'group'/'群聊' → 'group'"""
key = str(chat_type or "").strip().lower()
if key in ("single", "单聊", "single_chat", "person", "个人", "私聊"):
return "single"
if key in ("group", "群聊", "group_chat", "群"):
return "group"
raise ValueError(f"未知推送通道「{chat_type}」,仅支持:single/单聊、group/群聊")
def _item_is_group(item) -> bool:
"""按消息结构自动判断推送通道:dict 含 group/群名 键 → 群聊;其余(元组 / msg_type dict)→ 单聊。"""
return isinstance(item, dict) and bool(item.get("group") or item.get("群名"))
def main(messages, record_dir="", chat_type=""):
"""影刀自定义指令「37du钉钉推送」统一调用入口。
通道判定(二选一):
- chat_type 显式传 'single'/'group':整批消息强制按该通道发送(兼容旧流程);
- chat_type 留空(默认):按每条消息结构自动判断——dict 含 group/群名 键为群聊,其余为单聊。
因此流程只需传消息列表,群聊消息自带 group 字段即可,无需单独配置 chat_type。
chat_type='single'/单聊:每项为五元组 (消息类型, 姓名, 工号, 消息内容, 文件地址),
或 dict 含 msg_type/name/user_id(缺省字段按空处理):
msg_type 'text'/'文本' 或 'file'/'文件'
name 接收人姓名
user_id 接收人工号
content 消息内容(文本类型必填)
file_path 文件地址(文件类型必填,可留空)
chat_type='group'/群聊:每项支持 dict 或元组:
dict: {"group": 群名, "content": 文本, "file_path": 文件,
"title": 标题, "at_all": bool, "at_open_ids": "openId1,openId2"}
元组: (群名, 文本内容, 文件地址, 标题, at_all, at_open_ids),后 4 项可省略
record_dir(可选):非空时每条结果写入 <record_dir>/YYYY-MM-DD/推送记录.csv,
并把记录文件路径写入影刀全局变量 push_record_path,供流程自行处理失败名单。
逐条发送,返回: {"success": bool, "message": str, "results": [...]}
"""
forced_channel = _normalize_chat_type(chat_type) if chat_type else ""
results = []
for item in messages or []:
if isinstance(item, dict):
msg_type = item.get("msg_type") or item.get("消息类型") or ""
name = item.get("name") or item.get("姓名") or ""
user_id = item.get("user_id") or item.get("工号") or ""
content = item.get("content") or item.get("消息内容") or ""
file_path = item.get("file_path") or item.get("文件地址") or ""
if (forced_channel == "group") or (not forced_channel and _item_is_group(item)):
# 群聊:按群名解析 openconversation_id 后发送(文本/文件可同时存在)
if isinstance(item, dict):
group = item.get("group") or item.get("群名") or ""
content = item.get("content") or item.get("文本内容") or ""
file_path = item.get("file_path") or item.get("文件地址") or ""
title = item.get("title") or item.get("标题") or ""
at_all = bool(item.get("at_all") or item.get("@所有人"))
at_open_ids = item.get("at_open_ids") or item.get("@成员") or ""
else:
group = item[0] if len(item) > 0 else ""
content = item[1] if len(item) > 1 else ""
file_path = item[2] if len(item) > 2 else ""
title = item[3] if len(item) > 3 else ""
at_all = bool(item[4]) if len(item) > 4 else False
at_open_ids = item[5] if len(item) > 5 else ""
results.append(send_group_message(group, content, file_path, title,
at_all, at_open_ids, record_dir))
else:
msg_type = item[0] if len(item) > 0 else ""
name = item[1] if len(item) > 1 else ""
user_id = item[2] if len(item) > 2 else ""
content = item[3] if len(item) > 3 else ""
file_path = item[4] if len(item) > 4 else ""
results.append(send_message(msg_type, name, user_id, content, file_path, record_dir))
# 单聊:按姓名解析 openDingTalkId 后发送
if isinstance(item, dict):
msg_type = item.get("msg_type") or item.get("消息类型") or ""
name = item.get("name") or item.get("姓名") or ""
user_id = item.get("user_id") or item.get("工号") or ""
content = item.get("content") or item.get("消息内容") or ""
file_path = item.get("file_path") or item.get("文件地址") or ""
else:
msg_type = item[0] if len(item) > 0 else ""
name = item[1] if len(item) > 1 else ""
user_id = item[2] if len(item) > 2 else ""
content = item[3] if len(item) > 3 else ""
file_path = item[4] if len(item) > 4 else ""
results.append(send_message(msg_type, name, user_id, content, file_path, record_dir))
ok = sum(1 for r in results if r.get("success"))
_write_record_path_to_glv(record_dir)
return {
@@ -604,10 +626,12 @@ def main(messages, record_dir=""):
if __name__ == "__main__":
# 本地自测/接口说明:不实际发送。业务脚本请 import 后调用
# main([("文本", "姓名", "工号", "消息内容", ""),
# ("文件", "姓名", "工号", "", r"文件绝对路径")])
# main_group([{"group": "群名", "content": "消息内容"},
# {"group": "群名", "content": "", "file_path": r"文件绝对路径"}])
# 单聊(chat_type 留空自动识别):
# main([("文本", "姓名", "工号", "消息内容", ""),
# ("文件", "姓名", "工号", "", r"文件绝对路径")])
# 群聊(消息 dict 含 group 键自动识别,无需传 chat_type):
# main([{"group": "群名", "content": "消息内容"},
# {"group": "群名", "content": "", "file_path": r"文件绝对路径"}])
messages = [
{"msg_type": "text", "name": "夏一平", "user_id": "37036361", "content": "你好,这是由ai推送的文本消息"},
# {"msg_type": "file", "name": "夏一平", "user_id": "37036361", "file_path": r"C:\Users\admin\Desktop\test.xlsx"},