Commit 43a64bf8 by chenxi

提交改动

1 parent e76ce717
......@@ -111,16 +111,16 @@ def compute_guangai_week_period(month, week_num):
def rating_text(pct):
"""广爱评灯:渗透率(小数) ≥0.2 绿 / ≥0.1 黄 / <0.1 红;空/分母 0 → ''。"""
"""广爱评灯:渗透率(小数) **>0.2 绿 / >0.1 黄 / 其余红**(严格大于:恰好 20% 判黄、恰好 10% 判红);空/分母 0 → ''。"""
if pct is None:
return ''
try:
p = Decimal(str(pct))
except Exception:
return ''
if p >= Decimal('0.2'):
if p > Decimal('0.2'):
return '绿'
if p >= Decimal('0.1'):
if p > Decimal('0.1'):
return '黄'
return '红'
......@@ -804,6 +804,15 @@ class GuangaiProcessor:
is_deleted=0).all()
prev_attach = {r.merchant_id: r for r in prev_rows}
# 各周累计交车数(W~Z 分母):同月 period_type='week' 的附件记录,
# week_num=1/2/3/4 对应「前 1/2/3/4 周」的累计口径(与 compute_guangai_week_period 一致);
# 该周没上传附件 → 明细该列留空,不扩列、也不回退 A062(2026-10-28 业务确认)。
week_attach = {}
for r in GuangaiStoreReportData.query.filter_by(
month=task.month, period_type='week', is_deleted=0).all():
if r.week_num:
week_attach[(int(r.week_num), str(r.merchant_id))] = r
return {
'stores': stores,
'province': province,
......@@ -820,6 +829,7 @@ class GuangaiProcessor:
'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,
'week_attach': week_attach, # {(week_num, merchant_id): 附件行},W~Z 分母
'prev_first': prev_first, 'prev_last': prev_last,
}
......@@ -827,6 +837,36 @@ class GuangaiProcessor:
# Excel 渲染
# ============================================================
@staticmethod
def _blank_zero_cells(ws):
"""全局展示规则:数值 0 与 0%(含 Decimal('0.00')、-0.0)一律留空。
2026-10-28 业务要求:"所有单元格的值如果是 0 或 0%,直接展示空白"。
- 只处理**数值型**单元格;文本(评灯「红/黄/绿」、占位符「-」、说明文字)
和公式单元格不动,避免误清模板里的说明性 "0"(字符串)。
- 只在**显示层**置空,不改动任何计算/累加逻辑(合计在置空前已算完),
也不改单元格数字格式——所以原本的 `0.00"%"` 等格式仍保留,
后续有人手工填数也不会丢格式。
- 只作用于数据页(`OUTPUT_SHEET`),「字段字典」页不动。
"""
cleared = 0
for row in ws.iter_rows():
for cell in row:
v = cell.value
if v is None or isinstance(v, bool):
continue # bool 是 int 子类,必须单独排除
if not isinstance(v, (int, float, Decimal)):
continue
try:
is_zero = (v == 0)
except Exception:
continue
if is_zero:
cell.value = None
cleared += 1
return cleared
def build_workbook(self, data, task, period_start, period_end, out_path):
"""按模板渲染广爱专项报表并保存到 out_path。"""
period_start = self._as_date(period_start)
......@@ -898,6 +938,11 @@ class GuangaiProcessor:
ws.merge_cells(start_row=min_row + delta, start_column=min_col,
end_row=max_row + delta, end_column=max_col)
# ---------- 8) 全局展示规则:数值 0 / 0% 一律留空 ----------
cleared = self._blank_zero_cells(ws)
if cleared:
logger.info(f"[广爱专项] 空白化 0 值单元格 {cleared} 个")
wb.save(out_path)
logger.info(f"[广爱专项] Excel 已生成: {out_path}({n} 门店, 维度="
f"{task.period_type}" + (f"W{task.week_num}" if task.period_type == 'week' else '') + ")")
......@@ -915,6 +960,7 @@ class GuangaiProcessor:
oe_cum = data['oe_cum']
oe_week = data['oe_week']
cur_attach, prev_attach = data['cur_attach'], data['prev_attach']
week_attach = data.get('week_attach') or {} # {(week_num, merchant_id): 附件行}
province, shop_type = data['province'], data['shop_type']
director, biz_dev = data['director'], data['biz_dev_date']
......@@ -931,6 +977,9 @@ class GuangaiProcessor:
for w, _s, _e in weeks}
week_a084_sums = {w: Decimal('0') for w, _s, _e in weeks}
week_a084_has = {w: False for w, _s, _e in weeks}
# W~Z 合计的分母:Σ该周附件累计交车数
week_deli_sums = {w: Decimal('0') for w, _s, _e in weeks}
week_deli_has = {w: False for w, _s, _e in weeks}
week_oe_sums = {w: Decimal('0') for w, _s, _e in weeks}
week_oe_has = {w: False for w, _s, _e in weeks}
......@@ -966,16 +1015,20 @@ class GuangaiProcessor:
l_val = prev_att.refer_rate if (prev_att and prev_att.refer_rate is not None) \
else _div(k_val, j_val)
u_val = _div(deal_cur, delivery_cur) # U 延保成交/A062
# U 交付渗透率 = 延保成交数 ÷ **附件交车数(Q)**(2026-10-28 口径调整:原 ÷ A062)
u_val = _div(deal_cur, q_val) if q_val not in (None, 0) else None
v_val = _div(u_val, Decimal('0.2')) if u_val is not None else None
# W1~W4 渗透率(周区间累计 延保成交/延保交车)
# W1~W4 渗透率(累计制):累计 A075 ÷ **该周累计交车数(同月 week_num=N 的附件记录)**
w_vals = {}
for w, _ws, _we in weeks:
wi = (week_ind.get(w) or {}).get(mid) or {}
w_vals[w] = _div(g1(wi, CODE_DEAL), g1(wi, CODE_DELIVERY))
wk_att = week_attach.get((w, str(mid)))
wk_deli = wk_att.group_delivery_cnt if wk_att else None
w_vals[w] = _div(g1(wi, CODE_DEAL), wk_deli) if wk_deli else None
aa_val = _div(g1(cum, CODE_DEAL), g1(cum, CODE_DELIVERY))
# AA 延保评灯:直接取 U 列值(2026-10-28 口径调整:原 累计A075÷累计A062)
aa_val = u_val
aa_text = rating_text(aa_val)
# 原厂权益(业务库 SQL,类目 189)
oe_deal_cur = (oe_c.get('deal') or 0) if oe_c else 0
......@@ -1073,14 +1126,29 @@ class GuangaiProcessor:
sums[c] += Decimal(str(v))
has_val[c] = True
for w, _ws, _we in weeks:
wi = week_ind.get(w) or {}
# ⚠ week_ind[w] 是 {merchant_id: {code: value}} 的**全店**映射,
# 必须再按 mid 取本店那一层,否则 g1() 永远返回 None →
# W~Z / AJ~AM 合计行恒为空(2026-10-28 修复)。
wi = (week_ind.get(w) or {}).get(mid) or {}
a84 = g1(wi, CODE_REFER_COUNT)
if a84 is not None:
week_a084_sums[w] += Decimal(str(a84))
week_a084_has[w] = True
# W~Z:分子 Σ累计A075、分母 Σ该周附件累计交车数
deal_w = g1(wi, CODE_DEAL)
if deal_w is not None:
week_sums[w]['deal'] += Decimal(str(deal_w))
week_sums[w]['has'] = True
wk_att = week_attach.get((w, str(mid)))
if wk_att and wk_att.group_delivery_cnt:
week_deli_sums[w] += Decimal(str(wk_att.group_delivery_cnt))
week_deli_has[w] = True
wk_oe = (oe_week.get(w) or {}).get(mid) or {}
if wk_oe.get('deal') is not None:
week_oe_sums[w] += Decimal(str(wk_oe['deal']))
# 权益 SQL 是聚合口径:某门店没出现在结果里 = 该周期确实 0 台
# (与指标库"无记录"不同)。明细行已按 0 计算,这里同样按 0 累加,
# 否则会出现「明细 0.00% 红、合计空白」的自相矛盾。
if w in oe_week:
week_oe_sums[w] += Decimal(str(wk_oe.get('deal') or 0))
week_oe_has[w] = True
# 合计行(行 6)
......@@ -1099,12 +1167,13 @@ class GuangaiProcessor:
set6(12, _pct(_div(sums[11], sums[10]) if has_val[11] and has_val[10] else None))
set6(15, _pct(_div(sums[13], sums[11]) if has_val[13] and has_val[11] else None))
set6(16, _pct(_div(sums[13], sums[10]) if has_val[13] and has_val[10] else None))
set6(21, _pct(_div(sums[19], sums[50]) if has_val[19] and has_val[50] else None))
u6 = _div(sums[19], sums[50]) if has_val[19] and has_val[50] else None
# U 合计 = ΣS ÷ ΣQ(附件交车数,2026-10-28 口径调整:原 ÷ ΣAX/A062)
u6 = _div(sums[19], sums[17]) if has_val[19] and has_val[17] else None
set6(21, _pct(u6))
set6(22, _pct(_div(u6, Decimal('0.2'))) if u6 is not None else None)
for w, _ws, _we in weeks:
set6(22 + w, _pct(_div(week_sums[w]['deal'], week_sums[w]['deli'])
if week_sums[w]['has'] and week_sums[w]['deli'] else None))
set6(22 + w, _pct(_div(week_sums[w]['deal'], week_deli_sums[w])
if week_sums[w]['has'] and week_deli_has[w] else None))
for col in (27, 28, 29, 30, 31, 40, 41, 42, 43, 44, 45, 46, 47, 48):
set6(col, '-')
# AH 合计 = ΣAF ÷ ΣR(附件触客);AI = AH ÷ 20%
......
......@@ -83,20 +83,49 @@ class TestWeekPeriod(unittest.TestCase):
class TestRating(unittest.TestCase):
"""广爱评灯阈值:≥20% 绿 / ≥10% 黄 / <10% 红"""
"""广爱评灯阈值(严格大于):>20% 绿 / >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.10), '红') # 恰好 10% → 红(严格大于)
self.assertEqual(rating_text(0.1001), '黄')
self.assertEqual(rating_text(0.1999), '黄')
self.assertEqual(rating_text(0.20), '绿')
self.assertEqual(rating_text(0.20), '黄') # 恰好 20% → 黄(严格大于)
self.assertEqual(rating_text(0.2001), '绿')
self.assertEqual(rating_text(0.5), '绿')
def test_empty(self):
self.assertEqual(rating_text(None), '')
class TestBlankZero(unittest.TestCase):
"""全局展示规则:数值 0 / 0% 一律留空(文本与公式不动)"""
def test_blank_zero_cells(self):
wb = openpyxl.Workbook()
ws = wb.active
ws['A1'] = 0
ws['A2'] = 0.0
ws['A3'] = Decimal('0.00')
ws['A4'] = 12
ws['A5'] = 0.25
ws['A6'] = '0' # 文本,保留
ws['A7'] = '-' # 占位符,保留
ws['A8'] = '红' # 评灯,保留
ws['A9'] = False # bool 不能被当成 0
n = GuangaiProcessor._blank_zero_cells(ws)
self.assertEqual(n, 3)
for coord in ('A1', 'A2', 'A3'):
self.assertIsNone(ws[coord].value, coord)
self.assertEqual(ws['A4'].value, 12)
self.assertEqual(ws['A5'].value, 0.25)
self.assertEqual(ws['A6'].value, '0')
self.assertEqual(ws['A7'].value, '-')
self.assertEqual(ws['A8'].value, '红')
self.assertIs(ws['A9'].value, False)
class TestCalc(unittest.TestCase):
"""4 位小数去尾 0 / 除法"""
......@@ -206,6 +235,8 @@ class TestBuildWorkbook(unittest.TestCase):
'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,
# W~Z 分母:各周累计交车数(同月 week_num=N 的附件行),仅给 W1 造一条
'week_attach': {(1, '1'): Att('1', '广汽丰田', '是', 20, 15)},
'prev_first': date(2026, 8, 1), 'prev_last': date(2026, 8, 31),
}
......@@ -274,9 +305,10 @@ class TestBuildWorkbook(unittest.TestCase):
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
self.assertAlmostEqual(self.ws.cell(row=7, column=21).value, 27.78, places=2) # U = S÷Q = 25/90(附件交车数)
self.assertAlmostEqual(self.ws.cell(row=7, column=22).value, 138.89, places=2) # V = U ÷ 20%
self.assertAlmostEqual(self.ws.cell(row=7, column=23).value, 25.0, places=2) # W1 = 5/20(该周附件交车数)
self.assertEqual(self.ws.cell(row=7, column=27).value, '绿') # AA 取 U 值 27.78% → 绿
# 差异 AY = 90 - 100 = -10(≠0 标黄)
self.assertEqual(self.ws.cell(row=7, column=51).value, -10)
# 差异 BB = 70 - 80 = -10
......@@ -289,10 +321,13 @@ class TestBuildWorkbook(unittest.TestCase):
self.assertEqual(self.ws.cell(row=8, column=51).value, -10)
def test_total_row(self):
"""合计行:Q 合计 90+40=130;AX 合计 100;AA-AE 保持 '-'"""
"""合计行:Q 合计 90+40=130;AX 合计 100;AA-AE 保持 '-';W~Z 按 ΣA075÷Σ周附件交车"""
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 合计
# W~Z 合计:只有门店1 有 W1 周附件(交车 20)、A075=5 → 5/20=25%
# ⚠ 2026-10-28 回归:此前 week_ind 未按 mid 取二层,合计恒为空
self.assertAlmostEqual(self.ws.cell(row=6, column=23).value, 25.0, places=2)
for col in (27, 28, 29, 30, 31, 45):
self.assertEqual(self.ws.cell(row=6, column=col).value, '-')
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!