test_guangai_processor.py 20.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 407 408 409 410 411 412 413 414 415 416 417 418 419 420 421 422 423 424 425 426
# -*- coding: utf-8 -*-
"""
广爱专项处理器 单元测试
=======================
不依赖数据库 / 指标系统网络 / OSS:
  - 纯函数:累计制周区间(W1~W4,无第 5 周)、评灯阈值(20%/10%)、4 位小数去尾 0
  - 附件解析校验:店名匹配/整数≥0/触客率一致性(需要 mock DB 时用 stub 方式单测 build_workbook)
  - Excel 渲染:假数据直调 build_workbook(stub 掉 DB/网络依赖)

运行(data-process 目录下):
  python test_guangai_processor.py
"""
import os
import sys
import types
import tempfile
import unittest
from datetime import date
from decimal import Decimal

import openpyxl

# ---- stub 重依赖(仅渲染层测试需要;纯函数测试不涉及) ----
_sqla = types.ModuleType('sqlalchemy')
_sqla.text = lambda *a, **k: None
_sqla.bindparam = lambda *a, **k: None
sys.modules.setdefault('sqlalchemy', _sqla)
if 'report_utils' not in sys.modules:
    _ru = types.ModuleType('report_utils')
    _ru.mark_task_failed = lambda *a, **k: None
    _ru.cleanup_tmp_dir = lambda p: None
    _ru.download_all_files = lambda t, d: {}
    _ru._get_biz_sql_conn = lambda: None
    sys.modules['report_utils'] = _ru
if 'oss_utils' not in sys.modules:
    _ou = types.ModuleType('oss_utils')
    _ou.upload_file = lambda *a, **k: 'http://x'
    sys.modules['oss_utils'] = _ou
if 'models' not in sys.modules:
    _md = types.ModuleType('models')
    _md.DataProcessTask = type('T', (), {})

    class _G:  # GuangaiStoreReportData stub:接受任意关键字参数并存为属性
        def __init__(self, **kw):
            for k, v in kw.items():
                setattr(self, k, v)

    _md.GuangaiStoreReportData = _G
    _md.db = types.SimpleNamespace(session=None)
    sys.modules['models'] = _md

from guangai_processor import (
    GuangaiProcessor, compute_guangai_week_period, rating_text, _q4, _div,
)


class TestWeekPeriod(unittest.TestCase):
    """累计制周区间:WN = 1 日 ~ 当月第 N 个周日,仅 1~4 周"""

    def test_aug_2026(self):
        """2026-08:8/1 周六 → 第 1 个周日 8/2;W4 = 1 日 ~ 8/23"""
        s, e = compute_guangai_week_period('2026-08', 1)
        self.assertEqual((s, e), (date(2026, 8, 1), date(2026, 8, 2)))
        s, e = compute_guangai_week_period('2026-08', 4)
        self.assertEqual((s, e), (date(2026, 8, 1), date(2026, 8, 23)))

    def test_month_starts_sunday(self):
        """月初恰为周日(2026-11-01 周日):W1 = 11/1~11/1"""
        s, e = compute_guangai_week_period('2026-11', 1)
        self.assertEqual((s, e), (date(2026, 11, 1), date(2026, 11, 1)))

    def test_no_week5(self):
        """无第 5 周:week_num=5 抛 ValueError"""
        with self.assertRaises(ValueError):
            compute_guangai_week_period('2026-08', 5)

    def test_always_same_start(self):
        """累计制:所有周的起始日都是 1 号"""
        for w in range(1, 5):
            s, _ = compute_guangai_week_period('2026-09', w)
            self.assertEqual(s, date(2026, 9, 1))


