report_utils.py 13.8 KB
# -*- coding: utf-8 -*-
"""
红黄门店盈利测算 - 共用工具模块
================================
被 warranty_processor / equity_processor / inshop_processor / park_processor 共同引用。
统一封装 Excel 下载解析、安全除法、指标系统调用、幂等检查、临时目录清理等。
"""
import os
import logging
import tempfile
import shutil
import time as _time
from decimal import Decimal, ROUND_HALF_UP

import pandas as pd

from models import (
    DataProcessTask, DataProcessFile, BizBudgetAchieve,
    ReportExtendedWarranty, ReportEquityService,
    ReportLightReformInshop, ReportLightReformPark,
    db,
)
from oss_utils import download_file
from indicator_client import IndicatorClient
from config import Config

logger = logging.getLogger('report_utils')


# ============================================================
# 调度器常量
# ============================================================
STORE_EFFECT_EARNINGS_TYPE = 'store_effect_earnings'

# biz_type 过滤值(各表不同)
BIZ_TYPE_WARRANTY = '2.3'   # 延保
BIZ_TYPE_EQUITY = '2.1'     # 权益

# 指标系统 biz 编码
INDICATOR_BIZ_MAP = {
    'warranty': Config.INDICATOR_BIZ_WARRANTY,        # 1
    'equity': Config.INDICATOR_BIZ_EQUITY,            # 3
    'light_reform': Config.INDICATOR_BIZ_LIGHT_REFORM,  # 2
}


# ============================================================
# 任务状态管理
# ============================================================

def mark_task_failed(task_id, error_msg):
    """标记任务为失败状态(独立函数,无类依赖)。"""
    try:
        task = DataProcessTask.query.filter_by(id=task_id).first()
        if task:
            task.status = 'FAILED'
            task.error_msg = (error_msg or '')[:500]
            db.session.commit()
            logger.info(f"[标记失败] 任务 {task_id} 已标记为失败")
    except Exception as e:
        logger.error(f"[标记失败] 更新失败: {e}")
        db.session.rollback()
        raise


def cleanup_tmp_dir(tmp_dir):
    """清理临时目录(Windows 文件占用重试 3 次)。"""
    try:
        if os.path.exists(tmp_dir):
            shutil.rmtree(tmp_dir, ignore_errors=True)
            for _ in range(3):
                if not os.path.exists(tmp_dir):
                    break
                _time.sleep(0.5)
                shutil.rmtree(tmp_dir, ignore_errors=True)
            if not os.path.exists(tmp_dir):
                logger.info(f"[清理] 临时目录已清理: {tmp_dir}")
            else:
                logger.warning(f"[清理] 临时目录仍被占用,跳过: {tmp_dir}")
    except Exception as e:
        logger.warning(f"[清理] 清理临时目录时出错: {str(e)}")


def is_output_already_done(task_id, output_category):
    """幂等检查:判断输出表里是否已有该 task_id 的有效数据"""
    model_map = {
        'warranty': ReportExtendedWarranty,
        'equity': ReportEquityService,
        'inshop': ReportLightReformInshop,
        'park': ReportLightReformPark,
    }
    model = model_map.get(output_category)
    if not model:
        return True
    cnt = model.query.filter_by(task_id=task_id, is_deleted=0).count()
    return cnt > 0


# ============================================================
# Excel 下载 & 解析
# ============================================================

def download_all_files(task_id, tmp_dir):
    """
    下载 task_id 关联的所有 Excel 文件到 tmp_dir。
    返回 {form_type: local_path} (下载失败则值为 None)。
    """
    files = DataProcessFile.query.filter_by(task_id=task_id, is_deleted=0).all()
    result = {}
    for f in files:
        if not f.file_url:
            logger.warning(f"[文件下载] form_type={f.form_type} 无 file_url,跳过")
            continue
        local_path = os.path.join(tmp_dir, f.file_name or f"{f.form_type}.xlsx")
        try:
            download_file(f.file_url, local_path)
            result[f.form_type] = local_path
            logger.info(f"[文件下载] {f.form_type} OK → {local_path}")
        except Exception as e:
            logger.error(f"[文件下载] {f.form_type} 失败: {e}")
            result[f.form_type] = None
    return result


def match_columns(columns, keywords_map):
    """
    模糊匹配列名。
    keywords_map = {标准名: [关键词列表]},返回 {标准名: 实际列名}。
    """
    result = {}
    for std, keywords in keywords_map.items():
        for col in columns:
            col_lower = str(col).lower()
            for kw in keywords:
                if kw.lower() in col_lower:
                    result[std] = col
                    break
            if std in result:
                break
    return result


