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)
|
||||
Reference in New Issue
Block a user