class TestRating(unittest.TestCase):
    """广爱评灯阈值:≥20% 绿 / ≥10% 黄 / <10% 红"""

    def test_thresholds(self):
        self.assertEqual(rating_text(0.05), '红')
        self.assertEqual(rating_text(0.0999), '红')
        self.assertEqual(rating_text(0.10), '黄')
        self.assertEqual(rating_text(0.1999), '黄')
        self.assertEqual(rating_text(0.20), '绿')
        self.assertEqual(rating_text(0.5), '绿')

    def test_empty(self):
        self.assertEqual(rating_text(None), '')


class TestCalc(unittest.TestCase):
    """4 位小数去尾 0 / 除法"""

    def test_q4(self):
        self.assertEqual(_q4(Decimal('0.11995')), 0.12)
        self.assertEqual(_q4(0.1000), 0.1)
        self.assertIsNone(_q4(None))

    def test_div(self):
        self.assertAlmostEqual(_div(453, 592), 0.7652027)
        self.assertIsNone(_div(1, 0))
        self.assertIsNone(_div(None, 2))


class TestBuildWorkbook(unittest.TestCase):
    """Excel 渲染(假数据,stub DB/网络)"""

    @classmethod
    def setUpClass(cls):
        from guangai_processor import (CODE_DELIVERY, CODE_TOUCH, CODE_DEAL,
                                       CODE_OUTPUT, CODE_AFTER_ORDER,
                                       CODE_REFER_COUNT, CODE_VEHICLE_DEAL)

        def ind(d, t, deal, out, after=0, a084=None, a066=None):
            base = {CODE_DELIVERY: d, CODE_TOUCH: t, CODE_DEAL: deal, CODE_OUTPUT: out}
            if after:
                base[CODE_AFTER_ORDER] = after
            if a084 is not None:
                base[CODE_REFER_COUNT] = a084
            if a066 is not None:
                base[CODE_VEHICLE_DEAL] = a066
            return base

        stores = [{'merchant_id': str(i), 'merchant_name': f'门店{i}'} for i in range(1, 6)]
        # 少于模板样例 31 行 → 触发行删除逻辑;A067 已停用,渗透率由 ΣA066÷Σ交付 计算
        cur_b1 = {
            '1': ind(100, 80, 25, 50000, after=3, a084=60, a066=20),
            '2': ind(50, 30, 3, 8000),
        }
        prev_b1 = {
            '1': {CODE_DEAL: 20, CODE_OUTPUT: 40000, CODE_DELIVERY: 90, CODE_TOUCH: 70},
            '2': {CODE_DEAL: 5, CODE_OUTPUT: 9000, CODE_DELIVERY: 60, CODE_TOUCH: 40},
        }
        weeks = [(1, date(2026, 9, 1), date(2026, 9, 6)),
                 (2, date(2026, 9, 1), date(2026, 9, 13)),
                 (3, date(2026, 9, 1), date(2026, 9, 20)),
                 (4, date(2026, 9, 1), date(2026, 9, 27))]
        # 周区间分母 A084(扁平字典)
        week_ind = {
            1: {'1': {CODE_DEAL: 5, CODE_DELIVERY: 20, CODE_REFER_COUNT: 15},
                '2': {CODE_REFER_COUNT: 10}},
            2: {'1': {CODE_DEAL: 12, CODE_DELIVERY: 50, CODE_REFER_COUNT: 30},
                '2': {CODE_REFER_COUNT: 18}},
            3: {'1': {CODE_DEAL: 18, CODE_DELIVERY: 80, CODE_REFER_COUNT: 45}},
            4: {'1': {CODE_DEAL: 25, CODE_DELIVERY: 100, CODE_REFER_COUNT: 60},
                '2': {CODE_REFER_COUNT: 22}},
        }
        cum_b1 = {'1': {CODE_DEAL: 25, CODE_DELIVERY: 100, CODE_REFER_COUNT: 60},
                  '2': {CODE_REFER_COUNT: 25}}
        oe_cur = {'1': {'deal': 4, 'output': 12000}}
        oe_cum = {'1': {'deal': 4, 'output': 12000}}
        oe_week = {
            1: {'1': {'deal': 1, 'output': 3000}},
            2: {'1': {'deal': 2, 'output': 6000}},
            3: {'1': {'deal': 3, 'output': 9000}},
            4: {'1': {'deal': 4, 'output': 12000}},
        }
        oe_prev_snap = {'1': {'deal': 2, 'output': 5000},
                        '99': {'deal': 3, 'output': 7000}}

        class Att:
            def __init__(self, mid, brand, after, dl, rf, rate=None, out_t=None, unit_t=None):
                self.merchant_id = mid
                self.brand = brand
                self.after_sales_enabled = after
                self.group_delivery_cnt = dl
                self.group_refer_cnt = rf
                self.refer_rate = rate
                self.output_target = out_t
                self.unit_target = unit_t

        cur_attach = {
            '1': Att('1', '广汽丰田', '是', 90, 70, rate=None, out_t=Decimal('200000'), unit_t=40),
            '2': Att('2', '广汽本田', '否', 40, 25),
        }
        prev_attach = {
            '1': Att('1', '广汽丰田', '是', 90, 70),
            '2': Att('2', '广汽本田', '否', 40, 25),
        }

        cls.data = {
            'stores': stores,
            'province': {s['merchant_id']: '湖南' for s in stores},
            'shop_type': {s['merchant_id']: '直营' for s in stores},
            'director': {s['merchant_id']: '张三' for s in stores},
            'biz_dev_date': {s['merchant_id']: '2026-01-06' for s in stores},
            'cur_b1': cur_b1,
            'prev_b1': prev_b1,
            'week_ind': week_ind, 'weeks': weeks,
            'cum_b1': cum_b1,
            'snapshot_mids': ['1', '2', '99'],
            'prev_snap_b1': {'1': {**prev_b1['1'], CODE_REFER_COUNT: 60},
                             '99': {CODE_DEAL: 3, CODE_OUTPUT: 6000,
                                    CODE_DELIVERY: 30, CODE_TOUCH: 20,
                                    CODE_REFER_COUNT: 12,
                                    CODE_VEHICLE_DEAL: 2}},
            'oe_cur': oe_cur, 'oe_cum': oe_cum,
            'oe_week': oe_week, 'oe_prev_snap': oe_prev_snap,
            'cur_attach': cur_attach, 'prev_attach': prev_attach,
            'prev_first': date(2026, 8, 1), 'prev_last': date(2026, 8, 31),
        }

        cls.tmp = tempfile.mkdtemp(prefix='guangai_test_')
        cls.out_path = os.path.join(cls.tmp, '广爱专项_测试.xlsx')
        cls.task = types.SimpleNamespace(month='2026-09', period_type='month',
                                         week_num=None)
        GuangaiProcessor().build_workbook(cls.data, cls.task,
                                          date(2026, 9, 1), date(2026, 9, 26),
                                          cls.out_path)
        cls.wb = openpyxl.load_workbook(cls.out_path)
        cls.ws = cls.wb.worksheets[0]
        cls.delta = len(stores) - 31  # -26

    @classmethod
    def tearDownClass(cls):
        for f in os.listdir(cls.tmp):
            os.remove(os.path.join(cls.tmp, f))
        os.rmdir(cls.tmp)

    def test_rate_cells_have_percent_format(self):
        """比率列(含合计行)必须带 0.00"%" 格式,导出后在单元格里显示 % 号。

        覆盖:L/O/P 上月、U 交付渗透率、V 达成率(目标20%)、W~Z 周渗透率、
        AH 权益交付渗透率、AI 权益达成率、AJ~AM 权益周渗透率、AT 产值达成、AV 件数达成。
        值本身已是 _pct() ×100 的百分数,格式只追加 % 号、不再缩放。
        """
        from guangai_processor import RATE_COLS, RATE_NUMBER_FORMAT
        self.assertTrue(RATE_COLS, 'RATE_COLS 不应为空')
        for col in sorted(RATE_COLS):
            for row in (6, 7, 8):   # 6=合计行,7/8=明细行
                cell = self.ws.cell(row=row, column=col)
                self.assertEqual(
                    cell.number_format, RATE_NUMBER_FORMAT,
                    f'第 {row} 行第 {col} 列应为 {RATE_NUMBER_FORMAT},实际 {cell.number_format}')

    def test_title_replaced(self):
        """行 1 标题:8月→9月、2026-08-16→2026-09-26、8.16→9.26"""
        t = str(self.ws.cell(row=1, column=1).value)
        self.assertIn('2026-09-26', t)
        self.assertIn('9.26', t)
        self.assertIn('9月新模板', t)
        self.assertNotIn('8月', t)

    def test_sample_rows_removed(self):
        """样例门店行已删除,仅剩 5 行门店数据 + 合计行"""
        self.assertEqual(self.ws.cell(row=7, column=4).value, '门店1')
        self.assertEqual(self.ws.cell(row=11, column=4).value, '门店5')
        self.assertIsNone(self.ws.cell(row=12, column=4).value)
        self.assertEqual(self.ws.cell(row=6, column=1).value, '合计')

    def test_detail_values(self):
        """明细取值:系统字段/附件/指标/评灯/差异"""
        # 门店1:直营、品牌广汽丰田、打通售后是、交车90 触客70(附件)
        self.assertEqual(self.ws.cell(row=7, column=1).value, 1)
        self.assertEqual(self.ws.cell(row=7, column=3).value, '直营')
        self.assertEqual(self.ws.cell(row=7, column=5).value, '广汽丰田')
        self.assertEqual(self.ws.cell(row=7, column=6).value, '延保')
        self.assertEqual(self.ws.cell(row=7, column=9).value, '是')
        self.assertEqual(self.ws.cell(row=7, column=13).value, 20)   # M 上月订单 A075 biz=1
        self.assertEqual(self.ws.cell(row=7, column=17).value, 90)   # Q 附件交车
        self.assertEqual(self.ws.cell(row=7, column=18).value, 70)   # R 附件触客
        self.assertEqual(self.ws.cell(row=7, column=19).value, 25)   # S 延保成交
        self.assertEqual(self.ws.cell(row=7, column=32).value, 4)   # AF 原厂权益成交(SQL)
        self.assertEqual(self.ws.cell(row=7, column=33).value, 12000)  # AG 原厂权益产值
        self.assertAlmostEqual(self.ws.cell(row=7, column=34).value, 5.71, places=2)  # AH = AF/R → 百分数
        self.assertAlmostEqual(self.ws.cell(row=7, column=36).value, 6.67, places=2)  # AJ = W1累计AF/W1累计A084
        self.assertEqual(self.ws.cell(row=7, column=40).value, '红')  # AN = 4/60 < 10%
        self.assertAlmostEqual(self.ws.cell(row=7, column=21).value, 25.0, places=2)  # U = 25/100 → 25%
        self.assertAlmostEqual(self.ws.cell(row=7, column=23).value, 25.0, places=2)  # W1 = 5/20 → 25%
        self.assertEqual(self.ws.cell(row=7, column=27).value, '绿')            # AA = 25/100
        # 差异 AY = 90 - 100 = -10(≠0 标黄)
        self.assertEqual(self.ws.cell(row=7, column=51).value, -10)
        # 差异 BB = 70 - 80 = -10
        self.assertEqual(self.ws.cell(row=7, column=54).value, -10)
        # AS/AU 目标 + AT 达成
        self.assertEqual(self.ws.cell(row=7, column=45).value, 200000)
        self.assertAlmostEqual(self.ws.cell(row=7, column=46).value, 45.0, places=2)  # AT = (上月+本月A036)/目标 → 百分数
        # 门店2:S=3(附件交车40 vs 指标A062=50 → 差异 -10)
        self.assertEqual(self.ws.cell(row=8, column=19).value, 3)
        self.assertEqual(self.ws.cell(row=8, column=51).value, -10)

    def test_total_row(self):
        """合计行:Q 合计 90+40=130;AX 合计 100;AA-AE 保持 '-'"""
        self.assertEqual(self.ws.cell(row=6, column=17).value, 130)
        self.assertEqual(self.ws.cell(row=6, column=50).value, 150)
        self.assertEqual(self.ws.cell(row=6, column=32).value, 4)  # AF 合计
        for col in (27, 28, 29, 30, 31, 45):
            self.assertEqual(self.ws.cell(row=6, column=col).value, '-')

    def test_brand_summary(self):
        """品牌汇总:本月数据行=42+delta(41 是取值说明行不可覆盖)、上月=48+delta"""
        r40 = 39 + self.delta      # 标题行
        r41 = 41 + self.delta      # 取值说明行(模板原文,不得篡改)
        r42 = 42 + self.delta      # 本月数据行
        self.assertIn('9月', str(self.ws.cell(row=r40, column=1).value))
        # 说明行保留模板原文(含"硬值"字样)
        self.assertIn('硬值', str(self.ws.cell(row=r41, column=1).value))
        self.assertEqual(self.ws.cell(row=r42, column=1).value, '广爱')
        self.assertEqual(self.ws.cell(row=r42, column=3).value, 5)     # 门店数
        self.assertEqual(self.ws.cell(row=r42, column=11).value, 20)   # K = ΣA066 整车延保成交
        # L = ΣA066 ÷ Σ交付数 = 20 ÷ (100+50) = 13.33%(不再 ΣA067,比率不可加)
        self.assertAlmostEqual(self.ws.cell(row=r42, column=12).value, 13.33, places=2)
        # I = 售后门店数 ÷ 门店数 = 1 ÷ 5 = 20%(百分数 + 0.00"%" 格式)
        self.assertAlmostEqual(self.ws.cell(row=r42, column=9).value, 20.0, places=2)
        self.assertEqual(self.ws.cell(row=r42, column=9).number_format, '0.00"%"')
        self.assertEqual(self.ws.cell(row=r42, column=13).value, 4)   # M = ΣAF
        self.assertAlmostEqual(self.ws.cell(row=r42, column=14).value, 4.71, places=2)  # N = 百分数
        # 上月行:快照门店 1+99
        r48 = 48 + self.delta
        self.assertEqual(self.ws.cell(row=r48, column=3).value, 3)     # 快照门店数
        self.assertEqual(self.ws.cell(row=r48, column=11).value, 2)    # K = 快照 A066
        # L 上月 = 2 ÷ (90+30) = 1.67%
        self.assertAlmostEqual(self.ws.cell(row=r48, column=12).value, 1.67, places=2)
        # I 上月 = 1 ÷ 3 = 33.33%
        self.assertAlmostEqual(self.ws.cell(row=r48, column=9).value, 33.33, places=2)
        self.assertEqual(self.ws.cell(row=r48, column=13).value, 5)    # M = 2+3(快照原厂权益成交)
        self.assertAlmostEqual(self.ws.cell(row=r48, column=14).value, 6.94, places=2)  # N = 百分数

    def test_no_formulas(self):
        """所有单元格为计算值,无公式"""
        for row in self.ws.iter_rows(min_row=1, max_row=self.ws.max_row):
            for c in row:
                self.assertFalse(
                    isinstance(c.value, str) and c.value.startswith('='),
                    f'{c.coordinate} 存在公式: {c.value}')




