feat: 新增多个业务需求脚本与共享模块

新增内容包括:
1. 7个业务需求占位文档目录与README
2. 共享OA登录、钉钉机器人推送工具模块
3. 雇主险变更清单导出脚本
4. 考勤月报封存检查两个检查脚本
5. 重庆社保停保导入名单生成脚本
This commit is contained in:
2026-09-08 16:16:15 +08:00
parent 4923b352f2
commit 2350ca671f
40 changed files with 0 additions and 0 deletions
@@ -0,0 +1,705 @@
# -*- coding: utf-8 -*-
"""
@FileName: attendance_abnormal.py
@Description: 周考勤异常处理(影刀单文件版)- 独立自 app/service/hrbp/ehr/attendance/attendance_abnormal.py,
业务逻辑:分页拉取本月(1 号查上月,否则当月)未调整考勤异常 → 导出 Excel → 分级分类
(轻微直接自动确认[整月]/其余仅上周钉钉核实)→ 按姓名-工号合并推送当事人(仅上周)
→ 生成条数汇总(自动确认数、推送当事人确认数)写入群全局变量。
规则见 docs/需求单/XQ0006 EHR系统周考勤异常处理/需求文档.md。
@Version: 1.1.0
登录(共享登录态,本脚本仅读取 cookies 文件,不 import 任何共享模块):
「37duHR登录」指令写入 %LOCALAPPDATA%\37duAutomation\.sessions\hr_cookies.json;
缺失/失效时先拖入「37duHR登录」指令再运行本流程。
钉钉推送(消息生成与发送解耦,本脚本不内联发送):
main() 将待推送 messages(元组列表 (msg_type, name, user_id, content, file_path),即
("text", 姓名, 工号, 文本内容, ""))写入影刀全局变量
glv['messages'];处理条数汇总(自动确认数、推送当事人确认数)写入 glv['group_messages']
(文本列表,每项一条),分别由流程拖「37du钉钉单聊推送」(个人,yingdao/share/dingtalk_dws_push.py)/
「37du钉钉群机器人推送」(群)指令完成发送。
自动确认:仅轻微异常(迟到/早退 < 30 分钟,不分职能序列)自动调用确认接口,确认条数计入群汇总。
由 AUTO_CONFIRM_ENABLED 总开关控制(布尔值,默认 True,本次起默认启用;置 False 关闭仅统计不执行)。
小范围测试按钮(影刀「调用模块」传 main(test_mode=True)):
仅筛选所属单位为「集团管理中心」「集团营建中心」「金色印象事业部」、且部门路径不含「大区」
的考勤异常作为完整数据源,跑通导出/分级/推送全流程;导出文件名带「测试」、
汇总消息标注「小范围测试」,与正式结果区分。筛选条件见 TEST_BELONG_UNITS 常量与 filter_test_units。
依赖安装(影刀版启动校验:所有库必须预先装齐,任一缺失启动即报错退出,不懒加载):
pip install requests python-dotenv pandas openpyxl
环境变量(.env 或系统变量,固定路径共享 .env 见 yingdao/share/hr_login.py):
dingtalk_push_enabled=true|false(默认 false,是否启用钉钉推送,总开关)
dingtalk_notify_target=人资专用号钉钉联系人姓名(处理汇总报表推送对象,如 夏一平)
attendance_save_dir=(可选)Excel 导出目录,默认 D:\\资料\\人资\\考勤异常
"""
import os
import sys
import json
import time
import csv
from datetime import date, datetime, timedelta
# ==================== 第三方库导入(影刀版启动校验:全部必须预先安装,不懒加载) ====================
try:
from dotenv import load_dotenv
import requests
import pandas as pd
except ImportError as _import_err:
raise RuntimeError(
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐,不懒加载)。\n"
"请先执行安装:\n"
" pip install requests python-dotenv pandas openpyxl\n"
"(钉钉推送相关依赖 pyautogui/pywin32/pyperclip/psutil/Pillow/numpy/"
"rapidocr onnxruntime 由共享指令 dingtalk_sender.py 校验,见其文档头)\n"
f"缺失依赖详情: {_import_err}"
)
load_dotenv()
# ==================== 日志(print) ====================
class _PrintLogger:
"""影刀版无 logging 依赖,直接用 print 输出,行为与项目 logger 对齐。"""
@staticmethod
def debug(msg, *args):
if args:
msg = msg % args
print(f"[DEBUG] {msg}")
@staticmethod
def info(msg, *args):
if args:
msg = msg % args
print(f"[INFO] {msg}")
@staticmethod
def warning(msg, *args):
if args:
msg = msg % args
print(f"[WARN] {msg}")
@staticmethod
def error(msg, *args):
if args:
msg = msg % args
print(f"[ERROR] {msg}")
logger = _PrintLogger()
# ==================== 影刀全局变量(glv) ====================
def _set_glv(name, value):
"""写入影刀全局变量(glv[name]=value);非影刀环境(本地独立运行)时静默跳过。"""
try:
glv[name] = value
except Exception:
pass
# ==================== 共享路径 & 常量配置(与 app 版统一,见 app/common/app_paths.py) ====================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
_SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
SHARED_ENV_FILE = os.path.join(_APP_DATA_DIR, '.env')
# HR 登录态:由「37duHR登录」共享指令写入
SHARED_HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
# ---------- HR 系统 ----------
HR_BASE_URL = "https://hr.37du.co"
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
ATTENDANCE_ABNORMAL_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
# 考勤异常确认/调整接口(type=1 自动确认异常)
ATTENDANCE_ADJUST_URL = f"{HR_BASE_URL}/RedseaPlatform/abnormalAdjust/KqCountAbnormal.mc"
PAGE_MAX_SIZE = 500
# 默认保存目录(可用环境变量覆盖)
SAVE_DIR = os.getenv("attendance_save_dir") or r"D:\资料\人资\考勤异常"
# 英文字段 → 中文字段映射(aa.md 手动导出的考勤异常列,仅导出这些列)
COL_MAP = {
"base_code": "工号",
"STAFF_NAME": "姓名",
"sex": "性别",
"age": "年龄",
"ORG_FULL_PATH": "部门路径",
"BELONG_UNIT_ORG_NAME": "所属单位",
"DEPT_ORG_NAME": "部门",
"POST_ORG_NAME": "岗位",
"join_date": "入职日期",
"work_day": "日期",
"bc_name": "班次",
"abnormal": "异常类型",
"is_adjusted": "处理状态",
"actual_begin_time": "开始时间",
"actual_end_time": "结束时间",
"abnormal_minute": "时长(分)",
"add_reason": "补签原因",
"operateName": "操作人",
"operateTime": "操作时间",
}
# 导出列顺序(与 aa.md 手动导出一致;「班段」由 begin_time~end_time 合成)
SHOW_ORDER = [
"工号", "姓名", "性别", "年龄", "部门路径", "所属单位", "部门", "岗位",
"入职日期", "日期", "班次", "班段", "异常类型", "处理状态", "处理方式",
"开始时间", "结束时间", "时长(分)", "补签原因", "操作人", "操作时间",
]
# 处理状态 is_adjusted 编码 → 中文(0=未调整、1=补签调整、2=确认异常、3=正常调整)
STATUS_MAP = {
"0": "未调整",
"1": "补签调整",
"2": "确认异常",
"3": "正常调整",
}
# 考勤异常调整状态过滤(本次只查询「未调整」);0=未调整、1=补签调整、2=确认异常、3=正常调整、空=所有
IS_ADJUSTED = "0"
# 钉钉推送总开关(True=启用,False=关闭)
DINGTALK_PUSH_ENABLED = True
# 自动确认总开关(默认启用:整月轻微异常直接批量确认;置 False 关闭仅统计不执行)
AUTO_CONFIRM_ENABLED = True
# 小范围测试:仅筛选以下所属单位(BELONG_UNIT_ORG_NAME)的考勤异常,且部门路径(ORG_FULL_PATH)
# 不含「大区」,作为「完整数据源」跑通全流程。
# 影刀流程通过 main(test_mode=True) 触发(即「小范围测试」按钮入口),
# 测试数据照常导出/分级/推送,但文件名与汇总消息会标注「测试」以区分正式结果。
TEST_BELONG_UNITS = ["集团管理中心", "集团营建中心", "金色印象事业部"]
# ======================================================
# ==================== 登录态(共享 cookies 文件) ====================
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 yingdao/share/hr_login.py),
# 本脚本为单文件自包含:仅读取共享 cookies 文件,不 import 任何共享模块。
class HRSessionExpiredError(Exception):
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
def hr_request_json(session, method, url, params, label, timeout=20):
"""POST/GET 请求并校验返回 JSON;失效抛 HRSessionExpiredError。"""
resp = session.request(method.upper(), url, data=params, timeout=timeout)
resp.raise_for_status()
text = resp.text
if not text or not text.lstrip().startswith(("{", "[")):
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
return resp.json()
def _load_shared_hr_cookies():
if not os.path.exists(SHARED_HR_COOKIE_FILE):
return None
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
return cookies or None
def _ensure_hr_cookies():
"""确保存在 HR 登录态文件(由「37duHR登录」指令写入);缺失时提示先运行登录指令。"""
if _load_shared_hr_cookies():
return True
raise RuntimeError(
"未找到 HR 登录态(hr_cookies.json)或已失效。\n"
"请在影刀流程开头先调用「37duHR登录」指令,或本地先运行 python yingdao/share/hr_login.py")
def build_hr_session():
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
_ensure_hr_cookies()
cookies = _load_shared_hr_cookies()
if not cookies:
raise RuntimeError("无 hr cookies,请先完成 HR 登录")
session = requests.Session()
session.headers.update({
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies:
if c.get("domain") and "37du.co" in c["domain"]:
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
return session
def _relogin_get_user_info():
"""登录态失效后:补登 → 重建会话 → 重新获取 userId/rootId。"""
_ensure_hr_cookies()
session = build_hr_session()
info = fetch_cur_user_info(session)
return session, info.get("userId", ""), info.get("rootId", "")
# ==================== HR 接口 ====================
def fetch_cur_user_info(session):
return hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
def fetch_attendance_abnormal_page(session, user_id, treecode, begin_date, end_date,
page_no=1, page_size=PAGE_MAX_SIZE,
is_adjusted=IS_ADJUSTED, abnormal_type=""):
params = {
"treecode": treecode,
"user_id": user_id,
"commonQuery": "",
"commonQueryStr": "",
"sqlId": "kq_count_abnormal_Select",
"redapiId": "rf_p_kq_count_abnormal_Select",
"treeCodeList": "",
"abnormal_type": abnormal_type,
"base_code": "",
"join_date": "",
"join_date_end": end_date,
"person_status": "",
"staff_id": "",
"post_no": "",
"post_type": "1",
"period_order": "",
"identity_test": "",
"identity": "",
"sex": "",
"age": "",
"age_end": "",
"start_operat_time": "",
"end_operat_time": "",
"operator_username": "",
"operator_userid": "",
"is_adjusted": is_adjusted,
"begin_date": begin_date,
"end_date": end_date,
"STAFF_NAME": "",
"start": str((page_no - 1) * page_size),
"sortType": "desc",
"sortName": "work_day",
"pageNo": page_no,
"pageSize": page_size,
}
return hr_request_json(session, "POST", ATTENDANCE_ABNORMAL_URL, params, "考勤异常")
def fetch_all_attendance_abnormal(session, user_id, treecode, begin_date, end_date,
is_adjusted=IS_ADJUSTED, abnormal_type=""):
"""分页拉取全部考勤异常;中途登录态失效自动补登后续抓。"""
all_rows = []
page_no = 1
while True:
try:
data = fetch_attendance_abnormal_page(
session, user_id, treecode, begin_date, end_date,
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
except HRSessionExpiredError:
logger.warning("考勤异常 HR 登录态过期,自动补登后续抓")
session, user_id, treecode = _relogin_get_user_info()
data = fetch_attendance_abnormal_page(
session, user_id, treecode, begin_date, end_date,
page_no, PAGE_MAX_SIZE, is_adjusted, abnormal_type)
if data.get("state") != "1":
logger.error("考勤异常第 %d 页请求失败:%s", page_no, data.get("meg"))
break
page_list = data.get("datas", []) or []
if not page_list:
logger.info("考勤异常无更多数据")
break
all_rows.extend(page_list)
total_page = data.get("pageCount", 0)
logger.info("考勤异常已抓取 %d/%d 页,累计 %d 条", page_no, total_page, len(all_rows))
if page_no >= total_page:
break
page_no += 1
time.sleep(0.2)
return all_rows
# ==================== 考勤异常确认 ====================
def adjust_abnormal(session, abnormal_ids, type_code=1):
"""确认/调整考勤异常单据(调用 HR 接口,type=1 自动确认异常)。
Args:
session: 已登录的 requests.Session 对象
abnormal_ids: 异常单据唯一编号 abnormal_id,可为单个 id 或 id 列表
type_code: 处理类型,1=自动确认异常(按接口约定)
Returns:
接口返回的 JSON 字典(state=1 表示处理成功)
"""
if isinstance(abnormal_ids, (list, tuple)):
ids = ",".join(str(i) for i in abnormal_ids)
else:
ids = str(abnormal_ids)
params = {"abnormalIds": ids, "type": type_code}
return hr_request_json(session, "POST", ATTENDANCE_ADJUST_URL, params, "考勤异常确认")
def confirm_abnormal(abnormal_ids, type_code=1, session=None):
"""确认/调整考勤异常单据(按 abnormal_id 唯一编号),会话为空时自动构建并校验。
Args:
abnormal_ids: 异常单据 id,可为单个 id 或 id 列表
type_code: 处理类型,1=自动确认异常(默认)
session: 已登录会话;为空时自动构建并校验
Returns:
接口返回的 JSON 字典(state=1 表示处理成功)
"""
if session is None:
session = build_hr_session()
try:
info = fetch_cur_user_info(session)
except HRSessionExpiredError:
session, _, _ = _relogin_get_user_info()
return adjust_abnormal(session, abnormal_ids, type_code)
def is_mild_abnormal(item):
"""轻微异常:迟到/早退 且 异常时长 < 30 分钟(自动确认范围,不分职能序列)。"""
return not classify_abnormal(item)
def auto_confirm_mild(data, session=None):
"""自动确认轻微异常(迟到/早退 < 30 分钟,不分职能序列)。
Args:
data: 未调整考勤异常记录列表
session: 已登录会话;为空时自动构建
Returns:
确认成功的条数
"""
mild = [it for it in data if is_mild_abnormal(it) and it.get("abnormal_id")]
if not mild:
logger.info("无轻微异常(迟到/早退<30分钟),跳过自动确认")
return 0
ids = [it["abnormal_id"] for it in mild]
logger.info("自动确认轻微异常 %d 条(不分职能序列)", len(ids))
result = confirm_abnormal(ids, session=session)
if result.get("state") == "1":
logger.info("自动确认接口返回处理成功,共 %d 条", len(ids))
return len(ids)
logger.error("自动确认失败:%s", result.get("meg") or result)
return 0
def build_group_summary(total_count, mild_count, confirmed_count, non_func_count, func_count,
push_count, other_count, month, begin, end, test_mode=False):
"""生成考勤异常处理条数汇总消息(与汇总日志格式一致,供钉钉群机器人推送)。"""
if test_mode:
title = "【考勤异常处理汇总(小范围测试)】"
else:
title = "【考勤异常处理汇总】"
return (
f"{title}\n\n"
f"查询范围:{begin} ~ {end}({month} 整月,推送仅上周)\n\n"
f"考勤异常总数:{total_count} 条\n\n"
f"直接处理(轻微,整月自动确认):{mild_count} 条,确认成功 {confirmed_count} 条\n\n"
f"待通知(职能,上周):{func_count} 条,合并为 {push_count} 条推送\n\n"
f"上周非职能(不推送):{non_func_count} 条\n\n"
f"本月其他严重异常(非上周,仅导出留痕):{other_count} 条"
)
# ==================== 业务规则(与 app 版一致) ====================
def last_week_range(today=None):
"""返回上周查询范围:(上周一, 上周日)。
上周定义:本周一往前推 7 天为上周一,上周一 + 6 天为上周日。
"""
today = today or date.today()
this_monday = today - timedelta(days=today.weekday()) # 本周一
last_monday = this_monday - timedelta(days=7)
last_sunday = this_monday - timedelta(days=1)
return last_monday.strftime("%Y-%m-%d"), last_sunday.strftime("%Y-%m-%d")
def query_month(today=None):
"""本次查询月份:1 号(2 号之前,不含 2 号)查上月,否则查当月。
当月数据过少(仅 1 天)时补处理上月整月;2 号及以后按当月处理。
"""
today = today or date.today()
if today.day < 2:
first_of_this_month = today.replace(day=1)
return (first_of_this_month - timedelta(days=1)).strftime("%Y-%m")
return today.strftime("%Y-%m")
def in_last_week(item, push_begin, push_end):
"""判断异常记录(按 work_day)是否落在上周范围内;work_day 缺失时返回 False。"""
work_day = str(item.get("work_day") or "")[:10]
return bool(work_day) and push_begin <= work_day <= push_end
def filter_test_units(data, units=None, exclude_path_keyword="大区"):
"""小范围测试:仅保留指定所属单位(BELONG_UNIT_ORG_NAME)的考勤异常作为完整数据源,
且部门路径(ORG_FULL_PATH)不包含指定关键字(默认排除「大区」)。
units 为空时返回原数据(不筛选)。
"""
units = units or TEST_BELONG_UNITS
if not units:
return data
kept = [
it for it in data
if str(it.get("BELONG_UNIT_ORG_NAME", "") or "").strip() in units
and exclude_path_keyword not in str(it.get("ORG_FULL_PATH", "") or "")
]
logger.warning("小范围测试:所属单位 %s 且部门路径不含「%s」,保留 %d/%d 条",
"、".join(units), exclude_path_keyword, len(kept), len(data))
return kept
def classify_abnormal(item):
"""判断该条异常是否需要钉钉推送。
迟到/早退 且 异常时长 < 30 分钟 → 不推送(轻微异常,直接处理);
迟到/早退 >= 30 分钟 或 其他类型(旷工/工时不足/漏打卡等)→ 推送。
"""
abnormal = str(item.get("abnormal", ""))
try:
minute = int(item.get("abnormal_minute", 0) or 0)
except (TypeError, ValueError):
minute = 0
if ("迟到" in abnormal or "早退" in abnormal) and minute < 30:
return False
return True
def is_func_staff(item):
"""判断该员工是否属于职能序列(first_type_name 含「职能」才推送)。"""
return "职能" in str(item.get("first_type_name", "") or "")
def build_notify_text(items):
"""按人员合并拼接钉钉通知文本(一人一条,含该人全部异常)。"""
first = items[0]
lines = [
"【考勤异常提醒】",
f"姓名:{first.get('STAFF_NAME', '')}",
f"工号:{first.get('base_code', '')}",
f"共{len(items)}条考勤异常,请在2日内主动对接人事处理考勤异常确认/请假审批/漏打卡监控查询等,"
"超时未对接,将视为考勤异常直接封存",
]
for idx, item in enumerate(items, 1):
abnormal = str(item.get("abnormal", "") or "").strip() or "考勤异常"
minute = item.get("abnormal_minute") or "0"
lines.append(
f"{idx}、考勤日期:{item.get('work_day', '')}|异常类型:{abnormal}|异常时长:{minute}分钟"
)
return "\n".join(lines)
# ==================== 导出 Excel ====================
def _status_cn(value):
"""处理状态 is_adjusted 编码转中文;空值/未知编码保持原样。"""
if value is None or value == "":
return ""
return STATUS_MAP.get(str(value), str(value))
def export_excel(data, save_dir, month_str, test_mode=False):
if not data:
raise ValueError("未查询到任何考勤异常数据,无法导出")
df = pd.DataFrame(data)
# 处理方式:轻微异常(自动确认)/ 需核实(钉钉推送)
df["处理方式"] = df.apply(
lambda r: "自动确认" if not classify_abnormal(r) else "钉钉推送", axis=1
)
# 班段:班次时段 begin_time~end_time(如 "09:00~18:00",无班段留空)
df["班段"] = df.apply(
lambda r: (
f"{str(r.get('begin_time') or '').strip()}~{str(r.get('end_time') or '').strip()}"
if (r.get("begin_time") or r.get("end_time")) else ""
),
axis=1,
)
# 英文字段 → 中文字段
df.rename(columns=COL_MAP, inplace=True)
# 处理状态:is_adjusted 编码转中文
if "处理状态" in df.columns:
df["处理状态"] = df["处理状态"].apply(_status_cn)
# 仅保留 aa.md 目标列(顺序一致;缺失列补空)
for col in SHOW_ORDER:
if col not in df.columns:
df[col] = ""
df = df[SHOW_ORDER]
os.makedirs(save_dir, exist_ok=True)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
# 测试模式:文件名标注「测试」,与正式结果区分,避免误用
prefix = "周考勤异常_测试" if test_mode else "周考勤异常"
save_path = os.path.abspath(os.path.join(save_dir, f"{prefix}_{month_str}_{ts}.xlsx"))
try:
df.to_excel(save_path, index=False)
except PermissionError:
raise RuntimeError(
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试"
)
logger.info("考勤异常数据:%d 条", len(data))
logger.info("文件已保存:%s", save_path)
return save_path
# ==================== 钉钉推送(总开关控制) ====================
def push_abnormal(items):
"""按「工号-姓名」分组,合并为 messages 元组列表,写入影刀全局变量 messages,
由流程拖「37du钉钉单聊推送」指令(yingdao/share/dingtalk_dws_push.py)发送(本脚本不内联发送,
保持单文件自包含)。
每项为 (msg_type, name, user_id, content, file_path) 五元组,此处均为 ("text", 姓名, 工号, 文本, ""):
msg_type 消息类型,文本推送固定 "text"
name 接收人姓名(发文本时仅用于记录/展示)
user_id 接收人工号(dws 按工号发送,避免同名误发)
content 消息内容
file_path 文件地址(文本推送留空)
返回 (待推送条数, 失败数=0)。
"""
groups = {}
for it in items:
name = it.get("STAFF_NAME", "") or ""
if not name:
logger.warning("异常记录缺少姓名,跳过:%s", it)
continue
key = (it.get("base_code", "") or "", name)
groups.setdefault(key, []).append(it)
messages = []
for (code, name), group in groups.items():
# 消息类型固定 "text",工号用于 dws 按工号发送,姓名用于记录
messages.append(("text", name, code, build_notify_text(group), ""))
# 写入影刀全局变量,供流程「37du钉钉单聊推送」指令读取(无数据也置空,避免 NameError)
_set_glv('messages', messages)
logger.info("当事人消息已生成并写入全局变量 messages:共 %d 条(由流程推送)", len(messages))
return len(messages), 0
# ==================== 主流程 ====================
def handle_attendance_abnormal(save_dir=None, month=None, test_mode=False):
save_dir = save_dir or SAVE_DIR
# 1. 会话:复用共享登录态,必要时补登
session = build_hr_session()
try:
info = fetch_cur_user_info(session)
except HRSessionExpiredError:
logger.warning("cookies 已失效,自动补登")
session, user_id, treecode = _relogin_get_user_info()
info = {"userId": user_id, "rootId": treecode}
user_id = info.get("userId", "")
treecode = info.get("rootId", "")
if not user_id or not treecode:
raise RuntimeError(f"员工基础信息接口未返回 userId/rootId:{info}")
logger.info("cookies 校验通过,user_id=%s,treecode=%s", user_id, treecode)
# 2. 查询范围:整月(1 号查上月,否则当月);推送仍按上周(周一~周日)
month = month or query_month()
begin = f"{month}-01"
end = f"{month}-31"
logger.info("===== 查询考勤异常日期范围:%s ~ %s(%s 整月),调整状态:%s =====",
begin, end, month, IS_ADJUSTED or "所有")
# 3. 拉取数据
data = fetch_all_attendance_abnormal(session, user_id, treecode, begin, end, IS_ADJUSTED)
# 小范围测试:仅保留指定所属单位数据,作为完整数据源跑通全流程
if test_mode:
data = filter_test_units(data)
if not data:
logger.info("本月(%s)无考勤异常数据,跳过导出与推送", month)
return None
# 4. 导出 Excel 底稿
month_str = month or end[:7] # 文件名月份标识取上周日所在月
path = export_excel(data, save_dir, month_str, test_mode=test_mode)
# 5. 分级分类:轻微异常整月自动确认;需推送的仅上周(周一~周日)严重异常
mild_list = [it for it in data if not classify_abnormal(it)]
push_begin, push_end = last_week_range()
push_list = [it for it in data if classify_abnormal(it) and in_last_week(it, push_begin, push_end)]
other_list = [it for it in data if classify_abnormal(it) and not in_last_week(it, push_begin, push_end)]
func_list = [it for it in push_list if is_func_staff(it)]
non_func_list = [it for it in push_list if not is_func_staff(it)]
# 6. 自动确认轻微异常(整月,迟到/早退<30分钟,不分职能序列)——总开关 AUTO_CONFIRM_ENABLED 控制
# 统计不受开关影响:始终按数据计算实际条数,便于查看真实情况(开关只决定是否真正调用确认接口)
mild_count = len([it for it in mild_list if it.get("abnormal_id")])
if AUTO_CONFIRM_ENABLED:
confirmed_count = auto_confirm_mild(mild_list, session=session)
else:
confirmed_count = 0
logger.warning("自动确认未启用(AUTO_CONFIRM_ENABLED=%s),仅统计待自动确认 %d 条,未执行确认",
AUTO_CONFIRM_ENABLED, mild_count)
# 7. 钉钉推送(总开关控制)
push_count, fail_count = 0, 0
if DINGTALK_PUSH_ENABLED:
if func_list:
push_count, fail_count = push_abnormal(func_list)
else:
logger.info("无需推送的异常,跳过当事人钉钉通知")
logger.info("当事人推送完成:成功 %d 条,失败 %d 条", push_count, fail_count)
else:
logger.info("钉钉推送未启用(dingtalk_push_enabled!=true),未发送任何钉钉消息")
# 8. 汇总日志 + 钉钉群条数汇总(与日志格式一致)
logger.info("=" * 60)
if test_mode:
logger.info("【考勤异常处理汇总(小范围测试)】")
else:
logger.info("【考勤异常处理汇总】")
logger.info(" 考勤异常总数:%d 条", len(data))
logger.info(" 直接处理(轻微,整月自动确认):%d 条,确认成功 %d 条", mild_count, confirmed_count)
logger.info(" 待通知(职能,上周):%d 条,合并为 %d 条推送", len(func_list), push_count)
logger.info(" 上周非职能(不推送):%d 条", len(non_func_list))
logger.info(" 本月其他严重异常(非上周,仅导出留痕):%d 条", len(other_list))
logger.info(" 导出文件:%s", path)
logger.info("=" * 60)
group_message = build_group_summary(
len(data), mild_count, confirmed_count, len(non_func_list), len(func_list), push_count,
len(other_list), month, begin, end, test_mode=test_mode)
_set_glv('group_messages', [group_message])
logger.info("处理条数汇总已写入全局变量 group_messages:%s", group_message)
return path
def main(save_dir=None, month=None, test_mode=False):
"""影刀「调用模块」入口;也可作为脚本直接运行,仅支持关键字参数。
参数说明:
save_dir: 导出目录,默认 SAVE_DIR
month: 查询月份 "YYYY-MM";默认本月(1 号查上月,否则当月);指定则查该月
test_mode: True=小范围测试:仅筛选 TEST_BELONG_UNITS 所属单位数据跑通全流程,默认 False
例:
main() # 正式全量
main(test_mode=True) # 小范围测试(按 TEST_BELONG_UNITS 筛选且排除大区)
main(test_mode=True, month="2026-08")
"""
# 始终定义影刀全局变量 messages / group_messages(默认空),避免后续流程步骤引用时 NameError
_set_glv('messages', [])
_set_glv('group_messages', [])
if not save_dir:
save_dir = sys.argv[1] if len(sys.argv) > 1 else None
if not month:
month = sys.argv[2] if len(sys.argv) > 2 else None
if not test_mode and len(sys.argv) > 3:
test_mode = str(sys.argv[3]).strip().lower() in ("1", "true", "yes", "on")
try:
out = handle_attendance_abnormal(save_dir, month, test_mode)
if out:
logger.info("===== 考勤异常处理完成,导出:%s =====", out)
else:
logger.info("===== 考勤异常处理完成:本月无数据 =====")
return {"success": True, "save_path": out}
except Exception as e:
if "正被占用" in str(e):
logger.error("=========== 提醒 ===========")
logger.error(str(e))
logger.error("请关闭该 Excel 文件后重新运行即可,无需重查数据。")
return {"success": False, "message": str(e)}
logger.error("考勤异常处理失败:%s", e)
return {"success": False, "message": str(e)}
if __name__ == "__main__":
main(test_mode=True)