Files

106 lines
4.0 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# -*- coding: utf-8 -*-
"""XQ0005 插件 - 银行字典接口(WAGE.BANKTYPE):银行编码 -> 开卡银行名称。
参考影刀版 bank_card_check.py:
- 优先读本机缓存(%LOCALAPPDATA%\\37duAutomation\\BankCardCheck\\bank_dict_*.json),
缓存 7 天过期后自动重新拉取;
- 拉取失败时降级使用旧缓存;无缓存返回空字典(开卡银行列留空,不影响其他核对)。
"""
import json
import os
import time
from ..config import (
BANK_DICT_CODE_TYPE, BANK_DICT_EXPIRE_SEC, BANK_DICT_LIST_FILE,
BANK_DICT_MAP_FILE, BANK_DICT_URL, MAX_REQUEST_RETRY, logger,
)
from ..config import _APP_DATA_DIR as DICT_CACHE_DIR
def _ensure_dir(path):
os.makedirs(path, exist_ok=True)
def fetch_bank_dict(session):
"""远程调用字典接口并写入本地缓存,返回 (list[dict], dict[code->name])。"""
payload = {
"codeType": BANK_DICT_CODE_TYPE,
"inUse": "0,1,2",
"platformMode": "redseaPlatform",
}
resp = session.post(BANK_DICT_URL, data=payload, timeout=30)
resp.raise_for_status()
resp_json = resp.json()
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}
_ensure_dir(DICT_CACHE_DIR)
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=False):
"""获取银行字典(优先本地缓存,过期/强制刷新才请求接口),返回 (list, map)。"""
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:
last_err = None
for attempt in range(1, MAX_REQUEST_RETRY + 1):
try:
return fetch_bank_dict(session)
except Exception as e:
last_err = e
logger.warning("银行字典远程拉取第 %d 次失败:%s", attempt, e)
time.sleep(1.0 * attempt)
logger.error("银行字典远程拉取失败:%s", last_err)
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):
"""按银行编码(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 or {}).get(bank_type, "")