feat(xq0002): 完成雇主险增减操作插件开发并补齐配套资源

- 新增XQ0002雇主险增减操作插件完整实现,包含数据层、逻辑层、UI界面
- 新增测试用的样板数据文件与插件打包脚本
- 更新文档说明插件当前状态与使用方式
- 新增收银系统登录共享模块供业务流程复用
This commit is contained in:
2026-09-22 12:41:16 +08:00
parent 6f78ed2e72
commit a1cf59f09c
39 changed files with 5938 additions and 204 deletions
@@ -197,6 +197,194 @@ PUSH_AT_ALL_ENV = "absence_push_at_all" # "1" 时推送文本 @所有
# 缓存以 月/工号 为键互不影响,如需强制刷新删除对应缓存文件即可。
CACHE_DIR = os.path.join(_APP_DATA_DIR, "absence_cache")
# ==================== 收银系统技师考勤(内联,单文件自包含) ====================
# 背景:HR 系统从 2026-09 起不再有技师考勤数据(技师考勤迁移到收银系统),需求9 需两个系统联动:
# - 技师:未出勤日集合来自收银技师月度考勤接口(旷工/请假/休息 逐日显式标记);
# - 非技师:仍走 HR 考勤统计报表 + 请假流程(下方 HR 逻辑不变)。
# 时间边界(重要):2026-09 是技师数据迁移分界——
# - 统计月 / 当前月 >= 2026-09 时,技师未出勤/返岗判定走收银(HR 该月起无技师数据);
# - 统计月早于 2026-09,以及跨月追溯的历史月(2026-09 之前),一律走 HR 原逻辑
# (历史技师数据仍在 HR,见 _month_status_map / _person_month_absent,不做收银覆盖)。
CASHIER_MIGRATE_MONTH = "2026-09" # HR 技师数据迁移到收银的起始月
CASHIER_TOKEN_FILE = os.path.join(_SESSIONS_DIR, 'cashier_tokens.json')
CASHIER_API_BASE = "https://api.37du.cashier.37du.co"
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")
# 收银逐日 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: "休息"}
# 收银扩展运行时状态(懒初始化):
# session 收银 requests 会话(由 _cashier_build_session 构建)
# tech_codes 已拉取收银考勤的技师 37工号 集合(用于跨月追溯判断「该人走收银数据」)
# month_status 收银未出勤映射缓存 {month: {code: {日期: 类别}}}
# month_on 收银出勤日缓存 {month: {code: {日期}}}(当前月返岗判定用)
_cashier_ext = {"session": None, "tech_codes": set(),
"month_status": {}, "month_on": {}}
def _cashier_build_session():
"""内联:读共享收银 token 构造 requests 会话(认证头 Access-Token/Refresh-Token)。"""
if not os.path.exists(CASHIER_TOKEN_FILE):
raise RuntimeError("未找到收银系统登录态 tokens,请先执行「37du收银登录」指令完成登录后再重试。")
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,请重新执行「37du收银登录」指令。")
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 _cashier_request(session, method, url, params=None, payload=None):
"""收银接口请求(项目级重试 3 次;401/非 JSON 视为登录失效直接报错)。"""
last_exc = None
for attempt in range(1, 4):
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),请重新执行「37du收银登录」指令。")
if resp.status_code != 200:
raise RuntimeError(f"收银接口状态码异常:HTTP {resp.status_code}")
text = resp.text
if not text.lstrip().startswith(("{", "[")):
raise RuntimeError("收银登录态已失效(接口未返回 JSON),请重新执行「37du收银登录」指令。")
return resp.json()
except RuntimeError:
raise
except Exception as e:
last_exc = e
if attempt >= 3:
break
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 _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 _cashier_tech_status(month_key):
"""拉取某月全部门店收银技师考勤 → 未出勤映射 {工号: {日期: 类别}}(带缓存)。
同时把该月各技师「出勤日集合」写入 _cashier_ext["month_on"][month_key][code],
供当前月返岗判定使用;技师工号并入 _cashier_ext["tech_codes"]。
未初始化收银会话(无 token)时返回空 dict(调用方降级仅用 HR 数据)。
注意:仅统计月 / 当前月(>= CASHIER_MIGRATE_MONTH)才调用本函数;跨月追溯的历史月
(2026-09 之前)技师数据仍在 HR,走 _month_status_map / _person_month_absent 原逻辑。
"""
if _cashier_ext["session"] is None:
return {}
if month_key in _cashier_ext["month_status"]:
return _cashier_ext["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(_cashier_ext["session"])
result, on_map = {}, {}
for store in stores:
store_id = store.get("store_id")
try:
data = _cashier_request(
_cashier_ext["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
_cashier_ext["tech_codes"].add(code)
_cashier_ext["month_status"][month_key] = result
_cashier_ext["month_on"][month_key] = on_map
logger.info("收银技师考勤 %s:%d 家门店、%d 名技师进入未出勤映射、%d 名有出勤日",
month_key, len(stores), len(result), len(on_map))
return result
# ==================== 登录态(共享 cookies 文件) ====================
# 登录态统一由「37duHR登录」影刀自定义指令维护(见 workflows/share/hr_login.py),
# 本脚本仅读取共享 cookies 文件;花名册由「37du花名册导出」指令导出到固定路径后由本脚本读取。
@@ -780,6 +968,15 @@ def _month_status_map(month_cache, session, user_id, month_str, seen=None):
mb, me = _month_range(month_str)
records = _cached_attendance(session, user_id, month_str.replace("-", ""))
merged = _report_records_to_status(records, mb, me, seen)
# 追溯月 >= 2026-09:HR + 收银两份数据,技师未出勤以收银为准覆盖(HR 该月起无技师数据)
if _is_cashier_month(month_str):
try:
tech_map = _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 = _cached_leave(session, user_id, "", month_str)
_merge_leave_status(merged, leaves, mb, me)
logger.info("已构建 %s 月缺勤映射(报表 %d 人 + 全集团请假 %d 条)",
@@ -843,6 +1040,16 @@ def _person_month_absent(session, user_id, code, month_str, seen=None, status_ca
d += timedelta(days=1)
i += 1
break
# 追溯月 >= 2026-09:技师未出勤以收银为准覆盖(HR 该月起无技师数据,避免技师段漏判)。
# 直接查该月收银映射是否含该工号,命中即视为技师并以收银为准(不依赖全局 tech_codes)。
if _is_cashier_month(month_str):
try:
tech_daymap = _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}, _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)
@@ -975,7 +1182,9 @@ def _analyze(emp, month_status, session, user_id, begin, end, cur_ctx=None):
再逐个解析起始日、统计备注并组装名单行。
month_status:查询月全集团状态映射 {工号: {日期: 类别}}(含 旷工/休息/请假)。
cur_ctx:返岗判定上下文 (cur_status, cur_rows, cur_begin, cur_end),None 表示不需要。
cur_ctx:返岗判定上下文 (cur_status, cur_rows, cur_begin, cur_end, cashier_cur),
None 表示不需要。cashier_cur 为收银技师当前月「出勤日集合」{工号: {日期}},
code 命中时以其判定返岗(技师源,HR 当前月无技师数据);未命中走 cur_rows 报表判定。
"""
seen = {}
query_month = begin.strftime("%Y-%m")
@@ -1034,16 +1243,23 @@ def _analyze(emp, month_status, session, user_id, begin, end, cur_ctx=None):
# 否则回到情况A:请假仍在进行(已备案假单 end_date > 统计月末)取请假截止日,无则「未归岗,时间待定」。
return_day = None
if cur_ctx is not None:
cur_status, cur_rows, cur_begin, cur_end = cur_ctx
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:
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
d += timedelta(days=1)
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")
@@ -1186,6 +1402,20 @@ def export_absence_list(save_dir=None, roster_path=None, month=None):
session = build_hr_session()
session, user_id = _validate_session(session)
# 2.5 收银系统会话(技师考勤源):HR 自 CASHIER_MIGRATE_MONTH(2026-09) 起不再有技师数据。
# 统计月或当前月落在迁移月及以后时初始化收银会话;无 token 时降级仅用 HR(不阻断流程)。
# 时间边界(与用户确认):月份 < 2026-09 只用 HR;>= 2026-09 则 HR + 收银两份,
# 技师未出勤以收银为准;跨月追溯历史月同样按此规则(见 _month_status_map / _person_month_absent)。
today_m = date.today().strftime("%Y-%m")
cashier_ready = False
if _is_cashier_month(month_str) or _is_cashier_month(today_m):
try:
_cashier_ext["session"] = _cashier_build_session()
cashier_ready = True
logger.info("收银系统会话就绪(技师考勤源,迁移月 %s)", CASHIER_MIGRATE_MONTH)
except Exception as e:
logger.warning("收银系统登录态不可用(技师考勤将缺失,非技师不受影响):%s", e)
# 3. 拉取上月全集团考勤统计报表,按报表判定「休息/旷工」,再并入整天请假(leave_days>=1)
# 统计月(上月)始终实时调接口,不走缓存;跨月追溯的历史月才走懒缓存。
seen = {}
@@ -1195,6 +1425,15 @@ def export_absence_list(save_dir=None, roster_path=None, month=None):
logger.error("考勤统计报表无数据,请检查月份或权限")
return ""
month_status = _report_records_to_status(records, begin, end, seen)
# 统计月 >= 2026-09:HR + 收银两份,技师未出勤以收银为准覆盖(HR 该月起无技师数据)
if cashier_ready and _is_cashier_month(month_str):
try:
tech_map = _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 = fetch_all_leave(
session, user_id, "", begin.strftime("%Y-%m-%d"), end.strftime("%Y-%m-%d"))
_merge_leave_status(month_status, leaves, begin, end)
@@ -1213,7 +1452,16 @@ def export_absence_list(save_dir=None, roster_path=None, month=None):
session, user_id, "", cur_begin.strftime("%Y-%m-%d"), cur_end.strftime("%Y-%m-%d"))
_merge_leave_status(cur_status, cur_leaves, cur_begin, cur_end)
cur_rows = {_clean(r.get("base_code")): r for r in cur_records if _clean(r.get("base_code"))}
cur_ctx = (cur_status, cur_rows, cur_begin, cur_end)
# 当前月 >= 2026-09:技师返岗判定用收银「出勤日集合」(HR 当前月无技师数据,row 为空会漏判)
cashier_cur = {}
if cashier_ready and _is_cashier_month(today_m):
try:
_cashier_tech_status(today_m) # 先确保当前月收银映射(含出勤日 month_on)已加载
cashier_cur = dict(_cashier_ext["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 考勤用于返岗判定(%d 人,请假 %d 条)",
month_str, cur_begin, cur_end, len(cur_rows), len(cur_leaves))