glsx_daily_processor.py 9.61 KB
# -*- coding: utf-8 -*-
"""广联日快照基础表处理:每日定时拉取通用品牌报表的「门店产值及个人成交排名」数据,
仅保存每个门店的 延保小计 / 权益小计 全量字段,落库到独立基础表 glsx_daily_deal_subtotal。

与本项目的 baic_special / avita_special 报表类型**无关联**:
  - 数据源:dj.glsx.com.cn 报表导出接口(report_type=yanbaoMerAndPerRanking,filename=报表月,
            取「通用品牌」一份),与 baic_special_processor.fetch_glsx_report / avita 的同名函数同源,
            但本模块独立实现,避免耦合到具体品牌。
  - 落库:独立基础表,按 stat_date(快照归属日期)做时间序列快照,与任何 DataProcessTask 无关。
  - 触发:
      · GlsxDailyScheduler 每日 Cron(07:00)→ scan_glsx_daily()(stat_date = 昨天);
      · 手动补数 → 直接调用 snapshot_glsx(指定日期)(如补某周日的快照,供北汽 W1/W2/W3 分母取数)。
    幂等:同 stat_date 先软删旧行再插新行。
"""
import io
import logging
from datetime import date, timedelta

import requests
import openpyxl
from decimal import Decimal, InvalidOperation

from models import db, GlsxDailyDealSubtotal

logger = logging.getLogger(__name__)

_GLSX_BASE = 'https://dj.glsx.com.cn/reportExport'
_GLSX_TIMEOUT = (30, 120)


def _norm_header(s):
    """表头单元格归一:去所有空白/换行,便于按列名定位(如 '整车延保\\n成交数'→'整车延保成交数')。"""
    return ''.join(str(s).split()) if s is not None else ''


def _glsx_to_int(v):
    """单元格转 int:空/非数字/'-' → None(用于成交/交付/触客计数聚合)。"""
    if v is None or v == '':
        return None
    s = str(v).strip().replace(',', '')
    if s in ('-', 'None'):
        return None
    try:
        return int(Decimal(s))
    except (InvalidOperation, ValueError):
        return None


def _to_dec(v):
    """单元格转 Decimal:空/'-' → None(用于目标产值 万元)。"""
    if v is None or v == '':
        return None
    s = str(v).strip().replace(',', '')
    if s in ('-', 'None'):
        return None
    try:
        return Decimal(s)
    except (InvalidOperation, ValueError):
        return None


def _download_glsx_rows(stat_month):
    """通用:列出报表→定位「通用品牌」→下载 xlsx→返回 (rows, header_index)。失败返回 (None, None)。"""
    if not stat_month:
        logger.warning('[广联日快照] stat_month 为空,跳过')
        return None, None
    try:
        resp = requests.get(_GLSX_BASE + '/queryAllExcel', params={
            'pageSize': 10, 'currentPage': 1, 'filename': stat_month,
            'business_type': 'yanbao', 'report_type': 'yanbaoMerAndPerRanking', 'key': '',
        }, timeout=_GLSX_TIMEOUT)
        resp.raise_for_status()
        items = (resp.json().get('data') or {}).get('list') or []
        target = next((x for x in items if '通用品牌' in (x.get('filename') or '')), None)
        if not target:
            logger.warning(f'[广联日快照] 未找到 通用品牌 报表(filename={stat_month})')
            return None, None
        key = target['key']
        dl = requests.get(_GLSX_BASE + '/download', params={'key': key}, timeout=_GLSX_TIMEOUT)
        dl.raise_for_status()
        dlist = (dl.json().get('data') or {}).get('list') or []
        if not dlist or not dlist[0].get('url'):
            logger.warning('[广联日快照] download 未返回有效文件 url')
            return None, None
        file_url = dlist[0]['url']
        x = requests.get(file_url, timeout=_GLSX_TIMEOUT)
        x.raise_for_status()
        wb = openpyxl.load_workbook(io.BytesIO(x.content), data_only=True)
        ws = wb[wb.sheetnames[0]]
        rows = list(ws.iter_rows(values_only=True))
        hidx = next((i for i, row in enumerate(rows)
                     if row and _norm_header(row[0]) == '业务类型'), None)
        if hidx is None:
            logger.warning('[广联日快照] 未找到表头行(业务类型)')
            return None, None
        return rows, hidx
    except Exception as e:
        logger.warning(f'[广联日快照] 报表获取失败(stat_month={stat_month}): {e}')
        return None, None


