rescue: 断电事故后工作区全量备份
This commit is contained in:
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
File diff suppressed because it is too large
Load Diff
@@ -1,38 +1,38 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""临时验证:技师岗/黄泥磅 是否在考勤方案列表中存在。验证后删除。"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import (
|
||||
HR_BASE_URL, build_hr_session, hr_request_json, fetch_cur_user_info, _clean,
|
||||
)
|
||||
|
||||
TEAM_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_team_ajax_list/redApiExec.mc"
|
||||
BASE = {
|
||||
"struTreeCode": "cq37du",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rule_name": "", "dk_num_type": "", "type": "", "containLower": "",
|
||||
"team_name": "", "work_date_name": "", "paiban_type": "",
|
||||
"IN_USE": "1", "start": "0", "sortType": "desc",
|
||||
"sortName": "t.operate_time", "pageNo": "1", "pageSize": "50",
|
||||
}
|
||||
|
||||
|
||||
def probe(label, **overrides):
|
||||
params = dict(BASE)
|
||||
params.update(overrides)
|
||||
d = hr_request_json(session, "POST", TEAM_LIST_URL, params, "考勤方案列表")
|
||||
data = d.get("data") or {}
|
||||
lst = data.get("list") or []
|
||||
print(f"--- {label}: total={data.get('total')}")
|
||||
for x in lst:
|
||||
print(" ", _clean(x.get("teamName")))
|
||||
|
||||
|
||||
session = build_hr_session()
|
||||
fetch_cur_user_info(session)
|
||||
|
||||
probe("team_name=技师岗", team_name="技师岗")
|
||||
probe("team_name=黄泥磅", team_name="黄泥磅")
|
||||
probe("team_name=技师", team_name="技师")
|
||||
# -*- coding: utf-8 -*-
|
||||
"""临时验证:技师岗/黄泥磅 是否在考勤方案列表中存在。验证后删除。"""
|
||||
import os
|
||||
import sys
|
||||
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import (
|
||||
HR_BASE_URL, build_hr_session, hr_request_json, fetch_cur_user_info, _clean,
|
||||
)
|
||||
|
||||
TEAM_LIST_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_p_kq_team_ajax_list/redApiExec.mc"
|
||||
BASE = {
|
||||
"struTreeCode": "cq37du",
|
||||
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
|
||||
"rule_name": "", "dk_num_type": "", "type": "", "containLower": "",
|
||||
"team_name": "", "work_date_name": "", "paiban_type": "",
|
||||
"IN_USE": "1", "start": "0", "sortType": "desc",
|
||||
"sortName": "t.operate_time", "pageNo": "1", "pageSize": "50",
|
||||
}
|
||||
|
||||
|
||||
def probe(label, **overrides):
|
||||
params = dict(BASE)
|
||||
params.update(overrides)
|
||||
d = hr_request_json(session, "POST", TEAM_LIST_URL, params, "考勤方案列表")
|
||||
data = d.get("data") or {}
|
||||
lst = data.get("list") or []
|
||||
print(f"--- {label}: total={data.get('total')}")
|
||||
for x in lst:
|
||||
print(" ", _clean(x.get("teamName")))
|
||||
|
||||
|
||||
session = build_hr_session()
|
||||
fetch_cur_user_info(session)
|
||||
|
||||
probe("team_name=技师岗", team_name="技师岗")
|
||||
probe("team_name=黄泥磅", team_name="黄泥磅")
|
||||
probe("team_name=技师", team_name="技师")
|
||||
|
||||
@@ -1,288 +1,288 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: working_days_shift_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 检查1「在职天数是否均排班验证」(影刀单文件,自包含)。
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。
|
||||
|
||||
数据来源(预处理封存表,由 seal_data_export.py 导出并预处理):
|
||||
- 先运行 seal_data_export.py:拉取当月全集团考勤封存数据(接口
|
||||
POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc,
|
||||
sqlId = kq_count_leave_wage_SelectV2),并做预处理:所属单位仅保留白名单单位
|
||||
(财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx。
|
||||
- 本模块只读取该预处理封存表,不再直连接口。
|
||||
- 每员工一条封存记录,检查1用到的字段(aa.md 列定义):
|
||||
base_code 工号 / staff_name 姓名
|
||||
join_date 入职日期 / leaveOffice_date 离职时间(算在职天数)
|
||||
kq_stat_month_yq_work_day_in 在职应勤工作日
|
||||
kq_stat_cal_ext9 休息天(考勤日报休息日天数总和)
|
||||
BELONG_UNIT_ORG_NAME 所属单位 / DEPT_ORG_ONE~FIVE 一级~五级部门
|
||||
|
||||
判断口径(对应需求文档 XQ0011 检查1):
|
||||
- 在职天数:由封存「入职/离职时间」计算员工当月应在职的自然天数;
|
||||
- 在职应勤工作日 + 休息天:直接取封存字段 kq_stat_month_yq_work_day_in / kq_stat_cal_ext9;
|
||||
- 差值 = 在职天数 - (应勤工作日 + 休息天);差值非 0 视为异常,异常类型 = 「当月在职天数有差缺排班」。
|
||||
样例:37035483 8-3 离职,在职天数 3;应勤 3、休息 0 → 差值 0 正常。
|
||||
|
||||
在职天数口径(统一采用「月初1日~末日」与「入职日起~离职日止」闭区间交集的自然天数,含首尾)
|
||||
- 全月在职:月初1日即已在职且当月末在职 → 在职天数 = 当月自然天数;
|
||||
- 月初1日在职、当月内离职:在职天数 = 离职日 - 1号 + 1 → 覆盖需求「离职时间 - 1号」;
|
||||
- 月初1日尚未入职、月末在职:在职天数 = 末日 - 入职日 + 1 → 覆盖需求「末日 - 入职时间」;
|
||||
- 当月在册(月初未入职且月内离职):在职天数 = 离职日 - 入职日 + 1 → 覆盖需求「离职 - 入职」;
|
||||
- 月初1日与末日均在职但有入离职异动:在职天数 = 自然天数 - 异动缺勤段。
|
||||
(注:口径与封存样例一致,均含入职/离职当天。若贵司某类口径不含离职/入职当天,请调 _working_days。)
|
||||
|
||||
输出:
|
||||
在职天数排班异常_{月份}_{时间戳}.xlsx 异常名单(含在职天数/应勤/休息/差值便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json,仅供导出模块使用)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_wd_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import enrich_dept_fields, load_seal_rows # noqa: E402
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_wd_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 异常类型(对应需求文档检查1)
|
||||
ABNORMAL_TYPE = "当月在职天数有差缺排班"
|
||||
|
||||
# 封存记录的字段→角色映射(字段名以 aa.md 接口列定义为准)
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_NAME_FIELD = "staff_name"
|
||||
SEAL_JOIN_FIELD = "join_date" # aa.md:入职日期
|
||||
SEAL_LEAVE_FIELD = "leaveOffice_date" # aa.md:离职时间
|
||||
SEAL_WORK_FIELD = "kq_stat_month_yq_work_day_in" # aa.md:_在职应勤工作日
|
||||
SEAL_REST_FIELD = "kq_stat_cal_ext9" # aa.md:休息天(考勤日报休息日天数总和)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_DEPT_FIELDS = ["DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE"] # 一~五级部门
|
||||
|
||||
# 输出列(对应需求文档检查1输出字段)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"在职天数", "应勤工作日", "休息天", "差值",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
return s
|
||||
|
||||
|
||||
def _text(v) -> str:
|
||||
t = _clean(v)
|
||||
if t.endswith(".0"):
|
||||
t = t[:-2]
|
||||
return t
|
||||
|
||||
|
||||
def _num(v) -> float:
|
||||
try:
|
||||
return float(_clean(v))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return None
|
||||
s = s[:10]
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _month_range(ym: str) -> Tuple[date, date]:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
total_days = pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||||
return date(y, m, 1), date(y, m, total_days)
|
||||
|
||||
|
||||
def _working_days(first: date, last: date, join: Optional[date], leave: Optional[date]) -> int:
|
||||
"""计算员工当月在职自然天数(月区间 ∩ 在职区间闭区间,含首尾)。"""
|
||||
lo = first if not join else (join if join >= first else first)
|
||||
hi = last if not leave else (leave if leave <= last else last)
|
||||
if lo > hi:
|
||||
return 0
|
||||
return (hi - lo).days + 1
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _build_seal_map(rows: List[dict]) -> Dict[str, dict]:
|
||||
"""按工号建立 封存记录索引(一员工一条)。"""
|
||||
mapping: Dict[str, dict] = {}
|
||||
for rec in rows:
|
||||
code = ""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _text(rec.get(f))
|
||||
if code:
|
||||
break
|
||||
if code:
|
||||
mapping.setdefault(code, rec)
|
||||
return mapping
|
||||
|
||||
|
||||
def run_working_days_shift_check(month: str = None) -> List[dict]:
|
||||
"""执行检查1「在职天数是否均排班验证」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
first, last = _month_range(month)
|
||||
except (ValueError, IndexError, TypeError):
|
||||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
first, last = _month_range(f"{py:04d}-{pm:02d}")
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
logger.info("===== 检查1「在职天数是否均排班验证」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
seal_map = _build_seal_map(seal_rows)
|
||||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
|
||||
|
||||
# 2. 逐人检查
|
||||
abnormal: List[dict] = []
|
||||
for code, rec in seal_map.items():
|
||||
join = _parse_date(rec.get(SEAL_JOIN_FIELD))
|
||||
leave = _parse_date(rec.get(SEAL_LEAVE_FIELD))
|
||||
wd = _working_days(first, last, join, leave)
|
||||
if wd <= 0:
|
||||
continue # 当月无在职日,跳过
|
||||
work = _num(rec.get(SEAL_WORK_FIELD))
|
||||
rest = _num(rec.get(SEAL_REST_FIELD))
|
||||
diff = wd - (work + rest)
|
||||
if diff != 0:
|
||||
abnormal.append(enrich_dept_fields({
|
||||
"37工号": code,
|
||||
"姓名": _text(rec.get(SEAL_NAME_FIELD)),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"在职天数": wd,
|
||||
"应勤工作日": int(work),
|
||||
"休息天": int(rest),
|
||||
"差值": diff,
|
||||
}, code, rec))
|
||||
logger.info("检查1命中异常 %d 人(在职天数≠应勤+休息)", len(abnormal))
|
||||
|
||||
# 3. 导出异常名单
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"在职天数排班异常_{ym}_{ts}.xlsx")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_wd_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = run_working_days_shift_check(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查1 在职天数是否均排班验证完成】")
|
||||
logger.info(" 检查月份:%s | 异常人数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
logger.error("检查1执行失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@FileName: working_days_shift_check.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-31
|
||||
@UpdateTime: 2026-09-07
|
||||
@Description: 考勤月报封存检查 - 检查1「在职天数是否均排班验证」(影刀单文件,自包含)。
|
||||
当月考勤封存完毕后执行,检查范围为「上月完整月份」。
|
||||
|
||||
数据来源(预处理封存表,由 seal_data_export.py 导出并预处理):
|
||||
- 先运行 seal_data_export.py:拉取当月全集团考勤封存数据(接口
|
||||
POST https://hr.37du.co/RedseaPlatform/kqController/getPageAjaxList.mc,
|
||||
sqlId = kq_count_leave_wage_SelectV2),并做预处理:所属单位仅保留白名单单位
|
||||
(财务管理部/集团管理中心/集团营建中心/金色印象事业部/金色湖畔事业部),
|
||||
保存为固定路径 考勤封存数据_{月份}.xlsx。
|
||||
- 本模块只读取该预处理封存表,不再直连接口。
|
||||
- 每员工一条封存记录,检查1用到的字段(aa.md 列定义):
|
||||
base_code 工号 / staff_name 姓名
|
||||
join_date 入职日期 / leaveOffice_date 离职时间(算在职天数)
|
||||
kq_stat_month_yq_work_day_in 在职应勤工作日
|
||||
kq_stat_cal_ext9 休息天(考勤日报休息日天数总和)
|
||||
BELONG_UNIT_ORG_NAME 所属单位 / DEPT_ORG_ONE~FIVE 一级~五级部门
|
||||
|
||||
判断口径(对应需求文档 XQ0011 检查1):
|
||||
- 在职天数:由封存「入职/离职时间」计算员工当月应在职的自然天数;
|
||||
- 在职应勤工作日 + 休息天:直接取封存字段 kq_stat_month_yq_work_day_in / kq_stat_cal_ext9;
|
||||
- 差值 = 在职天数 - (应勤工作日 + 休息天);差值非 0 视为异常,异常类型 = 「当月在职天数有差缺排班」。
|
||||
样例:37035483 8-3 离职,在职天数 3;应勤 3、休息 0 → 差值 0 正常。
|
||||
|
||||
在职天数口径(统一采用「月初1日~末日」与「入职日起~离职日止」闭区间交集的自然天数,含首尾)
|
||||
- 全月在职:月初1日即已在职且当月末在职 → 在职天数 = 当月自然天数;
|
||||
- 月初1日在职、当月内离职:在职天数 = 离职日 - 1号 + 1 → 覆盖需求「离职时间 - 1号」;
|
||||
- 月初1日尚未入职、月末在职:在职天数 = 末日 - 入职日 + 1 → 覆盖需求「末日 - 入职时间」;
|
||||
- 当月在册(月初未入职且月内离职):在职天数 = 离职日 - 入职日 + 1 → 覆盖需求「离职 - 入职」;
|
||||
- 月初1日与末日均在职但有入离职异动:在职天数 = 自然天数 - 异动缺勤段。
|
||||
(注:口径与封存样例一致,均含入职/离职当天。若贵司某类口径不含离职/入职当天,请调 _working_days。)
|
||||
|
||||
输出:
|
||||
在职天数排班异常_{月份}_{时间戳}.xlsx 异常名单(含在职天数/应勤/休息/差值便于排查)。
|
||||
|
||||
依赖安装(启动校验:必须预先装齐):
|
||||
pip install requests pandas openpyxl python-dotenv
|
||||
|
||||
运行前置:
|
||||
1. 需先运行「seal_data_export.py」导出并预处理当月封存数据;
|
||||
2. 需存在「37duHR登录」写入的共享登录态(hr_cookies.json,仅供导出模块使用)。
|
||||
|
||||
环境变量(可选):
|
||||
monthly_wd_save_dir 输出目录(默认 D:\\资料\\人资\\考勤异常)
|
||||
@Version: 1.1.0
|
||||
"""
|
||||
|
||||
# ==================== 标准库导入 ====================
|
||||
import os
|
||||
import sys
|
||||
import traceback
|
||||
from datetime import date, datetime
|
||||
from typing import Dict, List, Optional, Tuple
|
||||
|
||||
# 同目录模块引入(seal_data_export.py:封存数据导出与预处理,本模块只读取预处理封存表)
|
||||
sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))
|
||||
from seal_data_export import enrich_dept_fields, load_seal_rows # noqa: E402
|
||||
|
||||
# ==================== 第三方库(启动校验:全部装齐,不懒加载) ====================
|
||||
try:
|
||||
import pandas as pd
|
||||
except ImportError as _import_err:
|
||||
raise RuntimeError(
|
||||
"缺少必需依赖,无法启动(影刀版要求所有库在启动前装齐)。\n"
|
||||
"请先执行安装:\n pip install requests pandas openpyxl python-dotenv\n"
|
||||
f"缺失依赖详情: {_import_err}"
|
||||
)
|
||||
|
||||
|
||||
# ==================== 日志(print 替代 logging,保持单文件无外部依赖) ====================
|
||||
class _PrintLogger:
|
||||
def debug(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def info(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def warning(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def error(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
|
||||
def exception(self, msg, *args, **kwargs):
|
||||
print(msg % args if args else msg)
|
||||
traceback.print_exc()
|
||||
|
||||
|
||||
logger = _PrintLogger()
|
||||
|
||||
|
||||
# ==================== 共享路径 & 常量配置 ====================
|
||||
SAVE_DIR = os.getenv("monthly_wd_save_dir") or r"D:\资料\人资\考勤月报封存检查"
|
||||
|
||||
# 异常类型(对应需求文档检查1)
|
||||
ABNORMAL_TYPE = "当月在职天数有差缺排班"
|
||||
|
||||
# 封存记录的字段→角色映射(字段名以 aa.md 接口列定义为准)
|
||||
SEAL_CODE_FIELDS = ("base_code", "seal_base_code")
|
||||
SEAL_NAME_FIELD = "staff_name"
|
||||
SEAL_JOIN_FIELD = "join_date" # aa.md:入职日期
|
||||
SEAL_LEAVE_FIELD = "leaveOffice_date" # aa.md:离职时间
|
||||
SEAL_WORK_FIELD = "kq_stat_month_yq_work_day_in" # aa.md:_在职应勤工作日
|
||||
SEAL_REST_FIELD = "kq_stat_cal_ext9" # aa.md:休息天(考勤日报休息日天数总和)
|
||||
SEAL_UNIT_FIELD = "BELONG_UNIT_ORG_NAME" # aa.md:所属单位
|
||||
SEAL_DEPT_FIELDS = ["DEPT_ORG_ONE", "DEPT_ORG_TWO", "DEPT_ORG_THREE",
|
||||
"DEPT_ORG_FOUR", "DEPT_ORG_FIVE"] # 一~五级部门
|
||||
|
||||
# 输出列(对应需求文档检查1输出字段)
|
||||
OUTPUT_COLUMNS = [
|
||||
"37工号", "姓名", "月报检查月份", "异常类型",
|
||||
"在职天数", "应勤工作日", "休息天", "差值",
|
||||
"所属单位", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
|
||||
]
|
||||
|
||||
|
||||
# ==================== 通用工具 ====================
|
||||
def _clean(v) -> str:
|
||||
if v is None:
|
||||
return ""
|
||||
if pd.isna(v):
|
||||
return ""
|
||||
s = str(v).strip()
|
||||
if s.lower() in ("nan", "none", "nat"):
|
||||
return ""
|
||||
return s
|
||||
|
||||
|
||||
def _text(v) -> str:
|
||||
t = _clean(v)
|
||||
if t.endswith(".0"):
|
||||
t = t[:-2]
|
||||
return t
|
||||
|
||||
|
||||
def _num(v) -> float:
|
||||
try:
|
||||
return float(_clean(v))
|
||||
except (TypeError, ValueError):
|
||||
return 0.0
|
||||
|
||||
|
||||
def _parse_date(v) -> Optional[date]:
|
||||
s = _clean(v)
|
||||
if not s:
|
||||
return None
|
||||
s = s[:10]
|
||||
try:
|
||||
return datetime.strptime(s, "%Y-%m-%d").date()
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def _prev_month(year: int, month: int) -> Tuple[int, int]:
|
||||
if month == 1:
|
||||
return year - 1, 12
|
||||
return year, month - 1
|
||||
|
||||
|
||||
def _month_range(ym: str) -> Tuple[date, date]:
|
||||
y, m = int(ym[:4]), int(ym[5:7])
|
||||
total_days = pd.Timestamp(year=y, month=m, day=1).daysinmonth
|
||||
return date(y, m, 1), date(y, m, total_days)
|
||||
|
||||
|
||||
def _working_days(first: date, last: date, join: Optional[date], leave: Optional[date]) -> int:
|
||||
"""计算员工当月在职自然天数(月区间 ∩ 在职区间闭区间,含首尾)。"""
|
||||
lo = first if not join else (join if join >= first else first)
|
||||
hi = last if not leave else (leave if leave <= last else last)
|
||||
if lo > hi:
|
||||
return 0
|
||||
return (hi - lo).days + 1
|
||||
|
||||
|
||||
# ==================== 主流程 ====================
|
||||
def _build_seal_map(rows: List[dict]) -> Dict[str, dict]:
|
||||
"""按工号建立 封存记录索引(一员工一条)。"""
|
||||
mapping: Dict[str, dict] = {}
|
||||
for rec in rows:
|
||||
code = ""
|
||||
for f in SEAL_CODE_FIELDS:
|
||||
code = _text(rec.get(f))
|
||||
if code:
|
||||
break
|
||||
if code:
|
||||
mapping.setdefault(code, rec)
|
||||
return mapping
|
||||
|
||||
|
||||
def run_working_days_shift_check(month: str = None) -> List[dict]:
|
||||
"""执行检查1「在职天数是否均排班验证」,返回异常名单行列表(并写 Excel 留档)。
|
||||
|
||||
Args:
|
||||
month: 检查月份 "YYYY-MM",默认上月。
|
||||
|
||||
Returns:
|
||||
异常名单行列表(每行为 OUTPUT_COLUMNS 对应字段的 dict)。
|
||||
"""
|
||||
today = date.today()
|
||||
if month:
|
||||
try:
|
||||
first, last = _month_range(month)
|
||||
except (ValueError, IndexError, TypeError):
|
||||
raise ValueError(f"月份格式应为 YYYY-MM,收到:{month}")
|
||||
ym = month
|
||||
else:
|
||||
py, pm = _prev_month(today.year, today.month)
|
||||
first, last = _month_range(f"{py:04d}-{pm:02d}")
|
||||
ym = f"{py:04d}-{pm:02d}"
|
||||
logger.info("===== 检查1「在职天数是否均排班验证」月份:%s(%s ~ %s) =====", ym, first, last)
|
||||
|
||||
# 1. 读取预处理封存表(seal_data_export.py 已按所属单位白名单筛选并保存)
|
||||
seal_rows = load_seal_rows(ym)
|
||||
if not seal_rows:
|
||||
raise RuntimeError(f"当月「{ym}」预处理封存表为空,请确认该月已封存并已运行导出模块。")
|
||||
seal_map = _build_seal_map(seal_rows)
|
||||
logger.info("考勤封存加载完成,共 %d 人:%s", len(seal_map), ym)
|
||||
|
||||
# 2. 逐人检查
|
||||
abnormal: List[dict] = []
|
||||
for code, rec in seal_map.items():
|
||||
join = _parse_date(rec.get(SEAL_JOIN_FIELD))
|
||||
leave = _parse_date(rec.get(SEAL_LEAVE_FIELD))
|
||||
wd = _working_days(first, last, join, leave)
|
||||
if wd <= 0:
|
||||
continue # 当月无在职日,跳过
|
||||
work = _num(rec.get(SEAL_WORK_FIELD))
|
||||
rest = _num(rec.get(SEAL_REST_FIELD))
|
||||
diff = wd - (work + rest)
|
||||
if diff != 0:
|
||||
abnormal.append(enrich_dept_fields({
|
||||
"37工号": code,
|
||||
"姓名": _text(rec.get(SEAL_NAME_FIELD)),
|
||||
"月报检查月份": ym,
|
||||
"异常类型": ABNORMAL_TYPE,
|
||||
"在职天数": wd,
|
||||
"应勤工作日": int(work),
|
||||
"休息天": int(rest),
|
||||
"差值": diff,
|
||||
}, code, rec))
|
||||
logger.info("检查1命中异常 %d 人(在职天数≠应勤+休息)", len(abnormal))
|
||||
|
||||
# 3. 导出异常名单
|
||||
os.makedirs(SAVE_DIR, exist_ok=True)
|
||||
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
|
||||
save_path = os.path.join(SAVE_DIR, f"在职天数排班异常_{ym}_{ts}.xlsx")
|
||||
try:
|
||||
pd.DataFrame(abnormal if abnormal else [],
|
||||
columns=OUTPUT_COLUMNS).to_excel(save_path, index=False)
|
||||
except PermissionError:
|
||||
raise RuntimeError(
|
||||
f"导出失败:文件正被占用,请先关闭已打开的 Excel「{os.path.basename(save_path)}」后重试")
|
||||
logger.info("异常名单已保存:%s(共 %d 条)", save_path, len(abnormal))
|
||||
return abnormal
|
||||
|
||||
|
||||
def main(args=None) -> dict:
|
||||
"""影刀「调用模块」入口;也可作为脚本直接运行。
|
||||
args: dict,可选字段:month("YYYY-MM",默认上月)。
|
||||
"""
|
||||
if args is None:
|
||||
args = {}
|
||||
month = args.get("month") or os.getenv("monthly_wd_month") or (sys_argv_if(2))
|
||||
try:
|
||||
rows = run_working_days_shift_check(month)
|
||||
logger.info("=" * 60)
|
||||
logger.info("【检查1 在职天数是否均排班验证完成】")
|
||||
logger.info(" 检查月份:%s | 异常人数:%d", month or "默认上月", len(rows))
|
||||
logger.info(" 输出目录:%s", SAVE_DIR)
|
||||
logger.info("=" * 60)
|
||||
return {"success": True, "count": len(rows)}
|
||||
except Exception as e:
|
||||
logger.error("检查1执行失败:%s", e)
|
||||
return {"success": False, "message": str(e)}
|
||||
|
||||
|
||||
def sys_argv_if(idx):
|
||||
"""读取命令行第 idx 个参数(index from 1);不存在返回 None。"""
|
||||
return sys.argv[idx] if len(sys.argv) > idx else None
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
|
||||
@@ -1,52 +1,52 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""探针:打开 SSO 登录页(法人用户 tab),dump 所有输入框的真实属性,
|
||||
用于修正 sb_login.py 的选择器。用完可删。"""
|
||||
import sys
|
||||
import time
|
||||
sys.path.insert(0, r"d:\work\code\37duAutomation\workflows\XQ0001-0100\XQ0014 社保系统增减员办理")
|
||||
import sb_login
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
co = ChromiumOptions()
|
||||
co.auto_port(True)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(sb_login.APPLY_URL)
|
||||
time.sleep(2)
|
||||
sb_login._dismiss_notice(page)
|
||||
tab = sb_login._open_sso_tab(page)
|
||||
if tab is None:
|
||||
print("PROBE: 未进入 SSO 登录页")
|
||||
sys.exit(1)
|
||||
print("PROBE: SSO URL =", tab.url)
|
||||
sb_login._wait_sso_ready(tab)
|
||||
# 点法人用户 tab(精确文本匹配,避免命中包含该文字的外层容器 div)
|
||||
legal = tab.ele('tag:div@@text()=法人用户', timeout=10)
|
||||
print("PROBE: 法人用户tab元素 =", legal, "| tag:", legal.tag if legal else None,
|
||||
"| class:", (legal.attr('class') if legal else None))
|
||||
if legal:
|
||||
legal.click()
|
||||
time.sleep(1.5)
|
||||
active_btn = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=3)
|
||||
print("PROBE: 当前激活tab =", active_btn.text.strip() if active_btn else None)
|
||||
# dump 当前激活面板内的所有输入框
|
||||
panel = tab.ele('css:.ant-tabs-tabpane-active', timeout=5)
|
||||
inputs = panel.eles('tag:input') if panel else tab.eles('tag:input')
|
||||
print(f"PROBE: 共 {len(inputs)} 个 input")
|
||||
for i, ip in enumerate(inputs):
|
||||
try:
|
||||
print(f"[{i}] type={ip.attr('type')} placeholder={ip.attr('placeholder')!r} "
|
||||
f"id={ip.attr('id')!r} name={ip.attr('name')!r} class={(ip.attr('class') or '')[:60]!r}")
|
||||
except Exception as e:
|
||||
print(f"[{i}] 读取失败: {e}")
|
||||
# 顺带 dump 按钮
|
||||
for i, b in enumerate(panel.eles('tag:button') if panel else tab.eles('tag:button')):
|
||||
try:
|
||||
print(f"BTN[{i}] type={b.attr('type')} class={(b.attr('class') or '')[:50]!r} text={b.text.strip()!r}")
|
||||
except Exception as e:
|
||||
print(f"BTN[{i}] 读取失败: {e}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
# -*- coding: utf-8 -*-
|
||||
"""探针:打开 SSO 登录页(法人用户 tab),dump 所有输入框的真实属性,
|
||||
用于修正 sb_login.py 的选择器。用完可删。"""
|
||||
import sys
|
||||
import time
|
||||
sys.path.insert(0, r"d:\work\code\37duAutomation\workflows\XQ0001-0100\XQ0014 社保系统增减员办理")
|
||||
import sb_login
|
||||
from DrissionPage import ChromiumPage, ChromiumOptions
|
||||
|
||||
co = ChromiumOptions()
|
||||
co.auto_port(True)
|
||||
page = ChromiumPage(co)
|
||||
try:
|
||||
page.get(sb_login.APPLY_URL)
|
||||
time.sleep(2)
|
||||
sb_login._dismiss_notice(page)
|
||||
tab = sb_login._open_sso_tab(page)
|
||||
if tab is None:
|
||||
print("PROBE: 未进入 SSO 登录页")
|
||||
sys.exit(1)
|
||||
print("PROBE: SSO URL =", tab.url)
|
||||
sb_login._wait_sso_ready(tab)
|
||||
# 点法人用户 tab(精确文本匹配,避免命中包含该文字的外层容器 div)
|
||||
legal = tab.ele('tag:div@@text()=法人用户', timeout=10)
|
||||
print("PROBE: 法人用户tab元素 =", legal, "| tag:", legal.tag if legal else None,
|
||||
"| class:", (legal.attr('class') if legal else None))
|
||||
if legal:
|
||||
legal.click()
|
||||
time.sleep(1.5)
|
||||
active_btn = tab.ele('css:.ant-tabs-tab-active .ant-tabs-tab-btn', timeout=3)
|
||||
print("PROBE: 当前激活tab =", active_btn.text.strip() if active_btn else None)
|
||||
# dump 当前激活面板内的所有输入框
|
||||
panel = tab.ele('css:.ant-tabs-tabpane-active', timeout=5)
|
||||
inputs = panel.eles('tag:input') if panel else tab.eles('tag:input')
|
||||
print(f"PROBE: 共 {len(inputs)} 个 input")
|
||||
for i, ip in enumerate(inputs):
|
||||
try:
|
||||
print(f"[{i}] type={ip.attr('type')} placeholder={ip.attr('placeholder')!r} "
|
||||
f"id={ip.attr('id')!r} name={ip.attr('name')!r} class={(ip.attr('class') or '')[:60]!r}")
|
||||
except Exception as e:
|
||||
print(f"[{i}] 读取失败: {e}")
|
||||
# 顺带 dump 按钮
|
||||
for i, b in enumerate(panel.eles('tag:button') if panel else tab.eles('tag:button')):
|
||||
try:
|
||||
print(f"BTN[{i}] type={b.attr('type')} class={(b.attr('class') or '')[:50]!r} text={b.text.strip()!r}")
|
||||
except Exception as e:
|
||||
print(f"BTN[{i}] 读取失败: {e}")
|
||||
finally:
|
||||
try:
|
||||
page.quit()
|
||||
except Exception:
|
||||
pass
|
||||
|
||||
File diff suppressed because it is too large
Load Diff
@@ -168,8 +168,7 @@ HEADER_ROW = 3 # 表头所在行
|
||||
MAIN_COLS = 51 # 主表字段到「费用」列(AY)为止(AZ 为空列,其后为粘贴重复区)
|
||||
RETRY_TIMES = 3 # 全局重试次数
|
||||
|
||||
# 社保转移数据源(社保变更人员名单):独立于参保名单的另一份文件
|
||||
TRANSFER_EXCEL_KEYWORD = "社保变更人员名单" # 数据源文件名关键字
|
||||
# 社保转移数据源:转移参保数据已并入「社保变更及增减名单」文件的「变更-职能及干部/变更-门店」sheet
|
||||
TRANSFER_SHEET_GENERATE = ("变更-职能及干部", "变更-门店") # 生成覆盖的 sheet(关键字)
|
||||
TRANSFER_SHEET_PUSH = "变更-门店" # 推送仅限该 sheet
|
||||
TRANSFER_CHANGE_COL = "是否变更" # 筛选列
|
||||
@@ -185,7 +184,7 @@ BRANCHES = {
|
||||
},
|
||||
"转移参保": {
|
||||
"rule_keys": ("社保转移",),
|
||||
"excel_keyword": "社保变更人员名单",
|
||||
"excel_keyword": "社保变更及增减名单", # 与「新参保」同源文件,读其「变更-*」sheet
|
||||
},
|
||||
}
|
||||
|
||||
@@ -238,8 +237,8 @@ OA_MESSAGE_TEMPLATES = (
|
||||
"各位领导/同事:\n"
|
||||
"根据《社保执行细则》,本月人力资源部已输出“工作与参保单位不一致”的人员,"
|
||||
"现需要涉及门店/经营中心与员工本人进行转移确认(下载变更告知书、打印并与员工清晰讲解),"
|
||||
"在{m}月25日下班前完成签署并将《社保缴纳确认单》传递分部人行,"
|
||||
"在{m}月27日内传递人资周卫处。\n"
|
||||
"在{m}月27日下班前完成签署并将《社保缴纳确认单》传递分部人行,"
|
||||
"在{m}月29日内传递人资周卫处。\n"
|
||||
"特别注意:员工若有住院就医计划,须及时反馈可暂不转移,待处理完毕后办理。"
|
||||
"员工若属于暂调(后续会回到原门店),也须及时反馈可暂不转移。\n"
|
||||
"@@R人力资源部\n"
|
||||
@@ -346,12 +345,6 @@ def _find_excel(dir_path: str) -> str:
|
||||
return _find_current_month_excel(dir_path, EXCEL_KEYWORD)
|
||||
|
||||
|
||||
def _find_transfer_excel(dir_path: str = None) -> str:
|
||||
"""在目录内查找包含「社保变更人员名单」且月份=当月的 xlsx 文件(社保转移数据源)。"""
|
||||
dir_path = dir_path or BASE_DIR
|
||||
return _find_current_month_excel(dir_path, TRANSFER_EXCEL_KEYWORD)
|
||||
|
||||
|
||||
def _read_insurance_records(excel_path: str) -> list:
|
||||
"""读取「参保名单」sheet,返回人员记录列表(dict,key=表头字段名)。"""
|
||||
wb = openpyxl.load_workbook(excel_path, read_only=True, data_only=True)
|
||||
@@ -723,9 +716,16 @@ def _read_transfer_records(excel_path: str, roster_map: dict = None) -> list:
|
||||
for src, std in TRANSFER_COL_MAP.items():
|
||||
if src in col_idx:
|
||||
rec[std] = _cell(vals, src)
|
||||
for key in ("姓名", "二级部门", "四级部门", "37工号", "参保单位全称", "备注"):
|
||||
for key in ("姓名", "二级部门", "四级部门", "37工号", "备注"):
|
||||
if key in col_idx:
|
||||
rec[key] = _cell(vals, key)
|
||||
# 参保单位全称:优先「全称」列(转移后单位全称),缺失回退「参保单位全称」列
|
||||
full_key = "全称" if "全称" in col_idx else "参保单位全称"
|
||||
if full_key in col_idx:
|
||||
rec["参保单位全称"] = _cell(vals, full_key)
|
||||
# 转移参保单位:告知书文件名第二段用(门店=门店名/职能=公司简称)
|
||||
if "转移参保单位" in col_idx:
|
||||
rec["转移参保单位"] = _cell(vals, "转移参保单位")
|
||||
if rec.get("姓名") is None:
|
||||
continue
|
||||
rec["_source"] = ws.title
|
||||
@@ -747,12 +747,19 @@ def _ins_org_of(rec: dict) -> str:
|
||||
return ""
|
||||
|
||||
|
||||
def _trans_org_of(rec: dict) -> str:
|
||||
"""取记录转移参保单位(告知书文件名第二段用):优先「转移参保单位」列,缺失回退参保单位标识。"""
|
||||
v = str(rec.get("转移参保单位") or "").strip()
|
||||
return v or _ins_org_of(rec)
|
||||
|
||||
|
||||
def _resolve_dept2(rec: dict, all_records: list, roster_map: dict):
|
||||
"""解析记录的正确二级部门(经营中心),优先数据源内参保单位聚合,兜底花名册反查。
|
||||
"""解析记录的正确二级部门(经营中心),优先数据源内参保单位聚合,兜底记录自身/花名册反查。
|
||||
|
||||
1) 主查:数据源全量记录中按「参保单位」聚合,同参保单位记录的二级部门应唯一(一个经营中心);
|
||||
2) 兜底:主查不唯一/缺失时,把参保单位作为四级部门在花名册反查其二级部门;
|
||||
3) 仍解析不到返回 None,由调用方报错并跳过该记录(不推送)。
|
||||
2) 次查:记录自身「二级部门」字段(非空直接采用,覆盖职能/干部等与门店同参保单位但归属不同的人员);
|
||||
3) 兜底:主查/次查均无时,把参保单位作为四级部门在花名册反查其二级部门;
|
||||
4) 仍解析不到返回 None,由调用方报错并跳过该记录(不推送)。
|
||||
"""
|
||||
ins = _ins_org_of(rec)
|
||||
if not ins:
|
||||
@@ -764,6 +771,9 @@ def _resolve_dept2(rec: dict, all_records: list, roster_map: dict):
|
||||
dept2s.discard("")
|
||||
if len(dept2s) == 1:
|
||||
return dept2s.pop()
|
||||
own = str(rec.get("二级部门") or "").strip()
|
||||
if own:
|
||||
return own
|
||||
dept2s = {
|
||||
str(it.get("二级部门") or "").strip()
|
||||
for it in roster_map.values()
|
||||
@@ -1054,7 +1064,7 @@ def generate_notices(branch: str, output_dir: str = None, ym: tuple = None,
|
||||
rec.get("姓名"), _ins_org_of(rec))
|
||||
continue
|
||||
rec["二级部门"] = dept2
|
||||
key = (dept2, _ins_org_of(rec))
|
||||
key = (dept2, _trans_org_of(rec))
|
||||
groups.setdefault(key, []).append(rec)
|
||||
|
||||
for (dept2, ins_org), recs in groups.items():
|
||||
@@ -1107,4 +1117,4 @@ def main(branch: str) -> list:
|
||||
|
||||
if __name__ == "__main__":
|
||||
# 显式指定执行分支:'新参保' 或 '转移参保'(二选一,分别对应不同数据源文件)
|
||||
main("新参保")
|
||||
main("转移参保")
|
||||
|
||||
@@ -1,109 +1,109 @@
|
||||
"""物料收发汇总表 合并工具(XQ0031)。
|
||||
|
||||
将同目录(默认桌面最新「采购计划报表_日期」文件夹)下导出的各档报表
|
||||
(物料收发汇总表_60D.xlsx / _30D.xlsx / 自定义日期区间 ...)合并为一个汇总文件:
|
||||
- 每个报表第 4 行是表头;合并时在第 4 行表头第一列新增「时间区间」字段
|
||||
- 数据行第一列填入报表标签(60D / 30D / 日期区间 ...)
|
||||
- 汇总结果输出到同目录,命名:物料收发汇总表_YYYY-MM-DD.xlsx
|
||||
|
||||
自包含:仅依赖 openpyxl,无外部参数依赖。
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
# 合并目录:None → 自动取桌面最新「采购计划报表_*」目录;也可直接写绝对路径
|
||||
MERGE_DIR = None
|
||||
# 输出文件名:None → 物料收发汇总表_<目录日期>.xlsx
|
||||
OUT_NAME = None
|
||||
|
||||
|
||||
def _save_dir() -> Path:
|
||||
if MERGE_DIR:
|
||||
return Path(MERGE_DIR)
|
||||
desk = Path.home() / 'Desktop'
|
||||
cands = sorted(desk.glob('采购计划报表_*'),
|
||||
key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
if not cands:
|
||||
raise SystemExit(f'未找到桌面目录: {desk}/采购计划报表_*')
|
||||
return cands[0]
|
||||
|
||||
|
||||
def _label(name: str):
|
||||
"""从文件名提取报表标签:物料收发汇总表_60D.xlsx → 60D;
|
||||
物料收发汇总表_2026-07-01_2026-07-31.xlsx → 2026-07-01_2026-07-31。"""
|
||||
m = re.match(r'^物料收发汇总表_(.+)\.xlsx$', name)
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
def _read_report(path: Path):
|
||||
"""读取单个报表:表头位于第 4 行,数据从第 5 行起。
|
||||
每表最后一行是汇总行,明确跳过;再叠加空行过滤做兜底。返回 (表头, 数据行列表)。"""
|
||||
wb = openpyxl.load_workbook(path, data_only=True)
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
header = [ws.cell(4, c).value for c in range(1, ws.max_column + 1)]
|
||||
rows = []
|
||||
# 跳过最后一行汇总行
|
||||
for r in range(5, ws.max_row):
|
||||
row = [ws.cell(r, c).value for c in range(1, ws.max_column + 1)]
|
||||
if any(v is not None and str(v).strip() != '' for v in row):
|
||||
rows.append(row)
|
||||
return header, rows
|
||||
|
||||
|
||||
def merge() -> Path:
|
||||
save_dir = _save_dir()
|
||||
|
||||
date_tag = ''
|
||||
m = re.search(r'(\d{4}-\d{2}-\d{2})', save_dir.name)
|
||||
date_tag = m.group(1) if m else datetime.now().strftime('%Y-%m-%d')
|
||||
out = save_dir / (OUT_NAME or f'物料收发汇总表_{date_tag}.xlsx')
|
||||
|
||||
files = sorted(p for p in save_dir.glob('物料收发汇总表_*.xlsx')
|
||||
if _label(p.name) and p.name != out.name)
|
||||
if not files:
|
||||
raise SystemExit(f'目录下没有可合并的报表: {save_dir}')
|
||||
|
||||
header = None
|
||||
all_rows, labels = [], []
|
||||
for f in files:
|
||||
label = _label(f.name)
|
||||
h, rows = _read_report(f)
|
||||
if header is None:
|
||||
header = h
|
||||
elif h != header:
|
||||
print(f'[跳过] 表头不一致: {f.name}')
|
||||
continue
|
||||
all_rows.extend([[label] + row for row in rows])
|
||||
labels.append(label)
|
||||
print(f'[{label}] 数据 {len(rows)} 行 <- {f.name}')
|
||||
|
||||
if not all_rows:
|
||||
raise SystemExit('没有可合并的数据')
|
||||
if out.exists():
|
||||
out.unlink()
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = 'Sheet1'
|
||||
# 前 3 行说明,保持「表头在第 4 行」的结构与单报表一致
|
||||
ws.cell(1, 1, '物料收发汇总表(汇总)')
|
||||
ws.cell(2, 1, f'生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
|
||||
ws.cell(3, 1, f'合并报表: {", ".join(labels)}')
|
||||
# 第 4 行表头:第一列插入「时间区间」
|
||||
ws.cell(4, 1, '时间区间')
|
||||
for c, v in enumerate(header, start=2):
|
||||
ws.cell(4, c, v)
|
||||
# 数据(第一列为报表标签)
|
||||
for r, row in enumerate(all_rows, start=5):
|
||||
for c, v in enumerate(row, start=1):
|
||||
ws.cell(r, c, v)
|
||||
wb.save(out)
|
||||
print(f'已生成: {out}(共 {len(all_rows)} 条数据,{len(labels)} 个报表)')
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
merge()
|
||||
"""物料收发汇总表 合并工具(XQ0031)。
|
||||
|
||||
将同目录(默认桌面最新「采购计划报表_日期」文件夹)下导出的各档报表
|
||||
(物料收发汇总表_60D.xlsx / _30D.xlsx / 自定义日期区间 ...)合并为一个汇总文件:
|
||||
- 每个报表第 4 行是表头;合并时在第 4 行表头第一列新增「时间区间」字段
|
||||
- 数据行第一列填入报表标签(60D / 30D / 日期区间 ...)
|
||||
- 汇总结果输出到同目录,命名:物料收发汇总表_YYYY-MM-DD.xlsx
|
||||
|
||||
自包含:仅依赖 openpyxl,无外部参数依赖。
|
||||
"""
|
||||
import re
|
||||
from datetime import datetime
|
||||
from pathlib import Path
|
||||
|
||||
import openpyxl
|
||||
|
||||
# 合并目录:None → 自动取桌面最新「采购计划报表_*」目录;也可直接写绝对路径
|
||||
MERGE_DIR = None
|
||||
# 输出文件名:None → 物料收发汇总表_<目录日期>.xlsx
|
||||
OUT_NAME = None
|
||||
|
||||
|
||||
def _save_dir() -> Path:
|
||||
if MERGE_DIR:
|
||||
return Path(MERGE_DIR)
|
||||
desk = Path.home() / 'Desktop'
|
||||
cands = sorted(desk.glob('采购计划报表_*'),
|
||||
key=lambda p: p.stat().st_mtime, reverse=True)
|
||||
if not cands:
|
||||
raise SystemExit(f'未找到桌面目录: {desk}/采购计划报表_*')
|
||||
return cands[0]
|
||||
|
||||
|
||||
def _label(name: str):
|
||||
"""从文件名提取报表标签:物料收发汇总表_60D.xlsx → 60D;
|
||||
物料收发汇总表_2026-07-01_2026-07-31.xlsx → 2026-07-01_2026-07-31。"""
|
||||
m = re.match(r'^物料收发汇总表_(.+)\.xlsx$', name)
|
||||
return m.group(1) if m else None
|
||||
|
||||
|
||||
def _read_report(path: Path):
|
||||
"""读取单个报表:表头位于第 4 行,数据从第 5 行起。
|
||||
每表最后一行是汇总行,明确跳过;再叠加空行过滤做兜底。返回 (表头, 数据行列表)。"""
|
||||
wb = openpyxl.load_workbook(path, data_only=True)
|
||||
ws = wb[wb.sheetnames[0]]
|
||||
header = [ws.cell(4, c).value for c in range(1, ws.max_column + 1)]
|
||||
rows = []
|
||||
# 跳过最后一行汇总行
|
||||
for r in range(5, ws.max_row):
|
||||
row = [ws.cell(r, c).value for c in range(1, ws.max_column + 1)]
|
||||
if any(v is not None and str(v).strip() != '' for v in row):
|
||||
rows.append(row)
|
||||
return header, rows
|
||||
|
||||
|
||||
def merge() -> Path:
|
||||
save_dir = _save_dir()
|
||||
|
||||
date_tag = ''
|
||||
m = re.search(r'(\d{4}-\d{2}-\d{2})', save_dir.name)
|
||||
date_tag = m.group(1) if m else datetime.now().strftime('%Y-%m-%d')
|
||||
out = save_dir / (OUT_NAME or f'物料收发汇总表_{date_tag}.xlsx')
|
||||
|
||||
files = sorted(p for p in save_dir.glob('物料收发汇总表_*.xlsx')
|
||||
if _label(p.name) and p.name != out.name)
|
||||
if not files:
|
||||
raise SystemExit(f'目录下没有可合并的报表: {save_dir}')
|
||||
|
||||
header = None
|
||||
all_rows, labels = [], []
|
||||
for f in files:
|
||||
label = _label(f.name)
|
||||
h, rows = _read_report(f)
|
||||
if header is None:
|
||||
header = h
|
||||
elif h != header:
|
||||
print(f'[跳过] 表头不一致: {f.name}')
|
||||
continue
|
||||
all_rows.extend([[label] + row for row in rows])
|
||||
labels.append(label)
|
||||
print(f'[{label}] 数据 {len(rows)} 行 <- {f.name}')
|
||||
|
||||
if not all_rows:
|
||||
raise SystemExit('没有可合并的数据')
|
||||
if out.exists():
|
||||
out.unlink()
|
||||
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = 'Sheet1'
|
||||
# 前 3 行说明,保持「表头在第 4 行」的结构与单报表一致
|
||||
ws.cell(1, 1, '物料收发汇总表(汇总)')
|
||||
ws.cell(2, 1, f'生成时间: {datetime.now().strftime("%Y-%m-%d %H:%M:%S")}')
|
||||
ws.cell(3, 1, f'合并报表: {", ".join(labels)}')
|
||||
# 第 4 行表头:第一列插入「时间区间」
|
||||
ws.cell(4, 1, '时间区间')
|
||||
for c, v in enumerate(header, start=2):
|
||||
ws.cell(4, c, v)
|
||||
# 数据(第一列为报表标签)
|
||||
for r, row in enumerate(all_rows, start=5):
|
||||
for c, v in enumerate(row, start=1):
|
||||
ws.cell(r, c, v)
|
||||
wb.save(out)
|
||||
print(f'已生成: {out}(共 {len(all_rows)} 条数据,{len(labels)} 个报表)')
|
||||
return out
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
merge()
|
||||
|
||||
Reference in New Issue
Block a user