# -*- coding: utf-8 -*- """ @Module: hrbp.ehr.common.hr_api @FileName: bank_dict.py @Description: 银行字典接口(缓存 code -> 开卡银行 映射) @Version: 1.0.0 """ import json import os import time 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, BANK_DICT_CODE_TYPE, BANK_DICT_EXPIRE_SEC, ) from app.service.hrbp.common.hr_session import HRSessionExpiredError, hr_request_json from app.service.hrbp.common.hr_session import build_hr_session logger = get_logger(__name__) # 缓存文件统一放在 AppData\Local\37duAutomation\.sessions 目录 _BANK_DICT_CACHE_DIR = get_sessions_dir() BANK_DICT_LIST_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_list.json") BANK_DICT_MAP_FILE = os.path.join(_BANK_DICT_CACHE_DIR, "bank_dict_map.json") def _fetch_bank_dict(session=None): """远程调用接口获取银行字典,并写入本地缓存。 Returns: (list[dict], dict[code->name]) """ if session is None: session = build_hr_session() payload = { "codeType": BANK_DICT_CODE_TYPE, "inUse": "0,1,2", "platformMode": "redseaPlatform", } resp_json = hr_request_json(session, "POST", BANK_DICT_URL, payload, "银行字典", timeout=30) raw_list = resp_json.get(BANK_DICT_CODE_TYPE) or [] result_list = [{"code": str(item.get("code", "")), "name": item.get("name", "")} for item in raw_list] result_map = {item["code"]: item["name"] for item in result_list} os.makedirs(_BANK_DICT_CACHE_DIR, exist_ok=True) with open(BANK_DICT_LIST_FILE, "w", encoding="utf-8") as f: json.dump(result_list, f, ensure_ascii=False, indent=2) with open(BANK_DICT_MAP_FILE, "w", encoding="utf-8") as f: json.dump(result_map, f, ensure_ascii=False, indent=2) logger.info("银行字典远程拉取完成,共 %d 条", len(result_list)) return result_list, result_map def _load_bank_dict_cache(): """读取本地银行字典缓存,失败返回 (None, None)。""" try: with open(BANK_DICT_LIST_FILE, "r", encoding="utf-8") as f: lst = json.load(f) with open(BANK_DICT_MAP_FILE, "r", encoding="utf-8") as f: mp = json.load(f) return lst, mp except Exception as e: logger.warning("银行字典本地缓存读取失败:%s", e) return None, None def get_bank_dict(session=None, force_refresh: bool = False): """获取银行字典(优先本地缓存,过期/强制刷新才请求接口)。 Args: session: 可选的已登录 requests.Session;未提供时自动构建 force_refresh: True 强制重新调用接口 Returns: (list版本, dict[code->name]版本) """ need_refresh = force_refresh if not (os.path.exists(BANK_DICT_LIST_FILE) and os.path.exists(BANK_DICT_MAP_FILE)): need_refresh = True else: mtime = os.path.getmtime(BANK_DICT_LIST_FILE) if time.time() - mtime > BANK_DICT_EXPIRE_SEC: need_refresh = True if need_refresh: try: return _fetch_bank_dict(session) except Exception as e: logger.error("银行字典远程拉取失败:%s", e) lst, mp = _load_bank_dict_cache() if lst is not None: logger.warning("降级使用本地银行字典缓存,共 %d 条", len(lst)) return lst, mp return [], {} lst, mp = _load_bank_dict_cache() if lst is None: # 缓存异常时重新拉取 return _fetch_bank_dict(session) logger.info("读取本地银行字典缓存,共 %d 条", len(lst)) return lst, mp def bank_type_to_name(bank_type, bank_map) -> str: """按银行编码(BANK_TYPE)匹配字典 code,返回开卡银行;未命中返回空串。""" if bank_type is None: return "" if isinstance(bank_type, float): if bank_type != bank_type: # NaN return "" bank_type = str(int(bank_type)) elif isinstance(bank_type, int): bank_type = str(bank_type) else: bank_type = str(bank_type).strip() return bank_map.get(bank_type, "")