refactor: 替换排班/打卡接口为考勤逐日接口,清理旧依赖
1. 重构考勤相关接口:将get_attendance_html、get_attendance_records替换为get_attendance_daily,使用新的ATTENDANCE_DAILY_URL接口替代旧接口 2. 更新请假校验逻辑:使用考勤逐日接口统计上班天数,替换原跨月排班HTML请求逻辑 3. 升级测试用例:同步更新test_03_attendance.py和test_06_leave_online.py适配新接口 4. 新增/完善文档:新增多份流程与需求文档,删除旧版冗余文档,整理docs目录结构 5. 清理废弃文件:删除原周考勤异常、门店请休假异常相关旧需求文档 6. 配置更新:更新config.py中的考勤相关URL常量,补充注释说明 7. 待办优化:更新aa.md内容,同步加班审批规则说明
This commit is contained in:
@@ -26,11 +26,11 @@ WF_ACTIVITY_URL = f"{HR_BASE_URL}/RedseaPlatform/WfActivity.mc"
|
||||
# 表单引擎接口:通过 businessKey + formId 获取审批单的表单数据(如加班日期、申请人等)
|
||||
WORKFORM_ENGINE_URL = f"{HR_BASE_URL}/RedseaPlatform/WorkformEngine.mc"
|
||||
|
||||
# 排班接口(hr 域名,按员工 + 年月查询当月排班)
|
||||
PAIBAN_URL = f"{HR_BASE_URL}/RedseaPlatform/KqCount.mc"
|
||||
|
||||
# 考勤打卡明细接口(hr 域名,按员工 + 日期范围查询原始打卡记录)
|
||||
KQ_DATA_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_data_queryByStaffId_all/getExecuteResult.mc"
|
||||
# 考勤逐日接口(hr 域名,按员工 + 日期范围查询每日班次起止与上下班打卡,返回 data 数组)
|
||||
# 加班/请假流程校验统一使用该接口获取排班名/班次时段/上下班打卡,替代原排班日历接口与打卡流水接口。
|
||||
# 注意:kq_status_total 按考勤状态分类返回(0=休息日、1=正常班、9=未打卡、11=异常),
|
||||
# 需四种状态各查一次后按 work_day 合并去重,才能拿到全部班次信息与当天打卡。
|
||||
ATTENDANCE_DAILY_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_count_leave_yc_day_all/redApiExec.mc"
|
||||
|
||||
# 请假记录接口(hr 域名,按员工 + 日期范围查询请假明细)
|
||||
LEAVE_RECORD_URL = f"{HR_BASE_URL}/RedseaPlatform/redmagicapi/rf_s_kq_leave_record_SelectByStaffID/redApiExec.mc"
|
||||
@@ -43,7 +43,8 @@ ATTACHMENT_SAVE_DIR = r"D:\资料\人资\请假流程审批\附件"
|
||||
# ---------- 加班审批规则常量(对应 aa.md 审批规则) ----------
|
||||
# 次日正常上班时间 T(固定 09:00)
|
||||
WORK_START_TIME = "09:00"
|
||||
# 当日规定下班时间(固定 18:00,用于区间合规校验)
|
||||
# 当日规定下班时间兜底值:区间合规校验优先取员工当天排班结束时间(bc_end_time),
|
||||
# 未获取到排班时段时才回退该默认值
|
||||
WORK_END_TIME = "18:00"
|
||||
# 弹性额度触发阈值:实际下班打卡时间 >= 该时刻才计算弹性额度 D
|
||||
FLEX_TRIGGER_TIME = "23:00"
|
||||
|
||||
@@ -25,8 +25,7 @@ from app.service.hrbp.oa.common.oa_api.flow import (
|
||||
download_attachment,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.attendance import (
|
||||
get_attendance_html,
|
||||
get_attendance_records,
|
||||
get_attendance_daily,
|
||||
)
|
||||
from app.service.hrbp.oa.common.oa_api.leave import (
|
||||
fetch_leave_record_page,
|
||||
@@ -44,8 +43,7 @@ __all__ = [
|
||||
"extract_form_id",
|
||||
"get_business_data",
|
||||
"download_attachment",
|
||||
"get_attendance_html",
|
||||
"get_attendance_records",
|
||||
"get_attendance_daily",
|
||||
"fetch_leave_record_page",
|
||||
"get_leave_records",
|
||||
]
|
||||
|
||||
@@ -2,8 +2,8 @@
|
||||
"""
|
||||
@Module: hrbp.oa.common.oa_api
|
||||
@FileName: attendance.py
|
||||
@Description: 排班 HTML 与考勤打卡明细接口。
|
||||
@Version: 1.0.0
|
||||
@Description: 考勤逐日接口(按员工 + 日期范围查询每日班次与上下班打卡)。
|
||||
@Version: 1.3.0
|
||||
"""
|
||||
|
||||
from typing import List, Dict, Any
|
||||
@@ -14,60 +14,26 @@ try:
|
||||
except ImportError:
|
||||
SessionPage = None
|
||||
|
||||
from app.service.hrbp.oa.common.config import PAIBAN_URL, KQ_DATA_URL
|
||||
from app.service.hrbp.oa.common.config import ATTENDANCE_DAILY_URL
|
||||
from app.service.hrbp.oa.common.oa_api.base import oa_request_json
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
def get_attendance_html(
|
||||
session: SessionPage,
|
||||
staff_id: str,
|
||||
year: int,
|
||||
month: int
|
||||
) -> str:
|
||||
"""
|
||||
获取指定员工某月的排班 HTML。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
staff_id: 员工 UUID
|
||||
year: 年份(如 2026)
|
||||
month: 月份(1-12)
|
||||
|
||||
Returns:
|
||||
排班表格的 HTML 字符串(从返回 JSON 的 caleHtml 字段提取)
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
"""
|
||||
url = f"{PAIBAN_URL}?method=geRenPaibanByMonth"
|
||||
data = {
|
||||
"type": "2",
|
||||
"staffId": staff_id,
|
||||
"year": str(year),
|
||||
"month": str(month)
|
||||
}
|
||||
logger.info("获取排班: %s %d-%02d", staff_id, year, month)
|
||||
json_data = oa_request_json(session, "POST", url, data, "排班")
|
||||
|
||||
if json_data.get("success") != "true":
|
||||
raise RuntimeError(f"排班接口返回失败: {json_data}")
|
||||
|
||||
html = json_data.get("caleHtml")
|
||||
if not html:
|
||||
raise RuntimeError("排班接口未返回 caleHtml 字段")
|
||||
return html
|
||||
|
||||
|
||||
def get_attendance_records(
|
||||
def get_attendance_daily(
|
||||
session: SessionPage,
|
||||
staff_id: str,
|
||||
start_date: str,
|
||||
end_date: str
|
||||
) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
查询员工某时间段的原始打卡明细。
|
||||
按员工 + 日期范围查询每日考勤(含班次起止时间与上下班打卡)。
|
||||
|
||||
接口: rf_s_kq_count_leave_yc_day_all/redApiExec.mc
|
||||
kq_status_total 按考勤状态分类返回记录(来源为前端 JS 扒取的请求构造):
|
||||
- 0=休息日、1=正常班、9=未打卡、11=异常(如上班漏打卡)
|
||||
因此需按这四种状态各查一次,再按 work_day 合并去重,才能同时拿到
|
||||
班次名/班次时段与休息日、异常班当天的上下班打卡。
|
||||
|
||||
Args:
|
||||
session: 已登录的 SessionPage 对象
|
||||
@@ -76,25 +42,23 @@ def get_attendance_records(
|
||||
end_date: 查询结束日期 "YYYY-MM-DD"
|
||||
|
||||
Returns:
|
||||
打卡记录列表(接口返回的 jsonList,每条含 kq_time / status / time_order 等)
|
||||
- status: "1"=上班打卡, "5"=下班打卡, "6"=重复打卡
|
||||
- time_order: "1"=上班时段, "2"=下班时段
|
||||
|
||||
Raises:
|
||||
RuntimeError: 请求失败或响应异常
|
||||
每日考勤记录列表(四种状态合并去重后,按日期升序)
|
||||
"""
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"rootId": "",
|
||||
"countId": "",
|
||||
"bc_date": start_date,
|
||||
"bc_date_end": end_date,
|
||||
"begin": start_date,
|
||||
"end": end_date,
|
||||
}
|
||||
logger.info("获取打卡明细: staff_id=%s, %s 至 %s", staff_id, start_date, end_date)
|
||||
json_data = oa_request_json(session, "GET", KQ_DATA_URL, params, "考勤打卡")
|
||||
|
||||
records = json_data.get("jsonList", [])
|
||||
logger.info("打卡明细返回 %d 条", len(records))
|
||||
by_day: Dict[str, Dict[str, Any]] = {}
|
||||
for status in ("0", "1", "9", "11"):
|
||||
params = {
|
||||
"staff_id": staff_id,
|
||||
"begin_date": start_date,
|
||||
"end_date": end_date,
|
||||
"kq_status_total": status,
|
||||
}
|
||||
logger.info(
|
||||
"获取考勤逐日(kq_status_total=%s): staff_id=%s, %s 至 %s",
|
||||
status, staff_id, start_date, end_date,
|
||||
)
|
||||
json_data = oa_request_json(session, "POST", ATTENDANCE_DAILY_URL, params, "考勤逐日")
|
||||
for r in json_data.get("data", []) or []:
|
||||
by_day.setdefault(str(r.get("work_day", "")), r)
|
||||
records = [by_day[k] for k in sorted(by_day)]
|
||||
logger.info("考勤逐日合并返回 %d 天", len(records))
|
||||
return records
|
||||
|
||||
@@ -100,6 +100,13 @@ def parse_todo_list(data: Dict[str, Any]) -> List[Dict[str, Any]]:
|
||||
if detail_url and not detail_url.startswith(("http://", "https://")):
|
||||
detail_url = BASE_URL + detail_url
|
||||
|
||||
# 跳过"工作沟通/协作"类待办(如"请回复…与您的工作沟通:加班申请"):
|
||||
# 链接指向协作模块 kmCollaborateMain.do,非审批工作流,SSO 后仅到
|
||||
# unifyWorkFlow.jsp?fkId=… 拿不到 businessKey,永远无法解析,直接跳过避免无谓重试
|
||||
if "kmCollaborateMain.do" in detail_url:
|
||||
logger.warning("跳过非审批待办(工作沟通/协作): %s", title)
|
||||
continue
|
||||
|
||||
docs.append({
|
||||
"title": title,
|
||||
"creator": creator,
|
||||
|
||||
@@ -1,183 +0,0 @@
|
||||
# -*- coding: utf-8 -*-
|
||||
"""
|
||||
@Module: hrbp.oa.parser
|
||||
@FileName: parser.py
|
||||
@Author: 小布丁
|
||||
@CreateTime: 2026-08-05 17:10
|
||||
@Description: 解析模块(HTML 排班表格解析,供请假校验使用)
|
||||
@Version: 1.3.0
|
||||
"""
|
||||
|
||||
import re
|
||||
from collections import defaultdict
|
||||
from datetime import datetime
|
||||
from typing import Any, Dict, List
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
logger = get_logger(__name__)
|
||||
|
||||
|
||||
# ---------- 排班 HTML 解析 ----------
|
||||
def parse_attendance_html(html: str) -> Dict[str, str]:
|
||||
"""
|
||||
解析排班 HTML 表格,提取每个日期的班次名称。
|
||||
|
||||
实际 HTML 结构(属性用单引号):
|
||||
<a class='cale_a' title='经营正班A' short_bc_name='经营A'
|
||||
data-temp='2026-08-03' finalState='' onclick="...">正常</a>
|
||||
|
||||
- data-temp: 日期
|
||||
- title: 班次全称(如 经营正班A、职能正班A、休息)
|
||||
- 文本内容: 考勤状态(如 正常、异常、休息)
|
||||
|
||||
Args:
|
||||
html: 排班接口返回的 HTML 字符串
|
||||
|
||||
Returns:
|
||||
字典:{日期字符串: 班次名称}
|
||||
例如:{"2026-08-01": "休息", "2026-08-03": "经营正班A"}
|
||||
"""
|
||||
if not html:
|
||||
return {}
|
||||
|
||||
result = {}
|
||||
# 匹配含 data-temp 属性的 <a> 标签,兼容单引号和双引号
|
||||
a_tag_pattern = r"""<a\b[^>]*\bdata-temp=['"]([^'"]+)['"][^>]*>([^<]*)</a>"""
|
||||
|
||||
for match in re.finditer(a_tag_pattern, html, re.DOTALL):
|
||||
date_str = match.group(1).strip()
|
||||
text_content = match.group(2).strip()
|
||||
|
||||
# 从完整标签中提取 title 属性(班次名称),同样兼容单/双引号
|
||||
full_tag = match.group(0)
|
||||
title_match = re.search(r"""\btitle=['"]([^'"]*)['"]""", full_tag)
|
||||
shift_name = title_match.group(1).strip() if title_match else ""
|
||||
|
||||
# 优先使用 title(班次名称),休息日 title='休息'
|
||||
if shift_name:
|
||||
# 考勤异常时附加标注,便于报告展示
|
||||
if text_content and text_content == "异常":
|
||||
result[date_str] = f"{shift_name}(异常)"
|
||||
else:
|
||||
result[date_str] = shift_name
|
||||
else:
|
||||
result[date_str] = text_content
|
||||
|
||||
return result
|
||||
|
||||
|
||||
def get_work_days_in_range(
|
||||
attendance_dict: Dict[str, str],
|
||||
start_date: str,
|
||||
end_date: str
|
||||
) -> List[str]:
|
||||
"""
|
||||
根据排班字典和请假起止日期,返回请假区间内所有非“休息”的日期列表。
|
||||
|
||||
Args:
|
||||
attendance_dict: 由 parse_attendance_html 返回的字典
|
||||
start_date: 请假开始日期,格式 "YYYY-MM-DD"
|
||||
end_date: 请假结束日期,格式 "YYYY-MM-DD"
|
||||
|
||||
Returns:
|
||||
非休息日的日期字符串列表(格式 "YYYY-MM-DD")
|
||||
"""
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
start = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
|
||||
work_days = []
|
||||
current = start
|
||||
while current <= end:
|
||||
date_str = current.strftime("%Y-%m-%d")
|
||||
shift = attendance_dict.get(date_str, "")
|
||||
# 如果该日期没有排班信息,或明确为“休息”,视为休息日
|
||||
if shift != "休息" and shift != "":
|
||||
work_days.append(date_str)
|
||||
current += timedelta(days=1)
|
||||
return work_days
|
||||
|
||||
|
||||
# ---------- 打卡明细汇总 ----------
|
||||
def summarize_attendance_records(records: List[Dict[str, Any]]) -> List[Dict[str, Any]]:
|
||||
"""
|
||||
按日汇总员工打卡明细:每天取最早打卡和最晚打卡。
|
||||
|
||||
实际接口返回的打卡记录 status 多为 "6"、time_order 为 null,
|
||||
无法据其区分上下班,因此直接按 bc_date 分组后取时间最早和最晚的打卡。
|
||||
|
||||
Args:
|
||||
records: get_attendance_records 返回的原始打卡列表
|
||||
|
||||
Returns:
|
||||
每日汇总列表,每项含:
|
||||
- staff_id / staff_name / dept_name / post_name / attend_date
|
||||
- first_check_in: 当日最早打卡时间(字符串,无则 None)
|
||||
- last_check_out: 当日最晚打卡时间(字符串,仅1条时为 None,含跨天凌晨)
|
||||
"""
|
||||
time_format = "%Y-%m-%d %H:%M:%S"
|
||||
|
||||
# 按 (staff_id, bc_date) 分组,取每天最早和最晚的打卡
|
||||
group_map: Dict[tuple, List[Dict[str, Any]]] = defaultdict(list)
|
||||
|
||||
for item in records:
|
||||
staff_id = item.get("staff_id", "")
|
||||
bc_day = item.get("bc_date", "")
|
||||
if not staff_id or not bc_day:
|
||||
continue
|
||||
|
||||
try:
|
||||
kq_dt = datetime.strptime(item["kq_time"], time_format)
|
||||
except (KeyError, ValueError):
|
||||
continue
|
||||
|
||||
group_map[(staff_id, bc_day)].append({**item, "_dt": kq_dt})
|
||||
|
||||
summary: List[Dict[str, Any]] = []
|
||||
for (sid, day), items in group_map.items():
|
||||
items.sort(key=lambda x: x["_dt"])
|
||||
base = items[0]
|
||||
row = {
|
||||
"staff_id": sid,
|
||||
"staff_name": base.get("staff_name", ""),
|
||||
"dept_name": base.get("DEPT_ORG_NAME", ""),
|
||||
"post_name": base.get("POST_ALIAS_NAME", ""),
|
||||
"attend_date": day,
|
||||
"first_check_in": items[0]["kq_time"],
|
||||
"last_check_out": items[-1]["kq_time"] if len(items) > 1 else None,
|
||||
}
|
||||
summary.append(row)
|
||||
|
||||
return summary
|
||||
|
||||
|
||||
# ---------- 使用示例(测试用) ----------
|
||||
if __name__ == "__main__":
|
||||
from app.utils.logger import setup_logging
|
||||
setup_logging()
|
||||
|
||||
# 测试 HTML 解析(样例与真实接口一致,使用单引号)
|
||||
sample_html = """
|
||||
<a class='cale_a' href='javascript:;' title='休息' data-temp='2026-08-01' >休息</a>
|
||||
<a class='cale_a' href='javascript:;' title='经营正班A' data-temp='2026-08-02' >正常</a>
|
||||
<a class='cale_a' href='javascript:;' title='经营正班A' data-temp='2026-08-03' >异常</a>
|
||||
"""
|
||||
result = parse_attendance_html(sample_html)
|
||||
logger.info("解析结果: %s", result)
|
||||
|
||||
work = get_work_days_in_range(result, "2026-08-01", "2026-08-03")
|
||||
logger.info("工作日: %s", work)
|
||||
|
||||
# 测试打卡汇总
|
||||
sample_records = [
|
||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
||||
"kq_time": "2026-08-02 08:50:00", "status": "1", "time_order": "1",
|
||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
||||
{"staff_id": "S001", "staff_name": "张三", "bc_date": "2026-08-02",
|
||||
"kq_time": "2026-08-03 00:30:00", "status": "5", "time_order": "2",
|
||||
"DEPT_ORG_NAME": "技术部", "POST_ALIAS_NAME": "工程师"},
|
||||
]
|
||||
summary = summarize_attendance_records(sample_records)
|
||||
logger.info("打卡汇总: %s", summary)
|
||||
@@ -10,18 +10,17 @@
|
||||
- 事假/调休假/半天休/普通事假等:排班上班天数与填报天数一致 -> 通过,否则驳回
|
||||
- 病假/特别福利假/特殊事假/产假:天数一致 + 已上传附件 -> 人工复核(附件内容需人工核验);
|
||||
天数不一致或缺附件 -> 驳回
|
||||
2. 排班数据获取:调用排班接口,解析 HTML 表格,提取非"休息"日期
|
||||
@Version: 4.0.0
|
||||
2. 排班数据获取:调用考勤逐日接口,统计请假区间内非"休息"天数
|
||||
@Version: 4.1.0
|
||||
"""
|
||||
|
||||
from datetime import datetime
|
||||
from datetime import datetime, timedelta
|
||||
import math
|
||||
from typing import Any, Dict, List, Tuple
|
||||
from typing import Any, Dict, Tuple
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
from app.service.hrbp.oa.leave.parser import VACATION_TYPE_MAP, _resolve_vacation_type, _parse_leave_form
|
||||
from app.service.hrbp.oa.common.oa_api import get_attendance_html, download_attachment
|
||||
from app.service.hrbp.oa.common.parser import parse_attendance_html, get_work_days_in_range
|
||||
from app.service.hrbp.oa.common.oa_api import get_attendance_daily, download_attachment
|
||||
from app.utils.ocr import check_leave_attachment, marriage_within_one_year
|
||||
|
||||
logger = get_logger(__name__)
|
||||
@@ -54,46 +53,33 @@ def _get_date_range(start_time: str, end_time: str) -> Tuple[str, str]:
|
||||
return start_date, end_date
|
||||
|
||||
|
||||
def _get_months_in_range(start_date: str, end_date: str) -> List[Tuple[int, int]]:
|
||||
"""
|
||||
获取日期范围内所有 (year, month) 元组列表。
|
||||
若请假跨月,按月份分段请求,合并结果。
|
||||
"""
|
||||
start = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
months = []
|
||||
current = start.replace(day=1)
|
||||
while current <= end:
|
||||
months.append((current.year, current.month))
|
||||
# 下个月第一天
|
||||
if current.month == 12:
|
||||
current = current.replace(year=current.year + 1, month=1)
|
||||
else:
|
||||
current = current.replace(month=current.month + 1)
|
||||
return months
|
||||
|
||||
|
||||
def _get_work_days_count(session: Any, staff_id: str, start_date: str, end_date: str) -> int:
|
||||
"""
|
||||
获取请假区间内实际上班天数(非休息日)。
|
||||
|
||||
若请假跨月,按月份分段请求排班数据,合并结果后计算。
|
||||
数据源为考勤逐日接口(rf_s_kq_count_leave_yc_day_all),按日期范围一次查询,
|
||||
返回区间内每天的班次名(bc_name,休息日为"休息"),据此统计非休息的天数。
|
||||
"""
|
||||
months = _get_months_in_range(start_date, end_date)
|
||||
attendance = {}
|
||||
for year, month in months:
|
||||
try:
|
||||
html = get_attendance_html(session, staff_id, year, month)
|
||||
monthly = parse_attendance_html(html)
|
||||
attendance.update(monthly)
|
||||
logger.info("排班数据已获取: %d-%02d, 共 %d 天", year, month, len(monthly))
|
||||
except Exception as e:
|
||||
logger.warning("获取排班失败(%d-%02d): %s", year, month, str(e))
|
||||
try:
|
||||
records = get_attendance_daily(session, staff_id, start_date, end_date)
|
||||
logger.info("排班数据已获取: %s ~ %s, 共 %d 天", start_date, end_date, len(records))
|
||||
except Exception as e:
|
||||
logger.warning("获取排班失败(%s~%s): %s", start_date, end_date, str(e))
|
||||
records = []
|
||||
|
||||
if not attendance:
|
||||
if not records:
|
||||
raise RuntimeError("未能获取到任何排班数据")
|
||||
|
||||
work_days = get_work_days_in_range(attendance, start_date, end_date)
|
||||
attendance = {str(r.get("work_day", "")): r.get("bc_name", "") for r in records}
|
||||
work_days = []
|
||||
current = datetime.strptime(start_date, "%Y-%m-%d")
|
||||
end_dt = datetime.strptime(end_date, "%Y-%m-%d")
|
||||
while current <= end_dt:
|
||||
day = current.strftime("%Y-%m-%d")
|
||||
if attendance.get(day) not in (None, "", "休息"):
|
||||
work_days.append(day)
|
||||
current += timedelta(days=1)
|
||||
|
||||
logger.info("请假区间 %s ~ %s,实际上班天数: %d", start_date, end_date, len(work_days))
|
||||
return len(work_days)
|
||||
|
||||
|
||||
@@ -8,9 +8,10 @@
|
||||
@Version: 3.2.0
|
||||
"""
|
||||
|
||||
import calendar
|
||||
import math
|
||||
from datetime import datetime, timedelta
|
||||
from typing import Any, Dict, Optional
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
from app.utils.logger import get_logger
|
||||
|
||||
@@ -18,11 +19,9 @@ logger = get_logger(__name__)
|
||||
|
||||
from app.service.hrbp.oa.work_overtime.parser import parse_overtime_form
|
||||
from app.service.hrbp.oa.common.oa_api import (
|
||||
get_attendance_html,
|
||||
get_attendance_records,
|
||||
get_attendance_daily,
|
||||
get_leave_records,
|
||||
)
|
||||
from app.service.hrbp.oa.common.parser import parse_attendance_html, summarize_attendance_records
|
||||
from app.service.hrbp.oa.common.config import (
|
||||
WORK_START_TIME,
|
||||
WORK_END_TIME,
|
||||
@@ -124,15 +123,21 @@ def _is_spring_festival(date_str: str) -> bool:
|
||||
|
||||
# ---------- 排班 / 打卡 / 请假查询 ----------
|
||||
def _get_shift(session: Any, staff_id: str, date_str: str) -> str:
|
||||
"""获取指定日期员工的排班班次(自动处理跨月)"""
|
||||
"""获取指定日期员工的排班班次(数据源为考勤逐日接口的 bc_name)"""
|
||||
if not date_str or not staff_id:
|
||||
return "未知"
|
||||
try:
|
||||
year = int(date_str[:4])
|
||||
month = int(date_str[5:7])
|
||||
html = get_attendance_html(session, staff_id, year, month)
|
||||
attendance = parse_attendance_html(html)
|
||||
return attendance.get(date_str, "无排班")
|
||||
records = get_attendance_daily(session, staff_id, date_str, date_str)
|
||||
for r in records:
|
||||
if str(r.get("work_day", "")) == date_str:
|
||||
bc = r.get("bc_name")
|
||||
if bc:
|
||||
return str(bc)
|
||||
# 休息日记录 bc_name 为空,以异常状态标识判断(abnormal_name/kq_status_name1)
|
||||
if str(r.get("abnormal_name") or r.get("kq_status_name1") or "") == "休息":
|
||||
return "休息"
|
||||
return "无排班"
|
||||
return "无排班"
|
||||
except Exception as e:
|
||||
logger.warning("获取排班失败(%s): %s", date_str, str(e))
|
||||
return "获取失败"
|
||||
@@ -142,8 +147,8 @@ def _is_zhineng_schedule(session: Any, staff_id: str, date_str: str) -> bool:
|
||||
"""
|
||||
判断员工是否为职能排班(休息日/节假日加班半天规则专用)。
|
||||
|
||||
不看加班当天(当天排班通常显示'休息'),而是查看当月排班日历中的其他天:
|
||||
只要任一班次包含'职能'(如 职能正班A),即按职能排班处理。
|
||||
不看加班当天(当天排班通常显示'休息'),而是查看当月每日考勤中的其他天:
|
||||
只要任一天班次包含'职能'(如 职能正班A),即按职能排班处理。
|
||||
排班获取失败时优雅降级返回 False,沿用默认半天4小时规则。
|
||||
"""
|
||||
if not date_str or not staff_id:
|
||||
@@ -151,9 +156,10 @@ def _is_zhineng_schedule(session: Any, staff_id: str, date_str: str) -> bool:
|
||||
try:
|
||||
year = int(date_str[:4])
|
||||
month = int(date_str[5:7])
|
||||
html = get_attendance_html(session, staff_id, year, month)
|
||||
attendance = parse_attendance_html(html)
|
||||
return any("职能" in (shift or "") for shift in attendance.values())
|
||||
first_day = f"{year:04d}-{month:02d}-01"
|
||||
last_day = f"{year:04d}-{month:02d}-{calendar.monthrange(year, month)[1]:02d}"
|
||||
records = get_attendance_daily(session, staff_id, first_day, last_day)
|
||||
return any("职能" in (r.get("bc_name") or "") for r in records)
|
||||
except Exception as e:
|
||||
logger.warning("获取排班判断职能失败(%s): %s", date_str, str(e))
|
||||
return False
|
||||
@@ -164,6 +170,87 @@ def _check_attendance(session: Any, staff_id: str, ot_date: str) -> Dict[str, An
|
||||
return {"加班当天班次": _get_shift(session, staff_id, ot_date)}
|
||||
|
||||
|
||||
def _extract_shift_times(daily_records: List[Dict[str, Any]], date_str: str) -> tuple:
|
||||
"""从每日考勤记录中提取指定日期的班次起止时间("HH:MM"),无则返回 (None, None)。
|
||||
|
||||
数据源为 rf_s_kq_count_leave_yc_day_all 接口返回的每日记录
|
||||
(字段 work_day + bc_begin_time/bc_end_time),据此可拿到员工当天实际排班的
|
||||
下班时间(如维护早班 08:00-17:00),避免延时加班校验错误使用默认 18:00。
|
||||
"""
|
||||
for r in daily_records:
|
||||
if str(r.get("work_day", "")) != date_str:
|
||||
continue
|
||||
b = r.get("bc_begin_time")
|
||||
e = r.get("bc_end_time")
|
||||
return (str(b).strip()[:5] if b else None,
|
||||
str(e).strip()[:5] if e else None)
|
||||
return None, None
|
||||
|
||||
|
||||
def _resolve_single_punch(
|
||||
day_summary: Optional[Dict[str, Any]],
|
||||
shift_begin: Optional[str],
|
||||
shift_end: Optional[str],
|
||||
) -> tuple:
|
||||
"""当天仅一条打卡时,结合班次时段判断它是上班还是下班打卡。
|
||||
|
||||
考勤逐日数据中当天只有一条打卡时 last_check_out 固定为 None,
|
||||
会把唯一一条下班打卡误判成"当日无下班打卡"。这里按打卡时间与班次时段的
|
||||
相对位置修正:晚于班次中点(无班次时段时默认以 12:00 为分界)的打卡视为
|
||||
下班打卡,赋给"当日最晚打卡";否则仍视为上班打卡。
|
||||
|
||||
Returns:
|
||||
(当日最早打卡, 当日最晚打卡) 修正后的元组
|
||||
"""
|
||||
if not day_summary:
|
||||
return None, None
|
||||
first = day_summary.get("first_check_in")
|
||||
last = day_summary.get("last_check_out")
|
||||
if last is not None:
|
||||
return first, last
|
||||
if not first:
|
||||
return None, None
|
||||
t = _parse_dt(first)
|
||||
if t is None:
|
||||
return None, None
|
||||
mins = t.hour * 60 + t.minute
|
||||
mid = 12 * 60
|
||||
if shift_begin and shift_end:
|
||||
try:
|
||||
sb = int(shift_begin[:2]) * 60 + int(shift_begin[3:5])
|
||||
se = int(shift_end[:2]) * 60 + int(shift_end[3:5])
|
||||
mid = (sb + se) // 2
|
||||
except (ValueError, IndexError):
|
||||
pass
|
||||
if mins >= mid:
|
||||
# 晚于班次中点:视为下班打卡
|
||||
return None, first
|
||||
return first, None
|
||||
|
||||
|
||||
# 每日考勤记录中携带的上下班打卡字段(sb=上班、xb=下班,可能分多个时段)
|
||||
_PUNCH_TIME_FIELDS = ("sb_dk_time", "xb_dk_time", "sb_dk_time2", "xb_dk_time2", "sb_dk_time3", "xb_dk_time3")
|
||||
|
||||
|
||||
def _collect_day_punches(record: Optional[Dict[str, Any]], work_day: str) -> List[str]:
|
||||
"""收集某日考勤记录中的全部上下班打卡时间。
|
||||
|
||||
打卡字段为 "HH:MM:SS"(无打卡为 null),这里拼上日期返回
|
||||
"YYYY-MM-DD HH:MM:SS" 完整时间并升序排序,供最早/最晚打卡提取与 _parse_dt 解析。
|
||||
"""
|
||||
if not record or not work_day:
|
||||
return []
|
||||
punches = []
|
||||
for field in _PUNCH_TIME_FIELDS:
|
||||
v = record.get(field)
|
||||
if v:
|
||||
s = str(v).strip()
|
||||
if s:
|
||||
punches.append(f"{work_day} {s}")
|
||||
punches.sort()
|
||||
return punches
|
||||
|
||||
|
||||
def _check_punch_records(session: Any, staff_id: str, ot_date: str) -> Dict[str, Any]:
|
||||
"""
|
||||
查询员工在加班日及次日的打卡明细,按日汇总。
|
||||
@@ -171,35 +258,59 @@ def _check_punch_records(session: Any, staff_id: str, ot_date: str) -> Dict[str,
|
||||
加班常跨天(如 18:00 至次日 00:00),下班打卡可能落在次日,因此查询
|
||||
范围扩展到 ot_date 次日;次日最早打卡用于延时加班的弹性到岗兑换判定。
|
||||
另扩展到前一天:提前到岗型延时加班(开始<=6点)的到岗打卡可能被系统归到前一天。
|
||||
|
||||
数据源统一为考勤逐日接口(rf_s_kq_count_leave_yc_day_all),一次调用即可拿到
|
||||
班次起止时间与各时段上下班打卡,替代原打卡流水接口。
|
||||
"""
|
||||
if not ot_date or not staff_id:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "打卡备注": "缺少加班日期或员工ID"}
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": 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, 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 and not prev_summary:
|
||||
daily = get_attendance_daily(session, staff_id, prev_day, next_day)
|
||||
prev_record = next((r for r in daily if str(r.get("work_day", "")) == prev_day), None)
|
||||
day_record = next((r for r in daily if str(r.get("work_day", "")) == ot_date), None)
|
||||
next_record = next((r for r in daily if str(r.get("work_day", "")) == next_day), None)
|
||||
if not day_record and not next_record and not prev_record:
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "打卡备注": "当天及次日无打卡记录"}
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"打卡备注": "当天及次日无打卡记录"}
|
||||
# 班次起止时间:取当日实际班次时段(如维护早班 08:00-17:00),
|
||||
# 未获取到时由上层回退默认 09:00/18:00;接口失败不影响打卡数据
|
||||
shift_begin, shift_end = _extract_shift_times(daily, ot_date)
|
||||
# 当日最早/最晚打卡;单条打卡时结合班次时段识别是上班还是下班打卡
|
||||
day_punches = _collect_day_punches(day_record, ot_date)
|
||||
day_summary = {
|
||||
"first_check_in": day_punches[0] if day_punches else None,
|
||||
# 仅1条打卡时 last_check_out 置空,交由 _resolve_single_punch 结合班次时段修正
|
||||
"last_check_out": day_punches[-1] if len(day_punches) > 1 else None,
|
||||
}
|
||||
day_first, day_last = _resolve_single_punch(day_summary, shift_begin, shift_end)
|
||||
# 次日最早打卡(弹性兑换用)
|
||||
next_punches = _collect_day_punches(next_record, next_day)
|
||||
next_first = next_punches[0] if next_punches else None
|
||||
# 前一天最晚打卡(提前到岗型加班用)
|
||||
prev_punches = _collect_day_punches(prev_record, prev_day)
|
||||
prev_last = prev_punches[-1] if prev_punches else 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,
|
||||
"当日最早打卡": day_first,
|
||||
"当日最晚打卡": day_last,
|
||||
"次日最早打卡": next_first,
|
||||
"前一天最晚打卡": prev_last,
|
||||
"班次开始时间": shift_begin,
|
||||
"班次结束时间": shift_end,
|
||||
"打卡备注": "",
|
||||
}
|
||||
except Exception as e:
|
||||
logger.warning("获取打卡明细失败: %s", str(e))
|
||||
return {"当日最早打卡": None, "当日最晚打卡": None, "次日最早打卡": None,
|
||||
"前一天最晚打卡": None, "打卡备注": f"获取失败: {e}"}
|
||||
"前一天最晚打卡": None, "班次开始时间": None, "班次结束时间": None,
|
||||
"打卡备注": f"获取失败: {e}"}
|
||||
|
||||
|
||||
def _check_leave_covers_morning(session: Any, staff_id: str, date_str: str) -> bool:
|
||||
@@ -235,7 +346,9 @@ def _validate_delayed(
|
||||
(一)驳回门槛:
|
||||
1. 日期匹配:加班开始时间所属日期 = 申请加班日期;
|
||||
2. 时长达标:1小时起算,超1小时按0.5h累加,不足1h驳回;
|
||||
3. 区间合规:开始时间 >= 规定下班时间(18:00),结束时间 <= 实际下班打卡时间。
|
||||
3. 区间合规:开始时间 >= 规定下班时间(以排班结束时间为准,未获取到回退默认 18:00);
|
||||
结束时间晚于实际下班打卡时,按实际打卡区间(申请开始->实际下班打卡)取整后的
|
||||
实际在岗时长 >= 申请时长即通过,不足则驳回。
|
||||
|
||||
(二)弹性到岗兑换(仅影响结算,校验驳回则驳回):
|
||||
D 基于实际下班打卡时间计算,>= 23:00 时 D = 1 + floor((打卡-23:00)/0.5)*0.5。
|
||||
@@ -248,6 +361,8 @@ def _validate_delayed(
|
||||
end = _parse_dt(info.get("加班结束时间"))
|
||||
actual_checkout = _parse_dt(punch.get("当日最晚打卡"))
|
||||
reasons = []
|
||||
# 申请结束时间晚于实际下班打卡、但实际在岗时长(按系统取整)仍满足申请时长时,用于附加到通过备注
|
||||
end_checkout_note = ""
|
||||
|
||||
# 1. 日期校验:加班开始日期与申请加班日期不一致时直接驳回,
|
||||
# 无需再校验后续的时长、区间合规等内容
|
||||
@@ -270,10 +385,14 @@ def _validate_delayed(
|
||||
reasons.append(f"加班时长为{hours:g}小时,不足{OT_MIN_HOURS}小时")
|
||||
|
||||
# 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")
|
||||
# 提前到岗型延时加班:加班开始时间早于当天正常上班时间(09:00)。
|
||||
# 常规"晚于18:00""当日有下班打卡"校验不适用,改以加班开始时间附近的到岗打卡作为证据:
|
||||
# 班次起止时间优先用打卡明细携带的班次时段(bc_begin_time/bc_end_time),
|
||||
# 未获取到时回退默认 09:00/18:00(常规班次),避免非18点下班班次被误判。
|
||||
shift_begin = punch.get("班次开始时间") or WORK_START_TIME
|
||||
shift_end = punch.get("班次结束时间") or WORK_END_TIME
|
||||
work_start = datetime.strptime(f"{ot_date} {shift_begin}", "%Y-%m-%d %H:%M")
|
||||
work_end = datetime.strptime(f"{ot_date} {shift_end}", "%Y-%m-%d %H:%M")
|
||||
# 提前到岗型延时加班:加班开始时间早于当天班次开始时间。
|
||||
# 常规"晚于规定下班时间""当日有下班打卡"校验不适用,改以加班开始时间附近的到岗打卡作为证据:
|
||||
# - 开始<=6点时,到岗打卡可能被系统归到前一天(跨天打卡),需回看前一天记录;
|
||||
# - 6点~9点开始的,到岗打卡归属当天,只看当天记录。
|
||||
# 提前到岗型只会早到、不会晚到,打卡须不晚于加班开始时间。
|
||||
@@ -293,14 +412,27 @@ def _validate_delayed(
|
||||
info["到岗打卡"] = arrival_punch
|
||||
else:
|
||||
if start is not None and start < work_end:
|
||||
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({WORK_END_TIME})")
|
||||
reasons.append(f"申请开始时间({start:%H:%M})早于规定下班时间({shift_end})")
|
||||
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})"
|
||||
)
|
||||
elif start is not None and hours is not None:
|
||||
# 核心原则:申请的加班时长必须与打卡可支撑的实际在岗时长相符。
|
||||
# 按系统取整规则(_calc_delayed_hours),用实际打卡区间(申请开始->实际下班打卡)
|
||||
# 计算实际在岗时长,>= 申请时长即通过(申请结束时间比打卡晚几分钟也属正常)。
|
||||
# 例:申请 18:00-23:05(取整5h),实际打卡23:00:45,实际在岗取整后也是5h,应通过
|
||||
actual_hours = _calc_delayed_hours(start, actual_checkout)
|
||||
if actual_hours >= hours:
|
||||
if end > actual_checkout:
|
||||
end_checkout_note = (
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡({actual_checkout:%H:%M:%S}),"
|
||||
f"实际在岗时长按系统取整为{actual_hours:g}小时,满足申请时长"
|
||||
)
|
||||
else:
|
||||
reasons.append(
|
||||
f"申请结束时间({end:%H:%M})晚于实际下班打卡时间({actual_checkout:%H:%M:%S}),"
|
||||
f"实际在岗时长按取整仅{actual_hours:g}小时,不足申请{hours:g}小时"
|
||||
)
|
||||
|
||||
info["计算加班时长(小时)"] = hours
|
||||
if reasons:
|
||||
@@ -375,8 +507,10 @@ def _validate_delayed(
|
||||
info["有效加班时长(小时)"] = effective
|
||||
info["弹性额度D(小时)"] = d_hours
|
||||
note = f"审批通过,有效加班时长{effective:g}小时"
|
||||
if flex_note:
|
||||
note += f"({flex_note})"
|
||||
extra_parts = [end_checkout_note, flex_note]
|
||||
extra = ";".join(p for p in extra_parts if p)
|
||||
if extra:
|
||||
note += f"({extra})"
|
||||
return "通过", note
|
||||
|
||||
|
||||
|
||||
Reference in New Issue
Block a user