feat: 新增银行卡检查插件及相关依赖与配置文件

This commit is contained in:
2026-10-29 14:21:30 +08:00
parent 0a32518060
commit c77a26cd99
494 changed files with 66923 additions and 2714 deletions
+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