def fetch_daily_deal_subtotals(stat_month):
    """解析通用品牌报表,返回 {门店名称: {ext_warranty_deal_count, rights_deal_count,
    gl_rights_deal_count, actual_output_wan, delivery_cnt, visit_cnt}}。

    仅取 延保小计 / 权益小计 两个小计行(门店分段内的小计行,C 列为空、门店名从上一业务行向前携带);
    按列名(归一后)定位,不依赖固定列号。任何失败返回空 dict(不致命)。
    """
    rows, hidx = _download_glsx_rows(stat_month)
    if rows is None or hidx is None:
        return {}
    try:
        col = {_norm_header(n): j for j, n in enumerate(rows[hidx]) if n is not None}
        ext_c = col.get('整车延保成交数')
        rights_c = col.get('原厂权益成交数')       # 延保小计 行
        gl_rights_c = col.get('广联权益成交数')     # 权益小计 行
        actual_c = next((j for h, j in col.items() if '实际完成产值' in h), None)  # 延保小计 行(目标产值列在门店小计行为空)
        deliv_c = next((j for h, j in col.items() if '累计交付数' in h), None)
        visit_c = next((j for h, j in col.items() if '实际售前触客数' in h), None)
        store_c = col.get('门店')
        if store_c is None:
            logger.warning('[广联日快照] 报表缺少「门店」列,无法定位门店')
            return {}
        result = {}
        cur = None  # 向前携带的当前门店名(小计行 C 为空)
        for row in rows[hidx + 1:]:
            if not row:
                continue
            a = _norm_header(row[0]) if row[0] is not None else ''
            c = str(row[store_c]).strip() if len(row) > store_c and row[store_c] else ''
            if c:
                cur = c
            if not cur:
                continue
            rec = result.setdefault(cur, {})
            if a == '延保小计':
                if ext_c is not None and len(row) > ext_c and row[ext_c] not in (None, ''):
                    rec['ext_warranty_deal_count'] = _glsx_to_int(row[ext_c])
                if rights_c is not None and len(row) > rights_c and row[rights_c] not in (None, ''):
                    rec['rights_deal_count'] = _glsx_to_int(row[rights_c])
                if actual_c is not None and len(row) > actual_c and row[actual_c] not in (None, ''):
                    rec['actual_output_wan'] = _to_dec(row[actual_c])
                if deliv_c is not None and len(row) > deliv_c and row[deliv_c] not in (None, ''):
                    rec['delivery_cnt'] = _glsx_to_int(row[deliv_c])
                if visit_c is not None and len(row) > visit_c and row[visit_c] not in (None, ''):
                    rec['visit_cnt'] = _glsx_to_int(row[visit_c])
            elif a == '权益小计':
                if gl_rights_c is not None and len(row) > gl_rights_c and row[gl_rights_c] not in (None, ''):
                    rec['gl_rights_deal_count'] = _glsx_to_int(row[gl_rights_c])
        logger.info(f'[广联日快照] 解析到 {len(result)} 个门店的延保小计/权益小计数据')
        return result
    except Exception as e:
        logger.warning(f'[广联日快照] 解析失败(stat_month={stat_month}): {e}')
        return {}


def snapshot_glsx(stat_date):
    """把一个指定日期(stat_date)的通用品牌报表快照落库基础表(幂等)。

    - 报表月 filename = stat_date 所在月(月初跨月自动取上月)。
    - 幂等:先对 (stat_date, is_deleted=0) 旧行做软删除,再批量插入新快照。
    - 报表不可达 / 无数据 → 仅告警返回,不报错、不写空行。
    供每日任务(stat_date=昨天)与手动补数共用。
    """
    stat_month = stat_date.strftime('%Y-%m')
    data = fetch_daily_deal_subtotals(stat_month)
    if not data:
        logger.warning(f'[广联快照] {stat_month}(stat_date={stat_date})无数据,跳过')
        return {'success': 0, 'skipped': 'no_data', 'stat_date': str(stat_date)}
    # 幂等:软删旧行
    old_rows = GlsxDailyDealSubtotal.query.filter_by(
        stat_date=stat_date, is_deleted=0).all()
    for o in old_rows:
        o.is_deleted = 1
    db.session.flush()
    # 插入新快照
    objs = []
    for store_name, rec in data.items():
        objs.append(GlsxDailyDealSubtotal(
            stat_date=stat_date,
            store_name=store_name,
            ext_warranty_deal_count=rec.get('ext_warranty_deal_count'),
            rights_deal_count=rec.get('rights_deal_count'),
            gl_rights_deal_count=rec.get('gl_rights_deal_count'),
            actual_output_wan=rec.get('actual_output_wan'),
            delivery_cnt=rec.get('delivery_cnt'),
            visit_cnt=rec.get('visit_cnt'),
            is_deleted=0,
        ))
    db.session.add_all(objs)
    db.session.commit()
    logger.info(f'[广联快照] stat_date={stat_date} 落库 {len(objs)} 家门店'
                f'(软删旧 {len(old_rows)} 行)')
    return {'success': 1, 'stat_date': str(stat_date), 'stores': len(objs),
            'deleted_old': len(old_rows)}


def scan_glsx_daily():
    """每日定时任务:拉取昨天所在月的通用品牌报表,按 stat_date=昨天 幂等落库基础表。

    - 昨天 = today - 1 天;报表月 filename = 昨天所在月(月初跨月自动取上月)。
    - 落库细节见 snapshot_glsx()。
    """
    yesterday = date.today() - timedelta(days=1)
    return snapshot_glsx(yesterday)