Files
37duAutomation/plugins/xq0008/data/source_reader.py
T

155 lines
7.7 KiB
Python
Raw 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 -*-
"""数据层:源名单(参保名单/停保名单)与社保户头管理台账的读取、筛选、取号。
统一承载 XQ0008(名单制作)与 XQ0014(系统办理/核查)共用的数据读取逻辑:
- load_records(kind, operation_type, status_filter):读源名单并按业务口径筛选
- load_units / load_check_tasks:按参保单位分组(办理/核查任务)
- load_accounts:从台账取各单位政务平台账号
"""
import os
from datetime import datetime
from .. import config
def read_source(kind):
"""定位并解析源名单,返回 (source_file, sheet_name)。
kind: 'add' 参保名单 sheet / 'stop' 停保名单 sheet(sheet 名年月动态,取最新)。
"""
source_file = config._latest_file(config.get_base_dir(), config.SOURCE_GLOB)
now = datetime.now()
xl = __import__('pandas').ExcelFile(source_file)
if kind == 'add':
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}{config.SHEET_KEY_ADD}",
config.SHEET_KEY_ADD)
else:
sheet_name = config._pick_sheet(xl, f"{now:%Y%m}{config.SHEET_KEY_STOP}",
config.SHEET_KEY_STOP,
pattern=r"(20\d{2})(1[0-2]|[1-9])停保名单")
return source_file, sheet_name
def load_records(kind, operation_type=None, status_filter="empty", exclude_ids=frozenset()):
"""读源名单并按业务口径筛选,返回 DataFrame(表头第3行)。
- kind: 'add'(参保名单)/ 'stop'(停保名单)
- operation_type: 增员时的参保类型('新参保'/'转移参保');减员忽略(固定两类都办)
- status_filter: 'empty' 办理状态/办理停保为空;'待审核' 等于该值
- exclude_ids: 排除的身份证号集合(上次已回写人员,防重复申报/核查)
"""
import pandas as pd
source_file, sheet_name = read_source(kind)
print_source = os.path.basename(source_file)
# 对齐原版 dtype 保护:add 只指定身份证/电话两列为文本(18 位身份证防 float 丢精度),
# stop 全列文本;dtype 字典引用 sheet 不存在的列不会报错
dtype = {"身份证号码": str, "电话号码": str} if kind == 'add' else str
df = pd.read_excel(source_file, sheet_name=sheet_name,
header=config.SOURCE_HEADER_ROW - 1, dtype=dtype)
if kind == 'add':
status_col = "办理状态"
mask = (df["区域"].astype(str).str.strip() == config.TARGET_REGION)
mask &= (df["参保类型"].astype(str).str.strip() == operation_type)
else:
status_col = config.STOP_PROCESSED_COL
mask = (df["区域"].astype(str).str.strip() == config.TARGET_REGION)
mask &= (df["类型"].astype(str).str.strip().isin(config.STOP_TYPES))
if status_filter == "empty":
st_text = df[status_col].astype(str).str.strip().str.lower()
mask &= (df[status_col].isna() | st_text.isin(['', 'nan', 'none', 'nat']))
else:
mask &= (df[status_col].astype(str).str.strip() == status_filter)
sub = df[mask].copy()
if exclude_ids and '身份证号码' in sub.columns:
before = len(sub)
ref = [config._norm_id(x) for x in exclude_ids]
sub = sub[~sub['身份证号码'].map(lambda v: config._id_hit(config._norm_id(v), ref))]
dropped = before - len(sub)
if dropped:
config.log(f" 已排除 {dropped} 行上次运行已回写的人员(防重复申报/核查)")
return sub, source_file, sheet_name, status_col
def load_units(kind, operation_type=None, status_filter="empty", exclude_ids=frozenset()):
"""读取名单并筛选,返回 [(参保单位, 人数), ...](按单位分组,名称排序)。"""
sub, source_file, sheet_name, status_col = load_records(
kind, operation_type, status_filter, exclude_ids)
print_source = os.path.basename(source_file)
if kind == 'add':
desc = f"{config.TARGET_REGION} ∩ 参保类型={operation_type}"
else:
desc = f"{config.TARGET_REGION} ∩ 类型∈{'/'.join(config.STOP_TYPES)}"
config.log(f"源名单:{print_source}(sheet: {sheet_name})")
if sub.empty:
config.log(f"没有筛选到数据({desc} ∩ {status_col}={'空' if status_filter == 'empty' else status_filter})")
return [], source_file, sheet_name
grouped = sub.groupby(sub["参保单位"].astype(str).str.strip()).size()
units = sorted(grouped.items(), key=lambda t: t[0])
config.log(f"筛选结果:共 {sum(n for _, n in units)} 人 / {len(units)} 个参保单位")
return units, source_file, sheet_name
def load_check_tasks(kind, status_filter=config.CHECK_STATUS, exclude_ids=frozenset()):
"""读取名单筛选 办理状态/办理停保=待审核 的行,按参保单位分组。
返回 [{unit, count, cids(set)}],供核查流程使用。
"""
operation_type = config.WEB_ADD_TYPE if kind == 'add' else None
sub, source_file, sheet_name, status_col = load_records(
kind, operation_type, status_filter, exclude_ids)
print_source = os.path.basename(source_file)
config.log(f"源名单:{print_source}(sheet: {sheet_name})")
if sub.empty:
config.log(f"没有筛选到数据({status_col}={status_filter})")
return [], source_file, sheet_name
tasks = []
for unit, g in sub.groupby(sub["参保单位"].astype(str).str.strip()):
cids = {config._norm_id(v) for v in g['身份证号码']}
cids.discard('')
tasks.append({"unit": unit, "count": len(cids), "cids": cids})
tasks.sort(key=lambda t: t['unit'])
config.log(f"核查范围:共 {sum(t['count'] for t in tasks)} 人 / "
f"{len(tasks)} 个参保单位({status_col}={status_filter})")
return tasks, source_file, sheet_name
def load_accounts(unit_names):
"""从台账「YYYY年M月缴费比例」sheet 取各单位账号。
返回 {参保单位: {"username":..., "username_src": "信用代码|平台用户名", "password":...}},
取不到的单位不在返回值中(由预检统一报错)。
"""
import pandas as pd
ledger_file = config._latest_file(config.get_ledger_dir(), config.LEDGER_GLOB)
now = datetime.now()
xl = pd.ExcelFile(ledger_file)
sheet_name = config._pick_sheet(xl, f"{now.year}年{now.month}月缴费比例",
config.SHEET_KEY_LEDGER,
pattern=r"(20\d{2})年(1[0-2]|[1-9])月缴费比例")
config.log(f"台账:{os.path.basename(ledger_file)}(sheet: {sheet_name})")
# 表头为 1-2 行合并结构:跳过前 2 行,B列(户头)非空即数据行
df = pd.read_excel(ledger_file, sheet_name=sheet_name, header=None, skiprows=2)
df = df[df[config.LEDGER_COL["户头"]].notna()].copy()
for c in config.LEDGER_COL.values():
df[c] = df[c].map(config._to_text)
pool = df[(df[config.LEDGER_COL["城市"]] == config.TARGET_REGION)
& (df[config.LEDGER_COL["在用"]] == "是")]
accounts = {}
for name in unit_names:
hit = pool[pool[config.LEDGER_COL["户头"]] == name]
if hit.empty:
continue # 预检阶段统一报「台账未匹配」
row = hit.iloc[0]
credit, plat_user, plat_pwd = (
row[config.LEDGER_COL["信用代码"]], row[config.LEDGER_COL["平台用户名"]],
row[config.LEDGER_COL["平台密码"]])
# 用户名规则:I列信用代码优先,空则回退 K列平台用户名
username, src = (credit, "信用代码") if credit else (plat_user, "平台用户名")
accounts[name] = {"username": username, "username_src": src, "password": plat_pwd}
return accounts