feat: 新增多插件 UI 支持及运行日志集中回传功能

本次提交包含多项功能更新:
1. 为多个插件(xq0002/0003/0004/0008/0010/0011/0020/0031_xq0032/0033/0035/0037/0045_xq0046/0047/0048)新增 UI 界面及配置支持
2. 新增运行日志集中回传功能,客户端自动上传运行日志到中心机集中存储
3. 新增插件分类字段支持,用于场景库分组管理
4. 优化 xq0034/0037/0048 等插件的功能及描述
5. 修复控制面响应兼容问题,支持新旧版本数据格式
6. 新增 xq0033 插件的状态存储模块,用于历史记录管理
7. 优化 CRM 登录窗口模式,支持全屏置顶
This commit is contained in:
2026-10-26 15:42:50 +08:00
parent 9fd687ada8
commit 843ff244a6
453 changed files with 243002 additions and 4493 deletions
+92
View File
@@ -0,0 +1,92 @@
# -*- coding: utf-8 -*-
"""XQ0009 门店上月请休假异常人员名单梳理 插件入口。
流程编排(由影刀版 absence_analysis.py 移植,登录态改由底座注入,插件不做自动补登):
1) 会话校验:底座注入 HR session/userId → getCurUserInfo 校验(失效抛错提示重新登录);
2) 花名册:字段指定路径,或自动导出到输出目录(员工花名册.xlsx,15 分钟 TTL 缓存复用);
3) 收银会话(技师考勤源,统计月/当前月 >= 2026-09):插件字段提供账号密码时自动接口登录,
凭据错误中止运行;未提供凭据且无有效缓存登录态时告警降级仅用 HR 数据;
4) 统计月考勤报表(实时)→ 报表「休息/旷工」+ 收银技师覆盖 + 全集团整天请假并入缺勤判定;
5) 返岗判定:统计月已结束时补拉当前月考勤(技师走收银出勤日集合);
6) 计算月末往前连续未出勤 >= 5 天人员(跨月追溯逐月重估),导出 20 列 Excel 名单。
运行上下文:底座注入 HR 会话与 userId(config 全局钩子),platform = hr,uses_month = True
(前端页眉月份选择器经 payload.ref_month 注入)。
"""
from webhost.backend.plugins.base import ScenePlugin, PLUGINS
from . import config
from .report.absence_report import build_absence_report, resolve_month
class AbsenceAnalysisPlugin(ScenePlugin):
"""门店上月请休假异常人员名单梳理(需求 XQ0009)。"""
id = "xq0009"
name = "门店上月请休假异常人员名单梳理"
version = "1.0.3"
description = ("梳理上月请休假异常人员:月末往前连续未出勤 >= 5 天(休息/旷工/整天请假计入,"
"跨月往前追溯至返岗前一日)。技师考勤自 2026-09 起取收银系统数据,"
"非技师走 HR 考勤统计报表 + 请假流程,输出 20 列 Excel 名单。")
platform = "hr"
uses_month = True
capabilities = ["xq0009"]
permissions = {"platforms": ["hr"]}
fields = {
"ref_month": {
"type": "string", "title": "统计月份", "default": "",
"description": "留空=上月;格式 YYYY-MM",
},
"save_dir": {
"type": "string", "title": "输出目录",
"default": r"D:\资料\人资\请休假异常",
"description": "名单 Excel 与自动导出花名册的输出目录",
},
"roster_path": {
"type": "string", "title": "花名册文件路径", "default": "",
"description": "留空=自动导出到输出目录/员工花名册.xlsx(15 分钟内复用缓存)",
},
"cashier_username": {
"type": "string", "title": "收银系统账号", "default": "",
"description": "技师考勤数据源(2026-09 起技师考勤在收银系统);"
"留空=复用缓存登录态,无缓存时降级仅用 HR 数据(技师名单可能缺失)",
},
"cashier_password": {
"type": "string", "title": "收银系统密码", "format": "password", "default": "",
"description": "配套密码;提供凭据后登录失败将中止运行(防止静默缺技师数据出错名单)",
},
}
def run(self, fields: dict, ctx):
# ---- 注入运行上下文:日志 / HR 会话 / userId ----
config.set_log(ctx.log)
config.set_session(ctx.get_session("hr"))
config.set_user_id(ctx.get_user_id("hr"))
ref_month = (fields.get("ref_month") or fields.get("month") or "").strip()
save_dir = (fields.get("save_dir") or "").strip() or config.DEFAULT_SAVE_DIR
roster_path = (fields.get("roster_path") or "").strip()
cashier_username = (fields.get("cashier_username") or "").strip()
cashier_password = fields.get("cashier_password") or ""
_, _, month_str = resolve_month(ref_month)
ctx.log(f"===== 门店上月请休假异常名单梳理启动:统计月 {month_str},"
f"输出目录 {save_dir} =====", "INFO")
ctx.progress(3)
# ---- 主流程(会话校验 → 花名册 → 收银 → 统计月/当前月数据 → 分析 → 导出) ----
result = build_absence_report(
save_dir=save_dir, roster_path=roster_path, ref_month=ref_month,
cashier_username=cashier_username, cashier_password=cashier_password,
progress=ctx.progress,
)
summary = ("请休假异常名单梳理完成(统计 {b} ~ {e}):连续未出勤 >= {days} 天共 {n} 人。"
"文件:{path}").format(b=result["begin"], e=result["end"],
days=config.MIN_CONSECUTIVE_DAYS,
n=result["count"], path=result["path"])
return {"summary": summary, "detail": {"名单人数": result["count"]},
"path": result["path"], "ym": result["month"]}
PLUGINS.append(AbsenceAnalysisPlugin())
+184
View File
@@ -0,0 +1,184 @@
# -*- coding: utf-8 -*-
"""XQ0009 门店上月请休假异常人员名单梳理 插件 - 配置常量与全局钩子。
插件自包含:本包只依赖 Python 标准库 / 第三方库 / 底座注入的 RunContext。
所有业务模块统一经 config.logger 输出日志、config.require_session()/require_user_id() 取登录态。
HR 登录态由底座注入(hr 平台),插件不做自动补登,失效时提示「请重新登录」。
收银系统(技师考勤源)底座无平台支持,由插件 data/cashier_api.py 自包含实现纯接口登录。
"""
import os
# ==================== 共享目录(与影刀版同路径) ====================
_APP_DATA_DIR = os.path.join(
os.getenv('LOCALAPPDATA') or os.getenv('APPDATA') or os.path.expanduser('~'),
'37duAutomation')
SESSIONS_DIR = os.path.join(_APP_DATA_DIR, '.sessions')
# ==================== HR 系统 ====================
HR_BASE_URL = "https://hr.37du.co"
GET_CUR_USER_INFO_URL = f"{HR_BASE_URL}/RedseaPlatform/PtUsers.mc?method=getCurUserInfo"
LEAVE_URL = f"{HR_BASE_URL}/RedseaPlatform/kqController/getPageAjaxList.mc"
PAGE_MAX_SIZE = 500
# ---------- 考勤统计报表(逐日出勤) ----------
# 分页查询「考勤统计报表」,每人一行含 v_1~v_最后一天(当月逐日出勤状态),返回 JSON
MONTH_ATT_REPORT_URL = f"{HR_BASE_URL}/RedseaPlatform/pt/report/excel/detail/getPageAjax.mc"
MONTH_ATT_REPORT_ID = "f880c52a619446e0b74e3820b898d53b"
# 集团根组织 struId(struId / belongUnitStruId / ds1.struId / ds2.stru_id 共用)
COMPANY_STRU_ID = "596bae33-50e9-11ec-b526-822ff8ed5b28"
# 报表接口单页最大支持 1000 条(全集团一次拉取减少翻页请求)
REPORT_PAGE_SIZE = 1000
# 项目级重试(AGENTS.md):瞬时故障最多重试 3 次,三次仍失败后再记录错误日志
MAX_REQUEST_RETRY = 3
# ==================== 名单输出配置 ====================
# 默认保存目录
DEFAULT_SAVE_DIR = r"D:\资料\人资\请休假异常"
# 连续未出勤天数阈值:>= 该天数纳入名单
MIN_CONSECUTIVE_DAYS = 5
# 跨月追溯「逐月重估」:每往前推一个月,仍在追溯人数 >= TRACE_SINGLE_MAX 时用「整月全量缓存」
# (每月报表+请假各拉一次,多人共用),否则切「按工号单人查询」(少人数长缺勤,如产假/长期病假,
# 逐人回溯到上班日)。追溯人数逐月递减,早期月份批量、人少了自动切单人,减少全量拉取。不设月份上限。
TRACE_SINGLE_MAX = 10
# 名单输出列(含备注列):部门维度为花名册 所属单位/所属部门/一级~五级部门,并补充离职时间
COLUMNS = [
"序号", "所属单位", "所属部门", "一级部门", "二级部门", "三级部门", "四级部门", "五级部门",
"37工号", "姓名", "联系电话", "岗位",
"技师工号", "参保类型", "入职时间", "离职时间",
"请休假起始日期", "请休假结束日期", "请休假天数",
"备注",
]
# 未归岗占位文案(情况 A 且无任何请假流程)
NOT_BACK_TEXT = "未归岗,时间待定"
# 请假记录状态(bpm_status):001=申请中;002=已备案(生效);003=已撤销;004=销假中;
# 005=已销假;006=撤销加班;007=销差;008=已审批未备案。
# 整天请假缺勤判定与「仍在请假中」判定均只认 002 已备案记录:撤销(003)/已销假(005)/申请中(001)
# 的假单在考勤报表里不体现,若也计入会把实际正常上班的人误放进名单。
ACTIVE_LEAVE_STATUS = "002"
# 当前月「返岗」判定用:报表单元格命中任一请假类片段即视为「未到公司」。
# 休息/旷工 单独精确匹配(保持统计月口径:半天「上班旷工/下班旷工」不算整天缺席)。
NOT_ATTEND_FRAGMENTS = (
"事假", "病假", "产假", "调休假", "年度福利假", "特别福利假", "小时特假",
)
# ==================== 收银系统技师考勤 ====================
# 背景:HR 系统从 2026-09 起不再有技师考勤数据(技师考勤迁移到收银系统),需求9 需两个系统联动:
# - 技师:未出勤日集合来自收银技师月度考勤接口(旷工/请假/休息 逐日显式标记);
# - 非技师:仍走 HR 考勤统计报表 + 请假流程。
# 时间边界:2026-09 是技师数据迁移分界——
# - 统计月 / 当前月 >= 2026-09 时,技师未出勤/返岗判定走收银(HR 该月起无技师数据);
# - 统计月早于 2026-09,以及跨月追溯的历史月(2026-09 之前),一律走 HR 原逻辑。
CASHIER_MIGRATE_MONTH = "2026-09" # HR 技师数据迁移到收银的起始月
# 收银登录态(Access-Token/Refresh-Token 请求头,不走 cookie)与影刀「37du收银登录(接口版)」
# 共用同一落盘文件,登录态互通复用。
CASHIER_TOKEN_FILE = os.path.join(SESSIONS_DIR, 'cashier_tokens.json')
CASHIER_API_BASE = "https://api.37du.cashier.37du.co"
CASHIER_LOGIN_URL = f"{CASHIER_API_BASE}/sys/user/login"
CASHIER_VALIDATE_URL = f"{CASHIER_API_BASE}/sys/user/get/info"
CASHIER_STORE_LIST_URL = f"{CASHIER_API_BASE}/store/manager/connect/list"
CASHIER_ATT_URL = f"{CASHIER_API_BASE}/store/manager/techAttendanceMonthlyReport/month"
CASHIER_STORE_CACHE = os.path.join(_APP_DATA_DIR, 'data', 'cashier_stores.json')
CASHIER_UA = ("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 "
"Chrome/120.0.0.0 Safari/537.36")
# 与浏览器 SPA 同源请求头(防服务端后续加 Origin/Referer 校验)
CASHIER_ORIGIN = 'https://admin.37du.cashier.37du.co'
# 收银登录整轮重试(项目级重试机制)
CASHIER_LOGIN_ROUND_MAX = 3
CASHIER_TIMEOUT = 15
# 收银逐日 un_duty_type 首个 code → 需求9 未出勤类别(其余非空 code 一律归为请假)
# code:2=正休(休息)、6=旷工;7=假别7/特殊事假、3=假别3、5=病假、1=事假、4=长假、9/10=假别9/10(请假)
CASHIER_UN_DUTY_CAT = {6: "旷工", 2: "休息"}
# ==================== 接口数据懒缓存 ====================
# 统计月(上月)始终实时调接口;跨月追溯往前的历史月走缓存旁路:
# 每次先查本地缓存,没有才调接口,调完按「月 / 月+工号」落盘,下次直接复用;
# 缓存以 月/工号 为键互不影响,如需强制刷新删除对应缓存文件即可。
CACHE_DIR = os.path.join(_APP_DATA_DIR, "absence_cache")
# ==================== 全局钩子(run() 启动时注入) ====================
_log = None
_session = None
_user_id = ""
def set_log(fn):
"""注入 ctx.log(RunContext.log),各模块经 log()/logger 输出。"""
global _log
_log = fn
def log(msg, level="INFO"):
if _log:
_log(str(msg), level)
else:
print(f"[{level}] {msg}")
class _ModuleLogger:
"""模块级 logger 适配:保留影刀版 logger.info(...) 调用点,统一转发到 ctx.log。"""
@staticmethod
def debug(msg, *args):
if args:
msg = msg % args
log(msg, "DEBUG")
@staticmethod
def info(msg, *args):
if args:
msg = msg % args
log(msg, "INFO")
@staticmethod
def warning(msg, *args):
if args:
msg = msg % args
log(msg, "WARN")
@staticmethod
def error(msg, *args):
if args:
msg = msg % args
log(msg, "ERROR")
logger = _ModuleLogger()
def set_session(session):
global _session
_session = session
def get_session():
return _session
def require_session():
"""取插件运行期注入的 HR session(缺失抛错,提示先在插件界面登录 HR)。"""
if _session is None:
raise RuntimeError("未注入 HR 登录态,请先在插件界面完成 HR 登录")
return _session
def set_user_id(uid):
global _user_id
_user_id = str(uid or "")
def get_user_id():
return _user_id
def require_user_id():
uid = _user_id
if not uid:
raise RuntimeError("获取当前用户 userId 失败,请重新完成 HR 登录")
return uid
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""XQ0009 插件 - 数据层:HR 接口 / 花名册导出 / 收银系统技师考勤。"""
+428
View File
@@ -0,0 +1,428 @@
# -*- coding: utf-8 -*-
"""XQ0009 插件 - 收银系统技师考勤(自包含实现,底座无收银平台登录支持)。
由 workflows/.../absence_analysis.py 内联收银逻辑 + workflows/share/cashier_login_api.py
(接口版登录)移植,职责:
1. 纯接口登录(MD5 -> POST /sys/user/login -> 校验 token -> 落盘),登录态与影刀
「37du收银登录(接口版)」共用同一 token 文件,互通复用;
2. 门店列表(带本地缓存文件)与技师月度考勤逐门店拉取;
3. 模块级运行时 state(month_status 未出勤映射 / month_on 出勤日集合)供 logic 层查询。
插件化改造点:
- 凭据由插件界面字段传入(不再读 .env):提供凭据且缓存失效时自动登录,
凭据错误直接 RuntimeError 中止(用户显式配置凭据却静默缺技师数据会产生错误名单);
未提供凭据且无有效缓存登录态时返回 False,调用方告警降级仅用 HR 数据。
- 日志统一转发到 config.logger。
"""
import calendar
import hashlib
import json
import os
import time
from datetime import date
import requests
from ..config import (
logger, MAX_REQUEST_RETRY,
CASHIER_TOKEN_FILE, CASHIER_MIGRATE_MONTH,
CASHIER_LOGIN_URL, CASHIER_VALIDATE_URL,
CASHIER_STORE_LIST_URL, CASHIER_ATT_URL, CASHIER_STORE_CACHE, CACHE_DIR,
CASHIER_UA, CASHIER_ORIGIN, CASHIER_LOGIN_ROUND_MAX, CASHIER_TIMEOUT,
CASHIER_UN_DUTY_CAT,
)
# 收银扩展运行时状态:
# session 收银 requests 会话(ensure_session 成功后构建)
# month_status 收银未出勤映射缓存 {month_key: {工号: {日期: 类别}}}
# month_on 收银出勤日缓存 {month_key: {工号: {日期}}}(当前月返岗判定用)
state = {"session": None, "month_status": {}, "month_on": {}}
# ==================== Token 持久化(与影刀接口版登录格式一致) ====================
def _load_tokens():
if not os.path.exists(CASHIER_TOKEN_FILE):
return None
try:
with open(CASHIER_TOKEN_FILE, encoding='utf-8') as f:
tokens = json.load(f)
return tokens or None
except Exception as e:
logger.warning("收银 token 文件读取失败:%s(%s)", CASHIER_TOKEN_FILE, e)
return None
def _save_tokens(token, refresh_token):
"""落盘 {"access": ..., "refresh": ...},与影刀登录指令结构一致。"""
os.makedirs(os.path.dirname(CASHIER_TOKEN_FILE), exist_ok=True)
with open(CASHIER_TOKEN_FILE, 'w', encoding='utf-8') as f:
json.dump({"access": token, "refresh": refresh_token or ""},
f, ensure_ascii=False, indent=2)
logger.info("已保存收银 Access-Token/Refresh-Token 到 %s", CASHIER_TOKEN_FILE)
# ==================== Token 有效性校验 ====================
def _is_cashier_session_valid(tokens=None):
"""API 轻量校验收银 Access-Token:请求校验接口,HTTP 200 且 code==200 视为有效。
tokens 缺省时从共享 token 文件读取(复用缓存场景);传入时直接校验该 token
(登录后落盘前使用)。
"""
try:
if tokens is None:
tokens = _load_tokens()
if not tokens or not tokens.get("access"):
return False
session = requests.Session()
session.headers.update({
"User-Agent": CASHIER_UA,
"Access-Token": tokens["access"],
"Refresh-Token": tokens.get("refresh", ""),
"Origin": CASHIER_ORIGIN,
"Referer": CASHIER_ORIGIN + '/',
})
resp = session.get(CASHIER_VALIDATE_URL,
params={"_t": str(int(time.time() * 1000))},
timeout=CASHIER_TIMEOUT)
if resp.status_code != 200:
logger.debug("收银 Token 校验状态码异常:%s", resp.status_code)
return False
try:
data = resp.json()
except Exception:
return False
return isinstance(data, dict) and data.get("code") == 200
except Exception as e:
logger.warning("校验收银 Token 异常:%s", e)
return False
# ==================== 纯接口登录 ====================
def _login_headers():
return {
"User-Agent": CASHIER_UA,
"Content-Type": "application/json",
"Origin": CASHIER_ORIGIN,
"Referer": CASHIER_ORIGIN + '/login',
"Accept": "application/json, text/plain, */*",
}
def do_login_api(username, password):
"""完整接口登录:MD5 加密 -> POST /sys/user/login -> 校验 token -> 落盘。
返回 (ok, message)。凭据错误等被拒类响应重试无意义直接返回失败;
网络类异常按轮重试(最多 CASHIER_LOGIN_ROUND_MAX 轮,项目级重试机制)。
"""
md5_password = hashlib.md5(password.encode('utf-8')).hexdigest()
for rnd in range(1, CASHIER_LOGIN_ROUND_MAX + 1):
logger.info("--- 第 %d 轮收银登录(接口版) ---", rnd)
try:
resp = requests.post(
CASHIER_LOGIN_URL,
json={"account": username, "password": md5_password,
"response_token": "", "mode": "none"},
params={"_t": str(int(time.time() * 1000))},
headers=_login_headers(), timeout=CASHIER_TIMEOUT)
except Exception as e:
logger.warning("提交收银登录异常:%s", e)
time.sleep(1)
continue
if resp.status_code != 200:
logger.warning("收银登录接口状态码异常:%s", resp.status_code)
time.sleep(1)
continue
try:
data = resp.json()
except Exception:
logger.warning("收银登录响应非 JSON")
time.sleep(1)
continue
if not (isinstance(data, dict) and data.get("code") == 200):
msg = data.get("msg") if isinstance(data, dict) else str(resp.text[:200])
return False, f"登录被拒绝(账号或密码错误?):{msg}"
payload = data.get("data") or {}
token = payload.get("token") or ""
refresh_token = payload.get("refresh_token") or ""
if not token:
return False, "登录接口未返回 Access-Token"
# 落盘前先校验本次登录拿到的 token 真实可用
if _is_cashier_session_valid(tokens={"access": token, "refresh": refresh_token}):
_save_tokens(token, refresh_token)
return True, "登录成功"
logger.warning("收银登录接口返回成功但 token 校验未通过")
time.sleep(1)
return False, "登录失败(重试耗尽或接口异常)"
def _build_session():
"""读共享收银 token 构造 requests 会话(认证头 Access-Token/Refresh-Token,不走 cookie)。"""
if not os.path.exists(CASHIER_TOKEN_FILE):
raise RuntimeError("未找到收银系统登录态 tokens,请先完成收银登录后再重试。")
with open(CASHIER_TOKEN_FILE, encoding='utf-8') as f:
tokens = json.load(f)
access = tokens.get("access") or tokens.get("Access-Token") or ""
if not access:
raise RuntimeError("收银系统登录态 tokens 缺少 access token,请重新完成收银登录。")
s = requests.Session()
s.headers.update({
"User-Agent": CASHIER_UA,
"Access-Token": access,
"Refresh-Token": tokens.get("refresh") or tokens.get("Refresh-Token") or "",
})
return s
def ensure_session(username, password):
"""确保收银系统登录态可用,返回 True/False 表示是否有可用会话。
优先复用共享 token 文件的缓存登录态;失效且插件界面提供了账号密码时走接口登录,
凭据错误抛 RuntimeError 中止运行;未提供凭据时返回 False(调用方告警降级仅用 HR)。
"""
if _is_cashier_session_valid():
state["session"] = _build_session()
logger.info("复用缓存收银登录态:%s", CASHIER_TOKEN_FILE)
return True
username = (username or "").strip()
password = (password or "").strip()
if not username or not password:
logger.warning("收银系统登录态缺失且未提供技师考勤账号,"
"本次降级仅用 HR 数据(技师考勤可能缺失,名单口径不完整)")
return False
ok, msg = do_login_api(username, password)
if not ok:
raise RuntimeError(f"收银系统登录失败:{msg}")
state["session"] = _build_session()
logger.info("收银系统登录成功")
return True
def has_session():
"""收银会话是否已初始化(调用方据此决定技师数据是否走收银)。"""
return state.get("session") is not None
# ==================== 收银接口请求 ====================
def _cashier_request(session, method, url, params=None, payload=None):
"""收银接口请求(项目级重试 3 次;401/非 JSON 视为登录失效直接报错)。"""
last_exc = None
for attempt in range(1, MAX_REQUEST_RETRY + 1):
try:
kwargs = {"timeout": 30}
if params:
kwargs["params"] = params
if payload is not None:
kwargs["json"] = payload
resp = session.request(method, url, **kwargs)
if resp.status_code == 401:
raise RuntimeError("收银登录态已失效(HTTP 401),请更新收银账号后重试。")
if resp.status_code != 200:
raise RuntimeError(f"收银接口状态码异常:HTTP {resp.status_code}")
text = resp.text
if not text.lstrip().startswith(("{", "[")):
raise RuntimeError("收银登录态已失效(接口未返回 JSON),请重新完成收银登录。")
return resp.json()
except RuntimeError:
raise
except Exception as e:
last_exc = e
if attempt >= MAX_REQUEST_RETRY:
break
logger.warning("收银接口请求第 %d 次失败(%s),重试", attempt, e)
time.sleep(2.0 * attempt)
raise last_exc
# ==================== 门店列表 ====================
def cashier_store_list(session):
"""收银门店列表(带缓存文件复用,避免每次重复拉取)。"""
if os.path.exists(CASHIER_STORE_CACHE):
try:
with open(CASHIER_STORE_CACHE, encoding='utf-8') as f:
cached = json.load(f)
stores = cached.get("stores") or []
if stores:
return stores
except Exception:
pass
data = _cashier_request(session, "GET", CASHIER_STORE_LIST_URL,
params={"_t": str(int(time.time() * 1000))})
stores = data.get("data") or []
if not stores:
raise RuntimeError("收银门店列表接口未返回任何门店")
try:
os.makedirs(os.path.dirname(CASHIER_STORE_CACHE), exist_ok=True)
with open(CASHIER_STORE_CACHE, 'w', encoding='utf-8') as f:
json.dump({"updated_at": time.strftime("%Y-%m-%d %H:%M:%S"), "stores": stores},
f, ensure_ascii=False, indent=2)
except Exception as e:
logger.warning("收银门店缓存写入失败:%s", e)
return stores
# ==================== 技师月度考勤 ====================
def _month_range(month_str):
"""月份 "YYYY-MM"/"YYYYMM" → (当月1日, 当月最后日)。"""
s = str(month_str).replace("-", "")
year, mon = int(s[:4]), int(s[4:6])
last_day = calendar.monthrange(year, mon)[1]
return date(year, mon, 1), date(year, mon, last_day)
def _cashier_day_cat(det):
"""收银逐日明细 → 需求9 未出勤类别(旷工/请假/休息);正常出勤返回 None。
以 un_duty_type 首个 code 为准(6=旷工、2=正休,其余非空=请假);display_text 兜底。
"""
un = det.get("un_duty_type")
if isinstance(un, list) and un:
cat = CASHIER_UN_DUTY_CAT.get(un[0])
return cat if cat else "请假"
txt = "".join(det.get("display_text") or [])
if "旷工" in txt:
return "旷工"
if "正休" in txt:
return "休息"
if txt and txt != "正常":
return "请假"
return None
def is_cashier_month(month_str):
"""月份是否落在技师数据迁移月(2026-09)及以后——该月技师考勤需同时取收银数据。
兼容 "YYYY-MM" 与 "YYYYMM" 两种入参。
"""
try:
ym = int(str(month_str).replace("-", "")[:6])
return ym >= int(CASHIER_MIGRATE_MONTH.replace("-", ""))
except Exception:
return False
def _dump_tech(result, on_map):
"""把 date 键的内存结构转为 JSON 可存结构(date.isoformat 作键/元素)。"""
return {
"status": {code: {d.isoformat(): cat for d, cat in dm.items()}
for code, dm in result.items()},
"on": {code: sorted(d.isoformat() for d in ds) for code, ds in on_map.items()},
}
def _load_tech(data):
"""_dump_tech 的逆操作:日期转回 date,出勤日集合转回 set(坏行忽略)。"""
status = {}
for code, dm in (data.get("status") or {}).items():
daymap = {}
for ds, cat in dm.items():
try:
daymap[date.fromisoformat(ds)] = cat
except Exception:
continue
if daymap:
status[code] = daymap
on_map = {}
for code, days in (data.get("on") or {}).items():
on_days = set()
for ds in days or []:
try:
on_days.add(date.fromisoformat(ds))
except Exception:
continue
if on_days:
on_map[code] = on_days
return status, on_map
def _read_tech_cache(path):
"""读历史月收银技师缓存;不存在/损坏返回 None。"""
if not os.path.exists(path):
return None
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
status, on_map = _load_tech(data)
return {"status": status, "on": on_map}
except Exception as e:
logger.warning("收银技师缓存读取失败,忽略:%s(%s)", path, e)
return None
def _write_tech_cache(path, result, on_map):
"""历史月收银技师结果落盘(失败仅告警,不影响主流程)。"""
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(_dump_tech(result, on_map), f, ensure_ascii=False)
except Exception as e:
logger.warning("收银技师缓存写入失败,忽略:%s(%s)", path, e)
def cashier_tech_status(month_key):
"""拉取某月全部门店收银技师考勤 → 未出勤映射 {工号: {日期: 类别}}(模块内缓存)。
同时把该月各技师「出勤日集合」写入 state["month_on"][month_key][工号],
供当前月返岗判定使用。未初始化收银会话时返回空 dict(调用方降级仅用 HR 数据)。
注意:仅统计月 / 当前月(>= CASHIER_MIGRATE_MONTH)才调用本函数;跨月追溯的历史月
(2026-09 之前)技师数据仍在 HR,走 logic 层 HR 原逻辑。
完整结束的历史月(早于当前月)结果落盘 absence_cache/cashier_{YYYYMM}.json,
下次回溯直接读盘,不再逐门店重拉;统计月/当前月始终实时(数据仍在变化)。
"""
session = state.get("session")
if session is None:
return {}
if month_key in state["month_status"]:
return state["month_status"][month_key]
disk_path = None
if month_key < date.today().strftime("%Y-%m"): # 完整结束的历史月:数据不再变化
disk_path = os.path.join(CACHE_DIR, f"cashier_{month_key.replace('-', '')}.json")
cached = _read_tech_cache(disk_path)
if cached is not None:
state["month_status"][month_key] = cached["status"]
state["month_on"][month_key] = cached["on"]
logger.info("命中收银技师考勤缓存:%s(%d 名技师)",
os.path.basename(disk_path), len(cached["status"]))
return state["month_status"][month_key]
year, month = int(month_key[:4]), int(month_key[5:7])
mb, me = _month_range(month_key)
stores = cashier_store_list(session)
result, on_map = {}, {}
for store in stores:
store_id = store.get("store_id")
try:
data = _cashier_request(
session, "POST", CASHIER_ATT_URL,
payload={"store_id": store_id, "year": year, "month": month}).get("data") or []
except Exception as e:
logger.warning("收银门店 %s(%s) 考勤拉取失败:%s", store_id, store.get("store_name"), e)
continue
time.sleep(0.3) # 门店间限速,避免被接口限流
for t in data:
code = str(t.get("tech_base_code") or "").strip()
if not code:
continue
daymap, on_days = {}, set()
for det in (t.get("monthly_detail") or []):
day = det.get("day")
if not isinstance(day, int) or not (mb.day <= day <= me.day):
continue
d = date(year, month, day)
cat = _cashier_day_cat(det)
if cat:
daymap[d] = cat
else:
on_days.add(d) # 正常出勤日
if daymap:
result[code] = daymap
if on_days:
on_map[code] = on_days
state["month_status"][month_key] = result
state["month_on"][month_key] = on_map
if disk_path and result:
_write_tech_cache(disk_path, result, on_map)
logger.info("收银技师考勤 %s:%d 家门店、%d 名技师进入未出勤映射、%d 名有出勤日",
month_key, len(stores), len(result), len(on_map))
return result
+269
View File
@@ -0,0 +1,269 @@
# -*- coding: utf-8 -*-
"""XQ0009 插件 - HR 接口(考勤统计报表 / 请假记录)与按月懒缓存。
由 workflows/.../absence_analysis.py 内联 HR 逻辑移植:
- 会话改由底座注入(config 全局钩子),删除自动补登逻辑——登录态失效直接抛
HRSessionExpiredError,由调用方转为「请重新登录 HR」明确提示(插件开发规范 §7);
- 请求带项目级重试(最多 3 次,4xx 不重试);
- 历史月接口数据按月落盘懒缓存(跨月追溯复用),统计月/当前月始终实时。
"""
import json
import os
import time
import requests
from ..config import (
logger, CACHE_DIR, MAX_REQUEST_RETRY,
HR_BASE_URL, GET_CUR_USER_INFO_URL, LEAVE_URL, PAGE_MAX_SIZE,
MONTH_ATT_REPORT_URL, MONTH_ATT_REPORT_ID, COMPANY_STRU_ID, REPORT_PAGE_SIZE,
)
class HRSessionExpiredError(Exception):
"""HR 登录态失效(接口返回非 JSON,被重定向到登录页)。"""
def _request_with_retry(session, method, url, params, timeout, label):
"""带项目级重试的 HTTP 请求:连接/超时/5xx 等瞬时故障最多重试 MAX_REQUEST_RETRY 次。
4xx 业务类错误(401/403 等)重试无意义,直接抛出;三次仍失败后抛出最后一次异常。
"""
last_exc = None
for attempt in range(1, MAX_REQUEST_RETRY + 1):
try:
resp = session.request(method.upper(), url, data=params, timeout=timeout)
resp.raise_for_status()
return resp
except requests.HTTPError as e:
if e.response is not None and e.response.status_code < 500:
raise # 4xx 不重试
last_exc = e
except (requests.ConnectionError, requests.Timeout) as e:
last_exc = e
if attempt < MAX_REQUEST_RETRY:
delay = 2 ** (attempt - 1) # 1s / 2s / 4s 指数退避
logger.warning("%s 第 %d 次请求失败(%s),%d 秒后重试", label, attempt, last_exc, delay)
time.sleep(delay)
logger.error("%s 请求重试 %d 次仍失败:%s", label, MAX_REQUEST_RETRY, last_exc)
raise last_exc
def hr_request_json(session, method, url, params, label, timeout=20):
"""POST/GET 请求(带项目级重试)并校验返回 JSON;失效抛 HRSessionExpiredError。"""
resp = _request_with_retry(session, method, url, params, timeout, label)
text = resp.text
if not text or not text.lstrip().startswith(("{", "[")):
raise HRSessionExpiredError(f"{label}:HR 登录态失效(返回非 JSON),请重新登录 HR 后再重试")
return resp.json()
def validate_session(session):
"""调用 getCurUserInfo 校验登录态有效性,返回 userId;失效抛 HRSessionExpiredError。"""
info = hr_request_json(session, "POST", GET_CUR_USER_INFO_URL, {}, "获取当前用户信息")
user_id = info.get("userId", "")
if not user_id:
raise RuntimeError(f"员工基础信息接口未返回 userId:{info}")
logger.info("HR 会话校验通过,user_id=%s", user_id)
return user_id
# ==================== 考勤统计报表 ====================
def fetch_attendance_stat_page(session, user_id, month, page_no=1, page_size=REPORT_PAGE_SIZE,
stru_id=COMPANY_STRU_ID, base_code=""):
"""请求单页「考勤统计报表」数据。
返回 datas 一条记录 = 一个员工在查询月的逐日出勤,动态列 key 形如 v_1~v_最后一天,
值为该日状态(休息/旷工/迟到/漏打卡/早退等)。
"""
params = {
"reportId": MONTH_ATT_REPORT_ID,
"struId": stru_id,
"start": (page_no - 1) * page_size,
"sortType": "",
"sortName": "",
"pageNo": page_no,
"pageSize": page_size,
"ds1.userId": user_id,
"ds1.struId": stru_id,
"ds1.month": month,
"ds2.stru_id": stru_id,
"ds3.month": "#ds1.month#",
"orgTypeCode": "1",
"rootId": "cq37du",
"showSetField": "1",
"menuName": "考勤统计报表",
"treePermitType": "permit",
"struTreeCode": "cq37du",
"belongUnitStruId": stru_id,
"isVirtual": "0",
"isHistory": "undefined",
"useSealTreeData": "0",
"orgAlias": "集团",
"commonQuery": "[]",
"ds1.base_code": base_code,
}
url = f"{MONTH_ATT_REPORT_URL}?reportsId={MONTH_ATT_REPORT_ID}"
return hr_request_json(session, "POST", url, params, "考勤统计报表")
def fetch_all_attendance_stat(session, user_id, month, stru_id=COMPANY_STRU_ID, base_code=""):
"""分页抓取某月「考勤统计报表」明细(每人一行,含 v_1~v_最后一天)。
base_code 非空时仅查该员工(跨月追溯单人查询)。
某页请求失败(state != 1)直接抛异常终止,绝不返回部分数据(避免导出缺人名单)。
"""
all_rows = []
page_no = 1
while True:
data = fetch_attendance_stat_page(session, user_id, month, page_no,
REPORT_PAGE_SIZE, stru_id, base_code)
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_page(session, user_id, base_code, start_time, end_time,
treecode="cq37du", page_no=1, page_size=PAGE_MAX_SIZE):
"""请求单页请假记录数据。"""
params = {
"STRU_TREE_CODE": treecode,
"user_id": user_id,
"begin_date": "",
"end_date": "",
"sqlId": "select_kqLeave_record",
"commonQuery": "",
"commonQueryStr": "",
"post_no": "",
"source": "",
"person_status": "",
"staff_id": "",
"staffNames": "",
"post_type": "1",
"processing_reason": "",
"processing_date": "",
"start_operat_time": "",
"end_operat_time": "",
"orgAlias": "",
"dept_ids": "",
"base_code": base_code,
"staff_name": "",
"start_time": start_time,
"end_time": end_time,
"start": str((page_no - 1) * page_size),
"sortType": "desc",
"sortName": "operat_time",
"pageNo": page_no,
"pageSize": page_size,
}
return hr_request_json(session, "POST", LEAVE_URL, params, "请假查询")
def fetch_all_leave(session, user_id, base_code, start_time, end_time, treecode="cq37du"):
"""分页抓取指定工号、日期范围内的全部请假记录。
某页请求失败(state != 1)直接抛异常终止,绝不返回部分数据(避免漏掉仍在休假的假单)。
"""
all_rows = []
page_no = 1
while True:
data = fetch_leave_page(session, user_id, base_code, start_time, end_time,
treecode, page_no, PAGE_MAX_SIZE)
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 _cache_path(kind, month_key, code=""):
"""构造缓存文件路径。kind ∈ {att, leave};month_key 为 "YYYYMM";code 空表示全量。"""
fname = f"{kind}_{month_key}" + (f"_{code}" if code else "")
return os.path.join(CACHE_DIR, fname + ".json")
def _read_cache(path):
"""读取缓存列表;不存在/损坏返回 None。"""
if not os.path.exists(path):
return None
try:
with open(path, encoding="utf-8") as f:
data = json.load(f)
return data if isinstance(data, list) else None
except Exception as e:
logger.warning("缓存读取失败,忽略:%s(%s)", path, e)
return None
def _write_cache(path, records):
"""把接口返回的 datas 列表写入缓存(失败仅告警,不影响主流程)。"""
try:
os.makedirs(os.path.dirname(path), exist_ok=True)
with open(path, "w", encoding="utf-8") as f:
json.dump(records, f, ensure_ascii=False)
except Exception as e:
logger.warning("缓存写入失败,忽略:%s(%s)", path, e)
def cached_attendance(session, user_id, month_key, base_code=""):
"""按月缓存整月考勤统计报表:先查缓存,未命中才调接口并落盘,下次直接复用。
month_key:月份 "YYYYMM";base_code 非空时为该员工单人报表(跨月追溯单人模式)。
"""
path = _cache_path("att", month_key, base_code)
cached = _read_cache(path)
if cached is not None:
logger.info("命中考勤报表缓存:%s(%d 条)", os.path.basename(path), len(cached))
return cached
records = fetch_all_attendance_stat(session, user_id, month_key, base_code=base_code)
_write_cache(path, records)
return records
def cached_leave(session, user_id, base_code, month_str):
"""按月缓存整月请假记录:先查缓存,未命中才调接口并落盘,下次直接复用。
month_str:月份 "YYYY-MM";base_code 空为全集团,非空为该员工(跨月追溯单人模式)。
"""
month_key = month_str.replace("-", "")
path = _cache_path("leave", month_key, base_code)
cached = _read_cache(path)
if cached is not None:
logger.info("命中请假记录缓存:%s(%d 条)", os.path.basename(path), len(cached))
return cached
from datetime import date, timedelta
def month_range(m):
import calendar
s = str(m).replace("-", "")
year, mon = int(s[:4]), int(s[4:6])
last_day = calendar.monthrange(year, mon)[1]
return date(year, mon, 1), date(year, mon, last_day)
mb, me = month_range(month_str)
records = fetch_all_leave(session, user_id, base_code,
mb.strftime("%Y-%m-%d"), me.strftime("%Y-%m-%d"))
_write_cache(path, records)
return records
+483
View File
@@ -0,0 +1,483 @@
# -*- coding: utf-8 -*-
"""XQ0009 门店上月请休假异常人员名单梳理 插件 - 员工花名册导出(由 XQ0011 插件 data/roster_export_api.py 内嵌移植)。
纯接口版(无需浏览器):访问台账页面绑定会话 -> ws/bridge 注册 -> WebSocket 订阅主题 ->
POST exportCommonListData 异步导出(服务端生成 Excel 并翻译全部字典字段)-> 接收 "--end--|文件路径" 推送
-> 下载临时文件 -> 按状态合并(追加「类型」列)。
插件化改造点:
1. HR 会话优先用底座注入的 session(调用方传入),未传时兜底读共享 cookies 文件;
2. 日志统一转发到 config.logger。
"""
import json
import os
import time
import urllib.parse
from datetime import date, datetime, timedelta
import requests
import pandas as pd
import websocket # websocket-client
from ..config import logger, SESSIONS_DIR
SHARED_HR_COOKIE_FILE = os.path.join(SESSIONS_DIR, 'hr_cookies.json')
# ---------- 员工花名册查询/导出接口(与 app 版 ehr/common/hr_api 一致) ----------
ROSTER_ID = "1116da64-b094-11ea-b588-14187743d052"
ROSTER_PAGE_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/getCustomCommonList.mc"
ROSTER_EXPORT_URL = f"https://hr.37du.co/RedseaPlatform/hrRoster/{ROSTER_ID}/exportCommonListData.mc"
BRIDGE_URL = "https://hr.37du.co/RedseaPlatform/ws/bridge"
TEMPLATE_LIST_URL = ("https://hr.37du.co/RedseaPlatform/redmagicapi/"
"rf_pt_users_export_define_select/getExecuteResult.mc")
TEMPLATE_DETAIL_URL = "https://hr.37du.co/RedseaPlatform/ptUsersExportDefine/getPtusersexportdefine.mc"
WS_EXPORT_THEME = "HR_DEFINED_HMC_EXPORT"
WS_SERVICE_URL = "wss://hr.37du.co/RedseaPlatform/ws/service?theme=" + WS_EXPORT_THEME
XHR_HEADERS = {"X-Requested-With": "XMLHttpRequest"}
USER_AGENT = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 Chrome/120.0.0.0 Safari/537.36"
# 花名册查询固定入参(从浏览器抓包提取)
ROSTER_QUERY_BASE_PARAMS = {
"menuName": "员工花名册",
"useSealTreeData": "0",
"treePermitType": "permit",
"cancelNodeClick": "1",
"clickFlag": "true",
"in_use": "1",
"commonQuery": "",
"newCondition": "",
"urlConditions": "",
"exportConfig": "",
"tableId": "assemble-hr_staff_base",
"rosterId": ROSTER_ID,
"includeChildrenSetting": "",
"struTreeCode": "cq37du",
"djStruTreeCode": "",
"djStruId": "",
"djOrgName": "",
"struId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
"belongUnitStruId": "596bae33-50e9-11ec-b526-822ff8ed5b28",
"rootId": "cq37du",
"isVirtual": "0",
"currentUserRootId": "cq37du",
"currentUserId": "178b0efa-8a65-11f1-a7d9-000c296f9469",
"currentRoleIds": "POST_SYS_ADMIN,renshi",
"currentStaffId": "1342173e-36cf-4160-8826-6b17d7d084a4",
"baseHrefPath": "http:hr.37du.co:80RedseaPlatform",
"qrCodeUrl": "jspresumepage-01.jsp",
"orgName": "集团",
"belongUnitOrgName": "集团",
"throughParam": "",
"start": "0",
"sortType": "",
"sortName": "",
"pageNo": "1",
"pageSize": "15",
"dataIds": "",
"hideCols": "",
}
# ---------- 自定义导出模板(exportFilters 字段串,顺序与页面导出模板列一致) ----------
ROSTER_TEMPLATE_FILTERS = {
# 「员工基础信息」模板(31 列,与页面抓包 exportFilters 一致,含「职位序列」列)
"员工基础信息": ",".join([
"hr_staff_base.staff_name", # 姓名
"hr_staff_base.base_code", # 工号
"hr_staff_base.idCard", # 证件号
"hr_staff_base.join_date", # 入职时间
"hr_staff_base.leaveOffice_date", # 离职时间
"pt_staff_stru.BELONG_UNIT_ORG_NAME", # 所属单位
"pt_staff_stru.DEPT_ORG_NAME", # 所属部门
"pt_staff_stru.DEPT_ORG_ONE", # 一级部门
"pt_staff_stru.DEPT_ORG_TWO", # 二级部门
"pt_staff_stru.DEPT_ORG_THREE", # 三级部门
"pt_staff_stru.DEPT_ORG_FOUR", # 四级部门
"pt_staff_stru.DEPT_ORG_FIVE", # 五级部门
"pt_staff_stru.POST_ORG_NAME", # 岗位
"hr_staff_base_ext.ext_technician_code", # 技师工号
"hr_staff_base_ext.ext_star_level", # 星级
"pt_staff_stru.first_type_id", # 职位序列
"pt_staff_stru.POST_LEVEL_ID", # 职衔
"pt_staff_stru.PT_POST_GRADE_ID", # 职级
"pt_post_level.ext_grade_name", # 职等
"hr_staff_base.mobile_phone", # 手机号码
"hr_staff_base.person_status", # 在职状态
"hr_staff_base_ext.ext_insurance_type", # 参保类型
"pt_staff_stru.ORG_FULL_PATH", # 组织全路径
"hr_staff_base.nation", # 民族
"hr_staff_base.sex", # 性别
"hr_staff_base.age", # 年龄
"hr_staff_base.period", # 试用期限(月)
"hr_staff_base.pre_correction_date", # 试用期结束日期
"hr_staff_base_ext.ext_trans_type", # 上下班交通方式
"hr_staff_base_ext.ext_recruit_way", # 招聘渠道
"hr_staff_base.identity", # 用工类型
]),
}
# ---------- 默认导出参数 ----------
DEFAULT_TEMPLATE = "员工基础信息"
DEFAULT_STATUSES = ["在职", "离职"]
DEFAULT_TTL_SECONDS = 15 * 60 # 缓存有效期(秒)
EXPORT_TIMEOUT_SECONDS = 300 # 异步导出等待超时(秒)
MAX_ATTEMPTS = 3 # 项目级重试次数
class LoginRequiredError(Exception):
"""HR 登录态缺失或失效(接口返回登录页等非 JSON 内容)。"""
# ==================== commonQuery 前端加密(自实现,与前端行为一致,已实测接口可用) ====================
_CUSTOM_CHARS = "y!89(*z02BCcdD_bEeGHIJKLmnNOPQopRMSTqrUklVstWXYZafgh3ij1uvwx456A7"
_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_condition(query_field, query_type, query_value, query_text="",
left_bracket="", right_bracket="", logic="AND", input_type="text"):
"""构造一个符合前端格式的单条查询条件字典。"""
return {
"queryField": query_field,
"leftBracket": left_bracket,
"queryType": query_type,
"queryValue": query_value,
"queryText": query_text,
"rightBracket": right_bracket,
"logic": logic,
"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')) + _SALT
return en_str[:2] + en_str[-3:] + en_str[2:-3]
# ==================== 登录态(底座注入优先,兜底共享 cookies) ====================
def _build_session(session=None):
"""取 HR 会话:优先用调用方(底座注入)传入的 session,否则读共享 cookies 构建。"""
if session is not None:
return session
if not os.path.exists(SHARED_HR_COOKIE_FILE):
raise LoginRequiredError(
"未找到 HR 登录态 cookies,请先在插件界面完成 HR 登录后再重试。")
with open(SHARED_HR_COOKIE_FILE, encoding='utf-8') as f:
cookies = json.load(f)
session = requests.Session()
session.headers.update({
"User-Agent": USER_AGENT,
"Content-Type": "application/x-www-form-urlencoded",
})
for c in cookies or []:
if c.get("domain") and "37du.co" in c["domain"]:
session.cookies.set(c["name"], c["value"], domain=c["domain"], path=c.get("path", "/"))
return session
# ==================== 动态日期参数 ====================
def get_date_params():
"""生成花名册查询所需的动态日期参数(当月 / 上月 / 当年首月)。"""
now = datetime.now()
year, month, day = now.year, now.month, now.day
last_month_date = datetime(year, month, 1) - timedelta(days=1)
return {
"currentDate": f"{year}-{month:02d}-{day:02d}",
"currentMonth": f"{year}{month:02d}",
"currentMonthBar": f"{year}-{month:02d}",
"lastMonth": f"{last_month_date.year}{last_month_date.month:02d}",
"lastMonFirstDay": f"{last_month_date.year}-{last_month_date.month:02d}-01",
"lastMonLastDay": last_month_date.strftime("%Y-%m-%d"),
"curYearFirstMon": f"{year}01",
"curYearFirstMonBar": f"{year}-01",
}
def _get_leave_range(today=None):
"""计算离职筛选时间范围:默认上月 1 日到今天(离职时间不传时使用)。"""
today = today or date.today()
last_month_end = today.replace(day=1) - timedelta(days=1)
start = last_month_end.replace(day=1)
return start.strftime("%Y-%m-%d"), today.strftime("%Y-%m-%d")
# ==================== 查询条件构造 ====================
def _build_in_service_conditions():
return [
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
query_text="1", left_bracket="(", right_bracket=")",
input_type="select"),
build_condition("`hr_staff_base.person_status`", "in", "1",
query_text="1", left_bracket="(", right_bracket=")",
input_type="multipleSelect"),
]
def _build_leave_conditions(leave_start, leave_end):
return [
build_condition("`pt_staff_stru.POST_STRU_ID`", "in", "1",
query_text="1", left_bracket="(", right_bracket=")",
input_type="select"),
build_condition("`hr_staff_base.person_status`", "in", "2",
query_text="2", left_bracket="(", right_bracket=")",
input_type="multipleSelect"),
build_condition("`hr_staff_base.leaveOffice_date`", ">=", leave_start,
left_bracket="(", input_type="date"),
build_condition("`hr_staff_base.leaveOffice_date`", "<=", leave_end,
right_bracket=")", input_type="date"),
]
# ==================== 自定义导出模板动态解析 ====================
def resolve_template_filters(session, template_name):
"""按模板名动态解析 exportFilters 字段串(失败回退内置模板)。"""
try:
r = session.post(TEMPLATE_LIST_URL, headers=XHR_HEADERS, timeout=15).json()
templates = r.get("jsonList") or []
target = next((t for t in templates if t.get("ext1") == template_name), None)
if not target:
logger.warning("模板列表中未找到「%s」,回退内置模板", template_name)
return None
r2 = session.post(TEMPLATE_DETAIL_URL, headers=XHR_HEADERS,
data={"rosterId": ROSTER_ID, "id": target["id"]}, timeout=15).json()
export_field = (r2.get("result") or {}).get("exportField") or ""
fields = json.loads(export_field)
if not fields:
logger.warning("模板「%s」详情无 exportField,回退内置模板", template_name)
return None
filters = ",".join(f["tableCode"] for f in fields)
logger.info("模板「%s」动态解析成功(%d 列)", template_name, len(fields))
return filters
except Exception as e:
logger.warning("模板「%s」动态解析失败:%s,回退内置模板", template_name, e)
return None
# ==================== WebSocket 异步导出(单状态) ====================
def _bind_session(session):
"""绑定会话:先访问台账页面,再调用 ws/bridge 注册 HTTP 会话到 WS 容器。"""
session.get(ROSTER_PAGE_URL, params={"clickFlag": "true", "treePermitType": "permit",
"useSealTreeData": "0"}, timeout=30)
r = session.post(BRIDGE_URL, data={}, headers=XHR_HEADERS, timeout=10)
if "成功" not in r.text and r.text.strip() != "1":
raise LoginRequiredError(
f"ws/bridge 会话注册失败(登录态可能已失效):{r.text[:100]}。"
"请先在插件界面重新完成 HR 登录后再重试。")
def _export_one_status_once(session, status, download_dir, template_name,
leave_start=None, leave_end=None, export_filters=None):
"""单个在职状态的异步导出(单次尝试):提交任务 -> WS 收 --end-- -> 下载临时文件。"""
_bind_session(session)
cookie_hdr = "; ".join(f"{c.name}={c.value}" for c in session.cookies
if "hr.37du.co" in (c.domain or ""))
ws = websocket.WebSocket()
ws.connect(WS_SERVICE_URL, header=[
f"Cookie: {cookie_hdr}",
"Origin: https://hr.37du.co",
f"User-Agent: {USER_AGENT}",
], timeout=10)
try:
ws.send(json.dumps({"theme": WS_EXPORT_THEME, "code": "SUBCRIBE_THEME"}))
ack = json.loads(ws.recv())
if ack.get("code") != "SUBCRIBE_THEME_ACK":
raise RuntimeError(f"WS 订阅失败:{str(ack)[:100]}")
logger.info("WS 订阅成功(%s)", WS_EXPORT_THEME)
params = {k: str(v) for k, v in ROSTER_QUERY_BASE_PARAMS.items()}
if status == "离职":
ls = leave_start or ""
le = leave_end or ""
if not ls or not le:
ls, le = _get_leave_range()
params["commonQuery"] = encode_common_query(_build_leave_conditions(ls, le))
logger.info("离职时间范围:%s ~ %s", ls, le)
else:
params["commonQuery"] = encode_common_query(_build_in_service_conditions())
params.update(get_date_params())
params["exportConfig"] = json.dumps(
{"exportName": template_name,
"exportFilters": export_filters or ROSTER_TEMPLATE_FILTERS.get(template_name, "")},
ensure_ascii=False, separators=(",", ":"))
params["_t"] = str(int(time.time() * 1000))
resp = session.post(ROSTER_EXPORT_URL, data=params, headers=XHR_HEADERS, timeout=30)
if resp.status_code != 200:
raise RuntimeError(f"提交导出任务失败:HTTP {resp.status_code}")
logger.info("导出任务已提交(状态:%s,模板:%s)", status, template_name)
file_url = None
deadline = time.time() + EXPORT_TIMEOUT_SECONDS
ws.settimeout(EXPORT_TIMEOUT_SECONDS)
while time.time() < deadline:
msg = json.loads(ws.recv())
txt, code = msg.get("txt", ""), msg.get("code", "")
if code != "NORMAL_PUSH_TO":
continue
if txt.startswith("--end--"):
file_url = txt.split("|", 1)[1].strip()
break
if txt.startswith(("开始下载", "正在生成")):
logger.info(" 进度:%s", txt)
if not file_url:
raise RuntimeError(f"等待导出文件超时({EXPORT_TIMEOUT_SECONDS}s)")
logger.info("导出完成,文件地址:%s", file_url)
finally:
ws.close()
dl_url = "https://hr.37du.co" + file_url if file_url.startswith("/") else file_url
dl = session.get(dl_url, timeout=120)
if dl.status_code != 200 or not dl.content:
raise RuntimeError(f"下载导出文件失败:HTTP {dl.status_code},{len(dl.content)} 字节")
os.makedirs(download_dir, exist_ok=True)
temp_path = os.path.join(download_dir, f"花名册_{status}_{int(time.time())}.xlsx")
with open(temp_path, "wb") as f:
f.write(dl.content)
logger.info("已下载临时文件:%s(%d 字节)", temp_path, len(dl.content))
return temp_path
def _export_one_status(session, status, download_dir, template_name,
leave_start=None, leave_end=None, export_filters=None):
"""导出单个在职状态的花名册(项目级重试:最大 3 次,登录态失效不重试直接抛出)。"""
last_exc = None
for attempt in range(1, MAX_ATTEMPTS + 1):
try:
return _export_one_status_once(session, status, download_dir, template_name,
leave_start, leave_end, export_filters)
except LoginRequiredError:
raise # 确定性失败,不重试
except Exception as e:
last_exc = e
if attempt >= MAX_ATTEMPTS:
break
delay = 2.0 * attempt
logger.warning("导出在职状态「%s」第 %d 次失败:%s,%.1f 秒后重试",
status, attempt, e, delay)
time.sleep(delay)
logger.error("导出在职状态「%s」连续 %d 次失败,放弃", status, MAX_ATTEMPTS)
raise last_exc
# ==================== 合并输出 ====================
def _save_df_lowmem(df, path: str) -> None:
"""低内存写出 DataFrame:openpyxl write_only 逐行写入。
全集团花名册(在职+离职)数万行 × 30+ 列,pd.DataFrame.to_excel() 峰值内存
(DataFrame 拷贝 + openpyxl 全量 cell + zip 压缩缓冲)可能触发 MemoryError;
改以 write_only 流式逐行写出,内存占用与行数无关。
"""
from openpyxl import Workbook
wb = Workbook(write_only=True)
ws = wb.create_sheet(title="Sheet1")
ws.append([str(c) for c in df.columns])
for row in df.itertuples(index=False, name=None):
ws.append([None if (isinstance(v, float) and pd.isna(v)) else v for v in row])
wb.save(path)
def _normalize_and_save(files_with_status, output_path):
"""合并多个花名册 Excel 文件,添加「类型」列标识在职状态。
统一输出格式:只保留第2行表头,丢弃第1行标题;「类型」列追加在最后一列;
单 sheet,表头在第1行,数据第2行起。
"""
dfs = []
for status, path in files_with_status:
df = pd.read_excel(path, header=1) # 取第2行作表头,丢弃第1行标题
df["类型"] = status
dfs.append(df)
logger.info("读取花名册文件:%s(%s,%d 行)", path, status, len(df))
merged = pd.concat(dfs, ignore_index=True)
out_dir = os.path.dirname(output_path)
if out_dir:
os.makedirs(out_dir, exist_ok=True)
_save_df_lowmem(merged, output_path)
logger.info("合并完成,共 %d 行,已保存:%s", len(merged), output_path)
for _, path in files_with_status:
try:
os.remove(path)
except Exception:
pass
return output_path
# ==================== 导出主流程 ====================
def export_roster(download_dir=None, output_path=None, template_name=None,
statuses=None, leave_start=None, leave_end=None,
ttl=DEFAULT_TTL_SECONDS, session=None):
"""执行员工花名册自定义导出(按需在职状态,各导一次),合并为一个 Excel 文件。
带 TTL 缓存:output_path 已有且距上次导出不超过 ttl 秒时直接复用(跳过接口导出)。
Args:
session: 底座注入的 HR 会话(优先);None 时兜底读共享 cookies。
其余参数与影刀版 export_roster 一致。
Returns:
合并后的花名册文件路径
"""
download_dir = download_dir or os.path.dirname(output_path or "") or "."
output_path = output_path or "花名册.xlsx"
template_name = template_name or DEFAULT_TEMPLATE
statuses = list(statuses) if statuses else list(DEFAULT_STATUSES)
if ttl is None:
ttl = DEFAULT_TTL_SECONDS
# TTL 缓存:输出路径已有、非空且距上次导出不超过 ttl 秒时直接复用
if ttl > 0 and os.path.exists(output_path) \
and os.path.getsize(output_path) > 0 \
and time.time() - os.path.getmtime(output_path) <= ttl:
logger.info("花名册缓存命中(%.0f 分钟内已导出,直接复用):%s", ttl / 60.0, output_path)
return output_path
leave_desc = ""
if "离职" in statuses:
ls, le = leave_start or "", leave_end or ""
if not ls or not le:
ls, le = _get_leave_range()
leave_desc = f",离职时间 {ls} ~ {le}"
logger.info("===== 开始花名册导出(模板:%s,在职状态:%s%s) =====",
template_name, statuses, leave_desc)
session = _build_session(session)
export_filters = resolve_template_filters(session, template_name)
files_with_status = []
for status in statuses:
logger.info("===== 开始导出在职状态:%s =====", status)
path = _export_one_status(session, status, download_dir, template_name,
leave_start, leave_end, export_filters)
files_with_status.append((status, path))
result = _normalize_and_save(files_with_status, output_path)
logger.info("===== 花名册导出并合并完成:%s =====", result)
return result
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""XQ0009 插件 - 业务规则层:缺勤状态映射、连续未出勤段、跨月追溯与名单行组装。"""
+593
View File
@@ -0,0 +1,593 @@
# -*- coding: utf-8 -*-
"""XQ0009 插件 - 核心梳理逻辑(由 workflows/.../absence_analysis.py L722-1312 移植)。
业务规则(与影刀版 v2.2.0 一致):
- 花名册 + 考勤统计报表 + 请假记录,计算每人月末往前连续未出勤段并跨月追溯;
- 「没到公司」判定口径:报表「休息/旷工」精确全等;请假类由请假接口按整天请假
(已备案 002 且 leave_days>=1)逐日覆盖;迟到/漏打卡/早退/出差算到公司;
- 技师(2026-09 起数据迁移到收银系统):未出勤/返岗判定以收银技师月度考勤为准;
- 跨月追溯「逐月重估」:仍在追溯人数 >= TRACE_SINGLE_MAX 用整月全量缓存,
<10 切单人查询;历史月接口数据按月落盘懒缓存(data/hr_api)。
插件化改造点:接口调用统一走 data 层(hr_api/cashier_api);删除自动补登逻辑
(HR 会话失效由 data 层抛 HRSessionExpiredError,插件界面提示重新登录)。
"""
import calendar
import os
from datetime import date, datetime, timedelta
import pandas as pd
from ..config import (
logger, MIN_CONSECUTIVE_DAYS, TRACE_SINGLE_MAX, NOT_BACK_TEXT,
ACTIVE_LEAVE_STATUS, NOT_ATTEND_FRAGMENTS,
)
from ..data import hr_api, cashier_api
# ==================== 日期与清洗工具 ====================
def last_month_range(today=None):
"""返回上月完整月份的 (开始日期, 结束日期)。"""
today = today or date.today()
this_first = today.replace(day=1)
last_end = this_first - timedelta(days=1)
last_begin = last_end.replace(day=1)
return last_begin, last_end
def month_range(month):
"""按 "YYYY-MM" 或 "YYYYMM" 返回该月完整范围的 (开始日期, 结束日期)。"""
m = str(month).replace("-", "")
year, mon = int(m[:4]), int(m[4:6])
last_day = calendar.monthrange(year, mon)[1]
return date(year, mon, 1), date(year, mon, last_day)
def clean(v):
"""转字符串并去掉常见杂质(None、nan、浮点 .0 尾缀)。"""
if v is None:
return ""
s = str(v).strip()
if s.lower() in ("nan", "none"):
return ""
if s.endswith(".0"):
s = s[:-2]
return s
def date_part(v):
"""取日期字符串前 10 位(兼容 "YYYY-MM-DD HH:MM:SS")。"""
return clean(v)[:10]
def parse_date(v):
"""解析日期字符串为 date,失败返回 None。"""
s = date_part(v)
if not s:
return None
try:
return datetime.strptime(s, "%Y-%m-%d").date()
except (TypeError, ValueError):
return None
def _float(v, default=0.0):
"""把请假天数/小时等转 float,解析失败返回 default。"""
s = clean(v)
if not s:
return default
try:
return float(s)
except ValueError:
return default
# ==================== 花名册读取 & 员工映射 ====================
def load_roster(roster_path):
"""读取花名册数据(data/roster_export_api.py 导出的合并文件,表头在第 1 行)。"""
if not roster_path or not os.path.exists(roster_path):
raise RuntimeError(
f"未找到花名册文件:{roster_path}\n"
"插件会自动导出花名册到保存目录(员工花名册.xlsx);若配置了自定义花名册路径,"
"请确认文件存在后再重试。")
try:
df = pd.read_excel(roster_path, dtype=str)
except Exception as e:
raise RuntimeError(
f"花名册文件无法读取:{roster_path}\n"
f"可能原因:文件损坏、被 Excel/WPS 占用或格式不正确。详情:{e}")
df.columns = [str(c).strip() for c in df.columns]
logger.info("已读取花名册:%s,共 %d 行", roster_path, len(df))
return df
def build_emp_map(df):
"""按工号建员工信息映射;同一工号多条时优先「在职」记录。"""
emp = {}
for _, row in df.iterrows():
code = clean(row.get("工号"))
if not code:
continue
if code in emp and clean(row.get("类型")) != "在职":
continue # 已有在职记录,跳过离职/其他
emp[code] = row
logger.info("花名册有效员工:%d 人", len(emp))
return emp
# ==================== 核心梳理逻辑 ====================
# 「没到公司」判定口径:
# 1. 考勤统计报表负责精确判定两类「没到公司」:休息、旷工(均用 == 全等,不含「上班旷工/下班旷工」半天);
# 2. 请假类逐日出勤不由报表文本猜测,改由请假接口按「整天请假(leave_days>=1)」精确覆盖
# (半天假/小时特假 leave_days<1 不算整天缺席);
# 3. 迟到/漏打卡/早退/出差等一律算「到公司」。
def _is_absent(status, seen=None):
"""报表单个逐日状态是否算「没到公司」。仅精确命中 休息/旷工 才算。空值视为不在职该日,不算。"""
s = clean(status)
if not s:
return False
if seen is not None:
seen[s] = seen.get(s, 0) + 1
return s == "休息" or s == "旷工"
# ---------- 报表 / 请假 -> 缺勤状态映射 ----------
def report_records_to_status(records, begin, end, seen=None):
"""把某月全集团报表 datas 转成 {工号: {日期: 类别}}。
类别 ∈ {旷工, 休息}(报表「休息/旷工」判未出勤;其余如迟到/漏打卡算到公司)。
返回的同时保留每日具体类别,供「备注」列直接统计,无需再发请求。
"""
out = {}
for rec in records:
code = clean(rec.get("base_code"))
if not code:
continue
daymap = {}
d = begin
i = 1
while d <= end:
cell = clean(rec.get(f"v_{i}"))
if cell == "休息":
daymap[d] = "休息"
elif cell == "旷工":
daymap[d] = "旷工"
elif _is_absent(rec.get(f"v_{i}"), seen):
daymap[d] = "请假" # 报表里出现的其他缺勤态兜底归为请假
d += timedelta(days=1)
i += 1
if daymap:
out[code] = daymap
return out
def cur_month_status(records, begin, end):
"""构建当前月(部分月)「未到公司」状态映射 {工号: {日期: 类别}},仅用于返岗判定。
统计月之后的当前月 1 日~今天,判断某人是否已返岗:报表单元格非空且不在该映射内 = 当天出勤。
判定口径与统计月保持一致(休息/旷工 精确全等算未出勤),另把报表出现的请假类文本
(病假/事假/产假/调休假/福利假/小时特假等,见 NOT_ATTEND_FRAGMENTS)一并判为未出勤,
避免把「仍在请假中」的人误判成已返岗;「上班旷工,下班旷工」整天没来也判未出勤
(半天「上班旷工/下班旷工」单独出现仍算到公司,与统计月口径一致)。
"""
out = {}
for rec in records:
code = clean(rec.get("base_code"))
if not code:
continue
daymap = {}
d = begin
while d <= end:
cell = clean(rec.get(f"v_{d.day}"))
if cell == "休息":
daymap[d] = "休息"
elif cell == "旷工":
daymap[d] = "旷工"
elif cell and any(frag in cell for frag in NOT_ATTEND_FRAGMENTS):
daymap[d] = "请假"
elif "上班旷工" in cell and "下班旷工" in cell:
daymap[d] = "旷工"
d += timedelta(days=1)
if daymap:
out[code] = daymap
return out
def full_day_leave_status(leaves, begin, end):
"""把全集团请假记录转成 {工号: {日期: '请假'}}(仅已备案 002 且 leave_days>=1,半天/小时假排除)。
整天请假以请假记录起止区间逐日覆盖;半天假/小时特假(leave_days<1)不构成整天缺席。
仅认 status=002(已备案)的假单:已撤销(003)/已销假(005)/申请中(001) 的假单在考勤报表里
不体现,若计入会把实际正常上班的人误判为缺勤,故一并排除。
"""
out = {}
for rec in leaves:
code = clean(rec.get("base_code"))
if not code:
continue
# 只认已备案(002)的请假;已撤销/已销假/申请中的假单不构成整天缺席
if clean(rec.get("status")) != ACTIVE_LEAVE_STATUS:
continue
st = parse_date(rec.get("start_time") or rec.get("begin_date") or rec.get("START_TIME"))
et = parse_date(rec.get("end_time") or rec.get("end_date") or rec.get("END_TIME"))
if not st or not et:
continue
# leave_days 为空字符串/0/0.5 等(半天假、小时特假)一律不算整天缺席;
# _float 对空值返回默认 0.0,故 ""、0.0、0.5 都会被 <1 分支排除。
if _float(rec.get("leave_days")) < 1:
continue
d = st
while d <= et:
if begin <= d <= end:
out.setdefault(code, {})[d] = "请假"
d += timedelta(days=1)
return out
def merge_leave_status(base, leaves, begin, end):
"""把整天请假类目并入 base。优先级:已有 旷工/休息 不覆盖;否则记为 请假。"""
for code, daymap in full_day_leave_status(leaves, begin, end).items():
for d, cat in daymap.items():
base.setdefault(code, {}).setdefault(d, cat)
def status_to_set(status):
"""把状态映射 {工号: {日期: 类别}} 转成 {工号: 缺勤日集合},供连续段计算使用。"""
return {code: set(daymap.keys()) for code, daymap in status.items()}
def month_status_map(month_cache, session, user_id, month_str, seen=None):
"""构建并缓存某月全集团「没到公司」状态映射 {工号: {日期: 类别}}(报表 休息/旷工 + 全天请假)。
供跨月追溯复用:某月首次访问时拉一次全集团报表 + 一次全集团请假并合并存入缓存,
之后该月所有员工直接从缓存解析,避免按人逐次查询。类别含 旷工/休息/请假。
"""
if month_str not in month_cache:
mb, me = month_range(month_str)
records = hr_api.cached_attendance(session, user_id, month_str.replace("-", ""))
merged = report_records_to_status(records, mb, me, seen)
# 追溯月 >= 2026-09:HR + 收银两份数据,技师未出勤以收银为准覆盖(HR 该月起无技师数据)
if cashier_api.is_cashier_month(month_str):
try:
tech_map = cashier_api.cashier_tech_status(month_str)
for code, daymap in tech_map.items():
merged[code] = daymap
logger.info("收银技师考勤并入追溯月 %s:%d 人", month_str, len(tech_map))
except Exception as e:
logger.warning("收银技师考勤拉取失败(追溯月 %s 技师数据可能缺失):%s", month_str, e)
leaves = hr_api.cached_leave(session, user_id, "", month_str)
merge_leave_status(merged, leaves, mb, me)
logger.info("已构建 %s 月缺勤映射(报表 %d 人 + 全集团请假 %d 条)",
month_str, len(merged), len(leaves))
month_cache[month_str] = merged
return month_cache[month_str]
def log_statuses(seen):
"""打印观察到的所有逐日状态,供人工核对「休息/旷工精确判定」是否符合预期。"""
if not seen:
return
summary = ", ".join(f"{k}={v}" for k, v in sorted(seen.items(), key=lambda x: -x[1]))
logger.info("考勤统计报表逐日状态分布(值=次数):%s", summary)
# ---------- 连续未出勤段(休息日计入;月份边界触及则跨月往前推) ----------
def trailing_absence_run(abs_or_rest, begin, end):
"""计算「从月末最后一天往前」的连续未出勤段。
「没到公司」= 该日在 abs_or_rest(请假 ∪ 旷工 ∪ 休息)。
名单口径:仅统计月末最后一天往前连续未出勤 >= MIN_CONSECUTIVE_DAYS 天的人员
(即月末最后 MIN_CONSECUTIVE_DAYS 天均没出勤);最后一天已出勤、或连续段不足
阈值者不纳入名单(统计月内已回来出勤或月初即回岗的不算)。
Returns:
(start, end, opens_back) 或 None。
start:从月末往前连续未出勤段的起点;opens_back:段触及 begin(月首,需往前推)。
"""
d = end
while d >= begin and d in abs_or_rest:
d -= timedelta(days=1)
start = d + timedelta(days=1)
if (end - start).days + 1 < MIN_CONSECUTIVE_DAYS:
return None
return start, end, start == begin
def person_month_absent(session, user_id, code, month_str, seen=None, status_cache=None):
"""查某员工某月「没到公司」日集合(报表 base_code 单人查询 休息/旷工 + 该员工整天请假)。
同时把每月状态并入 status_cache({month: {code: {date: cat}}}),供「备注」统计复用,
避免单人追溯场景下备注再发请求。
"""
mb, me = month_range(month_str)
daymap = {}
records = hr_api.cached_attendance(session, user_id, month_str.replace("-", ""), code)
for rec in records:
if clean(rec.get("base_code")) != code:
continue
d = mb
i = 1
while d <= me:
cell = clean(rec.get(f"v_{i}"))
if cell == "休息":
daymap[d] = "休息"
elif cell == "旷工":
daymap[d] = "旷工"
elif _is_absent(rec.get(f"v_{i}"), seen):
daymap[d] = "请假"
d += timedelta(days=1)
i += 1
break
# 追溯月 >= 2026-09:技师未出勤以收银为准覆盖(HR 该月起无技师数据,避免技师段漏判)。
# 直接查该月收银映射是否含该工号,命中即视为技师并以收银为准(不依赖全局 tech_codes)。
if cashier_api.is_cashier_month(month_str):
try:
tech_daymap = cashier_api.cashier_tech_status(month_str).get(code, {})
if tech_daymap:
daymap = dict(tech_daymap)
logger.info("收银技师考勤覆盖追溯月 %s %s(%d 天)", month_str, code, len(daymap))
except Exception as e:
logger.warning("收银技师考勤拉取失败(%s %s):%s", month_str, code, e)
merge_leave_status({code: daymap},
hr_api.cached_leave(session, user_id, code, month_str), mb, me)
if status_cache is not None and daymap:
status_cache.setdefault(month_str, {}).setdefault(code, {}).update(daymap)
return set(daymap.keys())
def backward_starts_batch(session, user_id, begin, traced, month_cache, single_cache, seen=None):
"""逐月重估的跨月追溯:所有「段触及月首」的员工从统计月首前一日同速往回走。
每往前推一个月,先看「仍在追溯的人数」:
- 人数 >= TRACE_SINGLE_MAX → 整月全量缓存(month_cache,每月报表+请假各拉一次,多人共用);
- 人数 < TRACE_SINGLE_MAX → 逐人单人查询(single_cache,每月每人报表+请假各一次)。
追溯人数随月份往前递减(找到上班日的逐步毕业),早期月份批量、人少了自动切单人,
避免像固定「整月全量缓存」那样为最后几个人还每月全量拉取。
每月状态均并入对应缓存(month_cache / single_cache),供「备注」统计复用。
Args:
begin: 统计月首日期(opens_back 的段起点,即 begin-1 起步)。
traced: [(code, lower_bound), ...],段触及月首、需要跨月追溯的员工。
Returns:
{code: 请休假起始日期};回溯到入职日前仍未上班的返回 lower_bound。
"""
result = {}
d = begin - timedelta(days=1) # 所有人同速从统计月首前一日往回走
active = list(traced)
while active:
m_str = d.strftime("%Y-%m")
mb, _ = month_range(m_str)
if len(active) >= TRACE_SINGLE_MAX:
logger.info("追溯月 %s:%d 人在追溯,用整月全量缓存", m_str, len(active))
month_map = month_status_map(month_cache, session, user_id, m_str, seen)
def get_not_att(code, _map=month_map):
return _map.get(code, {})
else:
logger.info("追溯月 %s:%d 人在追溯,切为单人查询", m_str, len(active))
for code, _ in active:
person_month_absent(session, user_id, code, m_str, seen, single_cache)
def get_not_att(code, _m=m_str, _cache=single_cache):
return _cache.get(_m, {}).get(code, {})
next_active = []
for code, lower_bound in active:
not_att = get_not_att(code)
dd = d
while dd >= mb and dd >= lower_bound:
if dd in not_att:
dd -= timedelta(days=1)
else:
result[code] = dd + timedelta(days=1) # 昨日为上班日
break
else:
if lower_bound < mb:
next_active.append((code, lower_bound)) # 本月内未找到上班日,继续往前
else:
result[code] = lower_bound # 已回溯到入职日前仍未上班
d = mb - timedelta(days=1)
active = next_active
return result
def segment_breakdown(code, seg_start, seg_end, query_month, q_map, get_month_status):
"""统计连续未出勤段内 旷工/请假/休息 天数(纯内存,复用已拉取的状态映射,0 额外请求)。
query_month:查询月 "YYYY-MM";q_map:该员工查询月状态 {日期: 类别}。
get_month_status(month_str) -> {工号: {日期: 类别}},取查询月之外的追溯月状态。
"""
cnt = {"旷工": 0, "请假": 0, "休息": 0}
m_start = seg_start.replace(day=1)
while m_start <= seg_end:
m_str = m_start.strftime("%Y-%m")
mb, me = month_range(m_str)
if m_str == query_month:
dmap = q_map
else:
status_map = get_month_status(m_str)
dmap = status_map.get(code, {}) if status_map is not None else {}
lo = max(mb, seg_start)
hi = min(me, seg_end)
d = lo
while d <= hi:
cat = dmap.get(d)
if cat in cnt:
cnt[cat] += 1
d += timedelta(days=1)
m_start = me + timedelta(days=1)
return cnt
def latest_leave_end(session, user_id, code, begin, end):
"""查询该员工查询月请假记录,返回「请假实际截止日期晚于统计期最后一天」的最新请假截止日。
情况A(月末仍缺席)判定:仅当存在请假截止日期 > 统计期最后一天(请假仍在进行/跨出统计期)
时,以其截止日作为请休假结束日期;否则视为未归岗(返回 None,外部填「未归岗,时间待定」)。
统计月始终实时调接口,不走缓存。
两个防误判点:
1. 用 end_date(请假实际结束日期)而非 end_time(带时刻,跨下班时段结束的假会溢出到
下月 1 号 00:00/00:30…),避免把「月末下半段结束的假」误判成跨月仍在休;
2. 仅认 status=002(已备案)的假单:已撤销(003)/已销假(005) 的假单不构成「仍在休假中」。
"""
leaves = hr_api.fetch_all_leave(
session, user_id, code, begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d")
)
ongoing = []
for r in leaves:
if clean(r.get("status")) != ACTIVE_LEAVE_STATUS:
continue
d = parse_date(r.get("end_date") or r.get("end_time"))
if d and d > end:
ongoing.append(d)
if not ongoing:
return None
return max(ongoing).strftime("%Y-%m-%d")
def analyze(emp, month_status, session, user_id, begin, end, cur_ctx=None):
"""按每人「没到公司」日集合,计算月末往前连续未出勤段,组装名单行。
名单口径:仅保留「从月末最后一天往前连续未出勤 >= MIN_CONSECUTIVE_DAYS 天」的人员
(即月末最后 5 天均没出勤);统计月内已回来出勤、或月末最后 5 天内有出勤的不放入名单。
结束日期口径(情况A/B):
- 统计月已结束且当前月 != 统计月时,用当前月 1 日~今天 的考勤判定返岗(cur_ctx):
当前月内出现首次出勤 = 已返岗,结束日期 = 返岗日前一日(情况B);无出勤则走情况A;
- 情况A:请假仍在进行(已备案假单 end_date > 统计月末)取请假截止日,否则「未归岗,时间待定」。
两遍处理:
1. 先对全部候选算 trailing_absence_run,过滤掉不合格人员并统计需跨月追溯的人数;
2. 跨月追溯用「逐月重估」:每往前推一个月按仍在追溯的人数选整月缓存或单人查询,
再逐个解析起始日、统计备注并组装名单行。
month_status:查询月全集团状态映射 {工号: {日期: 类别}}(含 旷工/休息/请假)。
cur_ctx:返岗判定上下文 (cur_status, cur_rows, cur_begin, cur_end, cashier_cur),
None 表示不需要。cur_rows 为 {工号: 当前月报表记录};cashier_cur 为收银技师
当前月「出勤日集合」{工号: {日期}},code 命中时以其判定返岗(技师源,HR 当前月
无技师数据);未命中走 cur_rows 报表判定。
"""
seen = {}
query_month = begin.strftime("%Y-%m")
month_absent = status_to_set(month_status) # 供连续段计算使用的缺勤日集合
candidate_codes = list(month_absent.keys())
logger.info("候选员工(当月有请假/旷工/休息至少一天):%d 人", len(candidate_codes))
# 第一遍:求每人「月末往前」连续未出勤段 + 追溯需求,统计追溯人数
runs = {}
for code in candidate_codes:
r = emp.get(code)
res = trailing_absence_run(month_absent.get(code, set()), begin, end)
if res is None:
continue
seg_start, seg_end, opens_back = res
join = parse_date(r.get("入职时间")) if r is not None else None
lower_bound = (join if join and join < begin else begin - timedelta(days=365 * 2))
runs[code] = {
"r": r, "seg_start": seg_start, "seg_end": seg_end,
"opens_back": opens_back,
"lower_bound": lower_bound,
}
n_trace = sum(1 for it in runs.values() if it["opens_back"])
logger.info("需跨月追溯(段触及月首)员工:%d 人", n_trace)
# 跨月追溯「逐月重估」:详见 backward_starts_batch
cache = {} # 整月全量缓存 {month: {code: {date: cat}}}
single_cache = {} # 单人查询缓存 {month: {code: {date: cat}}}
def get_month_status(month_str):
if month_str == query_month:
return month_status
if month_str in cache:
return cache[month_str]
return single_cache.get(month_str)
# 追溯起始日:段触及月首的员工统一逐月往回推(逐月重估批量/单人),其余直接取段起点
traced = [(code, it["lower_bound"]) for code, it in runs.items() if it["opens_back"]]
starts = backward_starts_batch(session, user_id, begin, traced, cache, single_cache, seen) \
if traced else {}
log_statuses(seen)
# 第二遍:解析各人起始日 + 组装名单行
rows = []
for code, it in runs.items():
seg_start = starts.get(code, it["seg_start"])
seg_end = it["seg_end"]
r = it["r"]
# 结束日期与天数:
# 优先用「当前月考勤返岗判定」:统计月后当前月 1 日~今天 内首次出勤(报表有状态且非
# 休息/旷工/请假类)= 已返岗,结束日期 = 返岗日前一日(情况B口径),不再只靠请假判断;
# 否则回到情况A:请假仍在进行(已备案假单 end_date > 统计月末)取请假截止日,无则「未归岗,时间待定」。
return_day = None
if cur_ctx is not None:
cur_status, cur_rows, cur_begin, cur_end, cashier_cur = cur_ctx
# 技师(收银源,>= 2026-09 的当前月):用收银「出勤日集合」判定返岗(HR 当前月无技师数据)
if code in cashier_cur:
for d in sorted(cashier_cur[code]):
if cur_begin <= d <= cur_end:
return_day = d
break
else:
row = cur_rows.get(code)
if row is not None:
cur_absent = cur_status.get(code, {})
d = cur_begin
while d <= cur_end:
if clean(row.get(f"v_{d.day}")) and d not in cur_absent:
return_day = d
break
d += timedelta(days=1)
if return_day is not None:
end_date = return_day - timedelta(days=1)
end_str = end_date.strftime("%Y-%m-%d")
days_str = str((end_date - seg_start).days + 1)
else:
leave_end = latest_leave_end(session, user_id, code, begin, end)
if leave_end:
end_str = leave_end
days_str = str((parse_date(leave_end) - seg_start).days + 1)
else:
end_str = NOT_BACK_TEXT
days_str = ""
# 备注:统计连续未出勤段内 旷工/请假/休息 天数(纯内存复用已拉取状态,0 额外请求)
cnt = segment_breakdown(code, seg_start, seg_end, query_month,
month_status.get(code, {}), get_month_status)
note = "旷工{}天,请假{}天,休息{}天".format(cnt["旷工"], cnt["请假"], cnt["休息"])
rows.append({
"序号": 0,
"所属单位": clean(r.get("所属单位")) if r is not None else "",
"所属部门": clean(r.get("所属部门")) if r is not None else "",
"一级部门": clean(r.get("一级部门")) if r is not None else "",
"二级部门": clean(r.get("二级部门")) if r is not None else "",
"三级部门": clean(r.get("三级部门")) if r is not None else "",
"四级部门": clean(r.get("四级部门")) if r is not None else "",
"五级部门": clean(r.get("五级部门")) if r is not None else "",
"37工号": code,
"姓名": clean(r.get("姓名")) if r is not None else "",
"联系电话": clean(r.get("手机号码")) if r is not None else "",
"岗位": clean(r.get("岗位")) if r is not None else "",
"技师工号": clean(r.get("技师工号")) if r is not None else "",
"参保类型": clean(r.get("参保类型")) if r is not None else "",
"入职时间": date_part(r.get("入职时间")) if r is not None else "",
"离职时间": date_part(r.get("离职时间")) if r is not None else "",
"请休假起始日期": seg_start.strftime("%Y-%m-%d"),
"请休假结束日期": end_str,
"请休假天数": days_str,
"备注": note,
})
# 排序并补序号(按 所属单位/所属部门/一级~五级部门/工号)
rows.sort(key=lambda r: (r["所属单位"], r["所属部门"], r["一级部门"], r["二级部门"],
r["三级部门"], r["四级部门"], r["五级部门"], r["37工号"]))
for idx, item in enumerate(rows, 1):
item["序号"] = idx
logger.info("月末最后 %d 天均未出勤(连续未出勤,跨月前推)的员工:%d 人",
MIN_CONSECUTIVE_DAYS, len(rows))
return rows
+53
View File
@@ -0,0 +1,53 @@
{
"schema_version": 1,
"id": "xq0009",
"name": "门店上月请休假异常人员名单梳理",
"version": "1.0.4",
"description": "梳理上月请休假异常人员名单:花名册 + 考勤统计报表 + 请假记录(2026-09 起技师考勤联动收银系统),计算每人月末往前连续未出勤 ≥5 天并跨月追溯,确定请休假起止日期与天数(当前月返岗判定),导出 20 列 Excel 名单。",
"category": "人事考勤",
"icon": "",
"platform": "hr",
"uses_month": true,
"ui": true,
"capabilities": ["xq0009"],
"permissions": {
"platforms": ["hr"]
},
"fields": {
"type": "object",
"properties": {
"ref_month": {
"type": "string",
"title": "统计月份",
"default": "",
"description": "留空=上月;格式 YYYY-MM(如 2026-08)"
},
"save_dir": {
"type": "string",
"title": "输出目录",
"default": "D:\\资料\\人资\\请休假异常",
"description": "名单 Excel 与花名册输出目录"
},
"roster_path": {
"type": "string",
"title": "花名册路径",
"default": "",
"description": "留空=输出目录/员工花名册.xlsx(插件自动导出,15 分钟内缓存复用)"
},
"cashier_username": {
"type": "string",
"title": "收银系统账号",
"default": "",
"description": "技师考勤数据源(2026-09 起技师考勤迁移到收银系统);留空时复用已缓存登录态,无登录态则降级仅用 HR(技师数据缺失)"
},
"cashier_password": {
"type": "string",
"title": "收银系统密码",
"default": "",
"format": "password",
"description": "填了账号需同时填密码;凭据错误会中止运行(避免静默导出缺技师数据的名单)"
}
},
"required": []
}
}
+2
View File
@@ -0,0 +1,2 @@
# -*- coding: utf-8 -*-
"""XQ0009 插件 - 报告层:主流程编排与 Excel 导出。"""
+177
View File
@@ -0,0 +1,177 @@
# -*- coding: utf-8 -*-
"""XQ0009 插件 - 报告编排层:主流程 + Excel 导出(由影刀版 L1353-1490 移植)。
主流程(与影刀版 export_absence_list 一致,删除钉钉推送/影刀全局变量交接):
1) 会话校验:底座注入 HR 会话 → getCurUserInfo 校验取 userId(失效抛错提示重新登录);
2) 花名册:字段指定已有文件,或由 data/roster_export_api 自动导出到保存目录
(员工花名册.xlsx,15 分钟 TTL 缓存复用);
3) 收银会话:统计月或当前月 >= CASHIER_MIGRATE_MONTH(2026-09) 时初始化;
提供凭据登录失败直接中止(避免静默缺技师数据出错名单),无凭据降级仅用 HR;
4) 统计月数据(实时):考勤统计报表 → 报表缺勤映射 → 技师收银覆盖 → 全集团请假并入;
5) 返岗判定数据:统计月已结束时补拉当前月 1 日~今天(实时),技师出勤日集合走收银;
6) analyze 计算月末往前连续未出勤段(跨月追溯逐月重估)→ export_excel 导出 20 列名单。
"""
import os
from datetime import date, datetime
import pandas as pd
from ..config import (
logger, DEFAULT_SAVE_DIR, COLUMNS, MIN_CONSECUTIVE_DAYS, require_session,
)
from ..data import hr_api, cashier_api, roster_export_api
from ..logic import absence_analysis as core
def resolve_month(ref_month):
"""解析统计月份:"YYYY-MM"/"YYYYMM";留空=上月完整月份。返回 (begin, end, month_str="YYYYMM")。"""
ref = (ref_month or "").strip()
if ref:
begin, end = core.month_range(ref)
else:
begin, end = core.last_month_range()
return begin, end, f"{begin:%Y%m}"
def export_excel(rows, save_dir, month_str):
"""将名单行导出为 .xlsx(无数据时也保留表头,便于对照)。"""
os.makedirs(save_dir, exist_ok=True)
df = pd.DataFrame(rows, columns=COLUMNS)
ts = datetime.now().strftime("%Y%m%d_%H%M%S")
save_path = os.path.abspath(
os.path.join(save_dir, f"门店上月请休假异常名单_{month_str}_{ts}.xlsx"))
try:
df.to_excel(save_path, index=False)
except PermissionError:
raise RuntimeError(
f"导出失败:文件正被占用,请先关闭已打开的 Excel"
f"「{os.path.basename(save_path)}」后重试。无需重查数据。")
except OSError as e:
raise RuntimeError(
f"导出失败:无法写入文件「{save_path}」({e}),请检查磁盘空间或目录权限")
logger.info("名单数据:%d 条", len(rows))
logger.info("文件已保存:%s", save_path)
return save_path
def _prepare_roster(roster_path, save_dir, session):
"""花名册准备:指定路径直接用;否则自动导出到保存目录/员工花名册.xlsx(15 分钟 TTL 缓存)。"""
roster_path = (roster_path or "").strip()
if roster_path:
logger.info("使用指定花名册:%s", roster_path)
return roster_path
output_path = os.path.join(save_dir, "员工花名册.xlsx")
return roster_export_api.export_roster(download_dir=save_dir, output_path=output_path,
session=session)
def build_absence_report(save_dir=None, roster_path=None, ref_month="",
cashier_username="", cashier_password="", progress=None):
"""梳理上月请休假异常名单并导出 Excel。
Returns:
dict:{path 导出文件路径, count 名单人数, month 统计月 "YYYYMM", begin, end 统计范围}
"""
def _step(pct):
if progress:
try:
progress(pct)
except Exception:
pass
save_dir = (save_dir or "").strip() or DEFAULT_SAVE_DIR
os.makedirs(save_dir, exist_ok=True)
begin, end, month_str = resolve_month(ref_month)
today = date.today()
today_m = today.strftime("%Y-%m")
logger.info("===== 请休假异常名单梳理,统计范围:%s ~ %s =====",
begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"))
# 1. HR 会话校验(底座注入,失效抛 HRSessionExpiredError 提示重新登录)
_step(5)
session = require_session()
user_id = hr_api.validate_session(session)
# 2. 花名册
roster_file = _prepare_roster(roster_path, save_dir, session)
df = core.load_roster(roster_file)
emp = core.build_emp_map(df)
_step(10)
# 2.5 收银系统会话(技师考勤源):统计月或当前月落在迁移月及以后时初始化;
# 无凭据且无有效缓存登录态时降级仅用 HR(不阻断流程);
# 提供凭据后登录失败由 ensure_session 抛 RuntimeError 中止(避免错名单)。
cashier_ready = False
if cashier_api.is_cashier_month(month_str) or cashier_api.is_cashier_month(today_m):
cashier_ready = cashier_api.ensure_session(cashier_username, cashier_password)
_step(15)
# 3. 统计月数据(实时调接口,不走缓存)
seen = {}
records = hr_api.fetch_all_attendance_stat(session, user_id, month_str)
logger.info("考勤统计报表共 %d 人", len(records))
if not records:
raise RuntimeError("考勤统计报表无数据,请检查月份或权限")
month_status = core.report_records_to_status(records, begin, end, seen)
# 统计月 >= 2026-09:HR + 收银两份,技师未出勤以收银为准覆盖(HR 该月起无技师数据)
if cashier_ready and cashier_api.is_cashier_month(month_str):
try:
tech_map = cashier_api.cashier_tech_status(month_str)
for code, daymap in tech_map.items():
month_status[code] = daymap
logger.info("收银技师考勤并入统计月 %d 人", len(tech_map))
except Exception as e:
logger.warning("收银技师考勤拉取失败(技师数据可能缺失):%s", e)
leaves = hr_api.fetch_all_leave(
session, user_id, "", begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"))
core.merge_leave_status(month_status, leaves, begin, end)
logger.info("全集团请假记录 %d 条(整天请假已并入缺勤判定)", len(leaves))
core.log_statuses(seen)
_step(40)
# 3.5 返岗判定数据:统计月已结束且当前月 != 统计月时,补拉当前月 1 日~今天 的考勤报表
# +请假记录(实时),用于判断名单人员是否已返岗(不再只靠请假判断)。
cur_ctx = None
if end < today:
cur_begin = today.replace(day=1)
cur_end = today
cur_records = hr_api.fetch_all_attendance_stat(session, user_id, today.strftime("%Y%m"))
cur_status = core.cur_month_status(cur_records, cur_begin, cur_end)
cur_leaves = hr_api.fetch_all_leave(
session, user_id, "",
cur_begin.strftime("%Y-%m-%d"), cur_end.strftime("%Y-%m-%d"))
core.merge_leave_status(cur_status, cur_leaves, cur_begin, cur_end)
cur_rows = {core.clean(r.get("base_code")): r
for r in cur_records if core.clean(r.get("base_code"))}
# 当前月 >= 2026-09:技师返岗判定用收银「出勤日集合」(HR 当前月无技师数据,row 为空会漏判)
cashier_cur = {}
if cashier_ready and cashier_api.is_cashier_month(today_m):
try:
# 先确保当前月收银映射(含出勤日 month_on)已加载
cashier_api.cashier_tech_status(today_m)
cashier_cur = dict(cashier_api.state["month_on"].get(today_m, {}))
logger.info("收银技师当前月返岗判定:%d 名技师有出勤日", len(cashier_cur))
except Exception as e:
logger.warning("收银技师当前月数据拉取失败(返岗判定降级):%s", e)
cur_ctx = (cur_status, cur_rows, cur_begin, cur_end, cashier_cur)
logger.info("统计月 %s 已结束,补拉当前月 %s ~ %s 考勤用于返岗判定",
month_str, cur_begin.strftime("%Y-%m-%d"), cur_end.strftime("%Y-%m-%d"))
_step(55)
# 4. 计算月末往前连续未出勤段(跨月追溯「逐月重估」:批量/单人自适应)
rows = core.analyze(emp, month_status, session, user_id, begin, end, cur_ctx)
_step(95)
# 5. 导出
path = export_excel(rows, save_dir, month_str)
_step(100)
logger.info("=" * 60)
logger.info("【请休假异常名单汇总】")
logger.info(" 统计范围:%s ~ %s", begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"))
logger.info(" 连续未出勤 >= %d 天:%d 人", MIN_CONSECUTIVE_DAYS, len(rows))
logger.info(" 导出文件:%s", path)
logger.info("=" * 60)
return {"path": path, "count": len(rows), "month": month_str,
"begin": begin.strftime("%Y-%m-%d"), "end": end.strftime("%Y-%m-%d")}
+4
View File
@@ -0,0 +1,4 @@
requests
pandas
openpyxl
websocket-client
File diff suppressed because one or more lines are too long
File diff suppressed because one or more lines are too long
+13
View File
@@ -0,0 +1,13 @@
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8" />
<meta name="viewport" content="width=device-width, initial-scale=1.0" />
<title>门店上月请休假异常人员名单梳理</title>
<script type="module" crossorigin src="/pui/xq0009/assets/index-fU1lHPGO.js"></script>
<link rel="stylesheet" crossorigin href="/pui/xq0009/assets/index-CTFFjqMR.css">
</head>
<body>
<div id="app"></div>
</body>
</html>