def find_header_row(df, max_scan=5):
    """
    在 DataFrame 前 max_scan 行中找到包含'门店'的表头行索引。
    找不到返回 0。
    """
    for i in range(min(max_scan, len(df))):
        row_vals = [str(v) if v is not None else '' for v in df.iloc[i].tolist()]
        if any('门店' in v for v in row_vals):
            return i
    return 0


def parse_saas_base(file_path, biz_type_filter):
    """
    解析 SAAS门店预算分解表 sheet1,按 biz_type_filter 过滤。
    返回 list[dict]:store_name / brand / province / city / region_manager /
    training_supervisor / biz_manager / resident_type
    """
    logger.info(f"[SAAS预算分解] 解析 {file_path}, 过滤 biz_type={biz_type_filter}")
    df_raw = pd.read_excel(file_path, sheet_name=0, header=None)
    header_row = find_header_row(df_raw)
    df = pd.read_excel(file_path, sheet_name=0, header=header_row)
    df.columns = [str(c).strip() if c else '' for c in df.columns]

    col_map = match_columns(df.columns, {
        'biz_type': ['业务类型', '业务分类', 'biz_type'],
        'store_name': ['门店名称', '门店名', '厅店名称', 'store_name'],
        'brand': ['品牌', 'brand'],
        'province': ['省份', '省', 'province'],
        'city': ['城市', '市', 'city'],
        'region_manager': ['区域运营', '区域经理', '大区经理'],
        'training_supervisor': ['培训督导', '督导'],
        'biz_manager': ['业务经理'],
        'resident_type': ['驻店类型', '驻店'],
    })
    logger.info(f"[SAAS预算分解] 匹配列: {col_map}")

    biz_col = col_map.get('biz_type')
    store_col = col_map.get('store_name')
    if not store_col:
        logger.error("[SAAS预算分解] 未找到门店名列")
        return []

    result = []
    for _, row in df.iterrows():
        if biz_col:
            bt = str(row.get(biz_col, '')).strip()
            if bt != biz_type_filter:
                continue
        sn = str(row.get(store_col, '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue

        result.append({
            'store_name': sn,
            'brand': str(row.get(col_map.get('brand', ''), '')).strip() if col_map.get('brand') else '',
            'province': str(row.get(col_map.get('province', ''), '')).strip() if col_map.get('province') else '',
            'city': str(row.get(col_map.get('city', ''), '')).strip() if col_map.get('city') else '',
            'region_manager': str(row.get(col_map.get('region_manager', ''), '')).strip() if col_map.get('region_manager') else '',
            'training_supervisor': str(row.get(col_map.get('training_supervisor', ''), '')).strip() if col_map.get('training_supervisor') else '',
            'biz_manager': str(row.get(col_map.get('biz_manager', ''), '')).strip() if col_map.get('biz_manager') else '',
            'resident_type': str(row.get(col_map.get('resident_type', ''), '')).strip() if col_map.get('resident_type') else '',
        })
    logger.info(f"[SAAS预算分解] biz_type={biz_type_filter} 共 {len(result)} 条")
    return result


def parse_region_map(file_path):
    """
    解析关系表,按 (业务类型, 省份) → 片区。
    返回 dict[(biz_type, province)] = region_area (额外包含 ('', province) fallback)。
    """
    logger.info(f"[关系表] 解析 {file_path}")
    try:
        df = pd.read_excel(file_path)
    except Exception:
        logger.warning("[关系表] 读取失败,跳过")
        return {}

    df.columns = [str(c).strip() if c else '' for c in df.columns]
    col_map = match_columns(df.columns, {
        'biz_type': ['业务类型', '业务分类'],
        'province': ['省份', '省'],
        'region_area': ['片区', '大区'],
    })
    if 'region_area' not in col_map or 'province' not in col_map:
        logger.warning("[关系表] 缺少 片区/省份 关键列")
        return {}

    result = {}
    for _, row in df.iterrows():
        prov = str(row.get(col_map['province'], '')).strip()
        area = str(row.get(col_map['region_area'], '')).strip()
        if not prov or not area:
            continue
        bt = str(row.get(col_map.get('biz_type', ''), '')).strip() if col_map.get('biz_type') else ''
        result[(bt, prov)] = area
        result[('', prov)] = area

    logger.info(f"[关系表] 片区映射 {len(result)} 条")
    return result


def parse_delivery_table(file_path):
    """
    解析主机厂交车数据表(鸿蒙/广联共用结构)。
    返回 dict[store_name] = delivery_cnt (int)。
    """
    logger.info(f"[主机厂交车] 解析 {file_path}")
    try:
        df = pd.read_excel(file_path)
    except Exception:
        logger.warning(f"[主机厂交车] 读取失败 {file_path}")
        return {}

    df.columns = [str(c).strip() if c else '' for c in df.columns]
    col_map = match_columns(df.columns, {
        'store_name': ['门店名称', '厅店名称', '基础信息-门店'],
        'delivery': ['总交付', '交车数', '交付量', '主机厂数据'],
    })
    if 'store_name' not in col_map:
        logger.warning("[主机厂交车] 未找到门店名列")
        return {}

    store_col = col_map['store_name']
    delivery_col = col_map.get('delivery')

    result = {}
    for _, row in df.iterrows():
        sn = str(row.get(store_col, '')).strip()
        if not sn or sn in ('nan', 'None', ''):
            continue
        cnt = 0
        if delivery_col:
            try:
                v = row.get(delivery_col, 0)
                if v is not None and not pd.isna(v):
                    cnt = int(float(v))
            except (ValueError, TypeError):
                cnt = 0
        result[sn] = result.get(sn, 0) + cnt

    logger.info(f"[主机厂交车] {file_path} → {len(result)} 个门店")
    return result


# ============================================================
# 指标系统 API
# ============================================================

def fetch_indicator_data(start_str, end_str, biz_code, item_codes):
    """
    调指标系统 API,返回 {merchantName: {itemCode: itemValue}}。
    start_str / end_str: 'YYYY-MM-DD' 字符串,空则返回 {}。
    """
    if not start_str or not end_str or not item_codes:
        return {}
    client = IndicatorClient()
    return client.fetch(start_str, end_str, biz_code, item_codes)


# ============================================================
# 安全除法 / 百分比
# ============================================================

def safe_div(numerator, denominator, scale=2):
    """Decimal 安全除法,分母为 0 返回 Decimal('0')。"""
    if not denominator or denominator == 0:
        return Decimal('0')
    try:
        return (Decimal(str(numerator)) / Decimal(str(denominator))).quantize(
            Decimal('0.' + '0' * scale), rounding=ROUND_HALF_UP)
    except Exception:
        return Decimal('0')


def safe_div_pct(numerator, denominator):
    """整数/整数 → 百分比(*100),保留百分比后 2 位小数 → Decimal(10,6)。"""
    if not denominator or denominator == 0:
        return Decimal('0')
    try:
        return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
            Decimal('0.010000'), rounding=ROUND_HALF_UP)
    except Exception:
        return Decimal('0')


def safe_div_pct_decimal(numerator, denominator):
    """Decimal/Decimal → 百分比(*100)。"""
    if not denominator or denominator == 0:
        return Decimal('0')
    try:
        return (Decimal(str(numerator)) * Decimal('100') / Decimal(str(denominator))).quantize(
            Decimal('0.010000'), rounding=ROUND_HALF_UP)
    except Exception:
        return Decimal('0')


def prev_month(month_str):
    """'2026-09' → '2026-08'"""
    if not month_str or '-' not in month_str:
        return ''
    try:
        parts = month_str.split('-')
        y = int(parts[0])
        m = int(parts[1])
        if m == 1:
            y -= 1
            m = 12
        else:
            m -= 1
        return f"{y}-{m:02d}"
    except Exception:
        return ''


def fetch_prev_month_labor_ratio(task, base_records):
    """
    从上月 BizBudgetAchieve 表取人员工资占比 → 营销费用占比。
    store_name 模糊匹配 target_name。
    返回 dict[store_name] = Decimal
    """
    current_month = getattr(task, 'month', '')
    pm = prev_month(current_month)
    if not pm:
        return {}

    store_names = list({r.get('store_name', '') for r in base_records if r.get('store_name')})
    if not store_names:
        return {}

    results = {}
    try:
        rows = BizBudgetAchieve.query.filter(
            BizBudgetAchieve.month == pm,
            BizBudgetAchieve.is_deleted == 0,
        ).all()
        for row in rows:
            target = getattr(row, 'target_name', '') or ''
            ratio = getattr(row, 'personnel_salary_ratio_current', None)
            if ratio is None:
                continue
            for sn in store_names:
                if sn in target or target in sn:
                    results[sn] = Decimal(str(ratio))
                    break
        logger.info(f"[上月占比] month={pm} 匹配 {len(results)}/{len(store_names)}")
    except Exception as e:
        logger.warning(f"[上月占比] 查询失败: {e}")

    return results