chore: 版本升级至1.1.8,新增钉钉账号通知等功能

1. 版本号更新:shell.version与install.iss同步升级到1.1.8
2. 新增钉钉账号创建通知:新用户收账号密码,管理员收权限提醒
3. 优化钉钉扫码登录逻辑:自动补全账号信息并同步昵称
4. 修复首次改密校验逻辑,统一初始密码验证规则
5. 新增AGENTS文档写入操作沙箱规避规范
6. 优化雇主险调度脚本,新增四级部门自动填充逻辑
7. 重构前端更新弹窗,将下载进度从顶部条改为独立弹窗
8. 新增EHR考勤异常检查脚本,优化打卡判定逻辑
This commit is contained in:
2026-09-18 21:25:43 +08:00
parent a649a938e6
commit e0f16d6eb1
14 changed files with 1134 additions and 598 deletions
+1
View File
@@ -6,6 +6,7 @@ AI 智能体开发约束 & 项目执行规范
- 默认强制使用本地 .venv 虚拟环境,禁止使用任何沙箱环境、在线临时环境、容器模拟环境。
- 所有代码运行、依赖安装、调试、语法检查、模块测试,均基于项目根目录 .venv 环境执行。
- 如需安装依赖,仅操作本地虚拟环境,不污染全局 Python 环境。
- 所有需要【写入文件内容】的操作(导出落盘、覆盖目标文件、复制/移动文件、下载保存等)一律不使用沙箱:执行时触发沙箱外运行(requires_approval 申请用户批准),避免被沙箱拦截(如 D:\资料 等受保护目录只读可读、写入被拒)。
2. 影刀开发规范
- 影刀项目默认采用单文件自包含架构。
- 输出影刀脚本、逻辑代码、流程封装时,优先单文件独立实现,功能自包含、可直接导入运行,不拆分冗余子文件。
+25
View File
@@ -0,0 +1,25 @@
# -*- coding: utf-8 -*-
"""临时验证脚本:用实际 Excel 数据验证新 _match_rule 筛选(用后即删)"""
import sys
sys.path.insert(0, r"d:\work\code\37duAutomation\workflows\XQ0015 参保成功及异常告知书制作与下发")
import py_compile
py_compile.compile(r"d:\work\code\37duAutomation\workflows\XQ0015 参保成功及异常告知书制作与下发\notice_mail_merge.py", doraise=True)
print("SYNTAX OK")
import notice_mail_merge as nm
excel = r"D:\资料\人资\告知书制作与下发\2026年9月社保变更及增减名单及人数统计.xlsx"
records = nm._read_insurance_records(excel)
print("参保名单记录数:", len(records))
if records:
keys = [k for k in records[0].keys()]
print("首条字段数:", len(keys), "含参保告知:", "参保告知" in keys, "含费用:", "费用" in keys)
for rn, rule in nm.TEMPLATES.items():
if rn == "社保转移":
continue
matched = [r for r in records if nm._match_rule(r, rule["status"], rule["type"])]
print(f"[{rn}] status={rule['status']} type={rule['type']} -> 命中 {len(matched)} 人")
for r in matched[:10]:
print(" ", r.get("姓名"), "| 参保类型:", r.get("参保类型"), "| 办理状态:", r.get("办理状态"),
"| 参保告知:", repr(r.get("参保告知")), "| 费用:", r.get("费用"), "| 人员类型:", r.get("人员类型"), "| 二级部门:", r.get("二级部门"))
+175 -381
View File
@@ -1,383 +1,177 @@
{
"code": "10000",
"msg": null,
"subCode": "200",
"subMsg": "",
"data": {
"pageSize": 10,
"pageIndex": 0,
"total": 8,
"data": [
{
"bws041": null,
"bws061": null,
"bws021": "2098294969579888640",
"bws211": null,
"bws102": "2098295046716928000",
"aab003": "91500107MA61B4BT7B",
"aac001": null,
"aac002": "511381199310155558",
"aac003": "席枭阳",
"aae200": null,
"aae201": null,
"aae202": null,
"aad030": null,
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aab001": "30009572",
"aab004": "重庆金色湖畔酒店管理有限公司",
"aaa121": "Z1001",
"aaa120": "企业职工人员增加",
"xh": null,
"aae014": "1858909245211283457",
"aae015": "2026-09-11 14:19:37.0",
"aae110s": "审核通过",
"aae110": "1",
"aae111": "若申报险种有医疗保险、生育保险,申报信息已同步推送医保部门,最终以医保部门审核结果为准。",
"aae100": "1",
"aae002": "202609",
"asl001": "10049406053875",
"aae030": null,
"aae031": null,
"aae099": null,
"aae140": null,
"aab084": null,
"aab085": null,
"aab086": null,
"itmes": null,
"baz001": null,
"aae005": "18323329271"
},
{
"bws041": null,
"bws061": null,
"bws021": "2098294969579888641",
"bws211": null,
"bws102": "2098295046716928000",
"aab003": "91500107MA61B4BT7B",
"aac001": null,
"aac002": "511602198907066992",
"aac003": "肖飞",
"aae200": null,
"aae201": null,
"aae202": null,
"aad030": null,
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aab001": "30009572",
"aab004": "重庆金色湖畔酒店管理有限公司",
"aaa121": "Z1001",
"aaa120": "企业职工人员增加",
"xh": null,
"aae014": "1858909245211283457",
"aae015": "2026-09-11 14:19:37.0",
"aae110s": "审核通过",
"aae110": "1",
"aae111": "若申报险种有医疗保险、生育保险,申报信息已同步推送医保部门,最终以医保部门审核结果为准。",
"aae100": "1",
"aae002": "202609",
"asl001": "10049406053875",
"aae030": null,
"aae031": null,
"aae099": null,
"aae140": null,
"aab084": null,
"aab085": null,
"aab086": null,
"itmes": null,
"baz001": null,
"aae005": "17508262764"
},
{
"bws041": null,
"bws061": null,
"bws021": "2098294969579888642",
"bws211": null,
"bws102": "2098295046716928000",
"aab003": "91500107MA61B4BT7B",
"aac001": null,
"aac002": "51290219790311446X",
"aac003": "吴长春",
"aae200": null,
"aae201": null,
"aae202": null,
"aad030": null,
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aab001": "30009572",
"aab004": "重庆金色湖畔酒店管理有限公司",
"aaa121": "Z1001",
"aaa120": "企业职工人员增加",
"xh": null,
"aae014": "1858909245211283457",
"aae015": "2026-09-11 14:19:37.0",
"aae110s": "不通过",
"aae110": "2",
"aae111": "status 400 reading PersonRegisterApiClient#executeRegisterPerson(PersonInfoDTO)",
"aae100": "1",
"aae002": "202609",
"asl001": "10049406053875",
"aae030": null,
"aae031": null,
"aae099": null,
"aae140": null,
"aab084": null,
"aab085": null,
"aab086": null,
"itmes": null,
"baz001": null,
"aae005": "18090507933"
},
{
"bws041": null,
"bws061": null,
"bws021": "2098294969579888643",
"bws211": null,
"bws102": "2098295046716928000",
"aab003": "91500107MA61B4BT7B",
"aac001": null,
"aac002": "500113200506014322",
"aac003": "殷李圆",
"aae200": null,
"aae201": null,
"aae202": null,
"aad030": null,
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aab001": "30009572",
"aab004": "重庆金色湖畔酒店管理有限公司",
"aaa121": "Z1001",
"aaa120": "企业职工人员增加",
"xh": null,
"aae014": "1858909245211283457",
"aae015": "2026-09-11 14:19:37.0",
"aae110s": "不通过",
"aae110": "2",
"aae111": "status 400 reading PersonRegisterApiClient#executeRegisterPerson(PersonInfoDTO)",
"aae100": "1",
"aae002": "202609",
"asl001": "10049406053875",
"aae030": null,
"aae031": null,
"aae099": null,
"aae140": null,
"aab084": null,
"aab085": null,
"aab086": null,
"itmes": null,
"baz001": null,
"aae005": "15696188987"
},
{
"bws041": null,
"bws061": null,
"bws021": "2098294969579888644",
"bws211": null,
"bws102": "2098295046716928000",
"aab003": "91500107MA61B4BT7B",
"aac001": null,
"aac002": "511304200206221327",
"aac003": "付冬秀",
"aae200": null,
"aae201": null,
"aae202": null,
"aad030": null,
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aab001": "30009572",
"aab004": "重庆金色湖畔酒店管理有限公司",
"aaa121": "Z1001",
"aaa120": "企业职工人员增加",
"xh": null,
"aae014": "1858909245211283457",
"aae015": "2026-09-11 14:19:37.0",
"aae110s": "审核通过",
"aae110": "1",
"aae111": "若申报险种有医疗保险、生育保险,申报信息已同步推送医保部门,最终以医保部门审核结果为准。",
"aae100": "1",
"aae002": "202609",
"asl001": "10049406053875",
"aae030": null,
"aae031": null,
"aae099": null,
"aae140": null,
"aab084": null,
"aab085": null,
"aab086": null,
"itmes": null,
"baz001": null,
"aae005": "19122971035"
},
{
"bws041": null,
"bws061": null,
"bws021": "2098294969579888645",
"bws211": null,
"bws102": "2098295046716928000",
"aab003": "91500107MA61B4BT7B",
"aac001": null,
"aac002": "511622199812259425",
"aac003": "易伟列",
"aae200": null,
"aae201": null,
"aae202": null,
"aad030": null,
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aab001": "30009572",
"aab004": "重庆金色湖畔酒店管理有限公司",
"aaa121": "Z1001",
"aaa120": "企业职工人员增加",
"xh": null,
"aae014": "1858909245211283457",
"aae015": "2026-09-11 14:19:37.0",
"aae110s": "不通过",
"aae110": "2",
"aae111": "status 400 reading PersonRegisterApiClient#executeRegisterPerson(PersonInfoDTO)",
"aae100": "1",
"aae002": "202609",
"asl001": "10049406053875",
"aae030": null,
"aae031": null,
"aae099": null,
"aae140": null,
"aab084": null,
"aab085": null,
"aab086": null,
"itmes": null,
"baz001": null,
"aae005": "15608313153"
},
{
"bws041": null,
"bws061": null,
"bws021": "2098294969579888646",
"bws211": null,
"bws102": "2098295046716928000",
"aab003": "91500107MA61B4BT7B",
"aac001": null,
"aac002": "500221198608205133",
"aac003": "蒋洁",
"aae200": null,
"aae201": null,
"aae202": null,
"aad030": null,
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aab001": "30009572",
"aab004": "重庆金色湖畔酒店管理有限公司",
"aaa121": "Z1001",
"aaa120": "企业职工人员增加",
"xh": null,
"aae014": "1858909245211283457",
"aae015": "2026-09-11 14:19:37.0",
"aae110s": "不通过",
"aae110": "2",
"aae111": "status 400 reading PersonRegisterApiClient#executeRegisterPerson(PersonInfoDTO)",
"aae100": "1",
"aae002": "202609",
"asl001": "10049406053875",
"aae030": null,
"aae031": null,
"aae099": null,
"aae140": null,
"aab084": null,
"aab085": null,
"aab086": null,
"itmes": null,
"baz001": null,
"aae005": "18908365870"
},
{
"bws041": null,
"bws061": null,
"bws021": "2098294969579888647",
"bws211": null,
"bws102": "2098295046716928000",
"aab003": "91500107MA61B4BT7B",
"aac001": null,
"aac002": "50010519990524033X",
"aac003": "李国鑫",
"aae200": null,
"aae201": null,
"aae202": null,
"aad030": null,
"aad013": null,
"abi030": null,
"abj030": null,
"abk030": null,
"abl030": null,
"abm030": null,
"abi031": null,
"abj040": null,
"aab001": "30009572",
"aab004": "重庆金色湖畔酒店管理有限公司",
"aaa121": "Z1001",
"aaa120": "企业职工人员增加",
"xh": null,
"aae014": "1858909245211283457",
"aae015": "2026-09-11 14:19:37.0",
"aae110s": "审核通过",
"aae110": "1",
"aae111": "若申报险种有医疗保险、生育保险,申报信息已同步推送医保部门,最终以医保部门审核结果为准。",
"aae100": "1",
"aae002": "202609",
"asl001": "10049406053875",
"aae030": null,
"aae031": null,
"aae099": null,
"aae140": null,
"aab084": null,
"aab085": null,
"aab086": null,
"itmes": null,
"baz001": null,
"aae005": "17633503787"
}
],
"lastPageIndex": 0,
"pageCount": 1
}
"attributeMap" : null,
"count" : 1,
"datas" : [ {
"ORG_FULL_PATH" : "集团-金色印象事业部-第二大区-金色印象长沙经营中心-第三片区-八一路行政会馆-服务组",
"person_status" : "2",
"IDCARD" : "511823200909152619",
"base_code" : "37036650",
"POST_NO" : "287",
"BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469",
"BELONG_UNIT_ORG_NAME" : "金色印象事业部",
"POST_ALIAS" : "服务员",
"POST_ORG_NAME" : "服务员",
"staff_id" : "9bbaec51-f4aa-4271-bb75-44583d510331",
"staff_name" : "李俊熙",
"DEPT_STRU_ID" : "57fab6e7-c7fd-4ffa-ac1a-0a085a05f7de",
"DEPT_ORG_NAME" : "服务组",
"POST_ALIAS_NAME" : "服务员",
"leave_type" : "17",
"DEPT_ORG_ONE" : "第二大区",
"DEPT_ORG_TWO" : "金色印象长沙经营中心",
"DEPT_ORG_THREE" : "第三片区",
"DEPT_ORG_FOUR" : "八一路行政会馆",
"DEPT_ORG_FIVE" : "服务组",
"dept_one" : null,
"dept_two" : null,
"vacation_type_name" : "特殊事假",
"time_unit" : "天",
"start_time" : "2026-08-30 10:00:00",
"end_time" : "2026-08-30 19:00:00",
"leave_num" : "1",
"leave_reason" : "处理个人事务",
"status" : "005",
"leave_hours" : "",
"leave_days" : "1.00",
"businessKey" : "bpmc6afb65ed9a14078a467c0045994ad3e",
"process_id" : "dc63c919-04db-4fa1-9f6d-0eaa76037f90",
"form_id" : "399b1612-d410-4a59-86cb-b5260b933232",
"source" : "1",
"leave_id" : "bpmc6afb65ed9a14078a467c0045994ad3e",
"operat_time" : "2026-09-01 21:11:56",
"apply_time" : "2026-09-01 16:24:55",
"leave_hours_ori" : "0",
"leave_days_ori" : "1",
"begin_date" : "2026-08-30",
"begin_other_name" : "1",
"end_date" : "2026-08-30",
"end_other_name" : "2",
"if_other_name_open" : "1",
"begin_date_other_name" : "2026-08-30 上半段",
"end_date_other_name" : "2026-08-30 下半段",
"operat_user_id" : "fdb2e691-1f5c-46f1-b2b4-d69987a4ac96",
"operat_user_name" : "谌超",
"processing_reason" : null,
"remark" : null,
"kqext_create_user_id" : null,
"kqext_create_time" : null,
"kqext_operator_id" : null,
"kqext_operate_time" : null,
"hrext_hsb_ext_speciality" : null,
"hrext_ext_technician_code" : "",
"hrext_ext_cal_person2" : "",
"hrext_ext_call_phone2" : "",
"hrext_ext_star_level" : "正式",
"hrext_ext_rehiring_reason_type" : "",
"hrext_ext_staff_type" : "门店服务岗",
"hrext_ext_insurance_type" : "雇主险",
"hrext_ext_recruit_way" : "其它",
"hrext_ext_call_relationship2" : "",
"hrext_ext_is_CRBT_open" : "",
"hrext_ext_dept_principal" : "",
"hrext_ext_yb_pay_year" : "",
"hrext_ext_Have_worked" : "",
"hrext_ext_family_join" : "否",
"hrext_ext_criminal_record" : "否",
"hrext_ext_infectious_disease" : "否",
"hrext_ext_References" : "",
"hrext_ext_References_phone" : "",
"hrext_ext_References_outside" : "",
"hrext_ext_outside_References_phone" : "",
"hrext_ext_is_dormitory" : "是",
"hrext_ext_process_approval_status" : "已审批",
"hrext_ext_trans_type" : "其他"
} ],
"pageSize" : 15,
"start" : 0,
"pageNo" : 1,
"pageCount" : 1,
"allDatas" : {
"#result-set-1" : [ {
"ORG_FULL_PATH" : "集团-金色印象事业部-第二大区-金色印象长沙经营中心-第三片区-八一路行政会馆-服务组",
"person_status" : "2",
"IDCARD" : "511823200909152619",
"base_code" : "37036650",
"POST_NO" : "287",
"BELONG_UNIT_STRU_ID" : "0bcdedeb-e592-11ee-b449-000c296f9469",
"BELONG_UNIT_ORG_NAME" : "金色印象事业部",
"POST_ALIAS" : "服务员",
"POST_ORG_NAME" : "服务员",
"staff_id" : "9bbaec51-f4aa-4271-bb75-44583d510331",
"staff_name" : "李俊熙",
"DEPT_STRU_ID" : "57fab6e7-c7fd-4ffa-ac1a-0a085a05f7de",
"DEPT_ORG_NAME" : "服务组",
"POST_ALIAS_NAME" : "服务员",
"leave_type" : "17",
"DEPT_ORG_ONE" : "第二大区",
"DEPT_ORG_TWO" : "金色印象长沙经营中心",
"DEPT_ORG_THREE" : "第三片区",
"DEPT_ORG_FOUR" : "八一路行政会馆",
"DEPT_ORG_FIVE" : "服务组",
"dept_one" : null,
"dept_two" : null,
"vacation_type_name" : "特殊事假",
"time_unit" : "天",
"start_time" : "2026-08-30 10:00:00",
"end_time" : "2026-08-30 19:00:00",
"leave_num" : "1",
"leave_reason" : "处理个人事务",
"status" : "005",
"leave_hours" : "",
"leave_days" : "1.00",
"businessKey" : "bpmc6afb65ed9a14078a467c0045994ad3e",
"process_id" : "dc63c919-04db-4fa1-9f6d-0eaa76037f90",
"form_id" : "399b1612-d410-4a59-86cb-b5260b933232",
"source" : "1",
"leave_id" : "bpmc6afb65ed9a14078a467c0045994ad3e",
"operat_time" : "2026-09-01 21:11:56",
"apply_time" : "2026-09-01 16:24:55",
"leave_hours_ori" : "0",
"leave_days_ori" : "1",
"begin_date" : "2026-08-30",
"begin_other_name" : "1",
"end_date" : "2026-08-30",
"end_other_name" : "2",
"if_other_name_open" : "1",
"begin_date_other_name" : "2026-08-30 上半段",
"end_date_other_name" : "2026-08-30 下半段",
"operat_user_id" : "fdb2e691-1f5c-46f1-b2b4-d69987a4ac96",
"operat_user_name" : "谌超",
"processing_reason" : null,
"remark" : null,
"kqext_create_user_id" : null,
"kqext_create_time" : null,
"kqext_operator_id" : null,
"kqext_operate_time" : null,
"hrext_hsb_ext_speciality" : null,
"hrext_ext_technician_code" : "",
"hrext_ext_cal_person2" : "",
"hrext_ext_call_phone2" : "",
"hrext_ext_star_level" : "正式",
"hrext_ext_rehiring_reason_type" : "",
"hrext_ext_staff_type" : "门店服务岗",
"hrext_ext_insurance_type" : "雇主险",
"hrext_ext_recruit_way" : "其它",
"hrext_ext_call_relationship2" : "",
"hrext_ext_is_CRBT_open" : "",
"hrext_ext_dept_principal" : "",
"hrext_ext_yb_pay_year" : "",
"hrext_ext_Have_worked" : "",
"hrext_ext_family_join" : "否",
"hrext_ext_criminal_record" : "否",
"hrext_ext_infectious_disease" : "否",
"hrext_ext_References" : "",
"hrext_ext_References_phone" : "",
"hrext_ext_References_outside" : "",
"hrext_ext_outside_References_phone" : "",
"hrext_ext_is_dormitory" : "是",
"hrext_ext_process_approval_status" : "已审批",
"hrext_ext_trans_type" : "其他"
} ]
},
"url" : null,
"state" : "1",
"meg" : "",
"des" : "",
"viewMapper" : null
}
+3
View File
@@ -17,6 +17,7 @@ from controlplane import config, schemas
from controlplane.core.auth import _require_admin, _resolve_login
from controlplane.core.crypto import _hash_password
from controlplane.core.db import _audit, _db, _now
from controlplane.core.notify import notify_account_created
from controlplane.core.pkgutil import (
_SAFE_NAME_RE, _extract_manifest, _load_manifest, _prune_versions,
_validate_pkg_zip, _version_key,
@@ -67,6 +68,8 @@ def admin_account_create(a: schemas.AccountCreateIn,
(account, _hex, _salt, int(a.is_admin), (a.dept or "").strip(),
(a.nickname or "").strip(), _now()))
conn.commit()
# 钉钉工作通知(异步,失败不阻断建号):新用户收账号密码(按昵称解析),管理员收权限开通提醒
notify_account_created(account, (a.nickname or "").strip(), a.password, source="管理台")
return {"ok": True, "account": account, "dept": (a.dept or "").strip(),
"nickname": (a.nickname or "").strip(), "is_admin": a.is_admin}
+38 -13
View File
@@ -10,12 +10,13 @@ from fastapi import APIRouter, Header, HTTPException
from controlplane import config, schemas
from controlplane.core.auth import (
_AUTH_FAILS, _auth_account_lookup, _auth_fail, _auth_gate, _check_token,
_AUTH_FAILS, _auth_fail, _auth_gate, _check_token,
_cloud_account, _issue_cloud_token, _resolve_login, _require_admin, _sign_admin_token,
)
from controlplane.core.crypto import _hash_password, _verify_password
from controlplane.core.db import _db
from controlplane.core.dingtalk import _dingtalk_userinfo
from controlplane.core.notify import notify_account_created
router = APIRouter()
@@ -117,9 +118,8 @@ def admin_password(p: schemas.PwdIn,
(login,)).fetchone()
if not row:
raise HTTPException(401, "账号不存在")
# 首次登录(must_change_pwd=1,钉钉自动建号的默认密码)允许免旧密码直接改密
if not row["must_change_pwd"] and (
not row["salt"] or not _verify_password(p.old_password, row["salt"], row["password_hash"])):
# 旧密码校验(所有账号均带盐;首次改密的旧密码 = 钉钉通知下发的初始密码,同样必须输入)
if not row["salt"] or not _verify_password(p.old_password, row["salt"], row["password_hash"]):
raise HTTPException(401, "原密码错误")
_hex, _salt = _hash_password(p.new_password)
with _db() as conn:
@@ -130,14 +130,15 @@ def admin_password(p: schemas.PwdIn,
# ==================== 员工端登录 /auth/exchange(v3 最简方案,壳本机直连接 code) ====================
# 壳 login 云端的唯一接口:壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 只验证不建号
# → 签发云端会话 token(供壳调 /api/plugins 鉴权,见 apis/plugins §2.2)。token 存储统一在
# core.auth(_issue_cloud_token 签发落库 cloud_tokens 表、_cloud_account 解析),此处不再重复声明。
# 壳 login 云端的唯一接口:壳把浏览器带回的钉钉 code POST 到此,用 AppSecret 换身份 → 找建账号
# (不存在则自动建号:空壳+默认密码+强制改密,并推送钉钉通知)→ 签发云端会话 token(供壳调
# /api/plugins 鉴权,见 apis/plugins §2.2)。token 存储统一在 core.auth(_issue_cloud_token 签发
# 落库 cloud_tokens 表、_cloud_account 解析),此处不再重复声明。
@router.post("/auth/exchange")
def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
"""壳 → 云端:壳 POST 钉钉授权码 code,换取员工工号 + 云端会话 token(只验证不建号)。"""
"""壳 → 云端:壳 POST 钉钉授权码 code,换取员工工号 + 云端会话 token(找建账号)。"""
code = (d.code or "").strip()
if not code:
raise HTTPException(400, "缺少 code")
@@ -147,9 +148,33 @@ def auth_exchange(d: schemas.AuthExchangeIn) -> dict:
account = (info.get("account") or "").strip()
if not account:
raise HTTPException(401, "扫码未解析到有效账号,请重新扫码")
acct = _auth_account_lookup(account)
nickname = acct["nickname"] or (info.get("nickname") or "")
nickname = (info.get("nickname") or "").strip()
unionid = (info.get("unionid") or "").strip()
# 找建账号(与 /api/admin/dingtalk/auth 同语义):已存在则同步昵称;不存在则自动建号并通知
with _db() as conn:
row = conn.execute(
"SELECT nickname, status, must_change_pwd FROM accounts WHERE account = %s",
(account,)).fetchone()
if row:
if not row["status"]:
raise HTTPException(403, "账号已停用,请联系管理员")
if nickname and nickname != (row["nickname"] or ""):
conn.execute("UPDATE accounts SET nickname = %s WHERE account = %s",
(nickname, account))
conn.commit()
created, must_change = False, bool(row["must_change_pwd"])
else:
# 自动建号(空壳):初始密码取默认值,强制首次改密
pwd = config.DINGTALK_DEFAULT_PASSWORD
_hex, _salt = _hash_password(pwd)
conn.execute(
"INSERT INTO accounts(account, password_hash, salt, is_admin, dept, nickname, "
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
(account, _hex, _salt, nickname, unionid))
conn.commit()
created, must_change = True, True
notify_account_created(account, nickname, pwd, unionid, source="钉钉扫码")
token = _issue_cloud_token(account, nickname)
return {"token": token,
"account": account, "nickname": nickname,
"exists": bool(acct["exists"]), "is_admin": False}
return {"token": token, "account": account, "nickname": nickname,
"exists": True, "created": created, "must_change_pwd": must_change,
"is_admin": False}
+3
View File
@@ -18,6 +18,7 @@ from controlplane.core.auth import _check_token, _sign_admin_token
from controlplane.core.crypto import _hash_password
from controlplane.core.db import _db
from controlplane.core.dingtalk import _dingtalk_sns_userinfo, _dingtalk_userinfo
from controlplane.core.notify import notify_account_created
router = APIRouter()
@@ -63,6 +64,8 @@ def admin_dingtalk_auth(d: schemas.DingTalkIn,
"dingtalk_uid, must_change_pwd) VALUES (%s, %s, %s, 0, '', %s, %s, 1)",
(account, _hex, _salt, nickname, ding_uid))
conn.commit()
# 钉钉工作通知(异步,失败不阻断建号):新用户收默认账号密码,管理员收权限开通提醒
notify_account_created(account, nickname, pwd, ding_uid, source="钉钉扫码")
return {"ok": True, "account": account, "nickname": nickname,
"is_admin": False, "created": True, "must_change_pwd": True,
"token": _sign_admin_token(account)}
+9
View File
@@ -71,6 +71,15 @@ DINGTALK_APP_SECRET = os.getenv("DINGTALK_APP_SECRET", "")
# 钉钉扫码回调地址。网页扫码是"浏览器重定向"(非钉钉服务器回访),故可直接用内网 IP/域名,
# 只要与用户实际访问地址、钉钉后台登记的回调域名一致即可。留空禁用扫码。
DINGTALK_CALLBACK = os.getenv("DINGTALK_CALLBACK", "").rstrip("/")
# 钉钉群机器人通知(新账号创建等事件推送)。webhook 留空则静默跳过;加签密钥按机器人安全设置可选。
DINGTALK_WEBHOOK_URL = os.getenv("DINGTALK_WEBHOOK_URL", "")
DINGTALK_WEBHOOK_SECRET = os.getenv("DINGTALK_WEBHOOK_SECRET", "")
# 钉钉自建应用工作通知(corpconversation 异步推送)。AgentId 优先 DINGTALK_AGENT_ID,
# 兜底复用 CREDS_DINGTALK_AGENT_ID(同一套钉钉应用凭证);access_token 复用 DINGTALK_APP_KEY/SECRET。
DINGTALK_AGENT_ID = (os.getenv("DINGTALK_AGENT_ID", "")
or os.getenv("CREDS_DINGTALK_AGENT_ID", "")).strip()
# 权限开通提醒的管理员姓名(钉钉扫码自动建号时通知其开通权限),经「搜索用户」接口直查 userid。
DINGTALK_ADMIN_NAME = os.getenv("DINGTALK_ADMIN_NAME", "夏一平")
# 客户端敏感凭证默认值参考(webhost 不再明文落盘,中心机 .env 为唯一可信明文源)。
# 明文源只由管理员经 /api/admin/creds/seed 录入;客户端 register 不再自动填充本默认值
+173
View File
@@ -0,0 +1,173 @@
# -*- coding: utf-8 -*-
"""钉钉通知:自建应用工作通知(markdown 美化样式,个人推送)+ 群机器人 webhook(渠道保留,备用)。
后台线程发送,失败仅记日志不阻断业务。
配置项(controlplane/.env):
DINGTALK_AGENT_ID 自建应用的 AgentId;留空则不发工作通知(APP_KEY/SECRET 复用扫码登录那套)
DINGTALK_ADMIN_NAME 权限开通提醒的管理员姓名(默认 夏一平),经「搜索用户」接口直查 userid
DINGTALK_WEBHOOK_URL 群机器人 webhook 地址(备用渠道,当前业务不自动发送)
DINGTALK_WEBHOOK_SECRET 群机器人加签密钥(安全设置选"加签"时必填;留空则不加签)
"""
from __future__ import annotations
import base64
import hashlib
import hmac
import json
import logging
import threading
import time
from urllib.parse import quote_plus
from urllib.request import Request, urlopen
from controlplane.core import config
from controlplane.core.dingtalk import _dingtalk_topapi_token
log = logging.getLogger(__name__)
# 消息署名与标题着色(样式对齐 workflows/share/dingtalk_robot.py 的 send)
_SIGN_NAME = "37du 自动化平台"
_STATUS_COLORS = {
"info": "#0077ff", # 蓝色
"success": "#00b300", # 绿色
"warning": "#ff9900", # 橙色
"error": "#ff0000", # 红色
}
def _footer() -> str:
return f"###### {_SIGN_NAME} | {time.strftime('%Y-%m-%d %H:%M:%S')}"
def _post_json(url: str, payload: dict, headers: dict | None = None) -> dict:
req = Request(url, data=json.dumps(payload).encode("utf-8"), method="POST")
req.add_header("Content-Type", "application/json")
for k, v in (headers or {}).items():
req.add_header(k, v)
with urlopen(req, timeout=10) as resp:
return json.loads(resp.read().decode("utf-8"))
# ==================== userid 解析(单次直查,不做通讯录遍历/缓存) ====================
def _userid_by_unionid(at: str, unionid: str) -> str:
"""unionid → userid(精确,无重名歧义)。"""
try:
body = _post_json(
"https://oapi.dingtalk.com/topapi/user/getbyunionid?access_token=%s" % at,
{"unionid": unionid})
return ((body.get("result") or {}).get("userid")) or ""
except Exception: # noqa: BLE001
return ""
def _userid_by_name(at: str, name: str) -> str:
"""姓名 → userid:调「搜索用户」接口单次直查,命中多人取第一个。"""
try:
body = _post_json(
"https://api.dingtalk.com/v1.0/contact/users/search",
{"queryWord": name.strip(), "offset": 0, "size": 5, "maxResults": 5},
headers={"x-acs-dingtalk-access-token": at})
lst = body.get("list") or []
return str(lst[0]) if lst else ""
except Exception as e: # noqa: BLE001 查询失败不阻断业务
log.warning("钉钉搜索用户失败(%s):%s", name, e)
return ""
# ==================== 渠道一:自建应用工作通知(markdown 美化样式) ====================
def _send_work_to(at: str, agent_id: str, userid: str, title: str, content: str,
status: str = "info") -> bool:
"""向单个 userid 发工作通知,样式对齐 workflows/share/dingtalk_robot.py 的 send:
彩色加粗标题 + 正文 Markdown 直接渲染(引用块字段)+「###### 署名 | 时间」页脚。"""
color = _STATUS_COLORS.get(status, _STATUS_COLORS["info"])
text = f"**<font color='{color}'>{title}</font>**\n\n"
text += content.strip() + "\n"
text += f"\n\n---\n\n{_footer()}"
try:
body = _post_json(
"https://oapi.dingtalk.com/topapi/message/corpconversation/asyncsend_v2?access_token=%s" % at,
{"agent_id": agent_id, "userid_list": userid,
"msg": {"msgtype": "markdown", "markdown": {"title": title, "text": text}}})
if body.get("errcode") != 0:
log.warning("钉钉工作通知被拒: %s", body)
return False
return True
except Exception as e: # noqa: BLE001 通知失败不阻断业务
log.warning("钉钉工作通知异常: %s", e)
return False
# ==================== 统一入口:新账号创建通知(管理台/钉钉扫码共用) ====================
def _work_created(account: str, nickname: str, password: str, unionid: str, source: str) -> None:
agent_id = (config.DINGTALK_AGENT_ID or "").strip()
if not agent_id:
return
try:
at = _dingtalk_topapi_token()
if not at:
log.warning("钉钉建号通知失败:未配置 DINGTALK_APP_KEY/SECRET 或取 token 失败")
return
# 1) 新用户本人:unionid 精确解析 userid,兜底按昵称搜索直查
uid = _userid_by_unionid(at, unionid) if unionid else ""
if not uid and nickname:
uid = _userid_by_name(at, nickname)
if uid:
_send_work_to(
at, agent_id, uid, "账号开通通知",
f"**🔹 {nickname or account}‑账号开通**\n\n"
f"> 账号:{account}\n\n"
f"> 初始密码:{password}\n\n"
"> 备注:首次登录须修改密码,请及时登录并妥善保管",
status="success")
else:
log.warning("钉钉建号通知:无法解析新用户 userid(account=%s)", account)
# 2) 管理员:权限开通提醒(按姓名搜索直查,默认 夏一平)
admin_name = (config.DINGTALK_ADMIN_NAME or "夏一平").strip()
admin_uid = _userid_by_name(at, admin_name)
if admin_uid:
_send_work_to(
at, agent_id, admin_uid, "新账号待开通权限",
f"> 账号:{account}\n\n"
f"> 姓名:{nickname or '—'}\n\n"
f"> 来源:{source}\n\n"
"> 备注:请到管理台为该账号开通插件权限",
status="warning")
else:
log.warning("钉钉建号通知:管理员 %s 未搜索到 userid", admin_name)
except Exception as e: # noqa: BLE001 通知失败不阻断业务
log.warning("钉钉建号通知异常: %s", e)
def notify_account_created(account: str, nickname: str = "", password: str = "",
unionid: str = "", source: str = "管理台") -> None:
"""新账号创建通知(新用户收账号+初始密码,管理员收权限开通提醒),后台线程发送。"""
threading.Thread(target=_work_created, args=(account, nickname, password, unionid, source),
daemon=True).start()
# ==================== 渠道二:群机器人 webhook(+ 加签) ====================
def _signed_webhook_url() -> str:
url = (config.DINGTALK_WEBHOOK_URL or "").strip()
if not url:
return ""
secret = (config.DINGTALK_WEBHOOK_SECRET or "").strip()
if secret:
ts = str(int(time.time() * 1000))
sign = base64.b64encode(hmac.new(
secret.encode("utf-8"), f"{ts}\n{secret}".encode("utf-8"),
hashlib.sha256).digest()).decode("utf-8")
url += ("&" if "?" in url else "?") + f"timestamp={ts}&sign={quote_plus(sign)}"
return url
def _send_robot(title: str, text: str) -> None:
url = _signed_webhook_url()
if not url:
return
try:
body = _post_json(url, {"msgtype": "markdown", "markdown": {"title": title, "text": text}})
if body.get("errcode") != 0:
log.warning("钉钉群通知被拒: %s", body)
except Exception as e: # noqa: BLE001 通知失败不阻断业务
log.warning("钉钉群通知异常: %s", e)
+47 -17
View File
@@ -6,16 +6,9 @@
</div>
<LoginPage v-else-if="!store.current" :app-name="store.appName" @ok="onLogin" />
<div class="__app" v-else>
<!-- 壳子更新提示:下载进度 / 已就绪重启更新 / 发现新版本可下载 -->
<!-- 壳子更新提示:已就绪重启更新 / 下载失败重试 / 发现新版本可下载(下载进度改用弹窗) -->
<div v-if="updBarVisible" class="update-bar">
<template v-if="updDl.status === 'downloading'">
<span class="upd-txt">正在下载新版本 <b>v{{ updDl.version }}</b></span>
<div class="upd-mid">
<el-progress :percentage="updDl.pct" :show-text="false" :stroke-width="6" class="upd-progress" />
<span class="upd-pct">{{ updDl.total ? updDl.pct + '%' : fmtBytes(updDl.received) }}</span>
</div>
</template>
<template v-else-if="shellUpdate.downloaded">
<template v-if="shellUpdate.downloaded">
<span class="upd-txt">发现新版本 <b>v{{ shellUpdate.new }}</b><em v-if="shellUpdate.notes">{{ shellUpdate.notes }}</em></span>
<el-button size="small" type="primary" round :loading="updating" @click="doShellUpdate">重启更新</el-button>
</template>
@@ -164,6 +157,29 @@
</div>
</div>
<ProfilePanel v-if="profileOpen" @close="profileOpen = false" />
<!-- 壳子更新下载进度弹窗:点击「立即下载」后弹出,可最小化到后台继续下载 -->
<el-dialog v-model="updDlg" :title="`下载更新 v${updDl.version || ''}`" width="420px"
:close-on-click-modal="false" align-center class="upd-dl-dialog">
<template v-if="updDl.status === 'downloading'">
<div class="dl-dlg-body">
<el-progress :percentage="updDl.pct || 0" :stroke-width="10" />
<span class="dl-dlg-bytes">{{ fmtBytes(updDl.received) }}{{ updDl.total ? ' / ' + fmtBytes(updDl.total) : '' }}</span>
</div>
</template>
<template v-else-if="updDl.status === 'failed'">
<div class="dl-dlg-body">
<span class="dl-dlg-err">下载失败:{{ updDl.error || '未知错误' }}</span>
</div>
</template>
<template v-else>
<div class="dl-dlg-body"><span>已下载完成</span></div>
</template>
<template #footer>
<el-button v-if="updDl.status === 'failed'" size="small" type="primary" round
:loading="downloading" @click="onShellDownload">重试</el-button>
<el-button size="small" round @click="updDlg = false">后台下载</el-button>
</template>
</el-dialog>
</template>
<script setup>
@@ -328,10 +344,10 @@ let shellPollTimer = null // 状态轮询(setTimeout 递归,下
let lastDlStatus = '' // 上一轮下载状态,用于下载完成/失败时的一次性提示
const updDl = computed(() => shellUpdate.value.dl || {})
const updDlg = ref(false) // 下载进度弹窗(点击「立即下载」后弹出)
const updBarVisible = computed(() =>
shellUpdate.value.downloaded ||
updDl.value.status === 'downloading' ||
updDl.value.status === 'failed' ||
(updDl.value.status === 'failed' && !updDlg.value) ||
(shellUpdate.value.available && !shellDismissed.value)
)
@@ -355,6 +371,7 @@ async function refreshShellStatus() {
shellUpdate.value = s
const st = s.dl?.status || ''
if (lastDlStatus === 'downloading' && st === 'downloaded') {
updDlg.value = false // 弹窗开着时自动收起,顶部提示条转为「重启更新」
ElMessage.success(`新版本 v${s.new} 已下载完成,点击顶部「重启更新」完成升级`)
log('INFO', `壳子新版本 v${s.new} 已就绪,可重启更新`)
} else if (lastDlStatus === 'downloading' && st === 'failed') {
@@ -383,6 +400,7 @@ async function onShellDownload() {
if (downloading.value) return
downloading.value = true
shellDismissed.value = false
updDlg.value = true // 点击下载即弹出进度弹窗,不再用页头条展示进度
// 点击即进入"下载中"反馈(不等轮询):内网直连下载很快,若靠 15s 轮询拉状态,
// 进度条可能还没显示就已经下载完,用户会以为点了没反应
const v = shellUpdate.value.latest || ''
@@ -542,13 +560,23 @@ async function onLogin(ok) {
async function promptChangePwd(account) {
try {
// 旧密码 = 钉钉通知下发的初始密码,必须输入校验(与个人中心改密一致)
let op = ''
try {
const { value } = await ElMessageBox.prompt(
'当前账号正使用默认密码,请输入钉钉通知中的初始密码',
'首次登录 · 身份验证',
{ inputType: 'password', inputPlaceholder: '请输入初始密码',
confirmButtonText: '下一步', cancelButtonText: '稍后再说' })
op = value
} catch (_) { return /* 用户取消 */ }
const { value: np } = await ElMessageBox.prompt(
'当前账号正使用默认密码,请立即设置新密码(至少 6 位),避免他人误登录',
'首次登录 · 修改密码',
'请设置新密码(至少 6 位),避免他人误登录',
'首次登录 · 设置新密码',
{ inputType: 'password', inputPattern: /^.{6,}$/, inputErrorMessage: '密码至少 6 位',
confirmButtonText: '设置新密码', cancelButtonText: '稍后再说' })
try {
await adminPassword({ account, old_password: '', new_password: np })
await adminPassword({ account, old_password: op, new_password: np })
ElMessage.success('密码已更新')
} catch (e) {
ElMessage.warning('改密失败:' + (e.message || e))
@@ -630,10 +658,12 @@ async function login(id) {
}
.update-bar b { color: var(--primary); }
.update-bar em { font-style: normal; color: var(--text-faint); margin-left: 6px; }
.update-bar .upd-mid { display: flex; align-items: center; gap: 10px; flex: 1; max-width: 340px; }
.update-bar .upd-progress { flex: 1; }
.update-bar .upd-pct { font-size: 12px; color: var(--text-faint); min-width: 46px; text-align: right; }
.update-bar .upd-actions { display: flex; align-items: center; gap: 8px; }
/* 壳子更新下载进度弹窗 */
.dl-dlg-body { display: flex; flex-direction: column; gap: 10px; padding: 4px 2px; }
.dl-dlg-bytes { font-size: 12px; color: var(--text-faint); text-align: right; }
.dl-dlg-err { color: var(--danger, #e5484d); font-size: 13px; line-height: 1.6; }
.brand { display: flex; align-items: center; gap: 11px; }
.logo {
width: 36px; height: 36px; border-radius: 10px;
+1 -1
View File
@@ -5,7 +5,7 @@
; 升级不覆盖机器已有 .env;不含 37du-host-console.exe(调试版)、plugins/(登录后自下载)
#define MyAppName "37du 自动化工作台"
#define MyAppVersion "1.1.7"
#define MyAppVersion "1.1.8"
#define MyAppExeName "37du-host.exe"
[Setup]
+1 -1
View File
@@ -1 +1 @@
1.1.7
1.1.8
@@ -4,7 +4,12 @@
@Author: 小布丁
@CreateTime: 2026-08-13
@Description: 雇主险名额调度系统「步骤2:调度」
@Version: 1.2.0
@Version: 1.3.0
- v1.3.0:变更清单「费用会馆」列(表头含"费用会馆"即可,如 O列 新增费用会馆)
自动填充四级部门——按证件号关联「花名册导出-雇主险使用基础信息」中
表头含"四级部门"的列,仅「纯新增名额」(全新新增)的 增加 记录填写;
当日一增一减(复用离职/参保减少/替换迁出释放的名额)及名额替换
(修改/删除+增加对)均不填;四级部门为空时回退填「所属单位」并记日志。
- v1.2.0:
1) 变更清单「修改」仅用于"自己的名额档次替换、不涉及其他人"(未复用他人名额
且自己的旧名额未被他人复用);涉及他人的替换输出正常两条(删除+增加)。
@@ -1043,13 +1048,29 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
else:
ws_change = wb[change_sheet_name]
# 清空B列(第2列)、M列备注(第13列)、N列(第14列)、P~S列(第16~19列)从第3行开始
# ---------- 定位 O列(费用会馆/四级部门列)----------
# 表头名不固定(如「新增费用会馆\n(自留后续划成本用)」),按"包含「费用会馆」"模糊匹配;
# 扫描前20列表头(第1/2行都可能),匹配不到时兜底第15列
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列(第2列)、M列备注(第13列)、N列(第14列)、四级部门列、P~S列(第16~19列)从第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 # 四级部门列(如 O列 新增费用会馆)
for col in range(16, 20): # P~S列
ws_change.cell(row=row, column=col).value = None
@@ -1121,8 +1142,20 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
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})
# 新参保人员:仅「全新新增」名额(纯新增,当日名额净增加)在 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
@@ -1138,6 +1171,10 @@ def output_results(final_records, change_log, reused_source_employees, biz_df,
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列
# 四级部门列(如 O列 新增费用会馆):仅纯新增名额(全新新增)的「增加」记录才填,
# 当日一增一减(复用离职/参保减少/替换迁出释放的名额)及名额替换均不填
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列
@@ -118,8 +118,11 @@ WORK_OVERTIME_TYPE_REST = "3"
HALF_DAY = 0.5
EPS = 1e-6
# 打卡与班段边界匹配容差(分钟):上班打卡在班段开始前后、下班打卡在班段结束前后
PUNCH_TOLERANCE_MIN = 60
# 下班卡最晚截止:次日凌晨 06:00(相对加班日 0 点的分钟数,即 24h+6h=30h)。
# 跨天打卡(次日 0 点 ~ 6 点)归入加班前一天的下班卡,与 XQ0004 加班审核
# CROSS_DAY_BEFORE_HOUR=6 口径一致;休息日/延时加班常跨天,次日 06:00 前
# 有打卡即视为正常下班。
NEXT_DAY_PUNCH_DEADLINE_MIN = 30 * 60
# 假期类型编码 → 名称(与 app 版 common/config.VACATION_TYPE_MAP 一致)
VACATION_TYPE_MAP = {
@@ -137,6 +140,28 @@ VACATION_TYPE_MAP = {
"24": "年度福利假",
}
# 小时特假:请假类型编码(检查1规则1——该类型允许存在考勤异常,不提示)
VACATION_TYPE_HOURLY = "18"
# 请假流程状态(bpm_status):001=申请中;002=已备案(生效);003=已撤销;004=销假中;
# 005=已销假;006=撤销加班;007=销差;008=已审批未备案。
# 检查1/3 只认 002 已备案的请假流程:已撤销(003)/已销假(005)/申请中(001)等
# 非生效假单在考勤报表里不体现,不构成有效请假(口径同 XQ0009 absence_analysis)。
ACTIVE_LEAVE_STATUS = "002"
# 上/下半段分界(分钟):早于 12:00 视为上半段,否则下半段
# (与 XQ0004 加班半天判定口径一致:申请开始时间早于 12:00 视为上午半天)
HALF_DAY_NOON_MIN = 12 * 60
# 休息日半天加班放宽打卡窗口(分钟):休息日加班打卡不必严格对齐计划时段,
# 覆盖常规上/下半段时段即视为正常——上半段 09:00 ~ 12:30,下半段 13:30 ~ 18:00
HALF_DAY_RELAX_MORNING = (9 * 60, 12 * 60 + 30)
HALF_DAY_RELAX_AFTERNOON = (13 * 60 + 30, 18 * 60)
# 休息日半天加班兜底(分钟):放宽窗口与计划时段均不满足时,
# 首末打卡跨度达到 4 小时即视为正常(240 分钟)
HALF_DAY_FALLBACK_MINUTES = 4 * 60
# ==================== 登录态(共享 cookies 文件) ====================
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 workflows/share/hr_login.py),
@@ -578,12 +603,17 @@ def _float(value, default=0.0):
def _is_half_day_ot(rec):
"""判断加班记录是否为休息日半天(0.5 天)。依次取 ot_days / sys_ot_days / plan_ot_days。"""
"""判断加班记录是否为休息日半天(0.5 天)。依次取 ot_days / sys_ot_days / plan_ot_days(第一个非空字段为准)。
注意:只以第一个非空字段的值作判定,不能三个字段任一等于 0.5 即判半天——
休息日整日加班(ot_days=1.0)的 sys_ot_days 也可能是 0.5,若按任一字段判断会
把整日加班误当成半天加班(检查2误报)。ot_days 为审核天数,与 plan_ot_days 一致,
是本判定的权威字段。
"""
for key in ("ot_days", "sys_ot_days", "plan_ot_days"):
val = rec.get(key)
if val is not None and val != "":
if abs(_float(val) - HALF_DAY) <= EPS:
return True
return abs(_float(val) - HALF_DAY) <= EPS
return False
@@ -596,22 +626,85 @@ def _leave_type_name(rec):
return raw
def _leave_type_code(rec):
"""取请假类型原始编码(leave_type 等字段),用于精确比对(如小时特假=18)。"""
return str(_get(rec, "leave_type", "vacation_type", "sub_type", "LEAVE_TYPE", default="")).strip()
def _is_active_leave(rec):
"""请假流程是否已备案生效(status=002)。
接口返回的状态字段名即 status("001"~"008");
已撤销(003)/已销假(005)/申请中(001)/销假中(004)等非生效假单不构成有效请假;
status 字段缺失时按有效处理。
"""
status = str(_get(rec, "status", default="")).strip()
if not status:
return True
return status == ACTIVE_LEAVE_STATUS
def _staff_name(rec):
"""兼容取员工姓名字段(不同接口命名不同)。"""
return str(_get(rec, "STAFF_NAME", "staff_name", "staffName", default=""))
def _punch_analysis(records):
"""对某日打卡流水做统计(打卡记录无法可靠区分上下班,按最早=上班、最晚=下班)。"""
times = []
def _punch_abs_min(value, base_date):
"""将打卡时间转为相对 base_date 0 点的分钟数;跨天(次日)打卡自动 +1440。
打卡时间串形如 "YYYY-MM-DD HH:MM:SS"(含日期)或 "HH:MM[:SS]"(仅时间):
- 含日期时按日期与 base_date 的差值换算偏移(次日 +1440);
- 仅时间时视为当天;
- 解析失败返回 None。
"""
s = str(value).strip()
if not s:
return None
m = re.search(r"(\d{4})-(\d{1,2})-(\d{1,2})[ T](\d{1,2}):(\d{2})", s)
if m:
try:
day = datetime(int(m.group(1)), int(m.group(2)), int(m.group(3))).date()
base = datetime.strptime(base_date, "%Y-%m-%d").date()
except (ValueError, TypeError):
return None
diff = (day - base).days
if diff < 0 or diff > 1:
return None
hhmm = int(m.group(4)) * 60 + int(m.group(5))
return diff * 1440 + hhmm
return _to_minutes(s)
def _punch_analysis(records, base_date=None):
"""对打卡流水做统计(打卡记录无法可靠区分上下班,按最早=上班、最晚=下班)。
base_date 提供时(检查2跨天加班场景),按每条打卡相对该日 0 点的分钟数排序,
次日凌晨打卡自动 +1440 归并;只保留加班日当天到次日
NEXT_DAY_PUNCH_DEADLINE_MIN(06:00)内的卡(排除次日白班等无关卡),
供「次日06:00前有卡即正常下班」判定使用。
返回 first/last 原始时间串、count 次数,以及 mins 相对分钟数列表(升序,跨天 +1440)。
"""
items = []
for rec in records:
t = _get(rec, "kq_time", "kqTime", "punch_time")
if t:
times.append(str(t))
times.sort()
if not times:
return {"count": 0, "first": "", "last": ""}
return {"count": len(times), "first": times[0], "last": times[-1]}
if not t:
continue
t = str(t)
rm = _punch_abs_min(t, base_date) if base_date else None
if base_date:
# 跨天场景:仅保留加班日 0 点 ~ 次日 06:00 内的打卡(对齐 XQ0004 跨天口径)
if rm is None or rm >= NEXT_DAY_PUNCH_DEADLINE_MIN:
continue
items.append((rm, t))
if not items:
return {"count": 0, "first": "", "last": "", "mins": []}
items.sort(key=lambda x: x[0] if x[0] is not None else 10 ** 9)
return {
"count": len(items),
"first": items[0][1],
"last": items[-1][1],
"mins": [x[0] for x in items],
}
def _to_minutes(value):
@@ -642,6 +735,41 @@ def _shift_segment(rec):
return "%s ~ %s" % (b, e) if b or e else ""
def _leave_half_day(rec):
"""判定半天请假所在段:返回 "上"/"下"/""(半天及以下的假,整日假返回空串)。
优先取接口段名字段(begin_date_other_name/end_date_other_name 等,值为 上半段/下半段);
缺失时按 leave_days<=0.5 且 start_time 开始时刻判定:早于 12:00 视为上半段,
否则下半段(与 XQ0004 加班半天判定口径一致)。
"""
for key in ("begin_date_other_name", "end_date_other_name",
"begin_other_name", "end_other_name"):
v = str(_get(rec, key, default="")).strip()
if "上" in v:
return "上"
if "下" in v:
return "下"
# 段名字段缺失:仅半天(0.5天)及以下适用,按开始时刻判定
if _float(rec.get("leave_days"), 1.0) > HALF_DAY + EPS:
return ""
start_min = _to_minutes(_time_hhmm(_get(rec, "start_time")))
if start_min is None:
return ""
return "上" if start_min < HALF_DAY_NOON_MIN else "下"
def _abnormal_segment_half(ab):
"""判定异常记录班段所在段:返回 "上"/"下"/""。
按班段开始时刻(begin_time)判定:早于 12:00 视为上半段,否则下半段;
无班段时刻(如整日漏打卡)返回空串,不适用错位规则。
"""
start_min = _to_minutes(_time_hhmm(_get(ab, "begin_time")))
if start_min is None:
return ""
return "上" if start_min < HALF_DAY_NOON_MIN else "下"
def _parse_shift_time(bc_time):
"""解析班段时间 "09:00 ~ 18:00" -> (开始分钟, 结束分钟);无班段返回 (None, None)。"""
if not bc_time:
@@ -672,13 +800,57 @@ def _extract_day_shift(shift_rows, date_str):
return info
def _judge_punch_by_shift(p, shift_info):
"""结合班段时间判断当日打卡是否正常(容差 PUNCH_TOLERANCE_MIN 分钟)。"""
start_min, end_min = _parse_shift_time(shift_info.get("bc_time", ""))
count = p["count"]
tol = PUNCH_TOLERANCE_MIN
def _ot_plan_min_range(ot, base_date=None):
"""取加班记录的计划时段 (开始分钟, 结束分钟),作为检查2打卡覆盖基准。
# 无班段(休息日排班):按打卡次数判断
优先 PLAN_*,其次 FINAL_*;带日期字段按 _punch_abs_min 换算(跨天自动 +1440),
仅时间字段(无日期)用 end<start 兜底判跨天(如 22:00 ~ 02:00)。
字段缺失返回 (None, None)。
"""
start_raw = _get(ot, "PLAN_START_TIME") or _get(ot, "FINAL_START_TIME")
end_raw = _get(ot, "PLAN_END_TIME") or _get(ot, "FINAL_END_TIME")
if not start_raw or not end_raw:
return None, None
start = _punch_abs_min(start_raw, base_date)
end = _punch_abs_min(end_raw, base_date)
if start is None or end is None:
return None, None
if end < start:
end += 1440
return start, end
def _judge_punch_by_shift(p, shift_info, plan_min_range=None, base_date=None,
relax_ranges=None):
"""结合班段时间判断当日打卡,四档:正常 / 提前打卡 / 晚到 / 漏打卡。
参考班段优先级:加班计划时段(plan_min_range,检查2休息日半天场景,
打卡须覆盖实际加班时段)> 排班班段(bc_time)> 仅按打卡次数。
relax_ranges(休息日半天放宽窗口列表,可选):休息日加班打卡不必严格对齐
计划时段,首末卡覆盖常规上/下半段任一窗口(09:00~12:30 / 13:30~18:00)
即视为正常(允许上/下半段互换着干),优先于严格计划时段判定。
兜底(HALF_DAY_FALLBACK_MINUTES):放宽窗口与严格计划时段均不满足时,
首末打卡跨度达到 4 小时也视为正常。
覆盖判定(无容差,完全按班段边界):
- 正常:最早卡 ≤ 班段开始 且 最晚卡 ≥ 班段结束(提前来/晚走几小时都算覆盖);
- 提前打卡:最早卡 ≤ 班段开始,但最晚卡 < 班段结束(提前下班);
- 晚到:最早卡 > 班段开始,但最晚卡 ≥ 班段结束(迟到但覆盖下班);
- 漏打卡:无卡 / 仅 1 次卡 / 首末卡既不覆盖开始也不覆盖结束。
base_date 提供时(检查2跨天加班场景):跨天打卡(次日 0~6 点,对齐 XQ0004)
已由 _punch_analysis 归入当日并 +1440,次日 06:00 前的卡直接参与下班覆盖判定。
"""
count = p["count"]
# 参考班段:优先加班计划时段,其次排班班段
start_min, end_min = plan_min_range or (None, None)
if start_min is None or end_min is None:
start_min, end_min = _parse_shift_time(shift_info.get("bc_time", ""))
# 无班段(休息日排班且无计划时段):按打卡次数判断
if start_min is None or end_min is None:
if count >= 2:
return "正常(有上班+下班打卡)"
@@ -686,18 +858,29 @@ def _judge_punch_by_shift(p, shift_info):
return "漏打卡(当日仅 1 次打卡,缺一次)"
return "漏打卡(当日无打卡记录)"
# 有班段:最早打卡覆盖班段开始、最晚打卡覆盖班段结束
first_min = _to_minutes(p["first"])
last_min = _to_minutes(p["last"])
first_ok = first_min is not None and first_min <= start_min + tol
last_ok = last_min is not None and last_min >= end_min - tol
if count >= 2 and first_ok and last_ok:
return "正常(按班段上班/下班打卡齐全)"
if count == 0:
mins = p.get("mins") or []
if count == 0 or not mins:
return "漏打卡(当日无打卡记录)"
if count == 1:
return "漏打卡(当日仅 1 次打卡,缺一次)"
return "漏打卡(打卡未按班段覆盖上下班)"
first, last = mins[0], mins[-1]
# 休息日半天放宽判定:首末卡覆盖常规上/下半段任一窗口即视为正常,
# 不必严格对齐计划时段(允许上/下半段互换着干)
if relax_ranges:
for r_start, r_end in relax_ranges:
if first <= r_start and last >= r_end:
return "正常(休息日半天,覆盖常规上/下半段时段)"
if first <= start_min and last >= end_min:
return "正常(按考勤班段覆盖上下班打卡)"
# 兜底:放宽窗口与计划时段都不满足时,首末打卡跨度达 4 小时即视为正常
if last - first >= HALF_DAY_FALLBACK_MINUTES:
return "正常(休息日半天,打卡跨度达4小时)"
if first <= start_min and last < end_min:
return "提前打卡(下班卡早于计划结束)"
if first > start_min and last >= end_min:
return "晚到(上班卡晚于计划开始)"
return "漏打卡(打卡未按考勤班段覆盖上下班)"
# ==================== 会话校验 & 数据获取(与 app 版一致) ====================
@@ -747,14 +930,44 @@ def _fetch_all_data(session, user_id, treecode, begin, end):
}
# ==================== 过程数据保存 ====================
def _save_process_data(data, save_dir, month_str):
"""保存主流程拉取的原始接口数据为 JSON 文件,便于追溯复核。
保存内容:考勤异常(已确认/未调整)、请假、休息日加班四类原始记录;
检查2/3 内部拉取的打卡、排班数据不在本次保存范围内。
文件与 Excel 报告同目录,命名带月份与时间戳。
"""
os.makedirs(save_dir, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
save_path = os.path.abspath(os.path.join(
save_dir, f"月考勤异常三查_过程数据_{month_str}_{ts}.json"))
payload = {
"导出时间": datetime.now().strftime("%Y-%m-%d %H:%M:%S"),
"查询月份": month_str,
"考勤异常_已确认": data.get("abnormal_confirmed", []),
"考勤异常_未调整": data.get("abnormal_open", []),
"请假记录": data.get("leaves", []),
"休息日加班": data.get("rest_overtime", []),
}
with open(save_path, "w", encoding="utf-8") as f:
json.dump(payload, f, ensure_ascii=False, indent=2)
logger.info("过程数据已保存:%s", save_path)
return save_path
def _build_leave_set(leaves, need_full_day=False):
"""把请假记录索引化为 {(base_code, 'YYYY-MM-DD'): leave_rec}。
need_full_day=True 时只保留整日请假(leave_days>=1)的每一天;
否则保留请假范围内的每一天(供检查1判断「日期是否有请假流程」)。
仅索引已备案(002)的请假流程:已撤销(003)/已销假(005)/申请中(001)等
非生效假单不构成有效请假,直接排除(检查1/检查3 共用)。
"""
index = {}
for rec in leaves:
if not _is_active_leave(rec):
continue
code = str(_get(rec, "base_code")).strip()
# 用 begin_date/end_date(考勤归属日期)而非 start_time/end_time:
# 跨天夜班请假 end_time 会落到次日,导致请假范围多算一天
@@ -781,7 +994,14 @@ def _build_leave_set(leaves, need_full_day=False):
# ==================== 检查1:已确认异常 × 请假流程 ====================
def check_leave_after_confirm(abnormal_confirmed, leave_index):
"""已确认异常(is_adjusted=2)的日期,是否同时存在请假流程。"""
"""已确认异常(is_adjusted=2)的日期,是否同时存在有效请假流程。
命中后按以下规则排除「正常」场景(不需要提示):
1. 请假类型为小时特假:允许存在异常,跳过;
2. 半天假与异常错位:请上半段假→下半段出现异常、请下半段假→上半段出现异常,
视为正常,跳过;
3. 已撤销(003)/已销假(005)等非生效假单已在索引阶段排除,不构成有效请假。
"""
rows = []
for ab in abnormal_confirmed:
code = str(_get(ab, "base_code")).strip()
@@ -791,6 +1011,20 @@ def check_leave_after_confirm(abnormal_confirmed, leave_index):
leave_rec = leave_index.get((code, work_day))
if not leave_rec:
continue
# 规则1:小时特假允许存在异常
if _leave_type_code(leave_rec) == VACATION_TYPE_HOURLY:
logger.debug("【检查1跳过】%s %s %s:小时特假允许存在异常",
_staff_name(ab), code, work_day)
continue
# 规则2:半天假与异常分处不同上/下半段 → 正常
leave_half = _leave_half_day(leave_rec)
ab_half = _abnormal_segment_half(ab)
if leave_half and ab_half and leave_half != ab_half:
logger.debug("【检查1跳过】%s %s %s:请%s段假,%s段异常视为正常",
_staff_name(ab), code, work_day,
"上" if leave_half == "上" else "下",
"上" if ab_half == "上" else "下")
continue
rows.append({
"员工姓名": _staff_name(ab),
"工号": code,
@@ -819,15 +1053,23 @@ def check_rest_day_half_day_punch(session, user_id, treecode, rest_overtime, beg
ot_date = _to_date_str(_get(ot, "OT_DATE", "ot_date"))
if not code or not ot_date:
continue
kq = fetch_all_kq_data(session, user_id, code, ot_date, ot_date, treecode)
# 打卡查询范围扩到次日:加班可能跨天干到第二天凌晨(0~4点),
# 次日凌晨的打卡需纳入「次日4点前有卡即正常」判定。
next_day = (datetime.strptime(ot_date, "%Y-%m-%d") + timedelta(days=1)).strftime("%Y-%m-%d")
kq = fetch_all_kq_data(session, user_id, code, ot_date, next_day, treecode)
# 拉取该员工排班(缓存),取加班日的班段
if code not in shift_cache:
shift_cache[code] = fetch_all_shift(session, user_id, code, begin, end, treecode)
shift_info = _extract_day_shift(shift_cache.get(code, []), ot_date)
p = _punch_analysis(kq)
judge = _judge_punch_by_shift(p, shift_info)
p = _punch_analysis(kq, base_date=ot_date)
# 打卡覆盖基准:优先加班计划时段(实际加班时段),排班班段仅兜底/展示
plan_range = _ot_plan_min_range(ot, ot_date)
# 休息日半天放宽窗口:不必严格按计划时段,覆盖常规上/下半段任一窗口即正常
relax_ranges = [HALF_DAY_RELAX_MORNING, HALF_DAY_RELAX_AFTERNOON]
judge = _judge_punch_by_shift(p, shift_info, plan_min_range=plan_range,
base_date=ot_date, relax_ranges=relax_ranges)
rows.append({
"员工姓名": _staff_name(ot),
"工号": code,
@@ -846,8 +1088,13 @@ def check_rest_day_half_day_punch(session, user_id, treecode, rest_overtime, beg
# ==================== 检查3:整日请假 × 考勤异常 → 提示 ====================
def check_full_day_leave_abnormal(abnormal_confirmed, abnormal_open, leaves):
"""员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)→ 提示。"""
def check_full_day_leave_abnormal(abnormal_confirmed, abnormal_open, leaves,
session, user_id, treecode, begin, end):
"""员工整日请假(leave_days>=1)当日,仍存在其他考勤异常(未调整/已确认)→ 提示。
「班段」列取排班接口的真实班段时间({date}_bc_time,如 "09:00 ~ 18:00"),
而非异常记录的发生时段(begin_time ~ end_time);排班取不到时回退异常时段。
"""
rows = []
# 整日请假日期索引 {(code, date): leave_rec}
@@ -856,6 +1103,9 @@ def check_full_day_leave_abnormal(abnormal_confirmed, abnormal_open, leaves):
logger.info("无整日请假记录,检查3跳过")
return rows
# 按工号缓存排班记录,避免重复请求
shift_cache = {}
# 异常并集(同一员工同一日期可能同时有未调整/已确认,各自输出一条便于核查)
for ab in list(abnormal_open) + list(abnormal_confirmed):
code = str(_get(ab, "base_code")).strip()
@@ -865,6 +1115,12 @@ def check_full_day_leave_abnormal(abnormal_confirmed, abnormal_open, leaves):
leave_rec = full_day_leave.get((code, work_day))
if not leave_rec:
continue
# 拉取该员工排班(缓存),取请假日的真实排班班段时间
if code not in shift_cache:
shift_cache[code] = fetch_all_shift(session, user_id, code, begin, end, treecode)
shift_time = _extract_day_shift(shift_cache.get(code, []), work_day)["bc_time"]
is_adjusted = str(ab.get("is_adjusted", ""))
status = "确认异常" if is_adjusted == "2" else ("未调整" if is_adjusted == "0" else "异常")
hint = f"该员工{work_day}考勤状态存在异常"
@@ -875,7 +1131,7 @@ def check_full_day_leave_abnormal(abnormal_confirmed, abnormal_open, leaves):
"请假类型": _leave_type_name(leave_rec),
"请假天数": _get(leave_rec, "leave_days"),
"异常类型": _get(ab, "abnormal"),
"班段": _shift_segment(ab),
"班段": shift_time or _shift_segment(ab),
"异常状态": status,
"提示": hint,
})
@@ -910,7 +1166,7 @@ def export_report(results, save_dir, month_str):
{"检查项": "检查2:休息日半天加班打卡校验", "条数": len(c2)},
{"检查项": "检查3:整日请假当日仍有考勤异常", "条数": len(c3)},
]
summary[1]["备注"] = "「判定」列中 漏打卡 需人工复核"
summary[1]["备注"] = "「判定」列中 提前打卡 / 晚到 / 漏打卡 需人工复核"
summary[0]["备注"] = "可能为「提前确认后请假」仍为异常"
try:
@@ -946,6 +1202,9 @@ def handle_abnormal_check(save_dir=None):
data = _fetch_all_data(session, user_id, treecode, begin, end)
# 保存过程数据(主流程拉取的原始接口数据,与报告同目录)
process_path = _save_process_data(data, save_dir, month_str)
# 请假索引(全部请假,供检查1判断日期是否有请假流程)
leave_index = _build_leave_set(data["leaves"], need_full_day=False)
@@ -967,7 +1226,8 @@ def handle_abnormal_check(save_dir=None):
# 检查3
c3 = check_full_day_leave_abnormal(
data["abnormal_confirmed"], data["abnormal_open"], data["leaves"])
data["abnormal_confirmed"], data["abnormal_open"], data["leaves"],
session, user_id, treecode, begin, end)
logger.info("检查3(整日请假有异常):命中 %d 条", len(c3))
for r in c3:
logger.warning("【检查3】%s %s %s:%s(异常:%s / %s)",
@@ -3,28 +3,33 @@
@FileName: notice_mail_merge.py
@Author: 小布丁
@CreateTime: 2026-08-26
@Description: 告知书制作与下发(影刀版,单文件自包含)——读取《{YYYYMM}参保与停保名单.xlsx》
中「参保名单」sheet(表头第3行),按三类模板规则筛选当月人员,逐人生成
Word 告知书并转 PDF:
- 模板1 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保)
- 模板2 参保异常告知书(办理状态=参保失败 & 参保类型=新参保)
- 模板3 社保转移告知书(办理状态=已参 & 参保类型=转移参保)
公共过滤:人员类型不含「职能」、二级部门包含「经营中心」或「石桥铺会馆」、办理时间为当月。
输出命名:按(二级部门,四级部门)分组合并,同一部门+类型的所有员工合并为一份,
文件名 = 二级部门_四级部门_告知书类型.docx/pdf,同一部门内多人逐页排列。
OA 工作沟通推送:构造 2 条推送数据(员工参与社会保险+参保异常合并一条、
社保转移单独一条),各类型输出目录下全部告知书 PDF 均作为附件推送(不筛选),
接收人统一追加固定抄送人周卫;写入影刀全局变量 messages(列表),
@Description: 告知书制作与下发(影刀版,单文件自包含)——按分支读取当月数据源,
生成 Word 告知书并转 PDF:
- 分支「新参保」:读取《社保变更及增减名单.xlsx》中「参保名单」sheet(表头第3行),
模板1 员工参与社会保险告知书(办理状态=已参 & 参保类型=新参保 & 参保告知空)
模板2 参保异常告知书(办理状态=参保失败 & 参保类型=新参保 & 参保告知空)
- 分支「转移参保」:读取《社保变更人员名单.xlsx》,生成
模板3 社保转移告知书(是否变更=是)
数据源文件必须为当月(文件名月份=当前月),历史月份文件或缺失均报错。
输出命名:按(二级部门,参保单位)分组合并,同一二级部门+参保单位+类型的所有员工合并为一份,
文件名 = 二级部门_参保单位_告知书类型.docx/pdf,同组多人逐页排列。
二级部门解析:优先按该行「参保单位」(R 列)在数据源全量记录中聚合取唯一二级部门(经营中心);
不唯一/缺失时兜底把参保单位作为四级部门在花名册反查二级部门;
仍解析不到则报错并跳过该员工(不生成/不推送)。
OA 工作沟通推送:新参保分支=员工参与社会保险+参保异常合并一条、
转移参保分支=社保转移单独一条;各类型输出目录下全部告知书 PDF 均作为附件推送(不筛选),
接收人=店长+经营中心人行(按解析后的二级部门匹配),统一追加固定抄送人周卫;写入影刀全局变量 messages(列表),
供「OA工作沟通推送」指令逐条调用。
业务判定及占位符约定见 aa.md、docs/参保成功及异常告知书、docs/社保转移告知书。
@Version: 1.2.0
@Version: 1.5.0
设计说明(与 workflows 下其它单文件版一致):
- 单文件自包含,可放任意目录直接运行(含 App 项目目录或影刀环境)。
- 不 import 任何共享指令模块、不做 sys.path 注入、不做目录向上查找。
- 占位符约定:模板中仅允许纯变量占位符(如 {{姓名}}、{{下月}}、{{一次性扣款}}),
不支持 {{当前月+1}} / {{费用*2}} 这类带表达式的写法(脚本会自动兼容旧写法)。
- PDF 转换走 WPS 文字 COM(Kwps.Application),兼容未安装 MS Word 的环境;
- PDF 转换优先 WPS 文字 COM(Kwps.Application),失败自动回退 WPS 命令行
kwpsconvert.exe word2pdf(兼容 32 位 WPS / 未安装 MS Word 的环境);
另存/导出失败自动重试 3 次(AGENTS.md 全局重试约定)。
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
@@ -43,8 +48,10 @@ import os
import re
import sys
import time
import shutil
import random
import functools
import subprocess
import traceback
from copy import deepcopy
from datetime import datetime
@@ -155,15 +162,13 @@ TEMPLATES = {
},
}
EXCEL_KEYWORD = "参保与停保名单" # 表格文件名关键字
EXCEL_KEYWORD = "社保变更及增减名单" # 表格文件名关键字(表结构更新后新命名:2026年9月社保变更及增减名单及人数统计.xlsx)
SHEET_KEYWORD = "参保名单" # sheet 名关键字
HEADER_ROW = 3 # 表头所在行
MAIN_COLS = 49 # 主表字段到「费用」列为止(AX 为空列,其后为粘贴重复区)
EXCLUDE_TYPE_KEYWORDS = ("职能",) # 人员类型排除关键字
DEPT_KEYWORDS = ("经营中心", "石桥铺会馆") # 二级部门需包含的关键字(任一命中即可)
MAIN_COLS = 51 # 主表字段到「费用」列(AY)为止(AZ 为空列,其后为粘贴重复区)
RETRY_TIMES = 3 # 全局重试次数
# 社保转移数据源(社保变更人员名单):替代「参保与停保名单」中的转移参保
# 社保转移数据源(社保变更人员名单):独立于参保名单的另一份文件
TRANSFER_EXCEL_KEYWORD = "社保变更人员名单" # 数据源文件名关键字
TRANSFER_SHEET_GENERATE = ("变更-职能及干部", "变更-门店") # 生成覆盖的 sheet(关键字)
TRANSFER_SHEET_PUSH = "变更-门店" # 推送仅限该 sheet
@@ -172,9 +177,31 @@ TRANSFER_CHANGE_VALUE = "是" # 筛选值
# 列名映射:社保变更名单列名 -> 标准列名(模板占位符依赖标准列名)
TRANSFER_COL_MAP = {"新区域": "区域", "个人费用": "费用"}
# 执行分支:'新参保'=员工参保+参保异常(数据源:社保变更及增减名单);'转移参保'=社保转移(数据源:社保变更人员名单)
BRANCHES = {
"新参保": {
"rule_keys": ("新参保", "参保异常"), # 参与生成的模板名
"excel_keyword": "社保变更及增减名单", # 数据源文件名关键字
},
"转移参保": {
"rule_keys": ("社保转移",),
"excel_keyword": "社保变更人员名单",
},
}
# ---- OA 工作沟通推送数据构造 ----
ROSTER_PATH = r"D:\资料\人资\告知书制作与下发\员工花名册.xlsx" # 员工花名册路径
DEPT2_HR_OVERRIDE = {"石桥铺会馆": ["37001302"]} # 二级部门 -> 固定人事工号(梁敏)
# 二级部门(经营中心)-> 内置推送人工号(财务专员):优先于花名册人事查找直接命中;
# 未覆盖到的经营中心兜底走本文件原逻辑(DEPT2_HR_OVERRIDE 固定人事 + 花名册岗位含「人事」查找)
DEPT2_PUSH_OVERRIDE = {
"金色印象海口经营中心": ["37000700"], # 李明姣 财务专员
"金色印象昆明经营中心": ["37002511"], # 陈青 财务专员
"金色印象南宁经营中心": ["37009626"], # 石梦 财务专员
"金色印象深圳经营中心": ["37018211"], # 倪萍 财务专员
"金色印象郑州经营中心": ["37006992"], # 张勤 财务专员
}
OA_GLV_NAME = "messages" # 影刀全局变量名(列表:工作沟通推送数据)
# 测试模式:True=推送接收人统一覆盖为测试接收人(不推真实店长/人事);正式运行请改为 False
@@ -193,9 +220,9 @@ OA_MESSAGE_TEMPLATES = (
"subject": "{y}年{m}月员工参保结果告知书",
"content": (
"各位店长、人行伙伴:\n"
"重庆区域门店{m}月新参保已完成,以下是各门店《参保成功告知书》/《参保异常告知书》,\n"
"现需涉及的门店对员工本人进行传达告知(下载并签收);其中参保异常人员,重庆户籍的可以在渝快办APP上查询办理停保,"
"如办理不成功,也可打12333咨询社保机构,异地区域拨打区号+12333;若员工处理完毕,请店长报表至人资周卫,以便下月再参;\n"
"各区域门店{m}月新参保已完成,以下是各门店《参保成功告知书》/《参保异常告知书》,现需涉及的门店对员工本人进行传达告知(下载并签收);\n"
"其中参保异常人员,重庆户籍的可以在渝快办APP上查询办理停保,"
"如办理不成功,也可打12333咨询社保机构,异地区域拨打区号+12333;若员工处理完毕,请店长报备至人资周卫,以便下月再参;\n"
"请门店在{m}月26日前完成签署并将《签收回执》传递人行,"
"人行跟进本经营中心所有人员的告知书回收,{m}月28日前传递人资周卫。\n"
"@@R人力资源部\n"
@@ -265,21 +292,25 @@ def _fmt_num(value) -> str:
return ("%.2f" % f).rstrip("0").rstrip(".")
def _month_of(value):
"""把单元格值解析为 (年, 月);无法解析返回 None。"""
if value is None:
return None
if isinstance(value, datetime):
return (value.year, value.month)
if isinstance(value, str):
m = re.search(r"(20\d{2})[年\-/\.]?(\d{1,2})", value.strip())
if m:
return (int(m.group(1)), int(m.group(2)))
return None
def _match_rule(rec: dict, status: str, ins_type: str) -> bool:
"""按模板规则 + 参保告知为空 判断记录是否命中。
三项筛选:办理状态、参保类型、参保告知(AT 列)为空。
表结构更新后不再按人员类型/二级部门/办理时间过滤(见 aa.md 变更说明)。
"""
if str(rec.get("办理状态") or "").strip() != status:
return False
if str(rec.get("参保类型") or "").strip() != ins_type:
return False
# 参保告知为空才命中(未下发过的员工),避免重复下发
return not str(rec.get("参保告知") or "").strip()
def _extract_ym(filename: str):
"""从文件名解析 YYYYMM;失败返回当月。"""
"""从文件名解析 (年, 月);支持 '202609' 与 '2026年9月' 两种格式;失败返回当月。"""
m = re.search(r"(20\d{2})年(\d{1,2})月", filename)
if m:
return (int(m.group(1)), int(m.group(2)))
m = re.search(r"(20\d{2})(\d{2})", filename)
if m:
return (int(m.group(1)), int(m.group(2)))
@@ -287,25 +318,38 @@ def _extract_ym(filename: str):
return (now.year, now.month)
def _find_excel(dir_path: str) -> str:
"""在目录内查找包含「参保与停保名单」的 xlsx 文件。"""
def _find_current_month_excel(dir_path: str, keyword: str) -> str:
"""在目录内查找包含 keyword 且文件名月份=当月的 xlsx 文件。
只取当前月份的文件:命中历史月份文件或未找到均报错,避免使用过期数据源。
"""
if not os.path.isdir(dir_path):
raise FileNotFoundError(f"目录不存在:{dir_path}")
now = datetime.now()
current_ym = (now.year, now.month)
found = []
for name in os.listdir(dir_path):
if EXCEL_KEYWORD in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
if keyword in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
found.append(name)
if not found:
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{keyword}」的 xlsx 文件")
for name in found:
if _extract_ym(name) == current_ym:
return os.path.join(dir_path, name)
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{EXCEL_KEYWORD}」的 xlsx 文件")
raise FileNotFoundError(
f"目录 {dir_path} 下包含「{keyword}」的文件均非当前月份 {now.year}年{now.month}月:{found}"
)
def _find_excel(dir_path: str) -> str:
"""在目录内查找包含「社保变更及增减名单」且月份=当月的 xlsx 文件。"""
return _find_current_month_excel(dir_path, EXCEL_KEYWORD)
def _find_transfer_excel(dir_path: str = None) -> str:
"""在目录内查找包含「社保变更人员名单」的 xlsx 文件(社保转移数据源)。"""
"""在目录内查找包含「社保变更人员名单」且月份=当月的 xlsx 文件(社保转移数据源)。"""
dir_path = dir_path or BASE_DIR
if not os.path.isdir(dir_path):
raise FileNotFoundError(f"目录不存在:{dir_path}")
for name in os.listdir(dir_path):
if TRANSFER_EXCEL_KEYWORD in name and name.lower().endswith(".xlsx") and not name.startswith("~$"):
return os.path.join(dir_path, name)
raise FileNotFoundError(f"目录 {dir_path} 下未找到包含「{TRANSFER_EXCEL_KEYWORD}」的 xlsx 文件")
return _find_current_month_excel(dir_path, TRANSFER_EXCEL_KEYWORD)
def _read_insurance_records(excel_path: str) -> list:
@@ -339,21 +383,6 @@ def _read_insurance_records(excel_path: str) -> list:
wb.close()
def _match_rule(rec: dict, status: str, ins_type: str, ym: tuple) -> bool:
"""按模板规则 + 公共过滤条件判断记录是否命中。"""
if str(rec.get("办理状态") or "").strip() != status:
return False
if str(rec.get("参保类型") or "").strip() != ins_type:
return False
ptype = str(rec.get("人员类型") or "").strip()
if any(kw in ptype for kw in EXCLUDE_TYPE_KEYWORDS):
return False
dept2 = str(rec.get("二级部门") or "")
if not any(kw in dept2 for kw in DEPT_KEYWORDS):
return False
return _month_of(rec.get("办理时间")) == ym
def _build_placeholders(rec: dict, ym: tuple) -> dict:
"""根据记录与目标月份计算占位符替换值。"""
y, m = ym
@@ -496,36 +525,95 @@ def _fill_template(template_path: str, mapping: dict, out_path: str) -> int:
return len(_leftover_placeholders(doc))
# ==================== PDF 转换(WPS 文字 COM,兼容无 MS Word 环境) ====================
# ==================== PDF 转换(优先 WPS COM,失败自动回退 kwpsconvert 命令行) ====================
def _find_kwpsconvert() -> str:
"""定位 WPS 自带转换器 kwpsconvert.exe(wpscli word2pdf,不依赖 COM)。
本机 WPS 为 32 位时,COM 类 Kwps.Application 仅注册在 32 位注册表视图,
64 位 Python 无法调用(报 -2147221005 无效的类字符串),需回退命令行转换。
依次尝试:环境变量 wps_kwpsconvert 指定路径 -> 常见安装目录 -> PATH。
"""
env = os.getenv("wps_kwpsconvert")
if env and os.path.isfile(env):
return env
bases = [
os.path.join(os.environ.get("LOCALAPPDATA", ""), "Kingsoft", "WPS Office"),
os.path.join(os.environ.get("ProgramFiles(x86)", r"C:\Program Files (x86)"), "Kingsoft", "WPS Office"),
os.path.join(os.environ.get("ProgramFiles", r"C:\Program Files"), "Kingsoft", "WPS Office"),
]
for base in bases:
if not base or not os.path.isdir(base):
continue
for ver_dir in os.listdir(base):
cand = os.path.join(base, ver_dir, "office6", "kwpsconvert.exe")
if os.path.isfile(cand):
return cand
exe = shutil.which("kwpsconvert")
return exe or ""
def _publish_via_kwpsconvert(src_docx: str, target_pdf: str) -> None:
"""用 WPS 命令行 kwpsconvert.exe word2pdf 把 docx 转 PDF(不依赖 COM,兼容 32 位 WPS)。
目标 PDF 已存在时 kwpsconvert 会自动改名(不覆盖),故先删除旧文件确保落到目标路径。
"""
exe = _find_kwpsconvert()
if not exe:
raise RuntimeError("未找到 kwpsconvert.exe(WPS 命令行转换器),可设置环境变量 wps_kwpsconvert 指定路径")
src_docx = os.path.abspath(src_docx)
target_pdf = os.path.abspath(target_pdf)
os.makedirs(os.path.dirname(target_pdf), exist_ok=True)
if os.path.exists(target_pdf):
os.remove(target_pdf)
cmd = [exe, "word2pdf", src_docx, "-o", target_pdf]
kwargs = {}
if os.name == "nt":
kwargs["creationflags"] = 0x08000000 # CREATE_NO_WINDOW,避免弹出命令行窗口
proc = subprocess.run(cmd, capture_output=True, timeout=300, **kwargs)
if proc.returncode != 0:
err = (proc.stderr or proc.stdout or b"").decode("gbk", errors="ignore").strip()
raise RuntimeError(f"kwpsconvert 转换失败(exit={proc.returncode}): {err or target_pdf}")
if not os.path.exists(target_pdf):
raise RuntimeError(f"kwpsconvert 转换后未生成 PDF:{target_pdf}")
logger.info("kwpsconvert 转换成功:%s", os.path.basename(target_pdf))
@retry(max_attempts=RETRY_TIMES)
def _publish_via_wps(src_docx: str, target_docx: str, target_pdf: str) -> None:
"""用 WPS 打开 src_docx,另存为 target_docx 并导出 target_pdf。失败自动重试 3 次。"""
"""导出 target_pdf:优先 WPS 文字 COM(Kwps.Application),失败自动回退 kwpsconvert 命令行。
兼容 32 位 WPS(COM 类仅注册 32 位视图,64 位 Python 调不到)+ 未安装 MS Word 的环境。
"""
os.makedirs(os.path.dirname(target_docx), exist_ok=True)
src_docx = os.path.abspath(src_docx)
target_docx = os.path.abspath(target_docx)
target_pdf = os.path.abspath(target_pdf)
app = None
try:
app = win32com.client.Dispatch("Kwps.Application")
app.Visible = False
app = None
try:
app.DisplayAlerts = 0
except Exception:
pass
doc = app.Documents.Open(src_docx)
try:
doc.SaveAs2(target_docx, 12) # 12 = wdFormatXMLDocument
except Exception:
doc.SaveAs(target_docx, 12)
doc.ExportAsFixedFormat(target_pdf, 17) # 17 = wdFormatPDF
doc.Close(False)
finally:
if app is not None:
app = win32com.client.Dispatch("Kwps.Application")
app.Visible = False
try:
app.Quit()
app.DisplayAlerts = 0
except Exception:
pass
doc = app.Documents.Open(src_docx)
try:
doc.SaveAs2(target_docx, 12) # 12 = wdFormatXMLDocument
except Exception:
doc.SaveAs(target_docx, 12)
doc.ExportAsFixedFormat(target_pdf, 17) # 17 = wdFormatPDF
doc.Close(False)
finally:
if app is not None:
try:
app.Quit()
except Exception:
pass
except Exception as e:
logger.warning("WPS COM 转换失败(%s),自动回退 kwpsconvert 命令行", e)
_publish_via_kwpsconvert(src_docx, target_pdf)
# ==================== OA 工作沟通推送数据构造 ====================
@@ -650,6 +738,43 @@ def _read_transfer_records(excel_path: str, roster_map: dict = None) -> list:
wb.close()
def _ins_org_of(rec: dict) -> str:
"""取记录参保单位标识:优先 R 列「参保单位」(简称),其次「参保单位全称」「当前参保单位」。"""
for key in ("参保单位", "参保单位全称", "当前参保单位"):
v = str(rec.get(key) or "").strip()
if v:
return v
return ""
def _resolve_dept2(rec: dict, all_records: list, roster_map: dict):
"""解析记录的正确二级部门(经营中心),优先数据源内参保单位聚合,兜底花名册反查。
1) 主查:数据源全量记录中按「参保单位」聚合,同参保单位记录的二级部门应唯一(一个经营中心);
2) 兜底:主查不唯一/缺失时,把参保单位作为四级部门在花名册反查其二级部门;
3) 仍解析不到返回 None,由调用方报错并跳过该记录(不推送)。
"""
ins = _ins_org_of(rec)
if not ins:
return None
dept2s = {
str(r.get("二级部门") or "").strip()
for r in all_records if _ins_org_of(r) == ins
}
dept2s.discard("")
if len(dept2s) == 1:
return dept2s.pop()
dept2s = {
str(it.get("二级部门") or "").strip()
for it in roster_map.values()
if str(it.get("四级部门") or "").strip() == ins
}
dept2s.discard("")
if len(dept2s) == 1:
return dept2s.pop()
return None
def _find_store_manager_in_map(roster_map: dict, code: str):
"""在已读花名册中查店长(同四级部门岗位含「店长」,按行序取第一个),返回店长工号或 None。"""
info = roster_map.get(code)
@@ -661,12 +786,18 @@ def _find_store_manager_in_map(roster_map: dict, code: str):
return None
def _find_hr_personnel_in_map(roster_map: dict, code: str) -> list:
"""在已读花名册中查人事:二级部门为「石桥铺会馆」固定返回;经营中心下岗位含「人事」全量返回。"""
def _find_hr_personnel_in_map(roster_map: dict, code: str, dept2: str = None) -> list:
"""查人事/推送人:二级部门命中 DEPT2_PUSH_OVERRIDE(内置推送人)直接返回;
其次「石桥铺会馆」固定返回;经营中心下岗位含「人事」全量返回(兜底花名册查找)。
dept2: 外部解析出的正确二级部门(经营中心),缺省用员工本人花名册二级部门。
"""
info = roster_map.get(code)
if not info:
return []
dept2 = info["二级部门"]
dept2 = dept2 or info["二级部门"]
if dept2 in DEPT2_PUSH_OVERRIDE:
return list(DEPT2_PUSH_OVERRIDE[dept2])
if dept2 in DEPT2_HR_OVERRIDE:
return list(DEPT2_HR_OVERRIDE[dept2])
if "经营中心" not in dept2:
@@ -674,14 +805,18 @@ def _find_hr_personnel_in_map(roster_map: dict, code: str) -> list:
return [c for c, it in roster_map.items() if it["二级部门"] == dept2 and "人事" in it["岗位"]]
def _resolve_receivers(roster_map: dict, codes: list) -> list:
"""为员工工号列表解析接收人(店长+人事),按出现顺序去重,返回工号列表。"""
def _resolve_receivers(roster_map: dict, codes: list, dept2_map: dict = None) -> list:
"""为员工工号列表解析接收人(店长+人事),按出现顺序去重,返回工号列表。
dept2_map: 工号 -> 修正后的二级部门(经营中心),用于人事匹配(缺省用花名册本人二级部门)。
"""
dept2_map = dept2_map or {}
receivers = []
for code in codes:
mgr = _find_store_manager_in_map(roster_map, code)
if mgr and mgr not in receivers:
receivers.append(mgr)
for hr in _find_hr_personnel_in_map(roster_map, code):
for hr in _find_hr_personnel_in_map(roster_map, code, dept2_map.get(code)):
if hr and hr not in receivers:
receivers.append(hr)
return receivers
@@ -720,58 +855,68 @@ def _highlight_text(text: str, highlights: tuple, m: int = None) -> str:
return text
def build_work_communication_data(excel_path: str = None, output_dir: str = None,
ym: tuple = None, roster_path: str = None) -> list:
def build_work_communication_data(branch: str, output_dir: str = None, ym: tuple = None,
roster_path: str = None) -> list:
"""
构造 OA 工作沟通推送数据:员工参与社会保险+参保异常合并一条、社保转移单独一条。
附件为该类型输出目录下全部告知书 PDF(不筛选);接收人为店长+人事工号
并统一追加固定抄送人周卫(37001166)。每条含
按分支构造 OA 工作沟通推送数据:新参保分支=员工参与社会保险+参保异常合并一条;
转移参保分支=社保转移单独一条。附件为该类型输出目录下全部告知书 PDF(不筛选);
接收人为店长+人事工号并统一追加固定抄送人周卫(37001166)。每条含
subject/content(HTML)/attachment_paths/receivers/category,
并写入影刀全局变量 messages(列表),供「OA工作沟通推送」指令逐条调用。
Args:
excel_path: 参保/停保名单 xlsx 路径,默认自动在 BASE_DIR 查找
branch: 执行分支,'新参保' 或 '转移参保'(显式传参,不使用环境变量/命令行)
output_dir: 输出目录,默认 OUTPUT_ROOT(须先执行 generate_notices 生成 PDF)
ym: 目标年月 (year, month),默认从文件名解析
ym: 目标年月 (year, month),默认当月(数据源文件须为当月,历史月份文件会报错)
roster_path: 员工花名册路径,默认 ROSTER_PATH
Returns:
list: [{"subject", "content", "attachment_paths", "receivers", "category"}, ...]
"""
excel_path = excel_path or _find_excel(BASE_DIR)
ym = ym or _extract_ym(os.path.basename(excel_path))
if branch not in BRANCHES:
raise ValueError(f"未知分支:{branch},可选 {list(BRANCHES)}")
rule_keys = BRANCHES[branch]["rule_keys"]
excel_keyword = BRANCHES[branch]["excel_keyword"]
output_dir = output_dir or OUTPUT_ROOT
roster_path = roster_path or ROSTER_PATH
ym = ym or (datetime.now().year, datetime.now().month)
y, m = ym
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
roster_path = roster_path or ROSTER_PATH
logger.info("构造 OA 工作沟通数据:%s(%d-%02d)", excel_path, y, m)
records = _read_insurance_records(excel_path)
logger.info("构造 OA 工作沟通数据:分支=%s(%d-%02d)", branch, y, m)
# 社保转移:独立数据源(社保变更人员名单),推送仅限「变更-门店」sheet
# 数据源:按分支关键字查找当月文件(历史月份/缺失均报错)
excel_path = _find_current_month_excel(BASE_DIR, excel_keyword)
# 花名册(二级部门解析/店长人事查找用),读取失败置空(后续靠兜底或跳过)
try:
roster_map = _read_roster_map(roster_path or ROSTER_PATH)
roster_map = _read_roster_map(roster_path)
except Exception as e:
logger.warning("花名册读取失败,社保转移四级部门将回退二级部门:%s", e)
logger.warning("花名册读取失败,二级部门解析/接收人查找将受限:%s", e)
roster_map = {}
transfer_excel = _find_transfer_excel(BASE_DIR)
transfer_records = _read_transfer_records(transfer_excel, roster_map)
# 按模板规则筛出命中员工
matched_by_rule = {}
for rule_name, rule in TEMPLATES.items():
if rule_name == "社保转移":
matched = [r for r in transfer_records if TRANSFER_SHEET_PUSH in str(r.get("_source") or "")]
else:
matched = [r for r in records if _match_rule(r, rule["status"], rule["type"], ym)]
matched_by_rule[rule_name] = matched
logger.info("[%s] 命中 %d 人", rule_name, len(matched))
roster_map = _read_roster_map(roster_path)
logger.info("花名册共 %d 人:%s", len(roster_map), roster_path)
# 按分支筛出命中员工(all_records 供参保单位聚合二级部门用)
matched_by_rule = {}
if branch == "转移参保":
transfer_records = _read_transfer_records(excel_path, roster_map)
matched_by_rule["社保转移"] = [
r for r in transfer_records if TRANSFER_SHEET_PUSH in str(r.get("_source") or "")
]
logger.info("[社保转移] 命中 %d 人", len(matched_by_rule["社保转移"]))
all_records = transfer_records
else:
records = _read_insurance_records(excel_path)
all_records = records
for rule_name in rule_keys:
rule = TEMPLATES[rule_name]
matched_by_rule[rule_name] = [r for r in records if _match_rule(r, rule["status"], rule["type"])]
logger.info("[%s] 命中 %d 人", rule_name, len(matched_by_rule[rule_name]))
messages = []
for tpl in OA_MESSAGE_TEMPLATES:
if not any(rn in rule_keys for rn in tpl["rule_keys"]):
continue # 只构造本分支对应的推送
matched_recs = []
for rn in tpl["rule_keys"]:
matched_recs.extend(matched_by_rule.get(rn, []))
@@ -790,14 +935,24 @@ def build_work_communication_data(excel_path: str = None, output_dir: str = None
continue
# 接收人:店长 + 人事(工号去重),并统一加上固定抄送人(周卫)
codes = []
# 二级部门按「参保单位」解析修正(数据源聚合/花名册兜底),解析不到报错并跳过该员工
dept2_by_code, codes = {}, []
for r in matched_recs:
c = _norm_code(r.get("工号"))
if c:
codes.append(c)
else:
if not c:
logger.warning("员工「%s」无工号,跳过接收人解析", r.get("姓名"))
receivers = _resolve_receivers(roster_map, codes)
continue
d2 = _resolve_dept2(r, all_records, roster_map)
if not d2:
logger.error("员工「%s」无法解析二级部门(参保单位=%s),不推送该员工",
r.get("姓名"), _ins_org_of(r))
continue
dept2_by_code[c] = d2
codes.append(c)
if not codes:
logger.warning("[%s] 命中员工均无法解析二级部门,跳过该推送", tpl["key"])
continue
receivers = _resolve_receivers(roster_map, codes, dept2_by_code)
if TEST_MODE:
receivers = list(TEST_RECEIVER)
logger.info("[测试模式] [%s] 接收人覆盖为测试接收人:%s", tpl["key"], TEST_RECEIVER)
@@ -827,49 +982,57 @@ def build_work_communication_data(excel_path: str = None, output_dir: str = None
# ==================== 主流程 ====================
def generate_notices(excel_path: str = None, output_dir: str = None, ym: tuple = None,
def generate_notices(branch: str, output_dir: str = None, ym: tuple = None,
roster_path: str = None) -> dict:
"""
生成三类告知书(Word + PDF)。
按分支生成告知书(Word + PDF)。
Args:
excel_path: 参保/停保名单 xlsx 路径,默认自动在 BASE_DIR 查找
branch: 执行分支,'新参保' 或 '转移参保'(显式传参,不使用环境变量/命令行)
output_dir: 输出目录,默认 OUTPUT_ROOT
ym: 目标年月 (year, month),默认从文件名解析
ym: 目标年月 (year, month),默认当月(数据源文件须为当月,历史月份文件会报错)
roster_path: 员工花名册路径(社保转移四级部门补全用),默认 ROSTER_PATH
Returns:
{模板名: [输出文件路径, ...]}
"""
excel_path = excel_path or _find_excel(BASE_DIR)
ym = ym or _extract_ym(os.path.basename(excel_path))
if branch not in BRANCHES:
raise ValueError(f"未知分支:{branch},可选 {list(BRANCHES)}")
rule_keys = BRANCHES[branch]["rule_keys"]
excel_keyword = BRANCHES[branch]["excel_keyword"]
output_dir = output_dir or OUTPUT_ROOT
ym = ym or (datetime.now().year, datetime.now().month)
y, m = ym
month_dir = os.path.join(output_dir, f"{y}{m:02d}")
# 数据源:按分支关键字查找当月文件(历史月份/缺失均报错)
excel_path = _find_current_month_excel(BASE_DIR, excel_keyword)
logger.info("读取名单:%s(目标年月 %d-%02d)", excel_path, y, m)
records = _read_insurance_records(excel_path)
logger.info("「参保名单」共 %d 条记录", len(records))
# 社保转移:独立数据源(社保变更人员名单),生成覆盖职能及干部+门店两个 sheet
transfer_records, records = [], []
try:
roster_map = _read_roster_map(roster_path or ROSTER_PATH)
except Exception as e:
logger.warning("花名册读取失败,社保转移四级部门将回退二级部门:%s", e)
logger.warning("花名册读取失败,二级部门解析将受限:%s", e)
roster_map = {}
transfer_excel = _find_transfer_excel(BASE_DIR)
transfer_records = _read_transfer_records(transfer_excel, roster_map)
logger.info("「社保变更人员名单」命中 %d 人:%s", len(transfer_records), transfer_excel)
if branch == "转移参保":
transfer_records = _read_transfer_records(excel_path, roster_map)
logger.info("「社保变更人员名单」命中 %d 人:%s", len(transfer_records), excel_path)
else:
records = _read_insurance_records(excel_path)
logger.info("「参保名单」共 %d 条记录", len(records))
all_records = transfer_records if branch == "转移参保" else records
results = {}
for rule_name, rule in TEMPLATES.items():
for rule_name in rule_keys:
rule = TEMPLATES[rule_name]
tpl_path = rule["file"]
if not os.path.exists(tpl_path):
raise FileNotFoundError(f"模板不存在:{tpl_path}")
if rule_name == "社保转移":
matched = transfer_records
else:
matched = [r for r in records if _match_rule(r, rule["status"], rule["type"], ym)]
matched = [r for r in records if _match_rule(r, rule["status"], rule["type"])]
if not matched:
logger.info("[%s] 无命中人员,跳过", rule_name)
results[rule_name] = []
@@ -881,17 +1044,24 @@ def generate_notices(excel_path: str = None, output_dir: str = None, ym: tuple =
logger.info("=" * 70)
logger.info("[%s] 命中 %d 人(%s)", rule_name, len(matched), ", ".join(str(r.get("姓名")) for r in matched))
# 按(二级部门,四级部门)分组合并,生成一份告知书
# 按(二级部门,参保单位)分组合并,生成一份告知书;
# 二级部门按「参保单位」解析修正(数据源聚合/花名册兜底),解析不到报错并跳过该员工
groups = {}
for rec in matched:
key = (str(rec.get("二级部门") or "未知").strip(), str(rec.get("四级部门") or "未知").strip())
dept2 = _resolve_dept2(rec, all_records, roster_map)
if not dept2:
logger.error("员工「%s」无法解析二级部门(参保单位=%s),跳过生成",
rec.get("姓名"), _ins_org_of(rec))
continue
rec["二级部门"] = dept2
key = (dept2, _ins_org_of(rec))
groups.setdefault(key, []).append(rec)
for (dept2, dept4), recs in groups.items():
for (dept2, ins_org), recs in groups.items():
# 每人生成一份已填充的内存文档,再合并(每份之间分页)
docs = [_fill_doc(tpl_path, _build_placeholders(r, ym)) for r in recs]
doc = _merge_notice_docs(docs) if len(docs) > 1 else docs[0]
base_name = _safe_filename(f"{dept2}_{dept4}_{rule['folder']}")
base_name = _safe_filename(f"{dept2}_{ins_org}_{rule['folder']}")
docx_path = os.path.join(out_folder, base_name + ".docx")
pdf_path = docx_path[:-5] + ".pdf"
@@ -909,20 +1079,25 @@ def generate_notices(excel_path: str = None, output_dir: str = None, ym: tuple =
return results
def main() -> list:
"""告知书制作与下发(影刀入口):生成当月三类告知书,并构造 OA 工作沟通推送数据。
def main(branch: str) -> list:
"""告知书制作与下发(影刀入口):按分支生成当月告知书,并构造 OA 工作沟通推送数据。
Args:
branch: 执行分支,'新参保' 或 '转移参保'(显式传参,不使用环境变量/命令行输入)
仅接受函数参数显式传递,数据源文件名须为当月(历史月份文件会报错)。
Returns:
工作沟通推送数据列表(每条含 receivers/subject/content/attachment_paths/category),
与影刀全局变量 messages 内容一致;即使无影刀环境,调用方也可直接用返回值推送。
"""
try:
results = generate_notices()
messages = build_work_communication_data()
results = generate_notices(branch)
messages = build_work_communication_data(branch)
_set_glv("notice_output_dir", os.path.join(OUTPUT_ROOT, datetime.now().strftime("%Y%m")))
_set_glv(OA_GLV_NAME, messages)
total = sum(len(files) for files in results.values())
logger.info("共生成 %d 份告知书(docx+pdf),构造 %d 条工作沟通推送数据", total, len(messages))
logger.info("分支[%s] 共生成 %d 份告知书(docx+pdf),构造 %d 条工作沟通推送数据",
branch, total, len(messages))
return messages
except Exception:
logger.exception("告知书制作与下发失败")
@@ -931,4 +1106,5 @@ def main() -> list:
if __name__ == "__main__":
main()
# 显式指定执行分支:'新参保' 或 '转移参保'(二选一,分别对应不同数据源文件)
main("新参保")