# -*- coding: utf-8 -*- """考勤月报封存检查 - 数据拉取(webhost 场景插件) 数据真源复用 desktop/shared(与桌面/影刀版单一真源一致),传入宿主构建的 requests.Session / user_id 即可,不内置任何登录逻辑。 session 由 webhost 宿主的共享登录态提供(RunContext.get_session / get_user_id)。 """ import calendar from datetime import datetime, timedelta from typing import Dict, List, Tuple from webhost.backend.shared import org_export, roster_export_api, seal_data_export from webhost.backend.plugins.seal_check import config # hr_request_json:统一做全局重试(3次) + 登录态失效判定(复用桌面 shared 真源) hr_request_json = seal_data_export.hr_request_json # ==================== 通用工具 ==================== def _clean(v) -> str: if v is None: return "" s = str(v).strip() if s.lower() in ("nan", "none", "nat"): return "" if s.endswith(".0"): s = s[:-2] return s def _norm_path(p: str) -> str: p = _clean(p).replace("\\", "/").strip("/") if p.startswith("集团/"): p = p[len("集团/"):] elif p == "集团": p = "" return p.strip("/") def last_month_ym(today: datetime = None) -> str: today = today or datetime.now() last_end = today.replace(day=1) - timedelta(days=1) return f"{last_end.year:04d}{last_end.month:02d}" # ==================== 1. 封存数据 ==================== def fetch_seal_rows(session, user_id: str, yearmonth: str) -> List[dict]: rows = seal_data_export.fetch_all_seal(session, user_id, yearmonth) return seal_data_export._filter_by_unit(rows) # ==================== 2. 组织表 ==================== def fetch_org_name_map(session) -> Dict[str, str]: """组织全路径 -> 组织名称(用于解析组织类型)。""" rows = org_export.fetch_all_orgs(session) name_map: Dict[str, str] = {} for rec in rows: path = _norm_path(rec.get("pt_structure.ORG_FULL_PATH")) name = _clean(rec.get("pt_organzation.ORG_NAME")) if path and name: name_map[path] = name return name_map # ==================== 3. 花名册(导出接口,职位序列已翻译) ==================== def fetch_roster_data(session) -> Tuple[Dict[str, str], List[dict]]: """导出花名册(在职+离职)。返回 (seq_map, in_service_records)。""" import pandas as pd path = roster_export_api.export_roster( output_path=config.ROSTER_EXPORT_PATH, download_dir=config.ROSTER_DOWNLOAD_DIR, template_name="员工基础信息", statuses=["在职", "离职"], ) df = pd.read_excel(path, dtype=str) df.columns = [str(c).strip() for c in df.columns] seq_map: Dict[str, str] = {} in_service_records: List[dict] = [] for _, r in df.iterrows(): code = _clean(r.get("工号")) seq = _clean(r.get("职位序列")) if code: seq_map[code] = seq if _clean(r.get("在职状态")) == "在职": in_service_records.append({ "工号": code, "姓名": _clean(r.get("姓名")), "所属单位": _clean(r.get("所属单位")), "一级部门": _clean(r.get("一级部门")), "二级部门": _clean(r.get("二级部门")), "三级部门": _clean(r.get("三级部门")), "四级部门": _clean(r.get("四级部门")), "五级部门": _clean(r.get("五级部门")), }) return seq_map, in_service_records # ==================== 4. 排班(批量导出) ==================== def fetch_shift_batch(session, user_id: str, yearmonth: str) -> Dict[str, int]: """批量拉取某月全集团排班,返回 {工号: 应出勤天数}。 base_code 留空 = 全集团批量;每条记录 = 一个员工整月排班, 逐日列 key 为 "YYYY-MM-DD_bc_name",休息日判定 bc_name == config.REST_SHIFT_NAME。 """ ym = str(yearmonth) year, month = int(ym[:4]), int(ym[4:6]) days_in_month = calendar.monthrange(year, month)[1] begin = f"{year:04d}-{month:02d}-01" end = f"{year:04d}-{month:02d}-{days_in_month:02d}" all_rows: List[dict] = [] page_no = 1 while True: params = { "treecode": "cq37du", "user_id": user_id, "sqlId": "kq_count_SelectBanci", "commonQuery": "", "commonQueryStr": "", "staff_ids": "", "person_status": "1,4", "post_no": "", "post_type": "1", "post_level": "", "identity": "", "showType": "1", "dateType": "1", "begin": begin, "end": end, "bc_date": begin, "base_code": "", "staff_name": "", "start": str((page_no - 1) * config.PAGE_MAX_SIZE), "sortType": "", "sortName": "", "pageNo": page_no, "pageSize": config.PAGE_MAX_SIZE, } data = hr_request_json(session, "POST", config.SHIFT_URL, params, "排班批量") if data.get("state") != "1": break page_list = data.get("datas", []) or [] if not page_list: break all_rows.extend(page_list) # 分页保护:pageCount 缺失/为 0 时不能提前 break,否则会静默截断数据 page_count = data.get("pageCount") or 0 if page_count and page_no >= page_count: break if len(page_list) < config.PAGE_MAX_SIZE: break page_no += 1 result: Dict[str, int] = {} for rec in all_rows: code = _clean(rec.get("base_code")) if not code: continue work_days = 0 for d in range(1, days_in_month + 1): bc = _clean(rec.get(f"{year:04d}-{month:02d}-{d:02d}_bc_name")) if bc and bc != config.REST_SHIFT_NAME: work_days += 1 result[code] = work_days return result # ==================== 5. 对比差异(检查3,接口待封装) ==================== def fetch_compare_diffs(session, user_id: str, yearmonth: str) -> Tuple[List[dict], str]: """考勤月报封存「对比」差异数据;接口未封装前返回空 + 提示。""" return [], "检查3「封存值是否最新」的对比接口尚未封装,本次跳过该检查,请在数据层补充接口后启用"