class TestValidateAttachmentFile(unittest.TestCase):
    """附件解析校验:说明行跳过 / 同名商户取首个 / 无效门店名报错。"""

    def setUp(self):
        from guangai_processor import GuangaiProcessor
        self.proc = GuangaiProcessor()
        # mock 门店清单(含同名不同商户号)
        self.stores = [
            {'merchant_id': '1001', 'merchant_name': '门店A'},
            {'merchant_id': '1002', 'merchant_name': '门店A'},   # 同名第二条
            {'merchant_id': '2001', 'merchant_name': '门店B'},
        ]
        self.proc.load_store_list = lambda: self.stores
        self.tmp = tempfile.mkdtemp(prefix='guangai_val_')

    def tearDown(self):
        for f in os.listdir(self.tmp):
            os.remove(os.path.join(self.tmp, f))
        os.rmdir(self.tmp)

    def _make_file(self, rows, name='att.xlsx'):
        """rows: list of (门店名称, 品牌, 打通售后, 交车, 触客, 触客率, 产值目标, 件数目标)"""
        wb = openpyxl.Workbook()
        ws = wb.worksheets[0]
        ws.cell(row=2, column=1, value='门店名称')
        for c, h in enumerate(['门店名称', '品牌', '是否有打通售后',
                               '一店一群·交车数', '一店一群·触客数',
                               '触客率', '产值目标(元)', '件数目标(台)'], 1):
            ws.cell(row=2, column=c, value=h)
        r = 3
        for row in rows:
            for c, v in enumerate(row, 1):
                ws.cell(row=r, column=c, value=v)
            r += 1
        path = os.path.join(self.tmp, name)
        wb.save(path)
        return path

    def test_tips_row_skipped(self):
        """模板自带"填写说明"行(首列含"系统预填")必须跳过,不参与校验。"""
        path = self._make_file([
            # 说明行(模板第 3 行原样)
            ('系统预填,请勿修改(门店名称是唯一匹配依据,须与系统完全一致)',
             '广汽丰田 / 广汽本田 / 广汽传祺(三选一,必填)',
             '是 / 否(必填,每月一次)', '≥0 的整数,必填', '≥0 的整数,必填',
             '可留空;留空时系统自动计算', '元;未设目标留空', '台;未设目标留空'),
            ('门店A', '广汽丰田', '是', 10, 5, None, None, None),
        ])
        res = self.proc.validate_attachment_file(
            path, '2026-09', 'month', None,
            date(2026, 9, 1), date(2026, 9, 30))
        self.assertTrue(res['ok'])
        self.assertEqual(len(res['rows']), 1)
        self.assertEqual(res['rows'][0].merchant_id, '1001')

    def test_duplicate_name_takes_first_merchant(self):
        """同名商户(商户号不同):不报"重复",取第一个商户号;
        同商户重复行按商户号去重保首行(避免同批 INSERT 自撞唯一键)。"""
        path = self._make_file([
            ('门店A', '广汽丰田', '是', 10, 5, None, None, None),
            ('门店A', '广汽本田', '否', 8, 4, None, None, None),
            ('门店B', '广汽传祺', '是', 3, 1, None, None, None),
        ])
        res = self.proc.validate_attachment_file(
            path, '2026-09', 'month', None,
            date(2026, 9, 1), date(2026, 9, 30))
        self.assertTrue(res['ok'], res['errors'])
        # 两行门店A → 同商户号 1001,去重保第一行(广汽丰田/10/5)
        self.assertEqual(len(res['rows']), 2)
        self.assertEqual(res['rows'][0].merchant_id, '1001')
        self.assertEqual(res['rows'][0].brand, '广汽丰田')
        self.assertEqual(res['rows'][0].group_delivery_cnt, 10)
        self.assertEqual(res['rows'][1].merchant_id, '2001')

    def test_unknown_store_reported(self):
        """系统不存在的门店名 → 报错、不入库。"""
        path = self._make_file([
            ('不存在的门店', '广汽丰田', '是', 10, 5, None, None, None),
        ])
        res = self.proc.validate_attachment_file(
            path, '2026-09', 'month', None,
            date(2026, 9, 1), date(2026, 9, 30))
        self.assertFalse(res['ok'])
        self.assertEqual(len(res['rows']), 0)
        self.assertIn('不存在', list(res['errors'].values())[0])


if __name__ == '__main__':
    unittest.main(verbosity=2)