consumables_parser.py 4.59 KB
# -*- coding: utf-8 -*-
"""门店资产耗材明细表解析器。

职责:解析「D+门店资产耗材每月采购明细表」(.xls / .xlsx),提取计算门店资产耗材
(store_consumables) 分摊所需的字段:
    - 门店名称(对应结果表 traffic_name 的 F 匹配键)
    - 系统园区店名称(对应结果表 park_store 的 G 兜底匹配键)
    - 业务类型(用于按业务类型分别匹配预算行)
    - 月份(用于筛选与 stat_month 对应的当月明细)
    - 金额(采购金额,直接作为分摊基数,不做除法)

解析器只负责「读 Excel → 结构化数据」,不关心数据库读写。
支持 .xls(xlrd)与 .xlsx(openpyxl)两种格式,按文件魔数自动识别引擎。
"""
import os
import re

import pandas as pd

# 业务类型后缀(需归一化去掉,使其与预算达成表的 business_type 对齐)
BT_SUFFIXES = ('精品', '权益', '延保', '尊享', '智行')


def _cell(row, col):
    """取单元格并清洗:None / NaN → ''。"""
    if col not in row:
        return ''
    v = row[col]
    if v is None or (isinstance(v, float) and pd.isna(v)):
        return ''
    return v


def _to_num(value):
    """单元格数值归一:None/空/布尔 → 0.0;数字原样;字符串去千分位与货币符号后转 float。"""
    if value is None or isinstance(value, bool):
        return 0.0
    if isinstance(value, (int, float)):
        return float(value)
    s = str(value).strip().replace(',', '')
    if not s:
        return 0.0
    s = re.sub(r'[^\d.\-]', '', s)        # 去掉 ¥、空格等非数字字符
    if s in ('', '.', '-'):
        return 0.0
    try:
        return float(s)
    except ValueError:
        return 0.0


def normalize_bt(s):
    """业务类型归一化:去掉 精品/权益/延保/尊享/智行 等后缀,与预算表 business_type 对齐。"""
    s = str(s or '').strip()
    for suf in BT_SUFFIXES:
        if s.endswith(suf):
            s = s[:-len(suf)]
    return s


def strip_dplus(name):
    """去掉名称前缀 'D+'(匹配时归一化用)。"""
    if name and name.startswith('D+'):
        return name[2:]
    return name


def _detect_engine(path):
    """按文件魔数识别 Excel 引擎:.xlsx = PK(zip) → openpyxl;.xls = OLE → xlrd。"""
    with open(path, 'rb') as f:
        head = f.read(8)
    if head[:2] == b'PK':
        return 'openpyxl'
    if head[:4] == b'\xd0\xcf\x11\xe0':
        try:
            import xlrd
        except ImportError:
            raise ImportError(
                '读取 .xls 格式的门店资产耗材文件需要 xlrd 库。\n'
                '请运行: pip install xlrd>=2.0.1\n'
                '或联系运维安装缺失的依赖包。'
            )
        return 'xlrd'
    return None


class ConsumablesDetailParser:
    """门店资产耗材明细表解析器。"""

    def __init__(self, file_path):
        if not os.path.exists(file_path):
            raise FileNotFoundError(f'门店资产耗材明细表不存在:{file_path}')
        self.file_path = file_path
        self.details = []

    def parse(self):
        """解析第一个 sheet,返回明细列表。

        每行返回 dict:
            store_name       门店名称
            park_store_name  系统园区店名称
            month           月份(如 '6月')
            business_type   业务类型(未归一化,如 '1.1精品')
            amount          金额(float)

        Returns:
            list[dict]
        """
        engine = _detect_engine(self.file_path)
        try:
            df = pd.read_excel(self.file_path, engine=engine, header=0, dtype=str)
        except ImportError:
            raise
        except Exception as e:
            raise RuntimeError(
                f'解析门店资产耗材文件失败(引擎={engine}, 文件={self.file_path}): {e}'
            ) from e
        details = []
        for _, row in df.iterrows():
            store_name = str(_cell(row, '门店名称')).strip()
            park_store = str(_cell(row, '系统园区店名称')).strip()
            # 门店名称与系统园区店名称均为空的行视为空行/合计行,跳过
            if not store_name and not park_store:
                continue
            details.append({
                'store_name': store_name,
                'park_store_name': park_store,
                'month': str(_cell(row, '月份')).strip(),
                'business_type': str(_cell(row, '业务类型')).strip(),
                'amount': _to_num(_cell(row, '金额')),
            })
        self.details = details
        return details