# -*- coding: utf-8 -*- """ @Module: hrbp.ehr.common.hr_api @FileName: code_dict.py @FileName 备注: HR 平台通用数据字典接口(PtCodeTypeValue.mc),供各业务模块翻译编码字段。 codeType 为「表名.字段名」格式(如 COMMON.SEX / WAGE.BANKTYPE), 支持 codeType 参数逗号分隔批量查询;返回 {codeType: {code: [名称, ...]}}。 本地缓存统一存放,默认 7 天过期(与 bank_dict 一致)。 @Version: 1.0.0 """ import json import os import time from typing import Any from app.common.app_paths import get_sessions_dir from app.utils.logger import get_logger from app.service.hrbp.ehr.common.config import BANK_DICT_URL from app.service.hrbp.common.hr_session import hr_request_json logger = get_logger(__name__) # 字典缓存文件({codeType: {code: name}}),7 天过期 _CODE_DICT_EXPIRE_SEC = 7 * 24 * 60 * 60 _CODE_DICT_FILE = os.path.join(get_sessions_dir(), "code_dicts.json") def _load_cache() -> dict: """读取本地字典缓存,异常返回空 dict。""" try: with open(_CODE_DICT_FILE, encoding="utf-8") as f: return json.load(f) except Exception: return {} def _save_cache(maps: dict) -> None: """写入本地字典缓存。""" os.makedirs(os.path.dirname(_CODE_DICT_FILE), exist_ok=True) with open(_CODE_DICT_FILE, "w", encoding="utf-8") as f: json.dump(maps, f, ensure_ascii=False, indent=2) def _parse_items(raw) -> dict: """将接口返回的字典项转换为 {code: 名称}。 兼容两种返回形态: - list[dict]: [{"code": "1", "name": "男", ...}, ...] - dict: {"1": ["男", ...], ...}(键值对形态) """ if isinstance(raw, dict): return {str(code): (item[0] if isinstance(item, (list, tuple)) and item else "") for code, item in raw.items()} result = {} for item in raw or []: code = item.get("code", "") result[str(code)] = item.get("name", "") return result def get_code_dicts(session, code_types, force_refresh: bool = False) -> dict: """批量获取数据字典(优先本地缓存,缺失/过期才请求接口)。 Args: session: 已登录的 requests.Session 对象 code_types: codeType 列表,如 ["COMMON.SEX", "COMMON.NATION"] force_refresh: True 强制重新请求接口刷新 Returns: {codeType: {code: 名称}} 字典(未命中的 codeType 值为空 dict) """ cache = {} if force_refresh else _load_cache() need = [ct for ct in code_types if ct not in cache or not isinstance(cache.get(ct), dict)] # 缓存命中校验:文件整体过期时间(mtime) if need and not force_refresh and os.path.exists(_CODE_DICT_FILE): if time.time() - os.path.getmtime(_CODE_DICT_FILE) <= _CODE_DICT_EXPIRE_SEC: # 文件未过期但缺 key -> 记为空字典,避免反复请求不存在的类型 for ct in need: cache.setdefault(ct, {}) need = [ct for ct in need if not cache.get(ct)] if need: payload = { "codeType": ",".join(need), "inUse": "0,1,2", "platformMode": "redseaPlatform", } resp = hr_request_json(session, "POST", BANK_DICT_URL, payload, "数据字典", timeout=30) for ct in need: raw = (resp.get("result") or {}).get(ct) or resp.get(ct) cache[ct] = _parse_items(raw) if raw else {} _save_cache(cache) logger.info("数据字典远程拉取完成:%s", {ct: len(cache[ct]) for ct in need}) return {ct: cache.get(ct, {}) for ct in code_types} def code_to_name(code, code_map: dict) -> Any: """按字典映射翻译编码;未命中返回原值(None/空串原样返回)。""" if code is None or code == "": return code return code_map.get(str(code).strip(), code)