feat(attendance_points): add rejoin ledger support and optimize push logic
新增离职当月再入职人员台账查询与无效积分段清理逻辑 优化积分推送逻辑,统一使用官方模板格式并修正日期显示格式 更新版本至1.1.0,完善登录态处理与错误提示
This commit is contained in:
@@ -3,19 +3,18 @@
|
||||
@FileName: attendance_points_push.py
|
||||
@Description: XQ0033 出勤积分「积分导入/积分删除」表 → OPM 平台(opm.jsyxapp.com)自动推送(独立脚本)。
|
||||
读取 attendance_points_update.py 生成的「员工出勤及遵章积分导入{MMDD}.xlsx」中的
|
||||
「积分导入」「积分删除」表,抽取 工号/姓名/积分日期,按 kaoqin.xlsx 格式
|
||||
构建上传文件,调用考勤积分上传接口推送到 OPM 平台。
|
||||
「积分导入」「积分删除」表,抽取 工号/姓名/积分日期,按 kaoqin.xlsx 三列格式
|
||||
(工号/姓名/积分日期,与官方模板一致)直接新建生成上传文件,
|
||||
调用考勤积分上传接口推送到 OPM 平台。
|
||||
默认「试运行」:只解析 + 校验会话 + 打印待推送清单,不真传;确认无误后把
|
||||
DRY_RUN 置 False 再跑即正式推送。
|
||||
|
||||
上传端点(逆向自 /point/list 前端 chunk-6e4bc3f7/a8477964 + 实测验证):
|
||||
- 考勤导入 POST /operation/point/list/importAttendance multipart file=<kaoqin.xlsx>
|
||||
- 考勤删除 POST /operation/point/list/importAttendanceDel multipart file=<kaoqin.xlsx>
|
||||
说明:XQ0033 数据只有 工号/姓名/积分日期,恰好是 kaoqin.xlsx 模板三列;
|
||||
普通「积分导入/删除」端点(importPoints/importDelPoints)走 jifen.xlsx 模板,
|
||||
需额外填积分类别/积分条例/事件描述必填列,直接传会被服务端拒绝(实测
|
||||
“第2行积分类型不能为空”)。故出勤积分推送走考勤端点,无需备注。
|
||||
若业务需改走普通积分端点,改 IMPORT_URL/DELETE_URL 并补充 jifen 必填列映射即可。
|
||||
上传端点(考勤导入/考勤删除按钮,与页面「积分导入/积分删除」sheet 数据直接对应):
|
||||
- 积分导入表 → 考勤导入 POST /operation/point/list/importAttendance multipart file=<kaoqin.xlsx>
|
||||
- 积分删除表 → 考勤删除 POST /operation/point/list/importAttendanceDel multipart file=<kaoqin.xlsx>
|
||||
说明:XQ0033 出勤积分数据只有 工号/姓名/积分日期,恰好是 kaoqin.xlsx 模板三列,
|
||||
直接由「积分导入/积分删除」sheet 按模板生成上传即可(无需 jifen.xlsx 的
|
||||
积分类别/积分条例/事件描述等列)。
|
||||
|
||||
登录态:复用 store_login_api.py(37du门店登录(接口版))写入的
|
||||
%LOCALAPPDATA%\\37duAutomation\\.sessions\\store_cookies.json,失效自动补登。
|
||||
@@ -173,13 +172,18 @@ def read_point_sheet(path, sheet_name):
|
||||
|
||||
|
||||
def build_kaoqin_bytes(rows):
|
||||
"""[(工号,姓名,日期)] → kaoqin.xlsx 模板(工号/姓名/积分日期)字节。"""
|
||||
"""[(工号,姓名,日期)] → kaoqin.xlsx 字节(Sheet1 三列:工号/姓名/积分日期,与官方模板一致)。
|
||||
字段固定为 3 列,直接新建工作簿写入即可;积分日期统一显示格式 yyyy/m/d(仍为日期类型)。"""
|
||||
import io
|
||||
wb = openpyxl.Workbook()
|
||||
ws = wb.active
|
||||
ws.title = "Sheet1"
|
||||
ws.append(['工号', '姓名', '积分日期'])
|
||||
for emp_no, name, d in rows:
|
||||
ws.append([emp_no, name, d])
|
||||
import io
|
||||
for i, (emp_no, name, d) in enumerate(rows, start=2):
|
||||
ws.cell(row=i, column=1, value=emp_no)
|
||||
ws.cell(row=i, column=2, value=name)
|
||||
ws.cell(row=i, column=3, value=d)
|
||||
ws.cell(row=i, column=3).number_format = "yyyy/m/d"
|
||||
buf = io.BytesIO()
|
||||
wb.save(buf)
|
||||
return buf.getvalue()
|
||||
|
||||
@@ -7,8 +7,14 @@
|
||||
→ COM 重算按 A 列公式圈人 → 滚动「考勤--今日导出/考勤-前一日导出」快照
|
||||
→ 对比结果(今日镜像-前一日镜像)逐日差值 → 新增积分(T-2 日代号=2)
|
||||
与修正积分(1~T-3 日差值正补/负删)写入「积分导入/积分删除」表。
|
||||
另拉取「离职当月再入职人员算薪台账」(实时查询接口,无导出)全量
|
||||
→ 追加写入「当月再入职名单」sheet(按工号去重,已存在行不重写,
|
||||
B/C/F/G/H + I备注沿用台账,D工号/E积分天数留空人工维护);
|
||||
并用台账的 离职日/再入职日 踢除再入职人员无效积分段:
|
||||
台账工号清 [离职日,再入职日) 中间段;再按身份证查「离职台账」找历史工号,
|
||||
若换工号(历史工号≠再入职工号)则旧工号清 [再入职日,月末] 的积分段。
|
||||
规则与文件结构见 docs/需求单/XQ0001-0100/XQ0033 门店管理及服务岗出勤积分更新/需求文档.md。
|
||||
@Version: 1.0.0
|
||||
@Version: 1.1.0
|
||||
|
||||
设计说明(与 workflows 下其它单文件版一致):
|
||||
- 单文件自包含,内联 HR 接口(XQ0009 同款),不依赖项目其它模块。
|
||||
@@ -35,6 +41,7 @@ import re
|
||||
import shutil
|
||||
import time
|
||||
import traceback
|
||||
import urllib.parse
|
||||
from datetime import date, datetime, timedelta
|
||||
|
||||
# ==================== 第三方库导入(影刀版启动校验) ====================
|
||||
@@ -127,6 +134,27 @@ EXP_DATA_START = 5 # 今日导出/前一日导出数据起始行
|
||||
CMP_DATA_START = 4 # 对比结果数据起始行
|
||||
IMP_DATA_START = 4 # 积分导入/删除数据起始行
|
||||
|
||||
SHEET_REJOIN = "当月再入职名单" # 行3表头,B4 起数据:B门店 C姓名 D工号 E积分天数 F离职日期 G再入职日期 H再入职工号 I备注(D/E 留空人工维护)
|
||||
REJOIN_DATA_START = 4 # 当月再入职名单数据起始行
|
||||
|
||||
# 离职当月再入职人员算薪台账(实时查询接口 queryRealTimeData.mc,无导出接口;逆向自 getCustomCommonList 页面抓包)
|
||||
REJOIN_ROSTER_ID = "4378442b-80e3-11ed-9735-822ff8ed5b28"
|
||||
REJOIN_TABLE_ID = "cq37du-hr_wage_leave_and_join_sp_cq37du"
|
||||
REJOIN_FIELD_PREFIX = "hr_wage_leave_and_join_sp_cq37du" # 台账字段前缀(与 tableId 不同,抓包所得)
|
||||
REJOIN_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/hrRoster/{REJOIN_ROSTER_ID}/queryRealTimeData.mc"
|
||||
REJOIN_PAGE_SIZE = 100
|
||||
REJOIN_ROLE_IDS = ("62367974-3904-409c-849a-2c3b0edcaf44,"
|
||||
"b90bb654-4c5e-4d57-b27d-77623d14f3ab,"
|
||||
"f30200a0-2154-4692-8e58-7d2758d9bb82,"
|
||||
"POST_SYS_ADMIN,renshi")
|
||||
|
||||
# 离职台账(历史工号查询,按身份证;配合换工号再入职时找旧工号清段)
|
||||
LEAVE_ROSTER_ID = "111823a2-b094-11ea-b588-14187743d052"
|
||||
LEAVE_TABLE_ID = "assemble-hr_staff_leaveoffice"
|
||||
LEAVE_MENU = "离职台账"
|
||||
LEAVE_QUERY_URL = f"{HR_BASE_URL}/RedseaPlatform/hrRoster/{LEAVE_ROSTER_ID}/queryRealTimeData.mc"
|
||||
LEAVE_PAGE_SIZE = 100
|
||||
|
||||
|
||||
# ==================== 工具函数 ====================
|
||||
def _clean(v):
|
||||
@@ -256,13 +284,15 @@ def hr_request_json(session, method, url, params, label, timeout=30):
|
||||
|
||||
|
||||
def build_hr_session():
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。"""
|
||||
"""用共享 hr_cookies.json 构建 requests.Session(过滤 hr.37du.co 域)。
|
||||
带 X-Requested-With 头:台账实时查询接口(queryRealTimeData.mc)缺该头返回登录页 HTML。"""
|
||||
_ensure_hr_cookies()
|
||||
cookies = _load_shared_hr_cookies()
|
||||
session = requests.Session()
|
||||
session.headers.update({
|
||||
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36",
|
||||
"Content-Type": "application/x-www-form-urlencoded",
|
||||
"X-Requested-With": "XMLHttpRequest",
|
||||
})
|
||||
for c in cookies:
|
||||
if c.get("domain") and "37du.co" in c["domain"]:
|
||||
@@ -290,6 +320,37 @@ def _relogin_get_user_info():
|
||||
"补登后 HR 登录态仍失效,请先重新运行「37duHR登录」指令,再重试本流程") from e
|
||||
|
||||
|
||||
def _ensure_cur_user_info(session):
|
||||
"""获取当前用户 userId;登录态失效自动补登重试(上限 RELOGIN_MAX 次)。
|
||||
|
||||
未登录/登录态失效时给出明确登录提示(不抛晦涩的「userId 为空」):
|
||||
- cookies 文件缺失:build_hr_session/_ensure_hr_cookies 已提示;
|
||||
- cookies 存在但失效(返回非 JSON 或 JSON 无 userId):本函数自动补登;
|
||||
- 补登后仍无效:抛出「请先运行 37duHR登录 指令」的明确提示。
|
||||
"""
|
||||
for attempt in range(1, RELOGIN_MAX + 1):
|
||||
user_id = ""
|
||||
try:
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
except HRSessionExpiredError:
|
||||
user_id = ""
|
||||
if user_id:
|
||||
return session, user_id
|
||||
if attempt >= RELOGIN_MAX:
|
||||
break
|
||||
logger.warning("HR 登录态失效,自动补登后重试(第 %d/%d 次)", attempt, RELOGIN_MAX)
|
||||
try:
|
||||
session, user_id = _relogin_get_user_info()
|
||||
except HRSessionExpiredError:
|
||||
user_id = ""
|
||||
if user_id:
|
||||
return session, user_id
|
||||
raise RuntimeError(
|
||||
"未检测到有效的 HR 登录态(未登录或登录已失效)。"
|
||||
"请先运行「37duHR登录(接口版)」指令完成登录后,再重跑本流程")
|
||||
|
||||
|
||||
def fetch_attendance_stat_page(session, user_id, month, page_no=1):
|
||||
"""请求单页「考勤统计报表」数据(每人一行,v_1~v_31 为当月逐日出勤状态)。"""
|
||||
params = {
|
||||
@@ -377,6 +438,320 @@ def report_row_to_list(rec):
|
||||
return row
|
||||
|
||||
|
||||
# ==================== 离职当月再入职台账(查询 + 写入当月再入职名单) ====================
|
||||
# commonQuery 前端加密(自实现,与 workflows/share/roster_export_api.py 同源,已实测可用)
|
||||
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
|
||||
_CQ_SALT = "yyryrtweasdasd"
|
||||
|
||||
|
||||
def _custom_base64_encode(data):
|
||||
"""使用自定义字符表进行 Base64 编码(data 为 UTF-8 字节序列)。"""
|
||||
result = []
|
||||
for i in range(0, len(data), 3):
|
||||
chunk = data[i:i + 3]
|
||||
b1 = chunk[0] if len(chunk) > 0 else 0
|
||||
b2 = chunk[1] if len(chunk) > 1 else 0
|
||||
b3 = chunk[2] if len(chunk) > 2 else 0
|
||||
enc1 = (b1 >> 2) & 0x3F
|
||||
enc2 = ((b1 << 4) | (b2 >> 4)) & 0x3F
|
||||
enc3 = ((b2 << 2) | (b3 >> 6)) & 0x3F
|
||||
enc4 = b3 & 0x3F
|
||||
if len(chunk) == 1:
|
||||
enc3 = 64
|
||||
enc4 = 64
|
||||
elif len(chunk) == 2:
|
||||
enc4 = 64
|
||||
result.append(_CUSTOM_CHARS[enc1])
|
||||
result.append(_CUSTOM_CHARS[enc2])
|
||||
result.append(_CUSTOM_CHARS[enc3])
|
||||
result.append(_CUSTOM_CHARS[enc4])
|
||||
return ''.join(result)
|
||||
|
||||
|
||||
def _build_rejoin_condition(query_field, query_type, query_value,
|
||||
left_bracket="", right_bracket="", input_type="text"):
|
||||
"""构造一条符合前端格式的查询条件。"""
|
||||
return {
|
||||
"queryField": query_field,
|
||||
"leftBracket": left_bracket,
|
||||
"queryType": query_type,
|
||||
"queryValue": query_value,
|
||||
"queryText": "",
|
||||
"rightBracket": right_bracket,
|
||||
"logic": "AND",
|
||||
"inputType": input_type,
|
||||
}
|
||||
|
||||
|
||||
def _encode_common_query(query_list):
|
||||
"""将查询条件列表加密为 commonQuery(encodeURIComponent + 自定义 Base64 + 盐值 + 首尾重排)。"""
|
||||
json_str = json.dumps(query_list, ensure_ascii=False, separators=(',', ':'))
|
||||
uri_encoded = urllib.parse.quote(json_str, safe="-_.~!*'()")
|
||||
en_str = _custom_base64_encode(uri_encoded.encode('utf-8')) + _CQ_SALT
|
||||
return en_str[:2] + en_str[-3:] + en_str[2:-3]
|
||||
|
||||
|
||||
def _build_roster_query_params(roster_id, table_id, menu_name, common_query, today):
|
||||
"""构造 HR 台账实时查询(queryRealTimeData.mc)完整参数。
|
||||
roster/table/menu/commonQuery 按调用方传入,其余为通用固定参数(与页面抓包一致)。"""
|
||||
month_first = date(today.year, today.month, 1)
|
||||
now_ms = str(int(time.time() * 1000))
|
||||
return {
|
||||
"menuName": menu_name,
|
||||
"useSealTreeData": "0",
|
||||
"treePermitType": "permit",
|
||||
"_t": now_ms,
|
||||
"in_use": "1",
|
||||
"commonQuery": common_query,
|
||||
"newCondition": "",
|
||||
"urlConditions": f"_t:{now_ms}#treePermitType:permit#useSealTreeData:0#"
|
||||
f"menuName:{menu_name}#_t:{now_ms}#",
|
||||
"exportConfig": "",
|
||||
"tableId": table_id,
|
||||
"rosterId": roster_id,
|
||||
"includeChildrenSetting": "",
|
||||
"struTreeCode": "cq37du",
|
||||
"djStruTreeCode": "",
|
||||
"djStruId": "",
|
||||
"djOrgName": "",
|
||||
"struId": COMPANY_STRU_ID,
|
||||
"belongUnitStruId": COMPANY_STRU_ID,
|
||||
"rootId": "cq37du",
|
||||
"isVirtual": "0",
|
||||
"currentUserRootId": "cq37du",
|
||||
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
|
||||
"currentRoleIds": REJOIN_ROLE_IDS,
|
||||
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
|
||||
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
|
||||
"qrCodeUrl": "jspresumepage-01.jsp",
|
||||
"orgName": "集团",
|
||||
"belongUnitOrgName": "集团",
|
||||
"currentDate": today.strftime("%Y-%m-%d"),
|
||||
"currentMonth": today.strftime("%Y%m"),
|
||||
"currentMonthBar": today.strftime("%Y-%m"),
|
||||
"lastMonth": (month_first - timedelta(days=1)).strftime("%Y%m"),
|
||||
"lastMonFirstDay": (month_first - timedelta(days=1)).replace(day=1).strftime("%Y-%m-%d"),
|
||||
"lastMonLastDay": (month_first - timedelta(days=1)).strftime("%Y-%m-%d"),
|
||||
"curYearFirstMon": f"{today.year}01",
|
||||
"curYearFirstMonBar": f"{today.year}-01",
|
||||
"throughParam": "",
|
||||
"start": "0",
|
||||
"sortType": "",
|
||||
"sortName": "",
|
||||
"pageNo": "1",
|
||||
"pageSize": "15",
|
||||
}
|
||||
|
||||
|
||||
def _build_rejoin_query_params(today):
|
||||
"""构造「离职当月再入职人员算薪台账」实时查询参数(与页面抓包一致)。
|
||||
查询条件 = 离职日期 ∈ [本月1日, 今天](只取本月数据)。"""
|
||||
month_first = date(today.year, today.month, 1)
|
||||
common_query = _encode_common_query([
|
||||
_build_rejoin_condition(f"`{REJOIN_FIELD_PREFIX}.leave_date`", ">=",
|
||||
month_first.strftime("%Y-%m-%d"), left_bracket="(",
|
||||
input_type="date"),
|
||||
_build_rejoin_condition(f"`{REJOIN_FIELD_PREFIX}.leave_date`", "<=",
|
||||
today.strftime("%Y-%m-%d"), right_bracket=")",
|
||||
input_type="date"),
|
||||
])
|
||||
params = _build_roster_query_params(REJOIN_ROSTER_ID, REJOIN_TABLE_ID,
|
||||
"离职当月再入职人员算薪台账", common_query, today)
|
||||
params["pageSize"] = str(REJOIN_PAGE_SIZE)
|
||||
return params
|
||||
|
||||
|
||||
def _fetch_roster_page_retry(session, url, label, params):
|
||||
"""抓单页 HR 台账实时查询(queryRealTimeData.mc);登录态失效自动补登重试(上限 RELOGIN_MAX 次)。"""
|
||||
for attempt in range(1, RELOGIN_MAX + 1):
|
||||
try:
|
||||
resp = _request_with_retry(session, "POST", url, params, 30, label)
|
||||
text = resp.text
|
||||
if not text or not text.lstrip().startswith("{"):
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON)")
|
||||
data = resp.json()
|
||||
if data.get("state") == "Nosession":
|
||||
raise HRSessionExpiredError(f"{label}:HR 登录态失效(Nosession)")
|
||||
return session, data
|
||||
except HRSessionExpiredError:
|
||||
logger.warning("%s HR 登录态过期,自动补登后重试(第 %d/%d 次)",
|
||||
label, attempt, RELOGIN_MAX)
|
||||
session, _user_id = _relogin_get_user_info()
|
||||
raise HRSessionExpiredError(
|
||||
f"{label}:HR 登录态多次补登仍失效,请先重新运行「37duHR登录」指令再重试")
|
||||
|
||||
|
||||
def _fetch_rejoin_page_retry(session, today, page_no):
|
||||
"""抓单页离职当月再入职台账;登录态失效自动补登重试(上限 RELOGIN_MAX 次)。"""
|
||||
params = _build_rejoin_query_params(today)
|
||||
params["pageNo"] = str(page_no)
|
||||
params["start"] = str((page_no - 1) * REJOIN_PAGE_SIZE)
|
||||
return _fetch_roster_page_retry(session, REJOIN_QUERY_URL, "离职当月再入职台账", params)
|
||||
|
||||
|
||||
def fetch_all_rejoin_ledger(session, today):
|
||||
"""分页抓取离职当月再入职台账全量(离职日期 ∈ [本月1日, 今天],只取本月),
|
||||
返回接口原始记录列表。某页失败直接抛异常终止,绝不返回部分数据。"""
|
||||
all_rows = []
|
||||
page_no = 1
|
||||
while True:
|
||||
session, data = _fetch_rejoin_page_retry(session, today, page_no)
|
||||
if data.get("state") != "1":
|
||||
raise RuntimeError(f"离职当月再入职台账第 {page_no} 页请求失败:{data.get('meg')}")
|
||||
page_list = data.get("datas", []) or []
|
||||
if not page_list:
|
||||
logger.info("离职当月再入职台账无更多数据")
|
||||
break
|
||||
all_rows.extend(page_list)
|
||||
total_page = data.get("pageCount", 0)
|
||||
logger.info("离职当月再入职台账已抓取 %d/%d 页,累计 %d 条",
|
||||
page_no, total_page, len(all_rows))
|
||||
if page_no >= total_page:
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_rows
|
||||
|
||||
|
||||
def _fetch_leave_history_codes(session, idc):
|
||||
"""按身份证查「离职台账」历史工号(分页抓全),返回 {历史工号} 集合(含再入职工号本身时一并返回)。
|
||||
某页失败直接抛异常终止。"""
|
||||
today = date.today()
|
||||
all_codes = set()
|
||||
page_no = 1
|
||||
while True:
|
||||
params = _build_roster_query_params(
|
||||
LEAVE_ROSTER_ID, LEAVE_TABLE_ID, LEAVE_MENU,
|
||||
_encode_common_query([
|
||||
_build_rejoin_condition("`hr_staff_base.idCard`", "like", idc, input_type="text"),
|
||||
]), today)
|
||||
params["pageNo"] = str(page_no)
|
||||
params["pageSize"] = str(LEAVE_PAGE_SIZE)
|
||||
params["start"] = str((page_no - 1) * LEAVE_PAGE_SIZE)
|
||||
session, data = _fetch_roster_page_retry(session, LEAVE_QUERY_URL, LEAVE_MENU, params)
|
||||
if data.get("state") != "1":
|
||||
raise RuntimeError(f"{LEAVE_MENU}第 {page_no} 页请求失败:{data.get('meg')}")
|
||||
page_list = data.get("datas", []) or []
|
||||
for r in page_list:
|
||||
c = _clean(r.get("hr_staff_leaveoffice.base_code"))
|
||||
if c:
|
||||
all_codes.add(c)
|
||||
if not page_list or page_no >= (data.get("pageCount", 0) or 1):
|
||||
break
|
||||
page_no += 1
|
||||
time.sleep(0.2)
|
||||
return all_codes
|
||||
|
||||
|
||||
def _build_rejoin_old_codes(session, rejoin_rows):
|
||||
"""按身份证查「离职台账」,找出换工号再入职者的历史工号。
|
||||
返回 {再入职工号: {历史工号,...}}(仅当历史工号 ≠ 再入职工号时收录);无换工号则返回空 dict。"""
|
||||
result = {}
|
||||
cache = {} # idCard -> {工号},同一身份证只查一次
|
||||
for r in rejoin_rows:
|
||||
rejoin_code = _clean(r.get("hr_staff_base.base_code"))
|
||||
idc = _clean(r.get("hr_staff_base.idCard"))
|
||||
if not rejoin_code or not idc:
|
||||
continue
|
||||
if idc not in cache:
|
||||
cache[idc] = _fetch_leave_history_codes(session, idc)
|
||||
old = {c for c in cache[idc] if c and c != rejoin_code}
|
||||
if old:
|
||||
result[rejoin_code] = old
|
||||
logger.info("再入职人员 %s(%s)存在历史工号:%s",
|
||||
rejoin_code, _clean(r.get("hr_staff_base.staff_name")),
|
||||
"、".join(sorted(old)))
|
||||
return result
|
||||
|
||||
|
||||
def _blank_rejoin_gap(report_rows, rejoin_rows, old_codes_map=None):
|
||||
"""踢除离职当月再入职人员的无效积分段(在写入「考勤统计报表」前对 report_rows 就地清空):
|
||||
- 台账工号(再入职工号)记录:清空 [离职日, 再入职日) 中间段 → 离职段/再入职段两段积分各保准确;
|
||||
- 历史工号(离职台账按身份证查得、与再入职工号不同者)记录:清空 [再入职日, 月末]
|
||||
→ 删除再入职段不该有的积分("原工号删 10 号及之后"场景)。
|
||||
返回清空的考勤状态单元格数。
|
||||
安全约束:历史工号可能已被重新分配给他人使用,故旧工号清段时必须同时满足
|
||||
「报告行工号 = 历史工号 且 报告行姓名 = 再入职人姓名」,否则视为工号复用跳过,
|
||||
绝不做单纯同名或单纯工号匹配(避免误清他人积分)。"""
|
||||
old_codes_map = old_codes_map or {}
|
||||
gaps = {} # 台账工号 -> (leave_day, join_day)
|
||||
old_gaps = {} # 历史工号 -> (join_day, rejoin_name)
|
||||
for r in rejoin_rows:
|
||||
code = _clean(r.get("hr_staff_base.base_code"))
|
||||
name = _clean(r.get("hr_staff_base.staff_name"))
|
||||
ld = r.get(f"{REJOIN_FIELD_PREFIX}.leave_date")
|
||||
jd = r.get(f"{REJOIN_FIELD_PREFIX}.join_date")
|
||||
if not code or not ld or not jd:
|
||||
continue
|
||||
try:
|
||||
leave = date.fromisoformat(str(ld).strip()[:10])
|
||||
join = date.fromisoformat(str(jd).strip()[:10])
|
||||
except ValueError:
|
||||
continue
|
||||
gaps[code] = (leave.day, join.day)
|
||||
for old_code in old_codes_map.get(code, ()):
|
||||
old_gaps[old_code] = (join.day, name)
|
||||
if not gaps and not old_gaps:
|
||||
return 0
|
||||
|
||||
cleared = 0
|
||||
for row in report_rows:
|
||||
code, row_name = row[0], row[8]
|
||||
if code in gaps:
|
||||
leave_day, join_day = gaps[code]
|
||||
for d in range(leave_day, join_day):
|
||||
if 1 <= d <= 31 and row[8 + d] not in (None, ""):
|
||||
row[8 + d] = ""
|
||||
cleared += 1
|
||||
elif code in old_gaps:
|
||||
join_day, rejoin_name = old_gaps[code]
|
||||
if row_name != rejoin_name:
|
||||
continue # 该历史工号现为他人使用(工号复用),不清,避免误清他人积分
|
||||
for d in range(join_day, 32):
|
||||
if 1 <= d <= 31 and row[8 + d] not in (None, ""):
|
||||
row[8 + d] = ""
|
||||
cleared += 1
|
||||
return cleared
|
||||
|
||||
|
||||
def write_rejoin_sheet(wb, rows):
|
||||
"""「当月再入职名单」:追加写入当月再入职台账,已存在行不重写。
|
||||
判定:按 H 再入职工号匹配(台账按月累加,每日只追加新出现的再入职人员)。
|
||||
已存在行保持原样(人工备注/工号/积分天数等均不被覆盖);
|
||||
仅新行写 B门店 C姓名 F离职日期 G再入职日期 H再入职工号,I备注沿用台账 remark;
|
||||
D员工工号/E合计享受出勤积分天数留空人工维护。"""
|
||||
ws = wb[SHEET_REJOIN]
|
||||
last = _scan_last_data_row(ws, 2, REJOIN_DATA_START)
|
||||
existing = set()
|
||||
for r in range(REJOIN_DATA_START, last + 1):
|
||||
code = _clean(ws.cell(row=r, column=8).value)
|
||||
if code:
|
||||
existing.add(code)
|
||||
out = []
|
||||
for r in rows:
|
||||
code = _clean(r.get("hr_staff_base.base_code"))
|
||||
if not code or code in existing:
|
||||
continue
|
||||
existing.add(code)
|
||||
out.append([
|
||||
_clean(r.get("pt_staff_stru.DEPT_ORG_FOUR")), # B 门店(四级部门=会馆)
|
||||
_clean(r.get("hr_staff_base.staff_name")), # C 员工姓名
|
||||
"", # D 员工工号(人工维护)
|
||||
"", # E 合计享受出勤积分天数(人工维护)
|
||||
_clean(r.get(f"{REJOIN_FIELD_PREFIX}.leave_date")), # F 离职日期
|
||||
_clean(r.get(f"{REJOIN_FIELD_PREFIX}.join_date")), # G 再入职日期
|
||||
code, # H 再入职工号(接口唯一工号)
|
||||
_clean(r.get(f"{REJOIN_FIELD_PREFIX}.remark")), # I 备注(人工登记,脚本不生成)
|
||||
])
|
||||
if out:
|
||||
n = _write_block(ws, last + 1, out, col_start=2, old_last_row=last, col_count=8)
|
||||
else:
|
||||
n = 0
|
||||
logger.info("当月再入职名单:新增 %d 行(原数据至第 %d 行,已存在 %d 人不重写)",
|
||||
len(out), last, len(rows) - len(out))
|
||||
return n
|
||||
|
||||
|
||||
# ==================== COM 重算 ====================
|
||||
def calc_and_save_via_com(target_file):
|
||||
"""经 WPS/Excel COM 打开目标文件:取消全部筛选 → 全量重算公式 → 保存关闭。
|
||||
@@ -755,6 +1130,9 @@ def write_import_sheet(wb, today, t2, new_rows, fix_rows, state, file_key, is_ne
|
||||
for info, d in fix_rows:
|
||||
out.append(list(info) + [datetime(d.year, d.month, d.day)])
|
||||
_write_block(ws, last + 1, out, col_start=2, old_last_row=last)
|
||||
# K 列积分日期统一显示格式 yyyy/m/d(值与模板兼容,仍为日期类型)
|
||||
for r in range(last + 1, last + 1 + len(out)):
|
||||
ws.cell(row=r, column=11).number_format = "yyyy/m/d"
|
||||
|
||||
# 登记本轮新增段日期(幂等:集合去重)
|
||||
dates = set(state.setdefault(file_key, {}).setdefault("new_dates", []))
|
||||
@@ -785,6 +1163,9 @@ def write_delete_sheet(wb, today, t2, del_rows):
|
||||
last = _scan_last_data_row(ws, 2, IMP_DATA_START)
|
||||
out = [list(info) + [datetime(d.year, d.month, d.day)] for info, d in del_rows]
|
||||
_write_block(ws, last + 1, out, col_start=2, old_last_row=last)
|
||||
# K 列积分日期统一显示格式 yyyy/m/d
|
||||
for r in range(last + 1, last + 1 + len(out)):
|
||||
ws.cell(row=r, column=11).number_format = "yyyy/m/d"
|
||||
logger.info("积分删除:删除旧行 %d,追加修正删行 %d 行,现共 %d 行",
|
||||
removed, len(out), _scan_last_data_row(ws, 2, IMP_DATA_START) - IMP_DATA_START + 1)
|
||||
return len(out)
|
||||
@@ -800,18 +1181,25 @@ def main(args=None):
|
||||
logger.info("===== XQ0033 门店管理及服务岗出勤积分更新开始,运行日 %s,T-2=%s,报表月份 %s =====",
|
||||
today, t2, month)
|
||||
|
||||
# 1. HR 登录态 + 分页拉取当月考勤统计报表
|
||||
# 1. HR 登录态 + 分页拉取当月考勤统计报表(登录失效自动补登;未登录给出明确提示)
|
||||
session = build_hr_session()
|
||||
info = fetch_cur_user_info(session)
|
||||
user_id = info.get("userId", "")
|
||||
if not user_id:
|
||||
raise RuntimeError("获取当前用户信息失败:userId 为空")
|
||||
session, user_id = _ensure_cur_user_info(session)
|
||||
raw_rows = fetch_all_attendance_stat(session, user_id, month)
|
||||
if not raw_rows:
|
||||
raise RuntimeError(f"考勤统计报表 {month} 无数据,请检查月份或权限")
|
||||
report_rows = [report_row_to_list(rec) for rec in raw_rows]
|
||||
logger.info("考勤统计报表共 %d 人", len(report_rows))
|
||||
|
||||
# 1b. 离职当月再入职人员算薪台账(实时查询接口,无导出)→ 供「当月再入职名单」
|
||||
rejoin_rows = fetch_all_rejoin_ledger(session, today)
|
||||
logger.info("离职当月再入职台账共 %d 人", len(rejoin_rows))
|
||||
# 1c. 按身份证查离职台账,找换工号再入职的历史工号(清旧工号再入职段用)
|
||||
old_codes_map = _build_rejoin_old_codes(session, rejoin_rows) if rejoin_rows else {}
|
||||
# 1d. 踢除再入职人员无效积分段(中间段 + 旧工号再入职段)
|
||||
cleared = _blank_rejoin_gap(report_rows, rejoin_rows, old_codes_map)
|
||||
if cleared:
|
||||
logger.info("已踢除离职当月再入职人员无效积分段 %d 个考勤状态", cleared)
|
||||
|
||||
# 2. 选择目标文件
|
||||
target_path, is_new_batch = pick_target_file(today)
|
||||
file_key = os.path.basename(target_path)
|
||||
@@ -819,11 +1207,13 @@ def main(args=None):
|
||||
|
||||
# 3. 写「考勤统计报表」+ 快照滚动(旧今日导出 → 前一日导出)
|
||||
wb = openpyxl.load_workbook(target_path, data_only=False)
|
||||
for name in (SHEET_REPORT, SHEET_TODAY, SHEET_PREV, SHEET_CMP, SHEET_IMPORT, SHEET_DELETE):
|
||||
for name in (SHEET_REPORT, SHEET_TODAY, SHEET_PREV, SHEET_CMP, SHEET_IMPORT, SHEET_DELETE,
|
||||
SHEET_REJOIN):
|
||||
if name not in wb.sheetnames:
|
||||
raise RuntimeError(f"目标文件缺少工作表「{name}」,请确认模板完整")
|
||||
write_report_sheet(wb, report_rows, today.year, today.month)
|
||||
copy_today_to_prev(wb)
|
||||
write_rejoin_sheet(wb, rejoin_rows)
|
||||
wb.save(target_path)
|
||||
wb.close()
|
||||
|
||||
|
||||
Reference in New Issue
Block a user