refactor: 统一所有缓存/会话文件的存储路径
1. 重构会话管理模块,新增app.common.app_paths统一管理缓存路径,所有登录态与缓存统一迁移至%LOCALAPPDATA%\37duAutomation\.sessions 2. 更新所有涉及文件存储路径的代码,包括考勤、工资卡、社保、审批等模块 3. 新增银行字典缓存功能,统一管理银行编码映射 4. 添加雇主险业务模块,实现花名册筛选复制功能 5. 更新.gitignore,将所有.sessions目录纳入忽略列表 6. 删除影刀脚本旧的本地缓存文件 7. 优化加班审批校验逻辑,新增提前到岗型加班校验规则 8. 完善工资卡核对功能,补充开卡银行信息展示
@@ -11,7 +11,7 @@
|
||||
@Version: 2.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 .sessions/hr_cookies.json;
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可查询当月考勤异常并导出 Excel。
|
||||
"""
|
||||
|
||||
|
Before Width: | Height: | Size: 72 KiB After Width: | Height: | Size: 94 KiB |
|
Before Width: | Height: | Size: 83 KiB After Width: | Height: | Size: 106 KiB |
|
After Width: | Height: | Size: 53 KiB |
|
After Width: | Height: | Size: 60 KiB |
|
After Width: | Height: | Size: 63 KiB |
|
After Width: | Height: | Size: 70 KiB |
|
After Width: | Height: | Size: 83 KiB |
|
After Width: | Height: | Size: 95 KiB |
|
Before Width: | Height: | Size: 4.3 KiB After Width: | Height: | Size: 7.0 KiB |
|
After Width: | Height: | Size: 3.6 KiB |
|
After Width: | Height: | Size: 4.6 KiB |
|
After Width: | Height: | Size: 5.7 KiB |
@@ -15,12 +15,20 @@ WAGE_CARD_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/HrStaffWageCard.m
|
||||
# 单页最大抓取条数
|
||||
PAGE_MAX_SIZE = 500
|
||||
|
||||
# ---------- 银行字典接口(aa.md 提供,按 BANK_TYPE 匹配 code -> 开卡银行) ----------
|
||||
BANK_DICT_URL = "https://hr.37du.co/RedseaPlatform/PtCodeTypeValue.mc?method=getCodeValueByCodes"
|
||||
BANK_DICT_CODE_TYPE = "WAGE.BANKTYPE"
|
||||
BANK_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60 # 缓存7天过期,自动重新拉取
|
||||
|
||||
# ---------- 员工花名册(自定义导出)页面 ----------
|
||||
# 花名册自定义导出页面(aa.md 提供),基于 DrissionPage 浏览器自动化操作
|
||||
ROSTER_URL = "https://hr.37du.co/RedseaPlatform/PtPortal.mc?method=classic#ajax&1&nworktoday-40175-24311-77128-52242&nworktoday-40175-24311|/RedseaPlatform/hrRoster/1116da64-b094-11ea-b588-14187743d052/getCustomCommonList.mc?clickFlag=true&treePermitType=permit&useSealTreeData=0&menuName=%E5%91%98%E5%B7%A5%E8%8A%B1%E5%90%8D%E5%86%8C"
|
||||
|
||||
# 花名册默认导出的自定义模板名称
|
||||
ROSTER_TEMPLATE_NAME = "员工基础信息"
|
||||
# 花名册自定义导出模板(下拉框中全部模板,后续各业务场景可按需选用)
|
||||
ROSTER_TEMPLATE_NAME = "员工基础信息" # 默认模板
|
||||
ROSTER_TEMPLATE_CADRE_SELECT = "干部选拔信息" # 干部选拔
|
||||
ROSTER_TEMPLATE_INDIVIDUAL_TAX = "个税申报基础信息" # 个税申报
|
||||
ROSTER_TEMPLATE_EMPLOYER_INSURANCE = "雇主险增减员导出模板" # 雇主险增减员
|
||||
|
||||
# ---------- 考勤异常查询接口 ----------
|
||||
# 获取当前用户信息(用于校验 cookies 有效性,并取得查询考勤异常所需的 userId / rootId(treecode))
|
||||
|
||||
@@ -8,9 +8,12 @@
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.ehr.common.config import (
|
||||
WAGE_CARD_URL,
|
||||
@@ -21,7 +24,11 @@ from app.service.hrbp.ehr.common.config import (
|
||||
SHIFT_URL,
|
||||
LEAVE_URL,
|
||||
OVERTIME_URL,
|
||||
BANK_DICT_URL,
|
||||
BANK_DICT_CODE_TYPE,
|
||||
BANK_DICT_EXPIRE_SEC,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.session_manager import build_hr_session
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
@@ -149,6 +156,113 @@ def fetch_all_wage_card(
|
||||
return all_rows
|
||||
|
||||
|
||||
# ---------- 银行字典接口(aa.md 提供,按 BANK_TYPE 匹配 code -> 开卡银行) ----------
|
||||
# 缓存文件统一放在 AppData\Local\37duAutomation\.sessions 目录
|
||||
_BANK_DICT_CACHE_DIR = get_sessions_dir()
|
||||
BANK_DICT_LIST_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_list.json")
|
||||
BANK_DICT_MAP_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_map.json")
|
||||
|
||||
|
||||
def _fetch_bank_dict(session=None):
|
||||
"""远程调用接口获取银行字典,并写入本地缓存。
|
||||
|
||||
Returns:
|
||||
(list[dict], dict[code->name])
|
||||
"""
|
||||
if session is None:
|
||||
session = build_hr_session()
|
||||
payload = {
|
||||
"codeType": BANK_DICT_CODE_TYPE,
|
||||
"inUse": "0,1,2",
|
||||
"platformMode": "redseaPlatform",
|
||||
}
|
||||
resp = session.post(BANK_DICT_URL, data=payload, timeout=30)
|
||||
if not resp:
|
||||
raise RuntimeError("银行字典请求失败,未获取到响应")
|
||||
if resp.status_code != 200:
|
||||
raise RuntimeError(f"银行字典接口状态码异常: {resp.status_code}")
|
||||
if _is_expired(resp.text):
|
||||
raise HRSessionExpiredError("HR 登录态已过期,银行字典接口返回非 JSON 内容")
|
||||
resp_json = resp.json()
|
||||
raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or []
|
||||
result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")}
|
||||
for item in raw_list]
|
||||
result_map = {item["code"]: item["name"] for item in result_list}
|
||||
|
||||
os.makedirs(_BANK_DICT_CACHE_DIR, exist_ok=True)
|
||||
with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_list, f, ensure_ascii=False, indent=2)
|
||||
with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f:
|
||||
json.dump(result_map, f, ensure_ascii=False, indent=2)
|
||||
logger.info("银行字典远程拉取完成,共 %d 条", len(result_list))
|
||||
return result_list, result_map
|
||||
|
||||
|
||||
def _load_bank_dict_cache():
|
||||
"""读取本地银行字典缓存,失败返回 (None, None)。"""
|
||||
try:
|
||||
with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f:
|
||||
lst = json.load(f)
|
||||
with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f:
|
||||
mp = json.load(f)
|
||||
return lst, mp
|
||||
except Exception as e:
|
||||
logger.warning("银行字典本地缓存读取失败:%s", e)
|
||||
return None, None
|
||||
|
||||
|
||||
def get_bank_dict(session=None, force_refresh: bool = False):
|
||||
"""获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。
|
||||
|
||||
Args:
|
||||
session: 可选的已登录 requests.Session;未提供时自动构建
|
||||
force_refresh: True 强制重新调用接口
|
||||
|
||||
Returns:
|
||||
(list版本, dict[code->name]版本)
|
||||
"""
|
||||
need_refresh = force_refresh
|
||||
if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)):
|
||||
need_refresh = True
|
||||
else:
|
||||
mtime = os.path.getmtime(BANK_DICT_LIST_FILE)
|
||||
if time.time() - mtime > BANK_DICT_EXPIRE_SEC:
|
||||
need_refresh = True
|
||||
|
||||
if need_refresh:
|
||||
try:
|
||||
return _fetch_bank_dict(session)
|
||||
except Exception as e:
|
||||
logger.error("银行字典远程拉取失败:%s", e)
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is not None:
|
||||
logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
return [], {}
|
||||
|
||||
lst, mp = _load_bank_dict_cache()
|
||||
if lst is None:
|
||||
# 缓存异常时重新拉取
|
||||
return _fetch_bank_dict(session)
|
||||
logger.info("读取本地银行字典缓存,共 %d 条", len(lst))
|
||||
return lst, mp
|
||||
|
||||
|
||||
def bank_type_to_name(bank_type, bank_map) -> str:
|
||||
"""按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。"""
|
||||
if bank_type is None:
|
||||
return ""
|
||||
if isinstance(bank_type, float):
|
||||
if bank_type != bank_type: # NaN
|
||||
return ""
|
||||
bank_type = str(int(bank_type))
|
||||
elif isinstance(bank_type, int):
|
||||
bank_type = str(bank_type)
|
||||
else:
|
||||
bank_type = str(bank_type).strip()
|
||||
return bank_map.get(bank_type, "")
|
||||
|
||||
|
||||
def adjust_abnormal(
|
||||
session,
|
||||
abnormal_ids,
|
||||
|
||||
@@ -18,6 +18,7 @@ import cv2
|
||||
import numpy as np
|
||||
import io
|
||||
from dotenv import load_dotenv
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
load_dotenv()
|
||||
|
||||
# ================== 配置 ==================
|
||||
@@ -40,8 +41,8 @@ TIMEOUT = 10
|
||||
HEADLESS = False
|
||||
DEBUG_DIR = os.path.join(os.path.dirname(__file__), 'captcha_debug')
|
||||
|
||||
# 登录 cookies 持久化目录(与 OA 系统一致,服务层统一管理各平台会话文件)
|
||||
_COOKIE_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '.sessions')
|
||||
# 登录 cookies 持久化目录(统一放在 AppData\Local\37duAutomation,与 OA 系统一致)
|
||||
_COOKIE_DIR = get_sessions_dir()
|
||||
COOKIE_FILE = os.path.join(_COOKIE_DIR, 'hr_cookies.json')
|
||||
|
||||
def ensure_dir(path):
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
import os
|
||||
import json
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
try:
|
||||
@@ -20,8 +21,8 @@ except ImportError:
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# HR 登录 cookies 持久化目录(login.py 登录成功后保存)
|
||||
_SESSIONS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '.sessions')
|
||||
# HR 登录 cookies 持久化目录(统一放在 AppData\Local\37duAutomation,login.py 登录成功后保存)
|
||||
_SESSIONS_DIR = get_sessions_dir()
|
||||
HR_COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'hr_cookies.json')
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,9 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance
|
||||
@FileName: __init__.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险名额调度系统(app 版):花名册业务处理 + 在参名单名额调度 + 变更清单生成
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
@@ -0,0 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.config
|
||||
@FileName: config.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险模块配置:集中管理文件路径、Sheet 名称、列名映射、校验常量等
|
||||
@Version: 1.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
from datetime import datetime
|
||||
|
||||
from app.service.hrbp.ehr.common.config import ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# ---------- 文件路径 ----------
|
||||
BASE_DIR = r"D:\资料\人资\雇主险"
|
||||
DATE_STR = datetime.now().strftime("%Y.%m.%d")
|
||||
DATE_SHORT = datetime.now().strftime("%m.%d")
|
||||
TODAY_DATE = datetime.now().strftime("%Y-%m-%d")
|
||||
|
||||
# 输入/输出文件路径
|
||||
TARGET_FILE = os.path.join(BASE_DIR, f"三十七度-雇主险变更记录-{DATE_STR}.xlsx")
|
||||
OUTPUT_IN_PARAM = os.path.join(BASE_DIR, f"新在参名单-{DATE_STR}.xlsx")
|
||||
|
||||
# 固定 Sheet 名称
|
||||
SHEET_BIZ = "花名册导出-雇主险使用基础信息"
|
||||
SHEET_IN_PARAM = "手动维护-在参名单"
|
||||
CHANGE_SHEET_PREFIX = "37度-雇员变更清单"
|
||||
CHANGE_SHEET_NAME = f"{CHANGE_SHEET_PREFIX}-{DATE_SHORT}"
|
||||
|
||||
# ---------- 花名册列名映射(表头在第4行) ----------
|
||||
BIZ_COL_EMPLOYEE_ID = "证件号" # O列,员工唯一标识
|
||||
BIZ_COL_CATEGORY = "工种类别" # P列
|
||||
BIZ_COL_SCHEME = "投保方案" # Q列
|
||||
BIZ_COL_HANDLE = "方案处理" # W列,值: 增加投保 / 要替换 / /
|
||||
|
||||
# 数据起始行(第17行开始是数据区域,前16行是固定标题/兼职数据)
|
||||
DATA_START_ROW = 17
|
||||
|
||||
# ---------- 校验常量 ----------
|
||||
VALID_CATEGORIES = ["一类", "二类", "三类", "四类"]
|
||||
VALID_SCHEMES = ["人保-20万", "人保-50万", "人保-80万"]
|
||||
|
||||
# ---------- 功能开关 ----------
|
||||
ENABLE_VALIDATION = False # True: 启用数据校验, False: 跳过校验(测试模式)
|
||||
|
||||
# ---------- 本场景 HR 花名册导出模板(roster_export 动态传入,取自 ehr/common 统一配置) ----------
|
||||
ROSTER_TEMPLATE_NAME = ROSTER_TEMPLATE_EMPLOYER_INSURANCE
|
||||
|
||||
# 本场景需导出的在职状态(雇主险增减员只需在职人员,无需离职)
|
||||
ROSTER_EXPORT_STATUSES = ["在职"]
|
||||
@@ -0,0 +1,773 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance
|
||||
@FileName: employer_insurance.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险名额调度系统(app 版)「步骤2:调度」
|
||||
前置:先运行 roster_filter.py(步骤1:筛选复制),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
1. 读取花名册业务数据(增加投保/要替换)
|
||||
2. 结合在参名单(空闲名额池、当前参保状态)
|
||||
3. 三阶段调度:初始化 → 处理业务 → 分配名额
|
||||
4. 输出:
|
||||
a. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
b. 精细更新"37度-雇员变更清单-MM.DD"(仅清空并重写B/N/P~S列数据)
|
||||
c. 备份新在参名单
|
||||
|
||||
【输入文件】三十七度-雇主险变更记录-YYYY.MM.DD.xlsx(已刷新公式)
|
||||
- Sheet1: 花名册导出-雇主险使用基础信息 (表头第4行)
|
||||
- Sheet2: 手动维护-在参名单 (表头第6行)
|
||||
- Sheet3: 37度-雇员变更清单-月.日 (已有模板,表头2行,第3行起数据)
|
||||
|
||||
【输出】原文件原地更新 + 备份"新在参名单-YYYY.MM.DD.xlsx"
|
||||
|
||||
【运行】python employer_insurance.py
|
||||
@Version: 2.0.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import re
|
||||
import sys
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
import pandas as pd
|
||||
from openpyxl import load_workbook
|
||||
from copy import copy
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
BASE_DIR,
|
||||
TODAY_DATE,
|
||||
TARGET_FILE,
|
||||
OUTPUT_IN_PARAM,
|
||||
SHEET_BIZ,
|
||||
SHEET_IN_PARAM,
|
||||
CHANGE_SHEET_PREFIX,
|
||||
CHANGE_SHEET_NAME,
|
||||
BIZ_COL_EMPLOYEE_ID,
|
||||
BIZ_COL_CATEGORY,
|
||||
BIZ_COL_SCHEME,
|
||||
BIZ_COL_HANDLE,
|
||||
DATA_START_ROW,
|
||||
VALID_CATEGORIES,
|
||||
VALID_SCHEMES,
|
||||
ENABLE_VALIDATION,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 一、数据校验
|
||||
# ============================================================
|
||||
def validate_biz_data(biz_df):
|
||||
"""
|
||||
校验花名册业务数据的合法性
|
||||
|
||||
校验规则:
|
||||
1. 工种类别(P列)必须为:一类/二类/三类/四类
|
||||
2. 方案处理 = "增加投保" 时,投保方案(Q列)必须为:
|
||||
人保-20万 / 人保-50万 / 人保-80万
|
||||
|
||||
返回:errors 错误列表,每个错误含 行号/员工ID/错误类型/详情;为空表示校验通过
|
||||
"""
|
||||
errors = []
|
||||
|
||||
for idx, row in biz_df.iterrows():
|
||||
row_num = idx + 5 # 数据从第5行开始(第4行是表头)
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
category = row[BIZ_COL_CATEGORY]
|
||||
scheme = row[BIZ_COL_SCHEME]
|
||||
handle = row[BIZ_COL_HANDLE]
|
||||
|
||||
# 校验1:工种类别必须合法
|
||||
if pd.isna(category) or category not in VALID_CATEGORIES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "工种类别非法",
|
||||
"详情": f"工种类别为 '{category}',允许值:{VALID_CATEGORIES}"
|
||||
})
|
||||
|
||||
# 校验2:增加投保时,投保方案必须合法
|
||||
if str(handle).strip() == "增加投保":
|
||||
if pd.isna(scheme) or scheme not in VALID_SCHEMES:
|
||||
errors.append({
|
||||
"行号": row_num,
|
||||
"员工ID": emp_id,
|
||||
"错误类型": "投保方案非法",
|
||||
"详情": f"增加投保但投保方案为 '{scheme}',允许值:{VALID_SCHEMES}"
|
||||
})
|
||||
|
||||
return errors
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 二、阶段0:初始化(从在参名单构建状态)
|
||||
# ============================================================
|
||||
def initialize(in_param_df):
|
||||
"""
|
||||
从"手动维护-在参名单"构建三个核心数据结构:
|
||||
|
||||
1. idle_pools: 空闲名额池 {方案名称: [{type, employee_id}, ...]}
|
||||
2. employee_map: 当前参保员工映射 {证件号: 投保方案}
|
||||
3. pending_queues: 待转入队列(初始为空){方案名称: [证件号, ...]}
|
||||
|
||||
列索引(0-based): K列(10)证件号 / M列(12)当前投保方案 / R列(17)方案处理
|
||||
"""
|
||||
idle_pools = defaultdict(list)
|
||||
employee_map = {}
|
||||
pending_queues = defaultdict(list)
|
||||
|
||||
IDX_EMP_ID = 10
|
||||
IDX_CUR_SCHEME = 12
|
||||
IDX_HANDLE = 17
|
||||
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[IDX_EMP_ID]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
|
||||
handle = str(row.iloc[IDX_HANDLE]).strip()
|
||||
scheme = row.iloc[IDX_CUR_SCHEME]
|
||||
|
||||
if handle in ["无需", "档次替换"]:
|
||||
# 正常参保或待替换,都视为当前已参保
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
employee_map[emp_id] = scheme
|
||||
|
||||
elif handle == "离职减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({
|
||||
"type": "离职减少",
|
||||
"employee_id": emp_id
|
||||
})
|
||||
|
||||
elif handle == "参保减少":
|
||||
if not pd.isna(scheme) and scheme != "":
|
||||
idle_pools[scheme].append({
|
||||
"type": "参保减少",
|
||||
"employee_id": emp_id
|
||||
})
|
||||
# 其他值(如'/')忽略
|
||||
|
||||
# 按优先级排序(离职减少优先)
|
||||
for scheme in idle_pools:
|
||||
idle_pools[scheme].sort(key=lambda x: 1 if x["type"] == "离职减少" else 2)
|
||||
|
||||
return idle_pools, employee_map, pending_queues
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 三、阶段1:处理花名册业务
|
||||
# ============================================================
|
||||
def process_business(biz_df, idle_pools, employee_map, pending_queues):
|
||||
"""
|
||||
遍历花名册业务数据,产生待转入队列和额外空闲名额
|
||||
|
||||
业务类型:
|
||||
1. 增加投保 → 批量加入待转入队列
|
||||
2. 要替换 → 逐行处理:产生"档次替换迁出"名额,员工置为未参保
|
||||
3. 其他 → 记录"非法事件跳过"
|
||||
|
||||
返回:idle_pools, employee_map, pending_queues, change_log
|
||||
"""
|
||||
change_log = []
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
# ---------- 1. 增加投保(批量处理) ----------
|
||||
df_add = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "增加投保"]
|
||||
if not df_add.empty:
|
||||
for scheme, group in df_add.groupby(BIZ_COL_SCHEME):
|
||||
if pd.isna(scheme) or scheme == "":
|
||||
for _, row in group.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "投保方案为空,无法增加投保",
|
||||
"时间": now
|
||||
})
|
||||
continue
|
||||
|
||||
emp_ids = group[BIZ_COL_EMPLOYEE_ID].tolist()
|
||||
pending_queues[scheme].extend(emp_ids)
|
||||
for emp_id in emp_ids:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "增加投保",
|
||||
"详情": f"加入 {scheme} 待转入队列",
|
||||
"时间": now
|
||||
})
|
||||
|
||||
# ---------- 2. 要替换(逐行处理,涉及状态变更) ----------
|
||||
df_replace = biz_df[biz_df[BIZ_COL_HANDLE].astype(str).str.strip() == "要替换"]
|
||||
for _, row in df_replace.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
target_scheme = row[BIZ_COL_SCHEME]
|
||||
|
||||
# 校验:员工必须当前已参保
|
||||
origin_scheme = employee_map.get(emp_id)
|
||||
if origin_scheme is None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "员工当前未参保,无法进行档次替换",
|
||||
"时间": now
|
||||
})
|
||||
continue
|
||||
|
||||
if pd.isna(target_scheme) or target_scheme == "":
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": "目标方案为空",
|
||||
"时间": now
|
||||
})
|
||||
continue
|
||||
|
||||
# 产生"档次替换迁出"名额
|
||||
idle_pools[origin_scheme].append({
|
||||
"type": "档次替换迁出",
|
||||
"employee_id": emp_id
|
||||
})
|
||||
# 重新排序(离职减少 > 参保减少 > 档次替换迁出)
|
||||
idle_pools[origin_scheme].sort(
|
||||
key=lambda x: 1 if x["type"] == "离职减少"
|
||||
else 2 if x["type"] == "参保减少"
|
||||
else 3
|
||||
)
|
||||
|
||||
# 员工置为未参保
|
||||
employee_map[emp_id] = None
|
||||
pending_queues[target_scheme].append(emp_id)
|
||||
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "档次替换迁出",
|
||||
"详情": f"从 {origin_scheme} 迁出,进入 {target_scheme} 待转入",
|
||||
"时间": now
|
||||
})
|
||||
|
||||
# ---------- 3. 其他未知类型 ----------
|
||||
df_other = biz_df[~biz_df[BIZ_COL_HANDLE].astype(str).str.strip().isin(["增加投保", "要替换"])]
|
||||
for _, row in df_other.iterrows():
|
||||
change_log.append({
|
||||
"员工ID": row[BIZ_COL_EMPLOYEE_ID],
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"未知业务类型: {row[BIZ_COL_HANDLE]}",
|
||||
"时间": now
|
||||
})
|
||||
|
||||
return idle_pools, employee_map, pending_queues, change_log
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 四、阶段2:分配名额
|
||||
# ============================================================
|
||||
def allocate_slots(idle_pools, employee_map, pending_queues, change_log):
|
||||
"""
|
||||
逐个方案处理待转入队列,分配空闲名额或创建新名额
|
||||
|
||||
逻辑:
|
||||
1. 队列中的每个员工必须未参保
|
||||
2. 有空闲名额 → 复用(记录来源)
|
||||
3. 无空闲名额 → 全新新增
|
||||
|
||||
返回:final_records, change_log, reused_source_employees
|
||||
"""
|
||||
final_records = []
|
||||
reused_source_employees = []
|
||||
all_schemes = set(idle_pools.keys()) | set(pending_queues.keys())
|
||||
now = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
|
||||
|
||||
for scheme in all_schemes:
|
||||
queue = pending_queues.get(scheme, [])
|
||||
pool = idle_pools.get(scheme, [])
|
||||
|
||||
for emp_id in queue:
|
||||
# 校验:员工必须未参保
|
||||
if employee_map.get(emp_id) is not None:
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "非法事件跳过",
|
||||
"详情": f"员工已参保 {employee_map[emp_id]},不能重复参保",
|
||||
"时间": now
|
||||
})
|
||||
continue
|
||||
|
||||
if pool:
|
||||
# 复用空闲名额(取出优先级最高的)
|
||||
slot = pool.pop(0)
|
||||
reused_source_employees.append(slot["employee_id"])
|
||||
employee_map[emp_id] = scheme
|
||||
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": slot["type"],
|
||||
"来源员工ID": slot["employee_id"]
|
||||
})
|
||||
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "复用空闲名额参保",
|
||||
"详情": f"复用 {slot['type']}(来源 {slot['employee_id']}),方案 {scheme}",
|
||||
"来源员工ID": slot["employee_id"],
|
||||
"时间": now
|
||||
})
|
||||
else:
|
||||
# 全新新增
|
||||
employee_map[emp_id] = scheme
|
||||
final_records.append({
|
||||
"证件号": emp_id,
|
||||
"投保方案": scheme,
|
||||
"参保状态": "正常参保",
|
||||
"名额来源": "全新新增"
|
||||
})
|
||||
|
||||
change_log.append({
|
||||
"员工ID": emp_id,
|
||||
"操作": "全新新增名额参保",
|
||||
"详情": f"新增名额,方案 {scheme}",
|
||||
"时间": now
|
||||
})
|
||||
|
||||
return final_records, change_log, reused_source_employees
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 五、阶段3:输出(更新在参名单 + 精细更新变更清单 + 备份)
|
||||
# ============================================================
|
||||
def output_results(final_records, change_log, reused_source_employees, biz_df,
|
||||
in_param_df, column_names, target_file, output_backup,
|
||||
change_sheet_name, in_param_sheet):
|
||||
"""
|
||||
输出三部分内容:
|
||||
1. 更新"手动维护-在参名单"(第17行起B~N列)
|
||||
2. 精细更新"变更清单"(仅清空并重写B/N/P~S列数据)
|
||||
3. 备份新在参名单
|
||||
"""
|
||||
from openpyxl import load_workbook
|
||||
from copy import copy
|
||||
|
||||
# ---------- 1. 构建需要清空的员工ID集合 ----------
|
||||
emp_ids_to_clear = set()
|
||||
for rec in final_records:
|
||||
emp_ids_to_clear.add(rec["证件号"])
|
||||
emp_ids_to_clear.update(reused_source_employees)
|
||||
|
||||
# ---------- 2. 保留的行 ----------
|
||||
handle_col = column_names[17]
|
||||
emp_id_col = column_names[10]
|
||||
keep_mask = (
|
||||
((in_param_df[handle_col] == "无需") & (~in_param_df[emp_id_col].isin(emp_ids_to_clear))) |
|
||||
((in_param_df[handle_col].isin(["离职减少", "参保减少"])) & (~in_param_df[emp_id_col].isin(reused_source_employees)))
|
||||
)
|
||||
kept_df = in_param_df[keep_mask].copy()
|
||||
kept_emp_ids = set(kept_df[emp_id_col].tolist())
|
||||
|
||||
# ---------- 3. 构建员工信息字典 ----------
|
||||
biz_dict = {}
|
||||
for idx, row in biz_df.iterrows():
|
||||
emp_id = row[BIZ_COL_EMPLOYEE_ID]
|
||||
if pd.notna(emp_id):
|
||||
biz_dict[emp_id] = row
|
||||
|
||||
# ---------- 4. 构建新参保记录(B~N列) ----------
|
||||
new_records = []
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id not in biz_dict:
|
||||
logger.warning("员工 %s 在花名册中找不到,跳过", emp_id)
|
||||
continue
|
||||
|
||||
row_biz = biz_dict[emp_id]
|
||||
new_records.append({
|
||||
"B": row_biz.get("工号"),
|
||||
"C": row_biz.get("年龄"),
|
||||
"D": row_biz.get("性别"),
|
||||
"E": row_biz.get("岗位"),
|
||||
"F": row_biz.get("职位序列"),
|
||||
"G": row_biz.get("参保类型"),
|
||||
"H": row_biz.get("上下班交通方式"),
|
||||
"I": row_biz.get("入职时间"),
|
||||
"J": row_biz.get("姓名"),
|
||||
"K": row_biz.get("证件号"),
|
||||
"L": row_biz.get("工种类别"),
|
||||
"M": row_biz.get("投保方案"),
|
||||
"N": TODAY_DATE,
|
||||
})
|
||||
|
||||
# ---------- 5. 打开工作簿 ----------
|
||||
wb = load_workbook(target_file)
|
||||
ws = wb[in_param_sheet]
|
||||
max_row = ws.max_row
|
||||
|
||||
# ---------- 6. 读取现有数据 ----------
|
||||
existing_rows = []
|
||||
for row_idx in range(DATA_START_ROW, max_row + 1):
|
||||
row_data = []
|
||||
for col in range(1, 27):
|
||||
row_data.append(ws.cell(row=row_idx, column=col).value)
|
||||
existing_rows.append({
|
||||
"row_idx": row_idx,
|
||||
"data": row_data,
|
||||
"emp_id": ws.cell(row=row_idx, column=11).value # K列
|
||||
})
|
||||
|
||||
# ---------- 7. 构建新数据列表 ----------
|
||||
new_rows = []
|
||||
|
||||
# 7.1 保留行
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if emp_id in kept_emp_ids:
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_info["data"],
|
||||
"emp_id": emp_id,
|
||||
"action": "keep"
|
||||
})
|
||||
|
||||
# 7.2 清空需要替换的行(仅清空B~N列,R/S列不动)
|
||||
for row_info in existing_rows:
|
||||
emp_id = row_info["emp_id"]
|
||||
if emp_id in emp_ids_to_clear or emp_id is None:
|
||||
row_data = row_info["data"].copy()
|
||||
# 清空B~N列(索引1-13)
|
||||
for i in range(1, 14):
|
||||
row_data[i] = None
|
||||
new_rows.append({
|
||||
"row_idx": row_info["row_idx"],
|
||||
"data": row_data,
|
||||
"emp_id": None,
|
||||
"action": "clear"
|
||||
})
|
||||
|
||||
# 7.3 填充新记录到空行
|
||||
empty_slots = [r for r in new_rows if r["action"] == "clear" and r["emp_id"] is None]
|
||||
empty_slots.sort(key=lambda x: x["row_idx"])
|
||||
|
||||
for rec in new_records:
|
||||
if empty_slots:
|
||||
slot = empty_slots.pop(0)
|
||||
row_data = slot["data"]
|
||||
row_data[1] = rec["B"]
|
||||
row_data[2] = rec["C"]
|
||||
row_data[3] = rec["D"]
|
||||
row_data[4] = rec["E"]
|
||||
row_data[5] = rec["F"]
|
||||
row_data[6] = rec["G"]
|
||||
row_data[7] = rec["H"]
|
||||
row_data[8] = rec["I"]
|
||||
row_data[9] = rec["J"]
|
||||
row_data[10] = rec["K"]
|
||||
row_data[11] = rec["L"]
|
||||
row_data[12] = rec["M"]
|
||||
row_data[13] = rec["N"]
|
||||
slot["emp_id"] = rec["K"]
|
||||
slot["action"] = "filled"
|
||||
else:
|
||||
# 追加新行(复制上一行样式)
|
||||
row_data = [None] * 26
|
||||
if existing_rows:
|
||||
src_row_idx = existing_rows[-1]["row_idx"]
|
||||
for col in range(1, 27):
|
||||
src_cell = ws.cell(row=src_row_idx, column=col)
|
||||
dst_cell = ws.cell(row=max_row + 1, column=col)
|
||||
if src_cell.has_style:
|
||||
dst_cell.font = copy(src_cell.font)
|
||||
dst_cell.border = copy(src_cell.border)
|
||||
dst_cell.fill = copy(src_cell.fill)
|
||||
dst_cell.number_format = src_cell.number_format
|
||||
dst_cell.alignment = copy(src_cell.alignment)
|
||||
last_row_data = existing_rows[-1]["data"]
|
||||
for i in range(14, 26):
|
||||
row_data[i] = last_row_data[i]
|
||||
row_data[1] = rec["B"]
|
||||
row_data[2] = rec["C"]
|
||||
row_data[3] = rec["D"]
|
||||
row_data[4] = rec["E"]
|
||||
row_data[5] = rec["F"]
|
||||
row_data[6] = rec["G"]
|
||||
row_data[7] = rec["H"]
|
||||
row_data[8] = rec["I"]
|
||||
row_data[9] = rec["J"]
|
||||
row_data[10] = rec["K"]
|
||||
row_data[11] = rec["L"]
|
||||
row_data[12] = rec["M"]
|
||||
row_data[13] = rec["N"]
|
||||
new_rows.append({
|
||||
"row_idx": None,
|
||||
"data": row_data,
|
||||
"emp_id": rec["K"],
|
||||
"action": "append"
|
||||
})
|
||||
|
||||
# ---------- 8. 更新现有行(B~N列,列号=索引+1) ----------
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is not None:
|
||||
row_idx = row_info["row_idx"]
|
||||
row_data = row_info["data"]
|
||||
# 写入B~N列:索引1~13 对应列号2~14
|
||||
for idx in range(1, 14):
|
||||
ws.cell(row=row_idx, column=idx + 1).value = row_data[idx]
|
||||
|
||||
# ---------- 9. 追加新行 ----------
|
||||
current_row = max_row + 1
|
||||
for row_info in new_rows:
|
||||
if row_info["row_idx"] is None:
|
||||
row_idx = current_row
|
||||
row_data = row_info["data"]
|
||||
# 写入所有列:索引0对应A列,索引1对应B列...
|
||||
for col_idx, value in enumerate(row_data, start=1):
|
||||
ws.cell(row=row_idx, column=col_idx).value = value
|
||||
current_row += 1
|
||||
|
||||
# ---------- 10. 重新编号A列 ----------
|
||||
seq = 1
|
||||
for row_idx in range(DATA_START_ROW, current_row):
|
||||
if ws.cell(row=row_idx, column=11).value is not None:
|
||||
ws.cell(row=row_idx, column=1).value = seq
|
||||
seq += 1
|
||||
else:
|
||||
ws.cell(row=row_idx, column=1).value = None
|
||||
|
||||
# ============================================================
|
||||
# ★★★ 11. 精细更新变更清单(复制模板/清空指定列)★★★
|
||||
# ============================================================
|
||||
# 如果变更清单Sheet不存在,则复制历史模板
|
||||
# (历史模板名带日期后缀,如"37度-雇员变更清单8.10",用前缀匹配并选最近一次)
|
||||
if change_sheet_name not in wb.sheetnames:
|
||||
# 收集所有以"37度-雇员变更清单"开头、且不是当前目标名的Sheet作为候选模板
|
||||
candidates = [
|
||||
name for name in wb.sheetnames
|
||||
if name.startswith(CHANGE_SHEET_PREFIX) and name != change_sheet_name
|
||||
]
|
||||
|
||||
def _template_sort_key(name):
|
||||
# 从名称中解析"月.日"后缀,用于挑选最近一次的历史模板
|
||||
m = re.search(r"(\d{1,2})\.(\d{1,2})", name)
|
||||
return (int(m.group(1)), int(m.group(2))) if m else (-1, -1)
|
||||
|
||||
template_name = max(candidates, key=_template_sort_key) if candidates else None
|
||||
|
||||
if template_name is not None:
|
||||
# 复制最近一次的历史模板Sheet(保留公式与样式)
|
||||
source = wb[template_name]
|
||||
target = wb.copy_worksheet(source)
|
||||
target.title = change_sheet_name
|
||||
logger.info("已从模板 [%s] 复制变更清单", template_name)
|
||||
else:
|
||||
# 没有任何历史模板,创建新Sheet(兜底)
|
||||
ws_change = wb.create_sheet(change_sheet_name)
|
||||
# 创建表头
|
||||
headers = ["序号", "批改标志*", "姓名", "证件类型", "证件号", "年龄",
|
||||
"员工职业类别", "每人责任限额", "方案组别编号", "是否有工伤保险",
|
||||
"工作单位", "", "备注", "批改日期", "新增费用会馆",
|
||||
"姓名", "证件号", "工种类别", "投保方案"]
|
||||
for col_idx, h in enumerate(headers, start=1):
|
||||
ws_change.cell(row=1, column=col_idx).value = h
|
||||
ws_change.cell(row=2, column=1).value = "公式"
|
||||
# 重新获取ws_change
|
||||
ws_change = wb[change_sheet_name]
|
||||
else:
|
||||
ws_change = wb[change_sheet_name]
|
||||
|
||||
# 清空B列(第2列)、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=14).value = None # N列
|
||||
for col in range(16, 20): # P~S列
|
||||
ws_change.cell(row=row, column=col).value = None
|
||||
|
||||
# 构建初始参保映射
|
||||
initial_employee_map = {}
|
||||
for _, row in in_param_df.iterrows():
|
||||
emp_id = row.iloc[10]
|
||||
if pd.isna(emp_id):
|
||||
continue
|
||||
handle = str(row.iloc[17]).strip()
|
||||
if handle in ["无需", "档次替换"]:
|
||||
initial_employee_map[emp_id] = True
|
||||
|
||||
final_emp_ids = set(rec["证件号"] for rec in final_records)
|
||||
|
||||
# 收集变更记录
|
||||
records = []
|
||||
|
||||
# 1. 删除记录
|
||||
for emp_id in emp_ids_to_clear:
|
||||
if emp_id in final_emp_ids:
|
||||
continue
|
||||
row_match = in_param_df[in_param_df.iloc[:, 10] == emp_id]
|
||||
if not row_match.empty:
|
||||
row = row_match.iloc[0]
|
||||
name = row.iloc[9]
|
||||
category = row.iloc[11]
|
||||
scheme = row.iloc[12]
|
||||
records.append(("删除", name, emp_id, category, scheme))
|
||||
else:
|
||||
records.append(("删除", "未知", emp_id, "未知", "未知"))
|
||||
|
||||
# 2. 修改/增加记录
|
||||
for rec in final_records:
|
||||
emp_id = rec["证件号"]
|
||||
if emp_id in biz_dict:
|
||||
row_biz = biz_dict[emp_id]
|
||||
name = row_biz.get("姓名")
|
||||
category = row_biz.get("工种类别")
|
||||
scheme = row_biz.get("投保方案")
|
||||
else:
|
||||
name = None
|
||||
category = None
|
||||
scheme = None
|
||||
op = "修改" if emp_id in initial_employee_map else "增加"
|
||||
records.append((op, name, emp_id, category, scheme))
|
||||
|
||||
# 写入新记录
|
||||
current_row_change = 3
|
||||
for op, name, emp_id, category, scheme in records:
|
||||
if name is None or emp_id is None or category is None or scheme is None:
|
||||
logger.warning("跳过变更记录:%s %s 信息不完整", op, emp_id)
|
||||
continue
|
||||
ws_change.cell(row=current_row_change, column=2).value = op # B列
|
||||
ws_change.cell(row=current_row_change, column=14).value = TODAY_DATE # N列
|
||||
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列
|
||||
ws_change.cell(row=current_row_change, column=19).value = scheme # S列
|
||||
current_row_change += 1
|
||||
|
||||
# ---------- 12. 保存工作簿 ----------
|
||||
wb.save(target_file)
|
||||
|
||||
# ---------- 13. 备份新在参名单 ----------
|
||||
df_final = pd.DataFrame(final_records)
|
||||
df_final.to_excel(output_backup, index=False)
|
||||
|
||||
logger.info("手动维护-在参名单已更新(保留 %d 个原有员工,清空 %d 个旧员工行,新增 %d 条参保记录)",
|
||||
len(kept_emp_ids), len(emp_ids_to_clear), len(new_records))
|
||||
logger.info("变更清单已精细更新(共 %d 条变更记录)", len(records))
|
||||
logger.info("备份新在参名单已保存:%s", output_backup)
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 六、入口(步骤2:调度)
|
||||
# ============================================================
|
||||
def main():
|
||||
"""步骤2:调度(读取已刷新公式的目标文件,输出结果)。
|
||||
|
||||
前置:先运行 roster_filter.py(步骤1:筛选复制),并手动打开目标文件
|
||||
刷新公式计算结果(Ctrl+S 保存)后,再运行本步骤。
|
||||
"""
|
||||
logger.info("目标文件:%s", TARGET_FILE)
|
||||
|
||||
# 检查文件是否存在
|
||||
if not os.path.exists(TARGET_FILE):
|
||||
logger.error("目标表不存在:%s,请先运行 roster_filter.py 步骤生成。", TARGET_FILE)
|
||||
return
|
||||
|
||||
# 检查必需Sheet
|
||||
xl = pd.ExcelFile(TARGET_FILE)
|
||||
required_sheets = [SHEET_BIZ, SHEET_IN_PARAM]
|
||||
for s in required_sheets:
|
||||
if s not in xl.sheet_names:
|
||||
logger.error("缺少必需 Sheet:%s", s)
|
||||
return
|
||||
logger.info("文件结构检查通过。")
|
||||
|
||||
# ---------- 读取并清洗花名册数据 ----------
|
||||
biz_df = pd.read_excel(TARGET_FILE, sheet_name=SHEET_BIZ, header=3)
|
||||
logger.info("原始花名册数据:%d 行", len(biz_df))
|
||||
|
||||
# 过滤:证件号为空 或 方案处理为 "/"
|
||||
biz_df = biz_df[
|
||||
biz_df[BIZ_COL_EMPLOYEE_ID].notna() &
|
||||
(biz_df[BIZ_COL_HANDLE].astype(str).str.strip() != "/")
|
||||
]
|
||||
logger.info("清洗后花名册数据:%d 行", len(biz_df))
|
||||
|
||||
# ---------- 读取在参名单 ----------
|
||||
in_param_df = pd.read_excel(TARGET_FILE, sheet_name=SHEET_IN_PARAM, header=5)
|
||||
column_names = in_param_df.columns.tolist()
|
||||
logger.info("在参名单:%d 行", len(in_param_df))
|
||||
|
||||
# ---------- 数据校验 ----------
|
||||
if ENABLE_VALIDATION:
|
||||
logger.info("正在校验数据...")
|
||||
errors = validate_biz_data(biz_df)
|
||||
if errors:
|
||||
logger.error("发现 %d 个校验错误:", len(errors))
|
||||
for e in errors:
|
||||
logger.error(" 行%s 员工%s:%s - %s",
|
||||
e["行号"], e["员工ID"], e["错误类型"], e["详情"])
|
||||
logger.error("数据校验失败,请修正后重新运行!")
|
||||
return
|
||||
else:
|
||||
logger.info("数据校验通过!")
|
||||
else:
|
||||
logger.info("已跳过数据校验(ENABLE_VALIDATION = False)")
|
||||
|
||||
# ---------- 阶段0:初始化 ----------
|
||||
logger.info("初始化状态...")
|
||||
idle_pools, employee_map, pending_queues = initialize(in_param_df)
|
||||
logger.info(" 空闲名额池:%d 个", sum(len(v) for v in idle_pools.values()))
|
||||
logger.info(" 当前参保员工:%d 人", len(employee_map))
|
||||
|
||||
# ---------- 阶段1:处理业务 ----------
|
||||
logger.info("处理花名册业务...")
|
||||
idle_pools, employee_map, pending_queues, change_log = process_business(
|
||||
biz_df, idle_pools, employee_map, pending_queues)
|
||||
logger.info(" 待转入总人数:%d 人", sum(len(v) for v in pending_queues.values()))
|
||||
logger.info(" 变更日志条数:%d", len(change_log))
|
||||
|
||||
# ---------- 阶段2:分配名额 ----------
|
||||
logger.info("分配名额...")
|
||||
final_records, change_log, reused_source_employees = allocate_slots(
|
||||
idle_pools, employee_map, pending_queues, change_log)
|
||||
logger.info(" 最终参保记录:%d 人", len(final_records))
|
||||
logger.info(" 变更日志条数(最终):%d", len(change_log))
|
||||
|
||||
# ---------- 阶段3:输出 ----------
|
||||
logger.info("输出结果...")
|
||||
output_results(
|
||||
final_records,
|
||||
change_log,
|
||||
reused_source_employees,
|
||||
biz_df,
|
||||
in_param_df,
|
||||
column_names,
|
||||
TARGET_FILE,
|
||||
OUTPUT_IN_PARAM,
|
||||
CHANGE_SHEET_NAME,
|
||||
SHEET_IN_PARAM
|
||||
)
|
||||
|
||||
logger.info("全部完成!")
|
||||
|
||||
|
||||
# ============================================================
|
||||
# 七、程序入口
|
||||
# ============================================================
|
||||
if __name__ == "__main__":
|
||||
setup_logging()
|
||||
main()
|
||||
@@ -0,0 +1,195 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.ehr.employer_insurance.roster_filter
|
||||
@FileName: roster_filter.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-13
|
||||
@Description: 雇主险流程「步骤1:筛选复制」。从员工花名册筛选数据,复制到雇主险变更记录表
|
||||
(复刻 aa.md 的 WPS JS 宏,仅复制,不校验)
|
||||
- 源表:员工花名册.xlsx(统一格式:单 sheet、表头自动定位、业务列 B~O 14列)
|
||||
- 过滤:排除指定事业部(B列/所属单位)+「虚拟大区」(C列/一级部门)
|
||||
- 目标:三十七度-雇主险变更记录 的「花名册导出-雇主险使用基础信息」sheet,表头第4行,数据第5行起(B~O 14列)
|
||||
- 源表缺失时自动调用 roster_export 从 HR 系统导出(输出位置由本场景指定)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import sys
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
# ---- 单文件运行支持:把项目根目录加入 sys.path,保证可独立运行 ----
|
||||
def _find_project_root() -> str:
|
||||
for parent in Path(__file__).resolve().parents:
|
||||
if (parent / "app").is_dir() and (parent / "app" / "__init__.py").is_file():
|
||||
return str(parent)
|
||||
return str(Path(__file__).resolve().parents[5])
|
||||
|
||||
|
||||
_root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
import pandas as pd # noqa: E402
|
||||
from openpyxl import load_workbook # noqa: E402
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.employer_insurance.config import ( # noqa: E402
|
||||
BASE_DIR,
|
||||
TARGET_FILE,
|
||||
SHEET_BIZ,
|
||||
ROSTER_TEMPLATE_NAME,
|
||||
ROSTER_EXPORT_STATUSES,
|
||||
)
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
# ---------- 源表配置(与 aa.md 宏保持一致) ----------
|
||||
EMPLOYEE_FILE = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
EXCLUDE_DEPT = ["金色湖畔事业部", "秒创传媒事业部", "水庄大鹅事业部"]
|
||||
EXCLUDE_REGION = "虚拟大区"
|
||||
|
||||
# 源表统一格式规范(roster_export._merge_roster_files 输出):
|
||||
# 单 sheet、只保留第2行表头(丢弃第1行标题)、「类型」列统一在最后一列
|
||||
# 读取时自动定位表头行(B 列 =「所属单位」),业务列 B~O 共14列不受「类型」列影响
|
||||
SOURCE_HEADER_MARK = "所属单位" # 表头定位标记(B列)
|
||||
TARGET_HEADER_ROW = 4 # 目标表表头在第4行(数据第5行起)
|
||||
DATA_COLUMNS = 14 # B~O 共14列(所属单位..证件号)
|
||||
|
||||
|
||||
def filter_and_copy_roster(employee_file: str = None, target_file: str = None) -> int:
|
||||
"""
|
||||
从员工花名册筛选数据,复制到雇主险变更记录表(仅复制,不校验)。
|
||||
|
||||
Args:
|
||||
employee_file: 源表路径,默认 D:\\资料\\人资\\雇主险\\员工花名册.xlsx
|
||||
target_file: 目标表路径,默认今日的三十七度-雇主险变更记录文件
|
||||
|
||||
Returns:
|
||||
复制的数据行数
|
||||
|
||||
Raises:
|
||||
FileNotFoundError: 源表或目标表不存在
|
||||
ValueError: 源表列数不足 或 目标表缺少指定 Sheet
|
||||
"""
|
||||
employee_file = os.path.abspath(employee_file or EMPLOYEE_FILE)
|
||||
target_file = os.path.abspath(target_file or TARGET_FILE)
|
||||
|
||||
if not os.path.exists(employee_file):
|
||||
raise FileNotFoundError(f"源表不存在:{employee_file}")
|
||||
if not os.path.exists(target_file):
|
||||
raise FileNotFoundError(
|
||||
f"目标表不存在:{target_file},请先准备三十七度-雇主险变更记录模板文件")
|
||||
|
||||
# ---------- 1. 读取源表(统一规范:单 sheet,自动定位表头行,业务列 B~O) ----------
|
||||
# 先不设表头读取前几行,找到 B 列 =「所属单位」的表头行位置
|
||||
probe = pd.read_excel(employee_file, header=None, nrows=8)
|
||||
header_row = None
|
||||
for idx in range(len(probe)):
|
||||
if str(probe.iloc[idx, 1]).strip() == SOURCE_HEADER_MARK:
|
||||
header_row = idx
|
||||
break
|
||||
if header_row is None:
|
||||
raise ValueError(f"源表未找到表头行(B 列应为「{SOURCE_HEADER_MARK}」)")
|
||||
|
||||
df = pd.read_excel(employee_file, header=header_row)
|
||||
if df.shape[1] < DATA_COLUMNS + 1:
|
||||
raise ValueError(f"源表列数不足:{df.shape[1]}(需要 B~O 共{DATA_COLUMNS}列)")
|
||||
data = df.iloc[:, 1:DATA_COLUMNS + 1].copy() # B~O 14列(「类型」列在末尾,不受影响)
|
||||
|
||||
# 与宏一致:以 B 列(所属单位)最后非空行为数据边界
|
||||
data = data[data.iloc[:, 0].notna()]
|
||||
|
||||
# ---------- 2. 过滤:排除指定事业部 +「虚拟大区」 ----------
|
||||
dept = data.iloc[:, 0].astype(str).str.strip()
|
||||
region = data.iloc[:, 1].astype(str).str.strip()
|
||||
mask = ~(dept.isin(EXCLUDE_DEPT) | (region == EXCLUDE_REGION))
|
||||
filtered = data[mask]
|
||||
logger.info("源表共 %d 行,过滤后 %d 行(排除事业部 %s 与「%s」)",
|
||||
len(data), len(filtered), EXCLUDE_DEPT, EXCLUDE_REGION)
|
||||
if len(filtered) == 0:
|
||||
logger.warning("筛选后没有数据!")
|
||||
|
||||
# ---------- 3. 写目标表(先覆盖写入,只清空超出新数据的旧行,避免大范围逐格清空) ----------
|
||||
wb = load_workbook(target_file)
|
||||
if SHEET_BIZ not in wb.sheetnames:
|
||||
raise ValueError(f"目标表缺少 Sheet:{SHEET_BIZ}")
|
||||
ws = wb[SHEET_BIZ]
|
||||
first_data_row = TARGET_HEADER_ROW + 1 # 第5行
|
||||
|
||||
# 找 B 列当前最后非空数据行(用于清空多余旧行)
|
||||
old_last = first_data_row - 1
|
||||
for r in range(first_data_row, ws.max_row + 1):
|
||||
if ws.cell(row=r, column=2).value is not None:
|
||||
old_last = r
|
||||
|
||||
# 写入 B~O(覆盖旧数据,本地化 cell 引用减少开销)
|
||||
rows = filtered.values.tolist()
|
||||
cell = ws.cell
|
||||
for i, row in enumerate(rows, start=first_data_row):
|
||||
for j, val in enumerate(row, start=2):
|
||||
cell(row=i, column=j).value = val
|
||||
|
||||
# 清空超出新数据的旧行
|
||||
new_last = first_data_row + len(rows) - 1
|
||||
if old_last > new_last:
|
||||
for r in range(new_last + 1, old_last + 1):
|
||||
for c in range(2, 2 + DATA_COLUMNS):
|
||||
cell(row=r, column=c).value = None
|
||||
|
||||
wb.save(target_file)
|
||||
logger.info("已写入目标表 %s 第%d行起,共 %d 行", target_file, first_data_row, len(rows))
|
||||
return len(rows)
|
||||
|
||||
|
||||
def export_roster_for_employer_insurance(download_dir: str = None) -> str:
|
||||
"""按本场景模板「雇主险增减员导出模板」导出花名册(复用 roster_export,操作 HR 系统)。
|
||||
|
||||
输出位置由本场景指定:D:\\资料\\人资\\雇主险\\员工花名册.xlsx(与筛选复制的源表路径一致)。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录,默认使用 roster_export 的默认目录。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径。
|
||||
"""
|
||||
from app.service.hrbp.ehr.roster.roster_export import export_roster
|
||||
output_path = os.path.join(BASE_DIR, "员工花名册.xlsx")
|
||||
logger.info("按本场景模板 [%s] 导出花名册(在职状态:%s),输出:%s",
|
||||
ROSTER_TEMPLATE_NAME, ROSTER_EXPORT_STATUSES, output_path)
|
||||
return export_roster(download_dir=download_dir, template_name=ROSTER_TEMPLATE_NAME,
|
||||
output_path=output_path, statuses=ROSTER_EXPORT_STATUSES)
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""步骤1:就绪检查 + 导出(如需)+ 筛选复制。
|
||||
|
||||
说明:openpyxl 写入后公式列(P~W 工种类别/投保方案/方案处理)的缓存结果会丢失,
|
||||
需手动打开目标文件刷新公式计算结果并保存,确认复制无误后再运行 schedule 步骤
|
||||
(employer_insurance.py)。
|
||||
"""
|
||||
setup_logging()
|
||||
args = sys.argv[1:]
|
||||
|
||||
# 目标表是用户每日准备的表,必须已存在;若未准备则提示并终止,不下载花名册
|
||||
if not os.path.exists(TARGET_FILE):
|
||||
logger.error("目标表未准备:%s,请先准备今日的雇主险变更记录表。", TARGET_FILE)
|
||||
return
|
||||
|
||||
# 源表(员工花名册)缺失才自动导出
|
||||
if "--export-roster" in args or not os.path.exists(EMPLOYEE_FILE):
|
||||
export_roster_for_employer_insurance()
|
||||
else:
|
||||
logger.info("源表已存在:%s,跳过导出", EMPLOYEE_FILE)
|
||||
|
||||
# 筛选复制,生成输入文件
|
||||
filter_and_copy_roster()
|
||||
|
||||
logger.info("=" * 70)
|
||||
logger.info("筛选复制完成。请手动打开目标文件刷新公式计算结果(Ctrl+S 保存),")
|
||||
logger.info("确认无误后运行:python employer_insurance.py schedule")
|
||||
logger.info("=" * 70)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -10,7 +10,7 @@
|
||||
@Version: 1.0.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 .sessions/hr_cookies.json;
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可触发花名册导出(会弹出浏览器窗口,请勿关闭)。
|
||||
3. 下载目录默认取环境变量 roster_output_dir,否则使用项目根目录。
|
||||
@@ -432,6 +432,11 @@ def _wait_download(page, download_dir, timeout=DOWNLOAD_FINISH_TIMEOUT):
|
||||
def _merge_roster_files(files_with_status, output_path):
|
||||
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
|
||||
|
||||
统一输出格式(各业务场景读取端按此规范读取):
|
||||
- 只保留第2行表头,丢弃第1行标题(源表第1行为模板名标题)
|
||||
- 「类型」列统一追加在最后一列,标识在职状态(在职/离职)
|
||||
- 单 sheet,表头在第1行,数据第2行起
|
||||
|
||||
Args:
|
||||
files_with_status: [(status, file_path), ...] 列表
|
||||
output_path: 合并后文件保存路径
|
||||
@@ -443,8 +448,8 @@ def _merge_roster_files(files_with_status, output_path):
|
||||
raise RuntimeError("缺少 pandas 依赖,无法合并 Excel")
|
||||
dfs = []
|
||||
for status, path in files_with_status:
|
||||
df = pd.read_excel(path, header=1)
|
||||
df.insert(0, "类型", status)
|
||||
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
|
||||
df["类型"] = status # 类型列统一追加到最后一列
|
||||
dfs.append(df)
|
||||
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
|
||||
merged = pd.concat(dfs, ignore_index=True)
|
||||
@@ -464,15 +469,19 @@ def _merge_roster_files(files_with_status, output_path):
|
||||
# 6. 对外入口
|
||||
# ---------------------------------------------------------------
|
||||
@retry(max_attempts=3)
|
||||
def _export_one_status(page, status, download_dir):
|
||||
"""导出单个在职状态的花名册(设置筛选 -> 自定义导出 -> 下载),失败自动重试。"""
|
||||
logger.info(">>> 开始导出在职状态:%s", status)
|
||||
def _export_one_status(page, status, download_dir, template_name):
|
||||
"""导出单个在职状态的花名册(设置筛选 -> 自定义导出 -> 下载),失败自动重试。
|
||||
|
||||
Args:
|
||||
template_name: 自定义导出模板名(如「员工基础信息」「雇主险增减员导出模板」)。
|
||||
"""
|
||||
logger.info(">>> 开始导出在职状态:%s(模板:%s)", status, template_name)
|
||||
try:
|
||||
_ensure_person_status(page, status)
|
||||
if status == "离职":
|
||||
_set_leave_date_range(page)
|
||||
_open_custom_export_dialog(page)
|
||||
_select_template(page)
|
||||
_select_template(page, template_name)
|
||||
_click_confirm_export(page)
|
||||
logger.info(">>> 等待在职状态「%s」的导出文件下载", status)
|
||||
path = _wait_download(page, download_dir)
|
||||
@@ -483,11 +492,17 @@ def _export_one_status(page, status, download_dir):
|
||||
raise
|
||||
|
||||
|
||||
def export_roster(download_dir: str = None) -> str:
|
||||
"""执行员工花名册自定义导出(在职 + 离职各一次),合并为一个 Excel 文件。
|
||||
def export_roster(download_dir: str = None, template_name: str = ROSTER_TEMPLATE_NAME,
|
||||
output_path: str = None, statuses: list = None) -> str:
|
||||
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
|
||||
|
||||
Args:
|
||||
download_dir: 浏览器下载临时目录,默认使用 OUTPUT_DIR。
|
||||
template_name: 自定义导出模板名,可按业务场景动态传入(默认「员工基础信息」)。
|
||||
output_path: 合并后文件的保存路径,由调用方传入(如某业务目录下的花名册文件);
|
||||
默认使用 OUTPUT_DIR/员工花名册.xlsx。
|
||||
statuses: 需要导出的在职状态列表,默认 ["在职", "离职"];
|
||||
业务场景可按需传入(如雇主险只需在职时传 ["在职"])。
|
||||
|
||||
Returns:
|
||||
合并后的花名册文件路径。
|
||||
@@ -498,9 +513,11 @@ def export_roster(download_dir: str = None) -> str:
|
||||
if ChromiumPage is None:
|
||||
raise RuntimeError("缺少 DrissionPage 依赖,请先安装: pip install DrissionPage")
|
||||
|
||||
statuses = list(statuses) if statuses else list(PERSON_STATUSES)
|
||||
download_dir = os.path.abspath(download_dir or OUTPUT_DIR)
|
||||
os.makedirs(download_dir, exist_ok=True)
|
||||
logger.info("===== 开始花名册导出,下载目录:%s =====", download_dir)
|
||||
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s),下载目录:%s =====",
|
||||
template_name, statuses, download_dir)
|
||||
|
||||
co = ChromiumOptions()
|
||||
page = ChromiumPage(co)
|
||||
@@ -523,15 +540,15 @@ def export_roster(download_dir: str = None) -> str:
|
||||
logger.info("浏览器下载目录已设置:%s", download_dir)
|
||||
|
||||
files_with_status = []
|
||||
for status in PERSON_STATUSES:
|
||||
for status in statuses:
|
||||
logger.info("===== 开始导出在职状态:%s =====", status)
|
||||
path = _export_one_status(page, status, download_dir)
|
||||
path = _export_one_status(page, status, download_dir, template_name)
|
||||
files_with_status.append((status, path))
|
||||
time.sleep(WAIT_MID)
|
||||
|
||||
# 合并所有花名册文件
|
||||
merged_path = os.path.join(OUTPUT_DIR, MERGED_NAME)
|
||||
os.makedirs(OUTPUT_DIR, exist_ok=True)
|
||||
merged_path = os.path.abspath(output_path or os.path.join(OUTPUT_DIR, MERGED_NAME))
|
||||
os.makedirs(os.path.dirname(merged_path), exist_ok=True)
|
||||
result = _merge_roster_files(files_with_status, merged_path)
|
||||
logger.info("===== 花名册导出并合并完成:%s =====", result)
|
||||
return result
|
||||
@@ -579,7 +596,10 @@ def debug_filter_only():
|
||||
|
||||
|
||||
def main() -> None:
|
||||
"""命令行入口:python roster_export.py [下载目录]"""
|
||||
"""命令行入口:python roster_export.py [下载目录] [模板名]
|
||||
|
||||
模板名也可通过环境变量 roster_template 传入,优先级:命令行参数 > 环境变量 > 默认「员工基础信息」。
|
||||
"""
|
||||
setup_logging()
|
||||
|
||||
# 调试模式:仅执行到筛选结束
|
||||
@@ -590,8 +610,14 @@ def main() -> None:
|
||||
download_dir = os.getenv("roster_output_dir")
|
||||
if not download_dir and len(sys.argv) > 1 and sys.argv[1] != "debug":
|
||||
download_dir = sys.argv[1]
|
||||
|
||||
template_name = os.getenv("roster_template")
|
||||
if not template_name and len(sys.argv) > 2:
|
||||
template_name = sys.argv[2]
|
||||
template_name = template_name or ROSTER_TEMPLATE_NAME
|
||||
|
||||
try:
|
||||
out = export_roster(download_dir)
|
||||
out = export_roster(download_dir, template_name)
|
||||
logger.info("===== 花名册导出完成:%s =====", out)
|
||||
except Exception as e:
|
||||
logger.error("花名册导出失败:%s", e)
|
||||
|
||||
@@ -27,6 +27,7 @@ if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api import get_bank_dict, bank_type_to_name # noqa: E402
|
||||
|
||||
try:
|
||||
import pandas as pd
|
||||
@@ -166,6 +167,7 @@ COL_CARD_IDCARD = "开户人身份证"
|
||||
COL_STAFF_NAME = "员工姓名"
|
||||
COL_CARD_NAME = "开户人姓名"
|
||||
COL_BANK_ACCOUNT = "银行卡号"
|
||||
COL_BANK_NAME = "开卡银行"
|
||||
|
||||
COL_BANK_STATUS = "银行卡状态"
|
||||
COL_BANK_REASON = "银行卡说明"
|
||||
@@ -199,11 +201,10 @@ def _normalize_id(val) -> str:
|
||||
def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
"""读取工资卡汇总表,执行核对并保存结果。
|
||||
|
||||
核对逻辑(按 4 类异常分类):
|
||||
1. 开户人信息或银行卡空白
|
||||
2. 员工身份证与开户人身份证不一致(单独存『身份证不一致表』)
|
||||
3. 员工姓名与开户人姓名不一致(仅身份证一致时比对)
|
||||
4. 银行卡信息异常(银行卡非空但格式/位数错误)
|
||||
输出文件:
|
||||
- {汇总表}_核对结果.xlsx:全量核对结果
|
||||
- 无银行卡表.xlsx:未提供银行卡号(银行卡空白)的人员
|
||||
- 工资卡异常名单.xlsx:除无银行卡外的其他异常人员(含身份证不一致)
|
||||
|
||||
Args:
|
||||
input_path: 工资卡汇总表 Excel 路径
|
||||
@@ -218,7 +219,12 @@ def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
df = pd.read_excel(input_path)
|
||||
logger.info("读取工资卡汇总表:%s(%d 行)", input_path, len(df))
|
||||
|
||||
id_mismatch_rows = []
|
||||
# 汇总表未带开卡银行列时,按银行编码(BANK_TYPE)补充(aa.md 银行字典接口)
|
||||
if COL_BANK_NAME not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df[COL_BANK_NAME] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
|
||||
no_bank_rows = []
|
||||
|
||||
for idx, row in df.iterrows():
|
||||
idcard = _normalize_id(row.get(COL_IDCARD, ""))
|
||||
@@ -227,11 +233,11 @@ def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
card_name = str(row.get(COL_CARD_NAME, "")).strip()
|
||||
bank_account = row.get(COL_BANK_ACCOUNT, "")
|
||||
|
||||
issues, basis, id_inconsistent, bk = classify_card_issue(
|
||||
issues, basis, _, bk = classify_card_issue(
|
||||
idcard, card_idcard, staff_name, card_name, bank_account,
|
||||
)
|
||||
if id_inconsistent:
|
||||
id_mismatch_rows.append(idx)
|
||||
if _is_empty(bank_account):
|
||||
no_bank_rows.append(idx)
|
||||
|
||||
df.at[idx, COL_CHECK_RESULT] = "、".join(issues) if issues else "通过"
|
||||
df.at[idx, COL_CHECK_BASIS] = ";".join(basis) if basis else ""
|
||||
@@ -262,17 +268,17 @@ def check_wage_card(input_path: str, output_path: str = None) -> str:
|
||||
df.to_excel(output_path, index=False)
|
||||
logger.info("核对结果已保存:%s", output_path)
|
||||
|
||||
# 身份证不一致单独存表(独立文件,供人工校验)
|
||||
if id_mismatch_rows:
|
||||
# 无银行卡人员单独存表(独立文件)
|
||||
if no_bank_rows:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
id_path = os.path.join(os.path.dirname(base), f"身份证不一致表{ext}")
|
||||
df.loc[id_mismatch_rows].to_excel(id_path, index=False)
|
||||
logger.info("身份证不一致表已保存:%s(%d 条)", id_path, len(id_mismatch_rows))
|
||||
no_bank_path = os.path.join(os.path.dirname(base), f"无银行卡表{ext}")
|
||||
df.loc[no_bank_rows].to_excel(no_bank_path, index=False)
|
||||
logger.info("无银行卡表已保存:%s(%d 条)", no_bank_path, len(no_bank_rows))
|
||||
else:
|
||||
logger.info("无身份证不一致记录")
|
||||
logger.info("无银行卡空白记录,跳过无银行卡表生成")
|
||||
|
||||
# ---- 生成异常名单(排除已单独成表的身份证不一致记录) ----
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (~df.index.isin(id_mismatch_rows))
|
||||
# ---- 生成异常名单(含身份证不一致,排除已单独成表的无银行卡记录) ----
|
||||
mask = (df[COL_CHECK_RESULT] != "通过") & (~df.index.isin(no_bank_rows))
|
||||
abnormal = df[mask]
|
||||
if len(abnormal) > 0:
|
||||
base, ext = os.path.splitext(output_path)
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
@Version: 1.3.0
|
||||
|
||||
使用说明:
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 .sessions/hr_cookies.json;
|
||||
1. 首次运行会调用 HR 登录模块(login.py)完成登录并缓存 cookies 到 AppData\Local\37duAutomation\.sessions\hr_cookies.json;
|
||||
后续运行自动复用缓存,登录态过期会自动重新登录。
|
||||
2. 直接运行本文件即可下载在职/离职工资卡数据并生成汇总 Excel。
|
||||
"""
|
||||
@@ -39,6 +39,8 @@ from app.utils.logger import get_logger, setup_logging # noqa: E402
|
||||
from app.service.hrbp.ehr.common.hr_api import ( # noqa: E402
|
||||
fetch_wage_card_page,
|
||||
fetch_all_wage_card,
|
||||
get_bank_dict,
|
||||
bank_type_to_name,
|
||||
HRSessionExpiredError,
|
||||
)
|
||||
from app.service.hrbp.ehr.common.session_manager import ( # noqa: E402
|
||||
@@ -93,7 +95,7 @@ COL_MAP: Dict[str, str] = {
|
||||
SHOW_ORDER = [
|
||||
"人员类型", "员工姓名", "员工ID", "身份证号", "入职日期", "离职日期",
|
||||
"所属事业部", "小组部门", "组织全路径", "是否主卡",
|
||||
"银行编码", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
"银行编码", "开卡银行", "银行卡号", "开户人姓名", "参保地点", "操作人", "操作时间",
|
||||
]
|
||||
|
||||
|
||||
@@ -149,6 +151,10 @@ def export_excel(data_on_job: List[dict], data_leave: List[dict], save_dir: str
|
||||
df = pd.DataFrame(total_all)
|
||||
# 替换英文列为中文
|
||||
df.rename(columns=COL_MAP, inplace=True)
|
||||
# 补充开卡银行:按银行编码(BANK_TYPE)匹配字典 code
|
||||
if "开卡银行" not in df.columns and "银行编码" in df.columns:
|
||||
_, bank_map = get_bank_dict()
|
||||
df["开卡银行"] = df["银行编码"].apply(lambda c: bank_type_to_name(c, bank_map))
|
||||
# 过滤表中实际存在的列,再拼接剩余其他字段
|
||||
exist_cols = [col for col in SHOW_ORDER if col in df.columns]
|
||||
other_cols = [col for col in df.columns if col not in exist_cols]
|
||||
|
||||
@@ -9,6 +9,8 @@
|
||||
@Version: 1.2.0
|
||||
"""
|
||||
|
||||
import os
|
||||
import time
|
||||
from typing import Any, Callable, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
@@ -35,6 +37,85 @@ from app.service.hrbp.oa.common.notify import push_report, build_push_summary
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ==================== 真实审批提交(默认关闭) ====================
|
||||
# 审批按钮:通过->同意(#chooseSubmit),驳回->退回申请人(#backApplySubmit)
|
||||
_APPROVE_BUTTONS = {
|
||||
"通过": ("#chooseSubmit", "同意"),
|
||||
"驳回": ("#backApplySubmit", "退回申请人"),
|
||||
}
|
||||
|
||||
|
||||
def _approve_enabled() -> bool:
|
||||
"""是否启用真实审批提交(同意/退回申请人)。默认关闭。
|
||||
开关:.env 中 overtime_approve_enabled=true/false。
|
||||
未确认校验准确性前保持关闭,确认后再启用。"""
|
||||
try:
|
||||
from dotenv import load_dotenv
|
||||
except ImportError:
|
||||
load_dotenv = lambda *args, **kwargs: None
|
||||
load_dotenv()
|
||||
return os.getenv("overtime_approve_enabled", "false").lower() == "true"
|
||||
|
||||
|
||||
def _find_button(browser, selector: str, timeout: float = 3.0):
|
||||
"""在详情页查找审批按钮:优先主文档,找不到则遍历 iframe(部分详情页按钮在 iframe 内)。"""
|
||||
try:
|
||||
btn = browser.ele(selector, timeout=timeout)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
pass
|
||||
try:
|
||||
frames = browser.get_frames()
|
||||
except Exception:
|
||||
frames = []
|
||||
for frame in frames:
|
||||
try:
|
||||
btn = frame.ele(selector, timeout=1)
|
||||
if btn:
|
||||
return btn
|
||||
except Exception:
|
||||
continue
|
||||
return None
|
||||
|
||||
|
||||
def submit_approval(browser, decision: str) -> Dict[str, str]:
|
||||
"""
|
||||
按校验结论在流程详情页执行真实审批提交。
|
||||
|
||||
Args:
|
||||
browser: 停留在详情页的 ChromiumPage
|
||||
decision: 校验决策(通过/驳回;其余决策不提交)
|
||||
|
||||
Returns:
|
||||
{"action": "同意"/"退回申请人"/"-", "ok": "true"/"false", "message": ...}
|
||||
"""
|
||||
if decision not in _APPROVE_BUTTONS:
|
||||
return {"action": "-", "ok": "true", "message": "无需提交"}
|
||||
selector, label = _APPROVE_BUTTONS[decision]
|
||||
try:
|
||||
btn = _find_button(browser, selector)
|
||||
if btn is None:
|
||||
msg = f"未找到审批按钮 {selector}({label}),可能页面未加载完成或按钮在未识别的 iframe 中"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
logger.info("点击审批按钮: %s(%s)", selector, label)
|
||||
btn.click()
|
||||
# 点击弹出的确认框"确定"按钮(同意/驳回共用同一确认框,仅标题不同)
|
||||
confirm = _find_button(browser, "#custom-confirm-modal-ok", timeout=3)
|
||||
if confirm is None:
|
||||
msg = "未找到确认框确定按钮 #custom-confirm-modal-ok,审批未提交"
|
||||
logger.error(msg)
|
||||
return {"action": label, "ok": "false", "message": msg}
|
||||
confirm.click()
|
||||
logger.info("已点击确认框确定按钮")
|
||||
time.sleep(1.0)
|
||||
return {"action": label, "ok": "true", "message": f"已执行审批提交[{label}]"}
|
||||
except Exception as e:
|
||||
logger.error("审批提交失败[%s]: %s", label, str(e))
|
||||
return {"action": label, "ok": "false", "message": f"审批提交[{label}]失败: {e}"}
|
||||
|
||||
|
||||
@retry(max_attempts=3)
|
||||
def _login():
|
||||
"""完整登录 OA(失败自动重试,最多 3 次)"""
|
||||
@@ -137,6 +218,12 @@ def run_flow(
|
||||
try:
|
||||
doc_detail = _fetch_doc_detail(browser, session, doc)
|
||||
result = validate_doc(doc_detail, session)
|
||||
# 真实审批提交:仅当 overtime_approve_enabled=true 时执行(默认关闭)
|
||||
if _approve_enabled():
|
||||
submit = submit_approval(browser, result.get("decision"))
|
||||
result["审批动作"] = submit["action"]
|
||||
result["审批结果"] = f"{'成功' if submit['ok'] == 'true' else '失败'},{submit['message']}"
|
||||
logger.info("审批提交: %s %s", submit["action"], result["审批结果"])
|
||||
results.append(result)
|
||||
logger.info(
|
||||
"已校验: %s - %s -> %s",
|
||||
|
||||
@@ -59,6 +59,12 @@ ZHINENG_HALF_MORNING_HOURS = 3.5
|
||||
ZHINENG_HALF_AFTERNOON_HOURS = 4.5
|
||||
# 职能排班上午/下午分界:申请加班开始时间早于该时刻(12点)视为上午半天
|
||||
ZHINENG_HALF_CUTOFF_HOUR = 12
|
||||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)视为提前到岗型,
|
||||
# 常规"晚于规定下班时间18:00""当日有下班打卡"校验不适用,改以到岗打卡为区间合规证据。
|
||||
# 提前到岗型员工只会提前到、不会晚到:打卡须不晚于加班开始时间(晚到则无法证明开始时刻已到岗)。
|
||||
# 到岗打卡证据窗口:加班开始时间前1小时内(含开始时刻)的打卡视为到岗
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS = 1
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES = 0
|
||||
|
||||
# ---------- 分页 ----------
|
||||
DEFAULT_PAGE_SIZE = 15
|
||||
|
||||
@@ -11,6 +11,7 @@
|
||||
import json
|
||||
import os
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -21,9 +22,9 @@ except ImportError:
|
||||
ChromiumPage = None
|
||||
SessionPage = None
|
||||
|
||||
# 登录 cookies 持久化目录:服务层统一管理各平台会话文件,文件名按平台区分
|
||||
# 登录 cookies 持久化目录:统一放在 AppData\Local\37duAutomation,文件名按平台区分
|
||||
# 如 oa_cookies.json / xxx_cookies.json,便于后续扩展其他平台
|
||||
_SESSIONS_DIR = os.path.join(os.path.dirname(os.path.abspath(__file__)), '..', '..', '..', '.sessions')
|
||||
_SESSIONS_DIR = get_sessions_dir()
|
||||
COOKIE_FILE = os.path.join(_SESSIONS_DIR, 'oa_cookies.json')
|
||||
|
||||
|
||||
|
||||
@@ -28,6 +28,7 @@ _root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
from app.service.hrbp.oa.common.config import BASE_URL
|
||||
@@ -110,10 +111,8 @@ FILTER_IDX_SUSPEND = "3"
|
||||
|
||||
# ---------- HR 参保记录核对(si_main 接口,对应 aa.md) ----------
|
||||
SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||||
# HR cookies 持久化文件(ehr/common/login.py 保存)
|
||||
HR_COOKIE_FILE = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), '..', '..', '..', '.sessions', 'hr_cookies.json')
|
||||
)
|
||||
# HR cookies 持久化文件(ehr/common/login.py 保存,统一放在 AppData\Local\37duAutomation)
|
||||
HR_COOKIE_FILE = os.path.join(get_sessions_dir(), 'hr_cookies.json')
|
||||
SI_BASE_PARAMS = {
|
||||
"start": "0", "pageNo": "1", "pageSize": "15",
|
||||
"USER_ID": "07b83185-6243-42bc-b79f-b81b4cffb471",
|
||||
|
||||
@@ -30,6 +30,7 @@ _root = _find_project_root()
|
||||
if _root not in sys.path:
|
||||
sys.path.insert(0, _root)
|
||||
|
||||
from app.common.app_paths import get_sessions_dir
|
||||
from app.utils.logger import get_logger, setup_logging
|
||||
from app.utils.intelligent_retry import retry
|
||||
|
||||
@@ -56,10 +57,8 @@ logger = get_logger(__name__)
|
||||
# HR 参保记录查询接口(aa.md 提供的 si_main 接口)
|
||||
SI_QUERY_URL = "https://hr.37du.co/RedseaPlatform/getPageAjax/si_main_SelectByTreeCode/CoreRequest.mc"
|
||||
|
||||
# HR cookies 持久化文件(login.py 保存)
|
||||
HR_COOKIE_FILE = os.path.abspath(
|
||||
os.path.join(os.path.dirname(__file__), '..', '..', '..', '.sessions', 'hr_cookies.json')
|
||||
)
|
||||
# HR cookies 持久化文件(login.py 保存,统一放在 AppData\Local\37duAutomation)
|
||||
HR_COOKIE_FILE = os.path.join(get_sessions_dir(), 'hr_cookies.json')
|
||||
|
||||
# 接口基础参数(aa.md 基础参数模板,base_codes 动态替换)
|
||||
SI_BASE_PARAMS = {
|
||||
|
||||
@@ -48,6 +48,8 @@ def _format_detail(info: Dict[str, Any]) -> str:
|
||||
("当日最早打卡", "最早打卡"),
|
||||
("当日最晚打卡", "最晚打卡"),
|
||||
("次日最早打卡", "次日最早打卡"),
|
||||
("前一天最晚打卡", "前一天最晚打卡"),
|
||||
("到岗打卡", "到岗打卡"),
|
||||
("计算加班时长(小时)", "计算时长"),
|
||||
("弹性扣减(小时)", "弹性扣减"),
|
||||
("有效加班时长(小时)", "有效时长"),
|
||||
@@ -105,6 +107,8 @@ def generate_report(results: List[Dict[str, Any]]) -> str:
|
||||
lines.append(f" {detail}")
|
||||
if note:
|
||||
lines.append(f" 备注: {note}")
|
||||
if r.get("审批动作"):
|
||||
lines.append(f" 审批动作: {r['审批动作']}({r.get('审批结果', '')})")
|
||||
lines.append("")
|
||||
|
||||
# ----- 驳回清单 -----
|
||||
|
||||
@@ -35,6 +35,8 @@ from app.service.hrbp.oa.common.config import (
|
||||
ZHINENG_HALF_MORNING_HOURS,
|
||||
ZHINENG_HALF_AFTERNOON_HOURS,
|
||||
ZHINENG_HALF_CUTOFF_HOUR,
|
||||
OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
|
||||
OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES,
|
||||
)
|
||||
|
||||
|
||||
@@ -86,6 +88,19 @@ def _next_day(date_str: str) -> str:
|
||||
return (d + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
|
||||
def _is_within_arrival_window(
|
||||
punch_str: Any,
|
||||
start_dt: datetime,
|
||||
before_hours: float = OT_PRE_SHIFT_ARRIVE_BEFORE_HOURS,
|
||||
after_minutes: int = OT_PRE_SHIFT_ARRIVE_AFTER_MINUTES,
|
||||
) -> bool:
|
||||
"""提前到岗型加班:判断打卡时间是否落在加班开始时间附近的到岗证据窗口内。"""
|
||||
p = _parse_dt(punch_str)
|
||||
if p is None:
|
||||
return False
|
||||
return (start_dt - timedelta(hours=before_hours)) <= p <= (start_dt + timedelta(minutes=after_minutes))
|
||||
|
||||
|
||||
def _is_spring_festival(date_str: str) -> bool:
|
||||
"""
|
||||
判断日期是否为春节法定节假日(初一至初三)。
|
||||
@@ -155,32 +170,36 @@ def _check_punch_records(session: Any, staff_id: str, ot_date: str) -> Dict[str,
|
||||
|
||||
加班常跨天(如 18:00 至次日 00:00),下班打卡可能落在次日,因此查询
|
||||
范围扩展到 ot_date 次日;次日最早打卡用于延时加班的弹性到岗兑换判定。
|
||||
另扩展到前一天:提前到岗型延时加班(开始<=6点)的到岗打卡可能被系统归到前一天。
|
||||
"""
|
||||
if not ot_date or not staff_id:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"打卡备注": "缺少加班日期或员工ID"}
|
||||
"前一天最晚打卡": None, "打卡备注": "缺少加班日期或员工ID"}
|
||||
|
||||
start = datetime.strptime(ot_date, "%Y-%m-%d")
|
||||
prev_day = (start - timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
next_day = (start + timedelta(days=1)).strftime("%Y-%m-%d")
|
||||
|
||||
try:
|
||||
records = get_attendance_records(session, staff_id, ot_date, next_day)
|
||||
records = get_attendance_records(session, staff_id, prev_day, next_day)
|
||||
summary = summarize_attendance_records(records)
|
||||
prev_summary = next((r for r in summary if r["attend_date"] == prev_day), None)
|
||||
day_summary = next((r for r in summary if r["attend_date"] == ot_date), None)
|
||||
next_summary = next((r for r in summary if r["attend_date"] == next_day), None)
|
||||
if not day_summary and not next_summary:
|
||||
if not day_summary and not next_summary and not prev_summary:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"打卡备注": "当天及次日无打卡记录"}
|
||||
"前一天最晚打卡": None, "打卡备注": "当天及次日无打卡记录"}
|
||||
return {
|
||||
"当日最早打卡": day_summary["first_check_in"] if day_summary else None,
|
||||
"当日最晚打卡": day_summary["last_check_out"] if day_summary else None,
|
||||
"次日最早打卡": next_summary["first_check_in"] if next_summary else None,
|
||||
"前一天最晚打卡": prev_summary["last_check_out"] if prev_summary else None,
|
||||
"打卡备注": "",
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning("获取打卡明细失败: %s", str(e))
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"打卡备注": f"获取失败: {e}"}
|
||||
"前一天最晚打卡": None, "打卡备注": f"获取失败: {e}"}
|
||||
|
||||
|
||||
def _check_leave_covers_morning(session: Any, staff_id: str, date_str: str) -> bool:
|
||||
@@ -250,17 +269,38 @@ def _validate_delayed(
|
||||
if hours < OT_MIN_HOURS:
|
||||
reasons.append(f"加班时长为{hours:g}小时,不足{OT_MIN_HOURS}小时")
|
||||
|
||||
# 3. 区间合规校验:开始 >= 规定下班时间,结束 <= 实际下班打卡时间
|
||||
# 3. 区间合规校验
|
||||
work_start = datetime.strptime(f"{ot_date} {WORK_START_TIME}", "%Y-%m-%d %H:%M")
|
||||
work_end = datetime.strptime(f"{ot_date} {WORK_END_TIME}", "%Y-%m-%d %H:%M")
|
||||
if start is not None and start < work_end:
|
||||
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({WORK_END_TIME})")
|
||||
if end is not None:
|
||||
if actual_checkout is None:
|
||||
reasons.append("当日无下班打卡记录,无法校验区间合规")
|
||||
elif end > actual_checkout:
|
||||
reasons.append(
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S})"
|
||||
)
|
||||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)。
|
||||
# 常规"晚于18:00""当日有下班打卡"校验不适用,改以加班开始时间附近的到岗打卡作为证据:
|
||||
# - 开始<=6点时,到岗打卡可能被系统归到前一天(跨天打卡),需回看前一天记录;
|
||||
# - 6点~9点开始的,到岗打卡归属当天,只看当天记录。
|
||||
# 提前到岗型只会早到、不会晚到,打卡须不晚于加班开始时间。
|
||||
is_pre_shift = start is not None and start < work_start
|
||||
if is_pre_shift:
|
||||
candidates = [punch.get("当日最早打卡")]
|
||||
cross_cutoff = start.replace(hour=CROSS_DAY_BEFORE_HOUR, minute=0, second=0, microsecond=0)
|
||||
if start <= cross_cutoff:
|
||||
candidates.append(punch.get("前一天最晚打卡"))
|
||||
arrival_punch = next(
|
||||
(c for c in candidates if _is_within_arrival_window(c, start)),
|
||||
None,
|
||||
)
|
||||
if arrival_punch is None:
|
||||
reasons.append(f"提前到岗型加班,未找到加班开始时间({start:%H:%M})附近的到岗打卡")
|
||||
else:
|
||||
info["到岗打卡"] = arrival_punch
|
||||
else:
|
||||
if start is not None and start < work_end:
|
||||
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({WORK_END_TIME})")
|
||||
if end is not None:
|
||||
if actual_checkout is None:
|
||||
reasons.append("当日无下班打卡记录,无法校验区间合规")
|
||||
elif end > actual_checkout:
|
||||
reasons.append(
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S})"
|
||||
)
|
||||
|
||||
info["计算加班时长(小时)"] = hours
|
||||
if reasons:
|
||||
|
||||