Commit 59a3feaa by zhouhaibao

feat(data-process): 增加费用分摊逻辑优化与未匹配金额统计功能

- 引入 Decimal 精确计算和 logging 日志记录功能
- 添加服务商过滤机制,仅处理含"深圳嘀加"的服务商数据
- 实现装修摊销和门店耗材的未匹配金额统计与对账功能
- 新增 biz_unmatched_fee 表模型用于存储未匹配费用汇总
- 重构市场费分摊逻辑,支持单条记录、双品牌场景和 GMV 分摊
- 优化 GMV 查询和分摊算法,增加 only_dijia 参数控制分摊范围
- 添加处理器侧未匹配金额收集和数据库写入功能
- 修改返回值结构,统一返回 (更新行数, 未匹配金额) 元组格式
1 parent 72d8e8e4
...@@ -38,12 +38,14 @@ ...@@ -38,12 +38,14 @@
python clean_budget_achievement.py -t budget_achievement -m 2026-06 --dry-run python clean_budget_achievement.py -t budget_achievement -m 2026-06 --dry-run
""" """
import argparse import argparse
import logging
import os import os
import re import re
import sys import sys
import tempfile import tempfile
import traceback import traceback
from datetime import datetime from datetime import datetime
from decimal import Decimal
from urllib.parse import urlparse from urllib.parse import urlparse
import warnings import warnings
warnings.filterwarnings( warnings.filterwarnings(
...@@ -81,6 +83,8 @@ CLEAN_PENDING, CLEAN_RUNNING, CLEAN_DONE = 1, 2, 3 ...@@ -81,6 +83,8 @@ CLEAN_PENDING, CLEAN_RUNNING, CLEAN_DONE = 1, 2, 3
MONTH_PATTERN = re.compile(r'^\d{4}-(0[1-9]|1[0-2])$') MONTH_PATTERN = re.compile(r'^\d{4}-(0[1-9]|1[0-2])$')
logger = logging.getLogger(__name__)
def log(msg): def log(msg):
print(f'[{datetime.now():%Y-%m-%d %H:%M:%S}] {msg}', flush=True) print(f'[{datetime.now():%Y-%m-%d %H:%M:%S}] {msg}', flush=True)
...@@ -400,12 +404,15 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV ...@@ -400,12 +404,15 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV
# 每条明细独立判定 F / G 模式,各自累加进对应池(每条明细只计一次) # 每条明细独立判定 F / G 模式,各自累加进对应池(每条明细只计一次)
f_pool = defaultdict(float) # key=归一化门店名称(F) → 应摊总额 f_pool = defaultdict(float) # key=归一化门店名称(F) → 应摊总额
g_pool = defaultdict(float) # key=归一化系统园区店名称(G) → 应摊总额 g_pool = defaultdict(float) # key=归一化系统园区店名称(G) → 应摊总额
total_detail_amount = Decimal('0') # 所有有效明细(in_window 且 amt!=0)的金额合计
unmatched_amount = Decimal('0') # 未匹配到任何 pool 的明细金额合计
for d in detail_rows: for d in detail_rows:
if not in_window(d['accept_date']): if not in_window(d['accept_date']):
continue continue
amt = (d['contract_amount'] or 0.0) / n_months amt = (d['contract_amount'] or 0.0) / n_months
if amt == 0: if amt == 0:
continue continue
total_detail_amount += Decimal(str(amt))
# 明细名先归一为标准名(别名归并),再 strip D+ 与预算行口径一致 # 明细名先归一为标准名(别名归并),再 strip D+ 与预算行口径一致
fn = strip_if_dplus(to_standard(d['store_name'], '4s')) fn = strip_if_dplus(to_standard(d['store_name'], '4s'))
gn = strip_if_dplus(to_standard(d['park_store_name'], 'yq')) gn = strip_if_dplus(to_standard(d['park_store_name'], 'yq'))
...@@ -415,6 +422,8 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV ...@@ -415,6 +422,8 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV
# G 模式(兜底):仅当「门店名称」列为空时才允许按系统园区店名称匹配; # G 模式(兜底):仅当「门店名称」列为空时才允许按系统园区店名称匹配;
# 门店名称非空但未命中 F 的明细,不允许再落到 G 池。 # 门店名称非空但未命中 F 的明细,不允许再落到 G 池。
g_pool[gn] += amt g_pool[gn] += amt
else:
unmatched_amount += Decimal(str(amt)) # 未匹配到任何 pool
# 按 GMV 占比分摊各池 # 按 GMV 占比分摊各池
# - F 池(按门店名称/traffic_name 匹配):用本行 GMV 在池内占比摊分; # - F 池(按门店名称/traffic_name 匹配):用本行 GMV 在池内占比摊分;
...@@ -427,6 +436,16 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV ...@@ -427,6 +436,16 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV
if total == 0: if total == 0:
continue continue
rows = row_map[key] rows = row_map[key]
# --- 服务商过滤:只保留 service_provider 含"深圳嘀加"的行 ---
dijia_rows = [r for r in rows if _is_dijia_row(r)]
if not dijia_rows:
# 全是非嘀加 → 不分摊(费用=0),跳过
continue
if len(dijia_rows) < len(rows):
logger.info(f"[装修分摊] key={key}: {len(rows)} 行中有 {len(dijia_rows)} 行"
f" 服务商=深圳嘀加,参与分摊;跳过 {len(rows)-len(dijia_rows)} 行")
rows = dijia_rows
if field == 'mgv_ratio_park': if field == 'mgv_ratio_park':
# 优先用 mgv_ratio_park(同业务类型+同园区店 GMV 占比); # 优先用 mgv_ratio_park(同业务类型+同园区店 GMV 占比);
# 若某行 mgv_ratio_park 为空(如 dry-run 预览时尚未写库), # 若某行 mgv_ratio_park 为空(如 dry-run 预览时尚未写库),
...@@ -463,6 +482,16 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV ...@@ -463,6 +482,16 @@ def compute_renovation_amounts(detail_rows, biz_rows, stat_month, n_months=RENOV
_allocate(g_pool, g_rows, field='mgv_ratio_park') _allocate(g_pool, g_rows, field='mgv_ratio_park')
# 全局对账:各池分摊合计对齐到「匹配明细金额总和(分取整)」,消除跨池四舍五入残差 # 全局对账:各池分摊合计对齐到「匹配明细金额总和(分取整)」,消除跨池四舍五入残差
reconcile_total(result, round(sum(f_pool.values()) + sum(g_pool.values()), 2)) reconcile_total(result, round(sum(f_pool.values()) + sum(g_pool.values()), 2))
# 记录未匹配金额到返回 dict 的特殊 key
pools_total = Decimal(str(round(sum(f_pool.values()) + sum(g_pool.values()), 2)))
residual = total_detail_amount - pools_total - unmatched_amount
if abs(float(residual)) >= 0.005:
logger.info(
f"[装修摊销对账] 明细总额={float(total_detail_amount):.2f} "
f"池合计={float(pools_total):.2f} 未匹配={float(unmatched_amount):.2f} "
f"残差={float(residual):.2f}"
)
result['_unmatched'] = float(unmatched_amount)
return result return result
...@@ -621,10 +650,10 @@ def query_all_biz_rows(conn, task_id, stat_month): ...@@ -621,10 +650,10 @@ def query_all_biz_rows(conn, task_id, stat_month):
"""查询本任务下指定统计月的全部预算达成结果行(门店资产耗材按业务类型分别匹配用)。 """查询本任务下指定统计月的全部预算达成结果行(门店资产耗材按业务类型分别匹配用)。
Returns: Returns:
list[dict]: {id, traffic_name, park_store, gmv, gmv_ratio_park, business_type} list[dict]: {id, traffic_name, park_store, gmv, gmv_ratio_park, business_type, service_provider}
""" """
sql = ( sql = (
'SELECT id, traffic_name, park_store, gmv, gmv_ratio_park, business_type ' 'SELECT id, traffic_name, park_store, gmv, gmv_ratio_park, business_type, service_provider '
'FROM biz_budget_achieve ' 'FROM biz_budget_achieve '
'WHERE task_id = %s AND stat_month = %s' 'WHERE task_id = %s AND stat_month = %s'
) )
...@@ -633,6 +662,17 @@ def query_all_biz_rows(conn, task_id, stat_month): ...@@ -633,6 +662,17 @@ def query_all_biz_rows(conn, task_id, stat_month):
return cur.fetchall() return cur.fetchall()
_DIJIA_SPIDER = '%深圳嘀加%' # 匹配服务商含"深圳嘀加"的行
def _is_dijia_row(row):
"""判断 biz_budget_achieve 行的 service_provider 是否含"深圳嘀加"。
row 可以是 dict(query_all_biz_rows 返回)或 sqlalchemy Row / pymysql dict。
"""
sp = (row.get('service_provider') or row.get('serviceProvider') or '').strip()
return '深圳嘀加' in sp
def compute_consumables_amounts(detail_rows, biz_rows, stat_month): def compute_consumables_amounts(detail_rows, biz_rows, stat_month):
"""按规则计算每行预算达成数据的「门店资产耗材」金额。 """按规则计算每行预算达成数据的「门店资产耗材」金额。
...@@ -683,12 +723,15 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month): ...@@ -683,12 +723,15 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month):
# 每条明细独立判定 F / G,累加进对应池(按 (bt, 名称) 聚合,每条明细只计一次) # 每条明细独立判定 F / G,累加进对应池(按 (bt, 名称) 聚合,每条明细只计一次)
f_pool = defaultdict(float) # (bt, 标准流量方名称) -> 应摊总额 f_pool = defaultdict(float) # (bt, 标准流量方名称) -> 应摊总额
g_pool = defaultdict(float) # (bt, 标准园区店名称) -> 应摊总额 g_pool = defaultdict(float) # (bt, 标准园区店名称) -> 应摊总额
total_detail_amount = Decimal('0') # 所有有效明细(本月且 amt!=0)的金额合计
unmatched_amount = Decimal('0') # 未匹配到任何 pool 的明细金额合计
for d in detail_rows: for d in detail_rows:
if d.get('month') != month_label: if d.get('month') != month_label:
continue continue
amt = float(d['amount'] or 0) amt = float(d['amount'] or 0)
if amt == 0: if amt == 0:
continue # 负数金额保留为负贡献,按园区店/流量方 GMV 占比作冲减扣减 continue # 负数金额保留为负贡献,按园区店/流量方 GMV 占比作冲减扣减
total_detail_amount += Decimal(str(amt))
bt = normalize_bt(d['business_type']) bt = normalize_bt(d['business_type'])
fmap = bt_f.get(bt, {}) fmap = bt_f.get(bt, {})
gmap = bt_g.get(bt, {}) gmap = bt_g.get(bt, {})
...@@ -715,6 +758,8 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month): ...@@ -715,6 +758,8 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month):
gkey = next((c for c in g_cands if c in gmap), None) gkey = next((c for c in g_cands if c in gmap), None)
if gkey: if gkey:
g_pool[(bt, gkey)] += amt # G 模式(兜底):按系统园区店名称匹配 g_pool[(bt, gkey)] += amt # G 模式(兜底):按系统园区店名称匹配
else:
unmatched_amount += Decimal(str(amt)) # 未匹配到任何 pool
# 按 GMV 占比分摊各池 # 按 GMV 占比分摊各池
# - F 池(按门店名称/traffic_name 匹配):用本行 GMV 在池内占比摊分; # - F 池(按门店名称/traffic_name 匹配):用本行 GMV 在池内占比摊分;
...@@ -727,6 +772,16 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month): ...@@ -727,6 +772,16 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month):
if total == 0: if total == 0:
continue # 净额为 0 才跳过;净负池同样分配成负摊消(冲减) continue # 净额为 0 才跳过;净负池同样分配成负摊消(冲减)
rows = row_map[key] rows = row_map[key]
# --- 服务商过滤:只保留 service_provider 含"深圳嘀加"的行 ---
dijia_rows = [r for r in rows if _is_dijia_row(r)]
if not dijia_rows:
# 全是非嘀加 → 不分摊(费用=0),跳过
continue
if len(dijia_rows) < len(rows):
logger.info(f"[耗材分摊] key={key}: {len(rows)} 行中有 {len(dijia_rows)} 行"
f" 服务商=深圳嘀加,参与分摊;跳过 {len(rows)-len(dijia_rows)} 行")
rows = dijia_rows
if field == 'mgv_ratio_park': if field == 'mgv_ratio_park':
ratios = [float(r['gmv_ratio_park']) if r.get('gmv_ratio_park') is not None else None ratios = [float(r['gmv_ratio_park']) if r.get('gmv_ratio_park') is not None else None
for r in rows] for r in rows]
...@@ -760,6 +815,16 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month): ...@@ -760,6 +815,16 @@ def compute_consumables_amounts(detail_rows, biz_rows, stat_month):
_alloc(g_pool, {(bt, n): bt_g[bt][n] for (bt, n) in g_pool}, field='mgv_ratio_park') _alloc(g_pool, {(bt, n): bt_g[bt][n] for (bt, n) in g_pool}, field='mgv_ratio_park')
# 全局对账:各池分摊合计对齐到「匹配明细金额总和(分取整)」,消除跨池四舍五入残差 # 全局对账:各池分摊合计对齐到「匹配明细金额总和(分取整)」,消除跨池四舍五入残差
reconcile_total(result, round(sum(f_pool.values()) + sum(g_pool.values()), 2)) reconcile_total(result, round(sum(f_pool.values()) + sum(g_pool.values()), 2))
# 记录未匹配金额到返回 dict 的特殊 key
pools_total = Decimal(str(round(sum(f_pool.values()) + sum(g_pool.values()), 2)))
residual = total_detail_amount - pools_total - unmatched_amount
if abs(float(residual)) >= 0.005:
logger.info(
f"[耗材对账] 明细总额={float(total_detail_amount):.2f} "
f"池合计={float(pools_total):.2f} 未匹配={float(unmatched_amount):.2f} "
f"残差={float(residual):.2f}"
)
result['_unmatched'] = float(unmatched_amount)
return result return result
...@@ -785,6 +850,64 @@ def update_consumables(conn, amounts): ...@@ -785,6 +850,64 @@ def update_consumables(conn, amounts):
raise raise
UNMATCHED_FEE_TABLE = 'biz_unmatched_fee'
# 未匹配费用的 fee_type 取值
UNMATCHED_FEE_RENOVATION = 'renovation_amortization' # 装修摊销
UNMATCHED_FEE_CONSUMABLES = 'store_consumables' # 门店资产耗材
def write_unmatched_fee(conn, task_id, stat_month, renovation_unmatched, consumables_unmatched):
"""把未匹配到预算行的明细金额写入 biz_unmatched_fee 表(先删后插,幂等)。
Args:
conn: pymysql 连接。
task_id: 任务主键。
stat_month: 统计月 'YYYY-MM'。
renovation_unmatched: 装修摊销未匹配金额(float)。
consumables_unmatched: 门店资产耗材未匹配金额(float)。
Returns:
int: 插入行数。
"""
# 先删后插,保证重跑幂等
try:
with conn.cursor() as cur:
cur.execute(
f'DELETE FROM {UNMATCHED_FEE_TABLE} WHERE task_id = %s AND stat_month = %s '
f"AND fee_type IN ('{UNMATCHED_FEE_RENOVATION}', '{UNMATCHED_FEE_CONSUMABLES}')",
(task_id, stat_month),
)
# 只有存在非零未匹配金额时才插入(全 0 不写)
rows = []
if abs(renovation_unmatched) > 0.005:
rows.append((task_id, stat_month, UNMATCHED_FEE_RENOVATION, renovation_unmatched))
if abs(consumables_unmatched) > 0.005:
rows.append((task_id, stat_month, UNMATCHED_FEE_CONSUMABLES, consumables_unmatched))
if rows:
with conn.cursor() as cur:
cur.executemany(
f'INSERT INTO {UNMATCHED_FEE_TABLE} '
f'(task_id, stat_month, fee_type, unmatched_amount) '
f'VALUES (%s, %s, %s, %s)',
rows,
)
conn.commit()
logger.info(
f"[未匹配写库] clean 侧: renovation_amortization={renovation_unmatched:.2f} "
f"store_consumables={consumables_unmatched:.2f} → 插入 {len(rows)} 行"
)
return len(rows)
# 全 0,只删除不插入
conn.commit()
logger.info(
f"[未匹配写库] clean 侧: renovation_amortization={renovation_unmatched:.2f} "
f"store_consumables={consumables_unmatched:.2f} → 全 0 不写入"
)
return 0
except Exception:
conn.rollback()
raise
# ---------------- 文件下载 ---------------- # ---------------- 文件下载 ----------------
...@@ -863,9 +986,13 @@ def process_task(conn, task, dry_run=False): ...@@ -863,9 +986,13 @@ def process_task(conn, task, dry_run=False):
update_clean_status(conn, file_row['id'], CLEAN_DONE) update_clean_status(conn, file_row['id'], CLEAN_DONE)
# 第二步:装修摊销(来自「装修费用表」附件,仅 1.1 业务) # 第二步:装修摊销(来自「装修费用表」附件,仅 1.1 业务)
ren_updated = process_renovation(conn, task_id, stat_month, dry_run=False) ren_updated, ren_unmatched = process_renovation(conn, task_id, stat_month, dry_run=False)
# 第三步:门店资产耗材(来自「门店资产耗材明细表」附件,按业务类型分别匹配) # 第三步:门店资产耗材(来自「门店资产耗材明细表」附件,按业务类型分别匹配)
cons_updated = process_consumables(conn, task_id, stat_month, dry_run=False) cons_updated, cons_unmatched = process_consumables(conn, task_id, stat_month, dry_run=False)
# 第四步:未匹配金额写库(biz_unmatched_fee,先删后插幂等)
unmatched_rows = write_unmatched_fee(conn, task_id, stat_month, ren_unmatched, cons_unmatched)
if unmatched_rows:
log(f' 写入 {UNMATCHED_FEE_TABLE}:新增 {unmatched_rows} 行未匹配费用记录')
return inserted + ren_updated + cons_updated return inserted + ren_updated + cons_updated
except Exception: except Exception:
if not dry_run: if not dry_run:
...@@ -884,19 +1011,25 @@ def _preview_renovation(conn, task_id, stat_month, dry_run=False): ...@@ -884,19 +1011,25 @@ def _preview_renovation(conn, task_id, stat_month, dry_run=False):
details = RenovationDetailParser(local).parse() details = RenovationDetailParser(local).parse()
biz_rows = query_task_biz_rows(conn, task_id, stat_month, RENOVATION_BIZ_TYPE) biz_rows = query_task_biz_rows(conn, task_id, stat_month, RENOVATION_BIZ_TYPE)
amounts = compute_renovation_amounts(details, biz_rows, stat_month) amounts = compute_renovation_amounts(details, biz_rows, stat_month)
unmatched = amounts.pop('_unmatched', 0)
log(f' [装修摊销预览] 明细 {len(details)} 行 / 1.1 结果 {len(biz_rows)} 行' log(f' [装修摊销预览] 明细 {len(details)} 行 / 1.1 结果 {len(biz_rows)} 行'
f' / 匹配命中 {len(amounts)} 行 / 摊销总额 {sum(amounts.values()):.2f}') f' / 匹配命中 {len(amounts)} 行 / 摊销总额 {sum(amounts.values()):.2f}'
f' / 未匹配 {unmatched:.2f}')
for rid, amt in list(amounts.items())[:5]: for rid, amt in list(amounts.items())[:5]:
br = next((b for b in biz_rows if b['id'] == rid), None) br = next((b for b in biz_rows if b['id'] == rid), None)
log(f' 行#{rid} {br["park_store"]}({br["traffic_name"]}) → {amt:.2f}') log(f' 行#{rid} {br["park_store"]}({br["traffic_name"]}) → {amt:.2f}')
def process_renovation(conn, task_id, stat_month, dry_run=False): def process_renovation(conn, task_id, stat_month, dry_run=False):
"""处理装修摊销:下载装修费用表 → 匹配 1.1 结果行 → GMV 占比分摊 → 写回。""" """处理装修摊销:下载装修费用表 → 匹配 1.1 结果行 → GMV 占比分摊 → 写回。
Returns:
tuple: (更新行数, 未匹配金额float)。无附件/无结果行时返回 (0, 0.0)。
"""
ren_files = query_renovation_file(conn, task_id) ren_files = query_renovation_file(conn, task_id)
if not ren_files: if not ren_files:
log(f' 跳过装修摊销:未找到未删除的「{FORM_TYPE_RENOVATION}」附件') log(f' 跳过装修摊销:未找到未删除的「{FORM_TYPE_RENOVATION}」附件')
return 0 return (0, 0.0)
if len(ren_files) > 1: if len(ren_files) > 1:
log(f' 注意:存在 {len(ren_files)} 个未删除的「{FORM_TYPE_RENOVATION}」附件,取最新一个(id={ren_files[0]["id"]})') log(f' 注意:存在 {len(ren_files)} 个未删除的「{FORM_TYPE_RENOVATION}」附件,取最新一个(id={ren_files[0]["id"]})')
ren_file = ren_files[0] ren_file = ren_files[0]
...@@ -909,16 +1042,18 @@ def process_renovation(conn, task_id, stat_month, dry_run=False): ...@@ -909,16 +1042,18 @@ def process_renovation(conn, task_id, stat_month, dry_run=False):
biz_rows = query_task_biz_rows(conn, task_id, stat_month, RENOVATION_BIZ_TYPE) biz_rows = query_task_biz_rows(conn, task_id, stat_month, RENOVATION_BIZ_TYPE)
if not biz_rows: if not biz_rows:
log(' 无 1.1 业务结果行,装修摊销跳过') log(' 无 1.1 业务结果行,装修摊销跳过')
return 0 return (0, 0.0)
amounts = compute_renovation_amounts(details, biz_rows, stat_month) amounts = compute_renovation_amounts(details, biz_rows, stat_month)
unmatched = amounts.pop('_unmatched', 0)
log(f' 装修摊销:明细 {len(details)} 行 / 1.1 结果 {len(biz_rows)} 行' log(f' 装修摊销:明细 {len(details)} 行 / 1.1 结果 {len(biz_rows)} 行'
f' / 匹配命中 {len(amounts)} 行 / 摊销总额 {sum(amounts.values()):.2f}') f' / 匹配命中 {len(amounts)} 行 / 摊销总额 {sum(amounts.values()):.2f}'
f' / 未匹配 {unmatched:.2f}')
if dry_run: if dry_run:
return len(amounts) return (len(amounts), unmatched)
updated = update_renovation(conn, amounts) updated = update_renovation(conn, amounts)
log(f' 写入 renovation_amortization:更新 {updated} 行(未匹配行保持 NULL)') log(f' 写入 renovation_amortization:更新 {updated} 行(未匹配行保持 NULL)')
return updated return (updated, unmatched)
def _preview_consumables(conn, task_id, stat_month): def _preview_consumables(conn, task_id, stat_month):
...@@ -932,22 +1067,28 @@ def _preview_consumables(conn, task_id, stat_month): ...@@ -932,22 +1067,28 @@ def _preview_consumables(conn, task_id, stat_month):
details = ConsumablesDetailParser(local).parse() details = ConsumablesDetailParser(local).parse()
biz_rows = query_all_biz_rows(conn, task_id, stat_month) biz_rows = query_all_biz_rows(conn, task_id, stat_month)
amounts = compute_consumables_amounts(details, biz_rows, stat_month) amounts = compute_consumables_amounts(details, biz_rows, stat_month)
unmatched = amounts.pop('_unmatched', 0)
cur_m = int(stat_month.split('-')[1]) cur_m = int(stat_month.split('-')[1])
m_label = f'{cur_m}月' m_label = f'{cur_m}月'
m_cnt = sum(1 for d in details if d.get('month') == m_label) m_cnt = sum(1 for d in details if d.get('month') == m_label)
log(f' [门店资产耗材预览] 明细总 {len(details)} 行(本月 {m_label} {m_cnt} 行)' log(f' [门店资产耗材预览] 明细总 {len(details)} 行(本月 {m_label} {m_cnt} 行)'
f' / 结果 {len(biz_rows)} 行 / 匹配命中 {len(amounts)} 行 / 金额总额 {sum(amounts.values()):.2f}') f' / 结果 {len(biz_rows)} 行 / 匹配命中 {len(amounts)} 行'
f' / 金额总额 {sum(amounts.values()):.2f} / 未匹配 {unmatched:.2f}')
for rid, amt in list(amounts.items())[:5]: for rid, amt in list(amounts.items())[:5]:
br = next((b for b in biz_rows if b['id'] == rid), None) br = next((b for b in biz_rows if b['id'] == rid), None)
log(f' 行#{rid} {br["park_store"]}({br["traffic_name"]}) → {amt:.2f}') log(f' 行#{rid} {br["park_store"]}({br["traffic_name"]}) → {amt:.2f}')
def process_consumables(conn, task_id, stat_month, dry_run=False): def process_consumables(conn, task_id, stat_month, dry_run=False):
"""处理门店资产耗材:下载明细表 → 按业务类型匹配预算行 → GMV 占比分摊 → 写回。""" """处理门店资产耗材:下载明细表 → 按业务类型匹配预算行 → GMV 占比分摊 → 写回。
Returns:
tuple: (更新行数, 未匹配金额float)。无附件/无结果行时返回 (0, 0.0)。
"""
cons_files = query_consumables_file(conn, task_id) cons_files = query_consumables_file(conn, task_id)
if not cons_files: if not cons_files:
log(f' 跳过门店资产耗材:未找到未删除的「{FORM_TYPE_CONSUMABLES}」附件') log(f' 跳过门店资产耗材:未找到未删除的「{FORM_TYPE_CONSUMABLES}」附件')
return 0 return (0, 0.0)
if len(cons_files) > 1: if len(cons_files) > 1:
log(f' 注意:存在 {len(cons_files)} 个未删除的「{FORM_TYPE_CONSUMABLES}」附件,取最新一个(id={cons_files[0]["id"]})') log(f' 注意:存在 {len(cons_files)} 个未删除的「{FORM_TYPE_CONSUMABLES}」附件,取最新一个(id={cons_files[0]["id"]})')
cons_file = cons_files[0] cons_file = cons_files[0]
...@@ -960,19 +1101,21 @@ def process_consumables(conn, task_id, stat_month, dry_run=False): ...@@ -960,19 +1101,21 @@ def process_consumables(conn, task_id, stat_month, dry_run=False):
biz_rows = query_all_biz_rows(conn, task_id, stat_month) biz_rows = query_all_biz_rows(conn, task_id, stat_month)
if not biz_rows: if not biz_rows:
log(' 无预算达成结果行,门店资产耗材跳过') log(' 无预算达成结果行,门店资产耗材跳过')
return 0 return (0, 0.0)
amounts = compute_consumables_amounts(details, biz_rows, stat_month) amounts = compute_consumables_amounts(details, biz_rows, stat_month)
unmatched = amounts.pop('_unmatched', 0)
cur_m = int(stat_month.split('-')[1]) cur_m = int(stat_month.split('-')[1])
m_label = f'{cur_m}月' m_label = f'{cur_m}月'
m_cnt = sum(1 for d in details if d.get('month') == m_label) m_cnt = sum(1 for d in details if d.get('month') == m_label)
log(f' 门店资产耗材:明细总 {len(details)} 行(本月 {m_label} {m_cnt} 行)' log(f' 门店资产耗材:明细总 {len(details)} 行(本月 {m_label} {m_cnt} 行)'
f' / 结果 {len(biz_rows)} 行 / 匹配命中 {len(amounts)} 行 / 金额总额 {sum(amounts.values()):.2f}') f' / 结果 {len(biz_rows)} 行 / 匹配命中 {len(amounts)} 行'
f' / 金额总额 {sum(amounts.values()):.2f} / 未匹配 {unmatched:.2f}')
if dry_run: if dry_run:
return len(amounts) return (len(amounts), unmatched)
updated = update_consumables(conn, amounts) updated = update_consumables(conn, amounts)
log(f' 写入 store_consumables:更新 {updated} 行(未匹配行保持 NULL)') log(f' 写入 store_consumables:更新 {updated} 行(未匹配行保持 NULL)')
return updated return (updated, unmatched)
def main(): def main():
......
...@@ -227,6 +227,35 @@ class BizBudgetAchieve(db.Model): ...@@ -227,6 +227,35 @@ class BizBudgetAchieve(db.Model):
} }
class BizUnmatchedFee(db.Model):
"""未匹配费用汇总表 — 7 类费用匹配失败的金额按 (task_id, stat_month, fee_type) 存储"""
__tablename__ = 'biz_unmatched_fee'
__table_args__ = (
db.UniqueConstraint('task_id', 'stat_month', 'fee_type',
name='uk_task_month_feetype'),
{'comment': '未匹配费用汇总表'},
)
id = db.Column(db.Integer, primary_key=True, autoincrement=True, comment='主键ID')
task_id = db.Column(db.Integer, nullable=False, comment='所属任务单据ID')
stat_month = db.Column(db.String(7), nullable=False, comment='统计月份YYYY-MM')
fee_type = db.Column(db.String(50), nullable=False, comment='费用类型: market_fee/external_construction/technician_salary/marketing_team_salary/rent_utilities/renovation_amortization/store_consumables')
unmatched_amount = db.Column(db.DECIMAL(15, 2), nullable=False, default=0, comment='未匹配金额(正数=未分摊的费用;负数=未冲减的金额)')
created_at = db.Column(db.DateTime, default=datetime.now, comment='创建时间')
updated_at = db.Column(db.DateTime, default=datetime.now, onupdate=datetime.now, comment='更新时间')
# fee_type 枚举常量
FEE_TYPES = [
'market_fee',
'external_construction',
'technician_salary',
'marketing_team_salary',
'rent_utilities',
'renovation_amortization',
'store_consumables',
]
class DataProcessSubtask(db.Model): class DataProcessSubtask(db.Model):
""" """
红黄门店盈利测算 - 子任务表。 红黄门店盈利测算 - 子任务表。
......
...@@ -33,7 +33,7 @@ import openpyxl ...@@ -33,7 +33,7 @@ import openpyxl
from openpyxl.styles import Font, Alignment, Border, Side, PatternFill from openpyxl.styles import Font, Alignment, Border, Side, PatternFill
from sqlalchemy import text from sqlalchemy import text
from models import DataProcessTask, DataProcessFile, BizBudgetAchieve, db from models import DataProcessTask, DataProcessFile, BizBudgetAchieve, BizUnmatchedFee, db
from oss_utils import download_file, upload_file from oss_utils import download_file, upload_file
from config import Config from config import Config
from parsers.consumables_parser import normalize_bt from parsers.consumables_parser import normalize_bt
...@@ -361,19 +361,31 @@ def parse_allocation_targets(target_str, flow_names_set, park_to_flows): ...@@ -361,19 +361,31 @@ def parse_allocation_targets(target_str, flow_names_set, park_to_flows):
return targets return targets
def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names=None): def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names=None, only_dijia=True):
"""查询指定流量方 / 园区店的 GMV 汇总。
Args:
db: SQLAlchemy db 对象(需有 session 属性)
task_id: 数据处理任务 ID
business_type: 业务类型(如 "1.1" / "2.1" / "2.3")
flow_names: 流量方标准名列表(可选)
park_names: 园区店标准名列表(可选)
only_dijia: True=只累计服务商含"深圳嘀加"的行(默认 True,GMV 分摊口径)
Returns:
dict: {name(str): gmv(float)},键为流量方或园区店名称
"""
from sqlalchemy import text, bindparam from sqlalchemy import text, bindparam
result = {} result = {}
sp_clause = "AND service_provider LIKE '%深圳嘀加%'" if only_dijia else ""
if flow_names: if flow_names:
# 使用 bindparam expanding=True 支持 IN 子句的列表参数(SQLAlchemy 2.0 兼容) sql = text(f"""
sql = text("""
SELECT traffic_name, SUM(gmv) as total_gmv SELECT traffic_name, SUM(gmv) as total_gmv
FROM biz_budget_achieve FROM biz_budget_achieve
WHERE traffic_name IN :names WHERE traffic_name IN :names
AND task_id = :task_id AND task_id = :task_id
AND business_type = :biz_type AND business_type = :biz_type
{sp_clause}
GROUP BY traffic_name GROUP BY traffic_name
""").bindparams(bindparam("names", expanding=True)) """).bindparams(bindparam("names", expanding=True))
...@@ -387,13 +399,13 @@ def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names ...@@ -387,13 +399,13 @@ def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names
logger.error(f"[GMV查询] 流量方GMV查询失败: {e}") logger.error(f"[GMV查询] 流量方GMV查询失败: {e}")
if park_names: if park_names:
# 使用 bindparam expanding=True 支持 IN 子句的列表参数(SQLAlchemy 2.0 兼容) sql = text(f"""
sql = text("""
SELECT park_store, SUM(gmv) as total_gmv SELECT park_store, SUM(gmv) as total_gmv
FROM biz_budget_achieve FROM biz_budget_achieve
WHERE park_store IN :names WHERE park_store IN :names
AND task_id = :task_id AND task_id = :task_id
AND business_type = :biz_type AND business_type = :biz_type
{sp_clause}
GROUP BY park_store GROUP BY park_store
""").bindparams(bindparam("names", expanding=True)) """).bindparams(bindparam("names", expanding=True))
...@@ -413,16 +425,23 @@ def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names ...@@ -413,16 +425,23 @@ def query_gmv_by_targets(db, task_id, business_type, flow_names=None, park_names
if name not in result: if name not in result:
result[name] = 0 result[name] = 0
logger.info(f"[GMV查询] only_dijia={only_dijia}, biz={business_type}, "
f"flows={len(flow_names or [])}, parks={len(park_names or [])}, result={len(result)} keys")
return result return result
def allocate_by_gmv_ratio(total_fee, targets, gmv_data): def allocate_by_gmv_ratio(total_fee, targets, gmv_data, only_dijia=True):
""" """按 GMV 占比分摊费用。
按 GMV 占比分摊费用
Args:
用户需求示例: total_fee: 总金额(Decimal)
假设A+B分账总和20000,Agmv占比40%,B占比60% targets: 分摊对象列表 [{'name': str, 'type': 'flow'|'park', ...}, ...]
A ---8000 B ----12000 gmv_data: {name(str): gmv(float)},来自 query_gmv_by_targets 的结果
only_dijia: True=gmv_data 已过滤非深圳嘀加;若 total_gmv=0 则直接返回 [](费用=0)
False=gmv_data 可能含非嘀加;total_gmv=0 时回退平均分配(原行为)
Returns:
list[dict]: [{'name': str, 'type': 'flow'|'park', 'share': Decimal, 'ratio': float}, ...]
""" """
if not targets or total_fee == 0: if not targets or total_fee == 0:
return [] return []
...@@ -443,7 +462,8 @@ def allocate_by_gmv_ratio(total_fee, targets, gmv_data): ...@@ -443,7 +462,8 @@ def allocate_by_gmv_ratio(total_fee, targets, gmv_data):
total_gmv += gmv total_gmv += gmv
gmv_details.append(f"{t['name']}={gmv}") gmv_details.append(f"{t['name']}={gmv}")
logger.info(f"[GMV分摊计算] total_fee={total_fee}, targets={len(targets)}, total_gmv={total_gmv}, gmv_details=[{', '.join(gmv_details)}]") logger.info(f"[GMV分摊计算] total_fee={total_fee}, targets={len(targets)}, total_gmv={total_gmv}, "
f"only_dijia={only_dijia}, gmv_details=[{', '.join(gmv_details)}]")
results = [] results = []
...@@ -467,6 +487,11 @@ def allocate_by_gmv_ratio(total_fee, targets, gmv_data): ...@@ -467,6 +487,11 @@ def allocate_by_gmv_ratio(total_fee, targets, gmv_data):
}) })
logger.info(f"[GMV分摊计算] target[{i}]: name={t['name']}, gmv={gmv}, ratio={ratio:.4f}, share={share}") logger.info(f"[GMV分摊计算] target[{i}]: name={t['name']}, gmv={gmv}, ratio={ratio:.4f}, share={share}")
else: else:
if only_dijia:
# 服务商过滤后 total_gmv=0 → 不分摊,直接返回 [](费用默认=0)
logger.info(f"[GMV分摊计算] only_dijia=True 且 total_gmv=0,跳过分摊(费用=0)")
return []
# total_gmv=0 且非 only_dijia → 保持原平均分配 fallback
flow_count = len(targets) flow_count = len(targets)
logger.warning(f"[GMV分摊计算] total_gmv=0, 平均分配给{flow_count}个对象") logger.warning(f"[GMV分摊计算] total_gmv=0, 平均分配给{flow_count}个对象")
for i, t in enumerate(targets): for i, t in enumerate(targets):
...@@ -1534,20 +1559,23 @@ class DataProcessor: ...@@ -1534,20 +1559,23 @@ class DataProcessor:
# 解析市场费(传入 settlement_map 用于 GMV 分摊) # 解析市场费(传入 settlement_map 用于 GMV 分摊)
market_results = [] market_results = []
unmatched_market = {}
if '市场费总表' in downloaded_files: if '市场费总表' in downloaded_files:
market_results = self._parse_market_fee(downloaded_files['市场费总表'], settlement_map) market_results, unmatched_market = self._parse_market_fee(downloaded_files['市场费总表'], settlement_map)
logger.info(f"[处理任务] 市场费解析完成,共 {len(market_results)} 条记录") logger.info(f"[处理任务] 市场费解析完成,共 {len(market_results)} 条记录")
# 解析外援施工费(传入 flow_ratio_entries 用于 gmv_ratio 分摊) # 解析外援施工费(传入 flow_ratio_entries 用于 gmv_ratio 分摊)
wage_results = [] wage_results = {}
unmatched_external = {}
if '外施施工费用表' in downloaded_files: if '外施施工费用表' in downloaded_files:
wage_results = self._parse_external_worker_fee(downloaded_files['外施施工费用表'], settlement_map=settlement_map, flow_ratio_entries=flow_ratio_entries) wage_results, unmatched_external = self._parse_external_worker_fee(downloaded_files['外施施工费用表'], settlement_map=settlement_map, flow_ratio_entries=flow_ratio_entries)
logger.info(f"[处理任务] 外援施工费解析完成,共 {len(wage_results)} 条记录") logger.info(f"[处理任务] 外援施工费解析完成,共 {len(wage_results)} 条记录")
# 解析人力成本(传递 flow_ratio_entries 用于无品牌比例分配) # 解析人力成本(传递 flow_ratio_entries 用于无品牌比例分配)
labor_results = {} labor_results = {}
unmatched_labor = {}
if '人力成本统计表' in downloaded_files: if '人力成本统计表' in downloaded_files:
labor_results = self._parse_labor_cost(downloaded_files['人力成本统计表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries) labor_results, unmatched_labor = self._parse_labor_cost(downloaded_files['人力成本统计表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries, task_id=task.id, stat_month=task.month, db=db)
logger.info(f"[处理任务] 人力成本解析完成,共 {len(labor_results)} 个key") logger.info(f"[处理任务] 人力成本解析完成,共 {len(labor_results)} 个key")
# 按主键id更新 # 按主键id更新
labor_total_input, labor_total_output, labor_updated = self._update_labor_cost_by_id( labor_total_input, labor_total_output, labor_updated = self._update_labor_cost_by_id(
...@@ -1558,9 +1586,50 @@ class DataProcessor: ...@@ -1558,9 +1586,50 @@ class DataProcessor:
# 解析房租水电施工费 # 解析房租水电施工费
utility_results = [] utility_results = []
gmv_allocated_utility = [] gmv_allocated_utility = []
unmatched_utility = {}
if '房租水电费用表' in downloaded_files: if '房租水电费用表' in downloaded_files:
utility_results, gmv_allocated_utility = self._parse_utility_fee(downloaded_files['房租水电费用表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries, task_id=task.id) utility_results, gmv_allocated_utility, unmatched_utility = self._parse_utility_fee(downloaded_files['房租水电费用表'], settlement_map=settlement_map, park_ratio_map=park_ratio_map, park_rows_data=park_rows_data, flow_ratio_entries=flow_ratio_entries, task_id=task.id)
logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录,GMV分摊 {len(gmv_allocated_utility)} 条") logger.info(f"[处理任务] 房租水电施工费解析完成,共 {len(utility_results)} 条记录,GMV分摊 {len(gmv_allocated_utility)} 条")
# 收集所有未匹配金额 + 写入 biz_unmatched_fee(幂等:先删后插)
unmatched_collector = {**unmatched_market, **unmatched_external, **unmatched_labor, **unmatched_utility}
logger.info(f"[未匹配收集] processor 侧: {unmatched_collector}")
# --- 写库 biz_unmatched_fee ---
# 注意:clean_budget_achievement(装修摊销+门店耗材)已在前置步骤写了自己的 fee_type,
# 这里只 DELETE + INSERT 本侧 5 个 fee_type,避免互相覆盖
PROCESSOR_FEE_TYPES = ['market_fee', 'external_construction',
'technician_salary', 'marketing_team_salary', 'rent_utilities']
try:
# 先删本侧 5 个 fee_type 的旧记录(保留 clean 侧的 renovation/consumables)
BizUnmatchedFee.query.filter(
BizUnmatchedFee.task_id == task.id,
BizUnmatchedFee.stat_month == task.month,
BizUnmatchedFee.fee_type.in_(PROCESSOR_FEE_TYPES),
).delete(synchronize_session='fetch')
db.session.flush()
# 只写有未匹配金额的 fee_type(unmatched_amount != 0)
inserted = 0
for fee_type, amount in unmatched_collector.items():
if fee_type not in PROCESSOR_FEE_TYPES:
continue # 保护:跳过 clean 侧的 fee_type
amt = Decimal(str(amount)) if amount is not None else Decimal('0')
if amt == 0:
continue
db.session.add(BizUnmatchedFee(
task_id=task.id, stat_month=task.month,
fee_type=fee_type, unmatched_amount=amt,
))
inserted += 1
if inserted > 0:
db.session.commit()
logger.info(f"[未匹配写库] processor 侧: task={task.id} month={task.month} 写入 {inserted} 条(market/wage/labor/utility)")
else:
db.session.commit() # 即使没 INSERT 也要提交 DELETE
logger.info(f"[未匹配写库] processor 侧: 全部 matched, 仅清理旧记录 (task={task.id})")
except Exception as e_unm:
logger.error(f"[未匹配写库] 失败: {e_unm}", e_unm)
db.session.rollback()
logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s") logger.info(f"[处理任务] 步骤 c 完成, 耗时: {time.time() - step_c_start:.2f}s")
# ========== 步骤 d: 执行成本计算 ========== # ========== 步骤 d: 执行成本计算 ==========
...@@ -1763,127 +1832,191 @@ class DataProcessor: ...@@ -1763,127 +1832,191 @@ class DataProcessor:
def _allocate_market_fee_by_gmv(self, records, settlement_map): def _allocate_market_fee_by_gmv(self, records, settlement_map):
""" """
根据 GMV 数据对市场费进行品牌分摊。 市场费品牌匹配主入口 —— 按 (流量方, 业务类型) 分组后走三个分支:
规则: 场景A. 单条记录 → 跳过品牌匹配 + 跳过 GMV 分摊,identify_brand 返回什么就是什么
1. 同一流量方+业务类型下,未知品牌的费用按已知品牌的 GMV 占比分摊 场景B. 多条且同时存在 问界+鸿蒙 → 逐行按车型匹配,无车型行跳过(fee=0)
2. 同一流量方+业务类型+品牌有多条记录时,先汇总再按 GMV 比例分摊 默认. 多条但单品牌/全未知 → 走原有 GMV 分摊逻辑(_apply_gmv_allocation)
参数: 参数:
- records: List[dict],原始记录列表,每条包含 {流量方名称, 业务类型, 品牌, 市场费} - records: List[dict],原始记录列表,每条包含 {流量方名称, 业务类型, 品牌, 市场费}
- settlement_map: {(流量方, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal}} - settlement_map: {(流量方, 业务类型, 品牌): {"GMV": Decimal, "产值": Decimal}}
返回:List[dict],分摊后的记录列表 返回:List[dict],最终输出列表,元素 {流量方名称, 业务类型, 品牌, 市场费}
""" """
if not records: if not records:
return [] return []
# 按 (流量方, 业务类型) 分组 # 按 (流量方, 业务类型) 分组
groups = defaultdict(list) groups = defaultdict(list)
for r in records: for r in records:
key = (r["流量方名称"], r["业务类型"]) key = (r["流量方名称"], r["业务类型"])
groups[key].append(r) groups[key].append(r)
result = [] result = []
for (flow, biz), group_records in groups.items(): for (flow, biz), group_records in groups.items():
# 按品牌汇总费用 # ---------- 场景A: 单条记录 ----------
brand_fees = defaultdict(Decimal) # {品牌: 费用合计} if len(group_records) == 1:
brand_records = defaultdict(list) # {品牌: [原始记录列表]} r = group_records[0]
unknown_brand_fee = Decimal("0") # 未知品牌的费用总和 brand = r.get("品牌") or "未知品牌"
for r in group_records:
brand = r.get("品牌", "未知品牌")
fee = r.get("市场费", Decimal("0")) fee = r.get("市场费", Decimal("0"))
if brand == "未知品牌": logger.info(f"[市场费分摊] 单条记录,跳过品牌匹配与 GMV 分摊: "
unknown_brand_fee += fee f"flow={flow}, biz={biz}, brand={brand}, fee={fee}")
else:
brand_fees[brand] += fee
brand_records[brand].append(r)
# 诊断日志:分摊前的品牌费用(仅针对特定流量方)
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 分摊前 flow={flow}, biz={biz}:")
for brand, fee in brand_fees.items():
logger.info(f"[市场费诊断] 品牌={brand}, 原始费用={fee}")
logger.info(f"[市场费诊断] 未知品牌费用={unknown_brand_fee}, 未知品牌行数={len([r for r in group_records if r.get('品牌') == '未知品牌'])}")
# 如果有未知品牌费用且存在已知品牌,进行 GMV 分摊
if unknown_brand_fee > 0 and brand_fees:
# 获取各品牌的 GMV
brand_gmv = {}
for brand in brand_fees.keys():
key = (flow, biz, brand)
if key in settlement_map:
brand_gmv[brand] = settlement_map[key]["GMV"]
else:
brand_gmv[brand] = Decimal("0")
total_gmv = sum(brand_gmv.values())
# 诊断日志:GMV 数据
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] GMV数据 flow={flow}, biz={biz}:")
for brand, gmv in brand_gmv.items():
logger.info(f"[市场费诊断] 品牌={brand}, GMV={gmv}")
logger.info(f"[市场费诊断] 总GMV={total_gmv}")
if total_gmv > 0:
# 按 GMV 占比分摊未知品牌费用
for brand in brand_fees.keys():
ratio = brand_gmv[brand] / total_gmv
allocated_fee = (unknown_brand_fee * ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
brand_fees[brand] += allocated_fee
# 诊断日志:分摊金额
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 品牌={brand}, GMV占比={ratio:.4f}, 分摊金额={allocated_fee}")
# 尾差归并
first_brand = list(brand_fees.keys())[0]
allocated_sum = sum(
(unknown_brand_fee * (brand_gmv[b] / total_gmv)).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
for b in brand_fees.keys()
)
diff = unknown_brand_fee - allocated_sum
if diff != 0:
brand_fees[first_brand] += diff
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 尾差={diff}, 加到第一个品牌={first_brand}")
else:
# GMV 都为 0,平均分摊
n = len(brand_fees)
avg_fee = (unknown_brand_fee / n).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
for brand in brand_fees.keys():
brand_fees[brand] += avg_fee
# 尾差归并
allocated_sum = avg_fee * n
diff = unknown_brand_fee - allocated_sum
if diff != 0:
first_brand = list(brand_fees.keys())[0]
brand_fees[first_brand] += diff
# 诊断日志:分摊后的品牌费用
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 分摊后 flow={flow}, biz={biz}:")
for brand, fee in brand_fees.items():
logger.info(f"[市场费诊断] 品牌={brand}, 分摊后费用={fee}")
# 输出结果
for brand, fee in brand_fees.items():
result.append({ result.append({
"流量方名称": flow, "流量方名称": flow,
"业务类型": biz, "业务类型": biz,
"品牌": brand, "品牌": brand,
"市场费": round_2(fee), "市场费": round_2(fee),
}) })
continue
# 处理:如果所有记录都是未知品牌(无已知品牌可分摊),直接保留
if not brand_fees and unknown_brand_fee > 0: # ---------- 多条:检查品牌集合 ----------
result.append({ known_brands = {
"流量方名称": flow, r.get("品牌") for r in group_records
"业务类型": biz, if r.get("品牌") and r.get("品牌") != "未知品牌"
"品牌": "未知品牌", }
"市场费": round_2(unknown_brand_fee),
}) has_wj = "问界" in known_brands
has_hm = "鸿蒙" in known_brands
logger.info(f"[市场费分摊] GMV 分摊完成,共 {len(result)} 条记录")
# ---------- 场景B: 同时有 问界 + 鸿蒙 ----------
if has_wj and has_hm:
logger.info(f"[市场费分摊] 双品牌场景(问界+鸿蒙),逐行按车型匹配,无车型行跳过: "
f"flow={flow}, biz={biz}, 总行数={len(group_records)}")
output_by_brand = defaultdict(Decimal)
skipped_fee = Decimal("0")
for r in group_records:
# 注: 上游 _parse_market_fee 已把 None 统一转成 "未知品牌",
# 这里只需判断 "未知品牌" 即可;brand 不可能为 None。
brand = r.get("品牌")
fee = r.get("市场费", Decimal("0"))
if brand == "未知品牌":
skipped_fee += fee
continue
output_by_brand[brand] += fee
if skipped_fee > 0:
logger.info(f"[市场费分摊] 双品牌场景跳过无车型行,金额={skipped_fee}")
for brand, fee in output_by_brand.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": brand,
"市场费": round_2(fee),
})
continue
# ---------- 默认: 单品牌 / 全未知 → 走原有 GMV 分摊 ----------
result.extend(self._apply_gmv_allocation(group_records, flow, biz, settlement_map))
logger.info(f"[市场费分摊] 完成,共 {len(result)} 条记录")
return result
def _apply_gmv_allocation(self, group_records, flow, biz, settlement_map):
"""
原有 GMV 分摊逻辑 —— 供 _allocate_market_fee_by_gmv 在默认分支调用。
规则与改造前完全一致:未知品牌费用按已知品牌 GMV 占比分摊。
"""
# 按品牌汇总费用
brand_fees = defaultdict(Decimal) # {品牌: 费用合计}
unknown_brand_fee = Decimal("0") # 未知品牌的费用总和
for r in group_records:
brand = r.get("品牌", "未知品牌")
fee = r.get("市场费", Decimal("0"))
if brand == "未知品牌":
unknown_brand_fee += fee
else:
brand_fees[brand] += fee
# 诊断日志:分摊前的品牌费用(仅针对特定流量方)
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 分摊前 flow={flow}, biz={biz}:")
for brand, fee in brand_fees.items():
logger.info(f"[市场费诊断] 品牌={brand}, 原始费用={fee}")
logger.info(f"[市场费诊断] 未知品牌费用={unknown_brand_fee}, "
f"未知品牌行数={len([r for r in group_records if r.get('品牌') == '未知品牌'])}")
# 如果有未知品牌费用且存在已知品牌,进行 GMV 分摊
if unknown_brand_fee > 0 and brand_fees:
# 获取各品牌的 GMV
brand_gmv = {}
for brand in brand_fees.keys():
key = (flow, biz, brand)
if key in settlement_map:
brand_gmv[brand] = settlement_map[key]["GMV"]
else:
brand_gmv[brand] = Decimal("0")
total_gmv = sum(brand_gmv.values())
# 诊断日志:GMV 数据
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] GMV数据 flow={flow}, biz={biz}:")
for brand, gmv in brand_gmv.items():
logger.info(f"[市场费诊断] 品牌={brand}, GMV={gmv}")
logger.info(f"[市场费诊断] 总GMV={total_gmv}")
if total_gmv > 0:
# 按 GMV 占比分摊未知品牌费用
for brand in brand_fees.keys():
ratio = brand_gmv[brand] / total_gmv
allocated_fee = (unknown_brand_fee * ratio).quantize(
Decimal("0.01"), rounding=ROUND_HALF_UP)
brand_fees[brand] += allocated_fee
# 诊断日志:分摊金额
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 品牌={brand}, "
f"GMV占比={ratio:.4f}, 分摊金额={allocated_fee}")
# 尾差归并
first_brand = list(brand_fees.keys())[0]
allocated_sum = sum(
(unknown_brand_fee * (brand_gmv[b] / total_gmv)).quantize(
Decimal("0.01"), rounding=ROUND_HALF_UP)
for b in brand_fees.keys()
)
diff = unknown_brand_fee - allocated_sum
if diff != 0:
brand_fees[first_brand] += diff
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 尾差={diff}, 加到第一个品牌={first_brand}")
else:
# GMV 都为 0,平均分摊
n = len(brand_fees)
avg_fee = (unknown_brand_fee / n).quantize(
Decimal("0.01"), rounding=ROUND_HALF_UP)
for brand in brand_fees.keys():
brand_fees[brand] += avg_fee
# 尾差归并
allocated_sum = avg_fee * n
diff = unknown_brand_fee - allocated_sum
if diff != 0:
first_brand = list(brand_fees.keys())[0]
brand_fees[first_brand] += diff
# 诊断日志:分摊后的品牌费用
if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 分摊后 flow={flow}, biz={biz}:")
for brand, fee in brand_fees.items():
logger.info(f"[市场费诊断] 品牌={brand}, 分摊后费用={fee}")
# 输出结果
result = []
for brand, fee in brand_fees.items():
result.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": brand,
"市场费": round_2(fee),
})
# 处理:如果所有记录都是未知品牌(无已知品牌可分摊),直接保留
if not brand_fees and unknown_brand_fee > 0:
result.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": "未知品牌",
"市场费": round_2(unknown_brand_fee),
})
return result return result
# ======================================================== # ========================================================
...@@ -1909,11 +2042,14 @@ class DataProcessor: ...@@ -1909,11 +2042,14 @@ class DataProcessor:
if not os.path.exists(file_path): if not os.path.exists(file_path):
logger.warning(f"[市场费] 文件不存在: {file_path}") logger.warning(f"[市场费] 文件不存在: {file_path}")
return [] return [], {'market_fee': Decimal('0')}
if settlement_map is None: if settlement_map is None:
settlement_map = {} settlement_map = {}
unmatched = {'market_fee': Decimal('0')}
total_input_fee = Decimal('0')
# 预构建:从 settlement_map 收集所有有 2.1 业务记录的流量方 # 预构建:从 settlement_map 收集所有有 2.1 业务记录的流量方
has_2_1_biz = set() has_2_1_biz = set()
for (flow_n, bt, brand) in settlement_map.keys(): for (flow_n, bt, brand) in settlement_map.keys():
...@@ -2093,7 +2229,25 @@ class DataProcessor: ...@@ -2093,7 +2229,25 @@ class DataProcessor:
logger.warning(f"[市场费诊断] Sheet '{sheet_name}' 车型诊断失败: {e}") logger.warning(f"[市场费诊断] Sheet '{sheet_name}' 车型诊断失败: {e}")
if not col_fee: if not col_fee:
logger.warning(f"[市场费] Sheet '{sheet_name}' 未找到取费列 (fee_col_type={fee_col_type})") # 尝试从 df 中兜底估算该 sheet 金额(取第一个非空数值列的合计,跳过比例类列)
try:
fallback_total = Decimal('0')
for col in df.columns:
col_str = str(col)
if any(kw in col_str for kw in ['比例', '比率', '占比', 'GMV', '产值', '数量', '台数']):
continue
vals = pd.to_numeric(df[col], errors='coerce')
col_sum = safe_decimal(vals.sum())
if col_sum != 0:
fallback_total = col_sum
break
if fallback_total != 0:
unmatched['market_fee'] += fallback_total
logger.warning(f"[市场费] Sheet '{sheet_name}' 未找到取费列,兜底估算金额={fallback_total} 累加到未匹配")
else:
logger.warning(f"[市场费] Sheet '{sheet_name}' 未找到取费列,且无法兜底估算金额")
except Exception as _e:
logger.warning(f"[市场费] Sheet '{sheet_name}' 未找到取费列,兜底估算失败: {_e}")
continue continue
# Sheet 级统计 # Sheet 级统计
...@@ -2116,29 +2270,30 @@ class DataProcessor: ...@@ -2116,29 +2270,30 @@ class DataProcessor:
sheet_skipped_count += 1 sheet_skipped_count += 1
continue continue
# 跳过汇总行(防止尾行公式导致双倍计算)
if any(k in flow_name for k in skip_keywords):
logger.info(f"[市场费] 跳过汇总行: Sheet='{sheet_name}', flow_name='{flow_name}'")
sheet_skipped_count += 1
total_skipped += 1
continue
# 从配置获取业务类型 # 从配置获取业务类型
biz_type = sheet_biz_type biz_type = sheet_biz_type
# 取费 # 提前取费(汇总行跳过等场景也需要用 fee 累加 unmatched)
fee = safe_decimal(row[col_fee]) fee = safe_decimal(row[col_fee])
# 2.3业务:市场费 = 市场费 + 资源费
if biz_type == BIZ_TYPE_2_3 and col_fee_resource and col_fee_resource != col_fee: if biz_type == BIZ_TYPE_2_3 and col_fee_resource and col_fee_resource != col_fee:
resource_fee = safe_decimal(row[col_fee_resource]) resource_fee = safe_decimal(row[col_fee_resource])
fee = fee + resource_fee fee = fee + resource_fee
logger.debug(f"[市场费][2.3费用] flow={flow_name}, 市场费={safe_decimal(row[col_fee])}, 资源费={resource_fee}, 合计={fee}")
# 跳过汇总行(防止尾行公式导致双倍计算)
if any(k in flow_name for k in skip_keywords):
logger.info(f"[市场费] 跳过汇总行: Sheet='{sheet_name}', flow_name='{flow_name}', fee={fee}")
sheet_skipped_count += 1
total_skipped += 1
if fee != 0:
unmatched['market_fee'] += fee
continue
if fee == 0: if fee == 0:
sheet_skipped_count += 1 sheet_skipped_count += 1
continue continue
total_input_fee += fee
# 识别品牌 # 识别品牌
brand = None brand = None
vehicle_model = None vehicle_model = None
...@@ -2275,7 +2430,7 @@ class DataProcessor: ...@@ -2275,7 +2430,7 @@ class DataProcessor:
if not all_results: if not all_results:
logger.info("[市场费] 无有效数据") logger.info("[市场费] 无有效数据")
return [] return [], unmatched
# 总量日志 # 总量日志
total_fee = sum(r["市场费"] for r in all_results) total_fee = sum(r["市场费"] for r in all_results)
...@@ -2285,8 +2440,15 @@ class DataProcessor: ...@@ -2285,8 +2440,15 @@ class DataProcessor:
logger.info(f"[市场费] 原始记录 {len(all_results)} 条,开始 GMV 分摊...") logger.info(f"[市场费] 原始记录 {len(all_results)} 条,开始 GMV 分摊...")
result = self._allocate_market_fee_by_gmv(all_results, settlement_map) result = self._allocate_market_fee_by_gmv(all_results, settlement_map)
# 总量校验:matched_sum 来自 result 聚合(已 GMV 分摊后的品牌维度金额)
matched_sum = sum(r["市场费"] for r in result)
# 用总量守恒计算未匹配(精确到 continue 跳过的 + 分摊差值)
unmatched_amount = total_input_fee - matched_sum
unmatched['market_fee'] += unmatched_amount
logger.info(f"[市场费][未匹配汇总] market_fee: 总额={total_input_fee} 已匹配={matched_sum} 未匹配={unmatched['market_fee']}")
logger.info(f"[市场费] 解析完成,共 {len(result)} 条汇总记录") logger.info(f"[市场费] 解析完成,共 {len(result)} 条汇总记录")
return result return result, unmatched
# ======================================================== # ========================================================
# 解析外援施工费表 # 解析外援施工费表
...@@ -2305,7 +2467,10 @@ class DataProcessor: ...@@ -2305,7 +2467,10 @@ class DataProcessor:
if not os.path.exists(file_path): if not os.path.exists(file_path):
logger.warning(f"[外援施工费] 文件不存在: {file_path}") logger.warning(f"[外援施工费] 文件不存在: {file_path}")
return {} return {}, {'external_construction': Decimal('0')}
unmatched = {'external_construction': Decimal('0')}
total_input_fee = Decimal('0')
xls = pd.ExcelFile(file_path) xls = pd.ExcelFile(file_path)
logger.info(f"[外援施工费] 所有 Sheet: {xls.sheet_names}") logger.info(f"[外援施工费] 所有 Sheet: {xls.sheet_names}")
...@@ -2346,7 +2511,7 @@ class DataProcessor: ...@@ -2346,7 +2511,7 @@ class DataProcessor:
if not col_source or not col_total: if not col_source or not col_total:
logger.warning(f"[外援施工费] 列匹配失败,所有列: {list(df.columns)}") logger.warning(f"[外援施工费] 列匹配失败,所有列: {list(df.columns)}")
return {} return {}, unmatched
# 按 (流量方, 业务类型) 聚合总金额 # 按 (流量方, 业务类型) 聚合总金额
result = {} result = {}
...@@ -2356,39 +2521,45 @@ class DataProcessor: ...@@ -2356,39 +2521,45 @@ class DataProcessor:
continue continue
flow_source = str(flow_source).strip() flow_source = str(flow_source).strip()
fee = safe_decimal(row[col_total])
# 跳过汇总行 # 跳过汇总行
if any(k in flow_source for k in ["合计", "汇总", "总计", "月外"]): if any(k in flow_source for k in ["合计", "汇总", "总计", "月外"]):
unmatched['external_construction'] += fee
continue continue
# 使用标准名映射 # 使用标准名映射
std_source = to_standard(flow_source, '4s') std_source = to_standard(flow_source, '4s')
fee = safe_decimal(row[col_total])
if fee == 0: if fee == 0:
continue continue
total_input_fee += fee
key = (std_source, BIZ_TYPE_1_1) key = (std_source, BIZ_TYPE_1_1)
result[key] = result.get(key, Decimal("0")) + fee result[key] = result.get(key, Decimal("0")) + fee
if not result: if not result:
logger.info("[外援施工费] 无有效数据") logger.info("[外援施工费] 无有效数据")
return {} return {}, unmatched
total_amount = sum(result.values()) total_amount = sum(result.values())
matched_sum = total_amount
unmatched_amount = total_input_fee - matched_sum
unmatched['external_construction'] += unmatched_amount
logger.info(f"[外援施工费][未匹配汇总] external_construction: 总额={total_input_fee} 已匹配={matched_sum} 未匹配={unmatched['external_construction']}")
logger.info(f"[外援施工费] 解析完成: {len(result)} 个key, 总金额={total_amount}") logger.info(f"[外援施工费] 解析完成: {len(result)} 个key, 总金额={total_amount}")
# 打印前3条预览 # 打印前3条预览
for i, (k, v) in enumerate(result.items()): for i, (k, v) in enumerate(result.items()):
if i >= 3: if i >= 3:
break break
logger.info(f"[外援施工费] 预览[{i}]: flow={k[0]}, biz={k[1]}, fee={v}") logger.info(f"[外援施工费] 预览[{i}]: flow={k[0]}, biz={k[1]}, fee={v}")
return result return result, unmatched
# ======================================================== # ========================================================
# 解析人力成本表 # 解析人力成本表
# ======================================================== # ========================================================
def _parse_labor_cost(self, file_path, settlement_map=None, park_ratio_map=None, park_rows_data=None, flow_ratio_entries=None): def _parse_labor_cost(self, file_path, settlement_map=None, park_ratio_map=None, park_rows_data=None, flow_ratio_entries=None, task_id=None, stat_month=None, db=None):
""" """
解析人力成本表(简化版)。 解析人力成本表(简化版)。
规则: 规则:
...@@ -2397,17 +2568,23 @@ class DataProcessor: ...@@ -2397,17 +2568,23 @@ class DataProcessor:
- 2.1/2.3业务:全部→营销团队工资 - 2.1/2.3业务:全部→营销团队工资
- 匹配策略:先用"入驻门店"直接匹配流量方名称 - 匹配策略:先用"入驻门店"直接匹配流量方名称
- 回退策略:匹配失败时用"入驻门店"匹配园区店名 - 回退策略:匹配失败时用"入驻门店"匹配园区店名
- 2.1/2.3 归属规则:同一门店若 DB 结果表只存在 2.1 或只存在 2.3,
则 Excel 里该门店的所有工资(不论写 2.1 还是 2.3)统一归属到 DB 实际存在的那个业务
返回:Dict[(流量方名称, 业务类型), {"技师工资": Decimal, "营销团队工资": Decimal}] 返回:Dict[(流量方名称, 业务类型), {"技师工资": Decimal, "营销团队工资": Decimal}]
""" """
logger.info(f"[人力成本] 解析文件: {file_path}") logger.info(f"[人力成本] 解析文件: {file_path}")
if not os.path.exists(file_path): if not os.path.exists(file_path):
logger.warning(f"[人力成本] 文件不存在: {file_path}") logger.warning(f"[人力成本] 文件不存在: {file_path}")
return {} return {}, {'technician_salary': Decimal('0'), 'marketing_team_salary': Decimal('0')}
if settlement_map is None: if settlement_map is None:
settlement_map = {} settlement_map = {}
unmatched = {'technician_salary': Decimal('0'), 'marketing_team_salary': Decimal('0')}
total_input_tech = Decimal('0')
total_input_mkt = Decimal('0')
# 构建流量方名称集合和映射 # 构建流量方名称集合和映射
flow_names_set = set() flow_names_set = set()
std_to_original_flow = {} std_to_original_flow = {}
...@@ -2431,24 +2608,43 @@ class DataProcessor: ...@@ -2431,24 +2608,43 @@ class DataProcessor:
park_to_flows[ps_std].append((flow_name, biz_type)) park_to_flows[ps_std].append((flow_name, biz_type))
# 构建 park_rows 索引(用于 gmv_ratio_park 分摊) # 构建 park_rows 索引(用于 gmv_ratio_park 分摊)
# 只保留 service_provider 含"深圳嘀加"的 entries(分摊分母口径)
# settlement_map 里每个 (flow_name, biz_type, brand) 存了服务商字段(L1068)
def _is_dijia_flow(flow_name, biz_type, brand=None):
"""判断 settlement_map 中该 key 的服务商是否含"深圳嘀加"。"""
if brand is not None:
sp = (settlement_map.get((flow_name, biz_type, brand), {}).get("服务商") or "").strip()
return "深圳嘀加" in sp
# brand=None → 查该 (flow, biz) 任意 brand 有嘀加就算
for (fn, bt, br), data in settlement_map.items():
if fn == flow_name and bt == biz_type and "深圳嘀加" in (data.get("服务商") or ""):
return True
return False
park_rows = defaultdict(list) park_rows = defaultdict(list)
if flow_ratio_entries: if flow_ratio_entries:
for (flow_name, biz_type), entries in flow_ratio_entries.items(): for (flow_name, biz_type), entries in flow_ratio_entries.items():
for brand, ps_raw, gmv_ratio, gmv_ratio_park in entries: for brand, ps_raw, gmv_ratio, gmv_ratio_park in entries:
if ps_raw: if ps_raw and _is_dijia_flow(flow_name, biz_type, brand):
park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio)) park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
ps_std = to_standard(ps_raw, 'yq') ps_std = to_standard(ps_raw, 'yq')
if ps_std != ps_raw: if ps_std != ps_raw:
park_rows[(ps_std, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio)) park_rows[(ps_std, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
if not park_rows and settlement_map: if not park_rows and settlement_map:
for (flow_name, biz_type, brand), data in settlement_map.items(): for (flow_name, biz_type, brand), data in settlement_map.items():
sp = (data.get("服务商") or "").strip()
if "深圳嘀加" not in sp:
continue
ps_raw = data.get("park_store_raw", "") ps_raw = data.get("park_store_raw", "")
gmv_ratio = data.get("gmv_ratio") gmv_ratio = data.get("gmv_ratio")
gmv_ratio_park = data.get("gmv_ratio_park") gmv_ratio_park = data.get("gmv_ratio_park")
if ps_raw: if ps_raw:
park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio)) park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
ps_std = to_standard(ps_raw, 'yq')
if ps_std != ps_raw:
park_rows[(ps_std, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
logger.info(f"[人力成本] park_rows 构建: {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合") logger.info(f"[人力成本] park_rows 构建(仅深圳嘀加服务商): {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合")
if not park_to_flows and settlement_map: if not park_to_flows and settlement_map:
for (flow_name, biz_type, brand), data in settlement_map.items(): for (flow_name, biz_type, brand), data in settlement_map.items():
...@@ -2464,7 +2660,7 @@ class DataProcessor: ...@@ -2464,7 +2660,7 @@ class DataProcessor:
logger.error(f"[人力成本] 读取失败: {e}") logger.error(f"[人力成本] 读取失败: {e}")
if is_decrypted and actual_path != file_path and os.path.exists(actual_path): if is_decrypted and actual_path != file_path and os.path.exists(actual_path):
os.unlink(actual_path) os.unlink(actual_path)
return {} return {}, unmatched
# 聚合桶 # 聚合桶
result = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")}) result = defaultdict(lambda: {"技师工资": Decimal("0"), "营销团队工资": Decimal("0")})
...@@ -2501,6 +2697,59 @@ class DataProcessor: ...@@ -2501,6 +2697,59 @@ class DataProcessor:
logger.info(f"[人力成本] 列匹配: 门店={col_store}, 业务归属={col_biz}, 岗位={col_position}, 薪资={col_salary}, 检核={col_check}") logger.info(f"[人力成本] 列匹配: 门店={col_store}, 业务归属={col_biz}, 岗位={col_position}, 薪资={col_salary}, 检核={col_check}")
# --- 归属规则预加载:查 DB 中每个门店实际存在哪些 business_type(2.1/2.3) ---
# 用于后续将 Excel 里 2.1/2.3 的工资行归属到 DB 实际存在的业务
store_biz_map = {} # {store_name: set(biz_types)}
if task_id and stat_month and db:
try:
all_store_names = set()
if col_store:
for sn in df[col_store].dropna():
sn_s = str(sn).strip()
if sn_s and sn_s != "nan":
all_store_names.add(sn_s)
if all_store_names:
from sqlalchemy import text as sa_text
in_clause = ",".join(f":s{i}" for i in range(len(all_store_names)))
sql_biz = sa_text(f"""
SELECT DISTINCT traffic_name, park_store, business_type
FROM biz_budget_achieve
WHERE task_id = :tid AND stat_month = :sm
AND business_type IN ('2.1', '2.3')
AND (traffic_name IN ({in_clause}) OR park_store IN ({in_clause}))
""")
params = {"tid": task_id, "sm": stat_month}
for i, sn in enumerate(all_store_names):
params[f"s{i}"] = sn
rows_biz = db.session.execute(sql_biz, params).fetchall()
# 用 set 存 (traffic_name, park_store) → biz_type 映射
for tn, ps, bt in rows_biz:
if tn:
store_biz_map.setdefault(tn, set()).add(bt)
if ps:
store_biz_map.setdefault(ps, set()).add(bt)
if store_biz_map:
logger.info(f"[人力成本归属] 预加载 {len(store_biz_map)} 个门店的 DB 业务类型"
f"(2.1/2.3)映射,用于归属纠正")
except Exception as e_map:
logger.warning(f"[人力成本归属] 预加载 DB 业务类型失败: {e_map},归属纠正跳过")
store_biz_map = {}
def _resolve_biz_by_store(sn, cur_biz):
"""归属规则:若 DB 中该门店只有 2.1 或只有 2.3,纠正 cur_biz 为 DB 存在的那个。
其他情况(DB 两个都有、都没有、Excel 不是 2.1/2.3)原样返回。
"""
if cur_biz not in (BIZ_TYPE_2_1, BIZ_TYPE_2_3):
return cur_biz
real = store_biz_map.get(sn)
if not real or len(real) != 1:
return cur_biz
only_bt = next(iter(real))
if only_bt != cur_biz:
logger.info(f"[人力成本归属] 门店='{sn}': Excel归属={cur_biz}, DB只有={only_bt} → 纠正为={only_bt}")
return only_bt
return cur_biz
for _, row in df.iterrows(): for _, row in df.iterrows():
# 检核列筛选 # 检核列筛选
if col_check: if col_check:
...@@ -2534,6 +2783,13 @@ class DataProcessor: ...@@ -2534,6 +2783,13 @@ class DataProcessor:
elif "2.3" in biz_val: elif "2.3" in biz_val:
biz_type = BIZ_TYPE_2_3 biz_type = BIZ_TYPE_2_3
# --- 归属纠正(2.1/2.3 规则) ---
if biz_type:
biz_type = _resolve_biz_by_store(store_name, biz_type)
if std_store_name != store_name:
# 也尝试标准化后的 store 名
biz_type = _resolve_biz_by_store(std_store_name, biz_type)
# 获取岗位 # 获取岗位
position = None position = None
if col_position: if col_position:
...@@ -2561,6 +2817,8 @@ class DataProcessor: ...@@ -2561,6 +2817,8 @@ class DataProcessor:
marketing_salary = salary marketing_salary = salary
total_input_salary += salary total_input_salary += salary
total_input_tech += technician_salary
total_input_mkt += marketing_salary
row_count += 1 row_count += 1
# 优先检查是否为园区店 # 优先检查是否为园区店
...@@ -2602,6 +2860,8 @@ class DataProcessor: ...@@ -2602,6 +2860,8 @@ class DataProcessor:
logger.info(f"[人力成本] 园区店分摊(平均回退): ps='{ps}', flows={flow_count}") logger.info(f"[人力成本] 园区店分摊(平均回退): ps='{ps}', flows={flow_count}")
else: else:
failed_match_count += 1 failed_match_count += 1
unmatched['technician_salary'] += technician_salary
unmatched['marketing_team_salary'] += marketing_salary
continue continue
# 直接匹配:检查是否为流量方 # 直接匹配:检查是否为流量方
...@@ -2645,8 +2905,12 @@ class DataProcessor: ...@@ -2645,8 +2905,12 @@ class DataProcessor:
logger.info(f"[人力成本] 园区店分摊(平均回退): ps='{ps_std}', flows={flow_count}") logger.info(f"[人力成本] 园区店分摊(平均回退): ps='{ps_std}', flows={flow_count}")
else: else:
failed_match_count += 1 failed_match_count += 1
unmatched['technician_salary'] += technician_salary
unmatched['marketing_team_salary'] += marketing_salary
else: else:
failed_match_count += 1 failed_match_count += 1
unmatched['technician_salary'] += technician_salary
unmatched['marketing_team_salary'] += marketing_salary
finally: finally:
if is_decrypted and actual_path != file_path and os.path.exists(actual_path): if is_decrypted and actual_path != file_path and os.path.exists(actual_path):
...@@ -2659,19 +2923,29 @@ class DataProcessor: ...@@ -2659,19 +2923,29 @@ class DataProcessor:
if not result: if not result:
logger.info("[人力成本] 无有效数据") logger.info("[人力成本] 无有效数据")
return {} return {}, unmatched
# 总量校验 # 总量校验
total_output = sum(v["技师工资"] + v["营销团队工资"] for v in result.values()) total_output = sum(v["技师工资"] + v["营销团队工资"] for v in result.values())
total_output_tech = sum(v["技师工资"] for v in result.values())
total_output_mkt = sum(v["营销团队工资"] for v in result.values())
logger.info(f"[人力成本] 总量校验: 输入={total_input_salary}, 输出={total_output}, 差值={total_input_salary - total_output}") logger.info(f"[人力成本] 总量校验: 输入={total_input_salary}, 输出={total_output}, 差值={total_input_salary - total_output}")
# 用总量守恒补全未匹配(精确匹配分摊后的微小差值也计入 unmatched)
tech_unmatched_from_conservation = total_input_tech - total_output_tech
mkt_unmatched_from_conservation = total_input_mkt - total_output_mkt
unmatched['technician_salary'] += tech_unmatched_from_conservation
unmatched['marketing_team_salary'] += mkt_unmatched_from_conservation
logger.info(f"[人力成本][未匹配汇总] technician_salary: 输入={total_input_tech} 已匹配={total_output_tech} 未匹配={unmatched['technician_salary']}")
logger.info(f"[人力成本][未匹配汇总] marketing_team_salary: 输入={total_input_mkt} 已匹配={total_output_mkt} 未匹配={unmatched['marketing_team_salary']}")
# 预览前3条 # 预览前3条
for i, (k, v) in enumerate(result.items()): for i, (k, v) in enumerate(result.items()):
if i >= 3: if i >= 3:
break break
logger.info(f"[人力成本] 预览[{i}]: flow={k[0]}, biz={k[1]}, tech={v['技师工资']}, mkt={v['营销团队工资']}") logger.info(f"[人力成本] 预览[{i}]: flow={k[0]}, biz={k[1]}, tech={v['技师工资']}, mkt={v['营销团队工资']}")
return result return result, unmatched
# ======================================================== # ========================================================
# 解析房租水电施工费表 # 解析房租水电施工费表
...@@ -2693,7 +2967,7 @@ class DataProcessor: ...@@ -2693,7 +2967,7 @@ class DataProcessor:
if not os.path.exists(file_path): if not os.path.exists(file_path):
logger.warning(f"[房租水电] 文件不存在: {file_path}") logger.warning(f"[房租水电] 文件不存在: {file_path}")
return [] return [], [], {'rent_utilities': Decimal('0')}
if settlement_map is None: if settlement_map is None:
settlement_map = {} settlement_map = {}
...@@ -2701,6 +2975,8 @@ class DataProcessor: ...@@ -2701,6 +2975,8 @@ class DataProcessor:
if flow_ratio_entries is None: if flow_ratio_entries is None:
flow_ratio_entries = {} flow_ratio_entries = {}
unmatched = {'rent_utilities': Decimal('0')}
# 构建索引 # 构建索引
flow_names_set = set() flow_names_set = set()
flow_ratios = defaultdict(list) flow_ratios = defaultdict(list)
...@@ -2708,6 +2984,17 @@ class DataProcessor: ...@@ -2708,6 +2984,17 @@ class DataProcessor:
park_to_flows = defaultdict(list) # 从 park_rows_data 直接构建 park_to_flows = defaultdict(list) # 从 park_rows_data 直接构建
# 优先使用独立查询的 park_rows_data(使用原始 park_store 值) # 优先使用独立查询的 park_rows_data(使用原始 park_store 值)
# 只保留 service_provider 含"深圳嘀加"的记录(分摊口径统一)
def _is_dijia_flow(flow_name, biz_type, brand=None):
"""从 settlement_map 查服务商是否含"深圳嘀加"。"""
if brand is not None:
return "深圳嘀加" in (settlement_map.get((flow_name, biz_type, brand), {}).get("服务商") or "")
# brand=None → 任意 brand 有嘀加就算
for (fn, bt, br), data in settlement_map.items():
if fn == flow_name and bt == biz_type and "深圳嘀加" in (data.get("服务商") or ""):
return True
return False
if park_rows_data: if park_rows_data:
for i, record in enumerate(park_rows_data): for i, record in enumerate(park_rows_data):
try: try:
...@@ -2724,15 +3011,22 @@ class DataProcessor: ...@@ -2724,15 +3011,22 @@ class DataProcessor:
else: else:
logger.warning(f"[房租水电][诊断] park_rows_data[{i}] 格式错误: len={len(record)}") logger.warning(f"[房租水电][诊断] park_rows_data[{i}] 格式错误: len={len(record)}")
continue continue
# --- 服务商过滤 ---
if not _is_dijia_flow(flow_name, bt, brand):
continue
if ps_raw and bt: if ps_raw and bt:
park_rows[(ps_raw, bt)].append((flow_name, brand, gmv_ratio_park, gmv_ratio)) park_rows[(ps_raw, bt)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
park_to_flows[ps_raw].append((flow_name, bt)) park_to_flows[ps_raw].append((flow_name, bt))
except Exception as e: except Exception as e:
logger.error(f"[房租水电][诊断] park_rows_data[{i}] 处理失败: {e}") logger.error(f"[房租水电][诊断] park_rows_data[{i}] 处理失败: {e}")
else: else:
# 回退:从 settlement_map 聚合(兼容旧数据) # 回退:从 settlement_map 聚合(兼容旧数据),同样过滤服务商
for (flow_name, biz_type, brand), data in settlement_map.items(): for (flow_name, biz_type, brand), data in settlement_map.items():
sp = (data.get("服务商") or "").strip()
if "深圳嘀加" not in sp:
continue
ps_raw = data.get("park_store_raw", "") ps_raw = data.get("park_store_raw", "")
gmv_ratio_park = data.get("gmv_ratio_park") gmv_ratio_park = data.get("gmv_ratio_park")
gmv_ratio = data.get("gmv_ratio") gmv_ratio = data.get("gmv_ratio")
...@@ -2740,8 +3034,8 @@ class DataProcessor: ...@@ -2740,8 +3034,8 @@ class DataProcessor:
park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio)) park_rows[(ps_raw, biz_type)].append((flow_name, brand, gmv_ratio_park, gmv_ratio))
park_to_flows[ps_raw].append((flow_name, biz_type)) park_to_flows[ps_raw].append((flow_name, biz_type))
logger.info(f"[房租水电] park_rows 构建: {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合") logger.info(f"[房租水电] park_rows 构建(仅深圳嘀加服务商): {sum(len(v) for v in park_rows.values())} 条记录, {len(park_rows)} 个 (ps, bt) 组合")
logger.info(f"[房租水电] park_to_flows 从 park_rows_data 构建: {len(park_to_flows)} 个园区店") logger.info(f"[房租水电] park_to_flows 从 park_rows_data 构建(仅深圳嘀加服务商): {len(park_to_flows)} 个园区店")
# 优先使用 flow_ratio_entries 构建流量方索引(保留所有 park_store 的比例值) # 优先使用 flow_ratio_entries 构建流量方索引(保留所有 park_store 的比例值)
# 这是关键修复:避免同一 (flow, biz_type, brand) 下不同 park_store 的比例被覆盖 # 这是关键修复:避免同一 (flow, biz_type, brand) 下不同 park_store 的比例被覆盖
...@@ -2778,7 +3072,7 @@ class DataProcessor: ...@@ -2778,7 +3072,7 @@ class DataProcessor:
logger.error(f"[房租水电] 读取失败: {e}") logger.error(f"[房租水电] 读取失败: {e}")
if is_decrypted and actual_path != file_path: if is_decrypted and actual_path != file_path:
os.unlink(actual_path) os.unlink(actual_path)
return [] return [], [], unmatched
raw_records = [] raw_records = []
gmv_allocated_records = [] # GMV分摊的记录,直接传递给数据库更新 gmv_allocated_records = [] # GMV分摊的记录,直接传递给数据库更新
...@@ -3129,6 +3423,7 @@ class DataProcessor: ...@@ -3129,6 +3423,7 @@ class DataProcessor:
if park_fail_count < 10: if park_fail_count < 10:
logger.warning(f"[房租水电] 园区店匹配失败: store='{target}'") logger.warning(f"[房租水电] 园区店匹配失败: store='{target}'")
park_fail_count += 1 park_fail_count += 1
unmatched['rent_utilities'] += total_fee
continue continue
key = (ps, BIZ_TYPE_1_1) key = (ps, BIZ_TYPE_1_1)
...@@ -3235,6 +3530,7 @@ class DataProcessor: ...@@ -3235,6 +3530,7 @@ class DataProcessor:
logger.warning(f"[园区店回退] ps='{ps}' 无匹配业务类型={biz_type}的流量方") logger.warning(f"[园区店回退] ps='{ps}' 无匹配业务类型={biz_type}的流量方")
if len(failed_stores) < 10: if len(failed_stores) < 10:
failed_stores.append(ps) failed_stores.append(ps)
unmatched['rent_utilities'] += fee
continue continue
# 优先查找 gmv_ratio_park # 优先查找 gmv_ratio_park
...@@ -3305,6 +3601,7 @@ class DataProcessor: ...@@ -3305,6 +3601,7 @@ class DataProcessor:
failed_stores.append(ps) failed_stores.append(ps)
available_keys = [(k, len(v)) for k, v in park_rows.items() if ps in str(k[0])] available_keys = [(k, len(v)) for k, v in park_rows.items() if ps in str(k[0])]
logger.warning(f"[园区店回退] 诊断: park_rows中含'{ps}'的key={available_keys}") logger.warning(f"[园区店回退] 诊断: park_rows中含'{ps}'的key={available_keys}")
unmatched['rent_utilities'] += fee
continue continue
finally: finally:
...@@ -3323,7 +3620,7 @@ class DataProcessor: ...@@ -3323,7 +3620,7 @@ class DataProcessor:
if not raw_records and not gmv_allocated_records: if not raw_records and not gmv_allocated_records:
logger.info("[房租水电] 无有效数据") logger.info("[房租水电] 无有效数据")
return [], [] return [], [], unmatched
# 按 (流量方名称, 业务类型, 品牌) 汇总 # 按 (流量方名称, 业务类型, 品牌) 汇总
aggregated = defaultdict(lambda: Decimal("0")) aggregated = defaultdict(lambda: Decimal("0"))
...@@ -3349,6 +3646,13 @@ class DataProcessor: ...@@ -3349,6 +3646,13 @@ class DataProcessor:
) )
logger.info(f"[房租水电] 总量校验: 原始输入={total_input}, 输出汇总={total_output}, 差值={total_input - total_output}") logger.info(f"[房租水电] 总量校验: 原始输入={total_input}, 输出汇总={total_output}, 差值={total_input - total_output}")
# 总量校验:用 total_input_fee(接纳到各流程的总金额)减去实际分配到 raw_records + gmv_allocated_records 的金额
gmv_allocated_total = sum(r["房租及水电费"] for r in gmv_allocated_records)
matched_sum = total_output + gmv_allocated_total
conservation_unmatched = total_input_fee - matched_sum
unmatched['rent_utilities'] += conservation_unmatched
logger.info(f"[房租水电][未匹配汇总] rent_utilities: 总额={total_input_fee} 已匹配={matched_sum} 未匹配={unmatched['rent_utilities']}")
# 打印 GMV 分摊记录详情 # 打印 GMV 分摊记录详情
if gmv_allocated_records: if gmv_allocated_records:
logger.info(f"[房租水电] GMV分摊记录详情({len(gmv_allocated_records)}条):") logger.info(f"[房租水电] GMV分摊记录详情({len(gmv_allocated_records)}条):")
...@@ -3356,7 +3660,7 @@ class DataProcessor: ...@@ -3356,7 +3660,7 @@ class DataProcessor:
logger.info(f"[房租水电] GMV记录[{i}]: name={rec['流量方名称']}, fee={rec['房租及水电费']}, type={rec.get('target_type', 'unknown')}, method={rec.get('匹配方式', 'unknown')}") logger.info(f"[房租水电] GMV记录[{i}]: name={rec['流量方名称']}, fee={rec['房租及水电费']}, type={rec.get('target_type', 'unknown')}, method={rec.get('匹配方式', 'unknown')}")
logger.info(f"[房租水电] 解析完成,共 {len(result)} 条记录,GMV分摊 {len(gmv_allocated_records)} 条") logger.info(f"[房租水电] 解析完成,共 {len(result)} 条记录,GMV分摊 {len(gmv_allocated_records)} 条")
return result, gmv_allocated_records return result, gmv_allocated_records, unmatched
# ======================================================== # ========================================================
# 构建成本汇总表 # 构建成本汇总表
...@@ -5385,6 +5689,66 @@ class DataProcessor: ...@@ -5385,6 +5689,66 @@ class DataProcessor:
cell.font = cell_font cell.font = cell_font
cell.border = thin_border cell.border = thin_border
# ---------- 5. 追加未匹配金额汇总行 ----------
# 映射 fee_type → ORDERED 里的 db_attr(用于定位 Excel 列)
FEE_TYPE_TO_DB_ATTR = {
'market_fee': 'market_fee',
'external_construction': 'external_construction',
'technician_salary': 'technician_salary',
'marketing_team_salary': 'marketing_team_salary',
'rent_utilities': 'rent_utilities',
'renovation_amortization': 'renovation_amortization',
'store_consumables': 'store_consumables',
}
# 反向查 db_attr → Excel 列索引(1-based)
db_attr_to_col = {attr: c for c, (h, attr) in enumerate(ORDERED, 1)}
try:
unmatched_rows = BizUnmatchedFee.query.filter_by(task_id=task_id, stat_month=month).all()
except Exception as e_uf:
logger.warning(f"[Excel] 查未匹配金额失败,跳过追加行: {e_uf}")
unmatched_rows = []
# 汇总到一个 dict(同 fee_type 可能多条 —— 用先删后插保证只有一条,这里保险用 sum)
unmatched_by_fee = {}
for ur in unmatched_rows:
amt = float(ur.unmatched_amount) if ur.unmatched_amount else 0
unmatched_by_fee[ur.fee_type] = unmatched_by_fee.get(ur.fee_type, 0) + amt
# 只有存在非零未匹配金额才追加行
has_any_nonzero = any(abs(v) > 0.001 for v in unmatched_by_fee.values())
if has_any_nonzero:
new_row_idx = len(rows) + 2 # 数据行最后一行 + 1
ws.cell(row=new_row_idx, column=1, value="未匹配合计").font = cell_font
ws.cell(row=new_row_idx, column=1).alignment = center_align
ws.cell(row=new_row_idx, column=1).border = thin_border
for fee_type, amt in unmatched_by_fee.items():
if abs(amt) <= 0.001:
continue
db_attr = FEE_TYPE_TO_DB_ATTR.get(fee_type)
if db_attr is None:
continue
col_idx = db_attr_to_col.get(db_attr)
if col_idx is None:
continue
cell = ws.cell(row=new_row_idx, column=col_idx)
cell.value = round(amt, 2)
cell.number_format = "#,##0.00"
cell.font = cell_font
cell.alignment = right_align
cell.border = thin_border
# 未匹配行其他列也画边框(保持视觉一致)
for c in range(2, len(HEADERS) + 1):
if ws.cell(row=new_row_idx, column=c).border.left.style is None:
cell = ws.cell(row=new_row_idx, column=c)
cell.border = thin_border
logger.info(f"[Excel] 追加未匹配合计行 row={new_row_idx}, 未匹配金额汇总: {unmatched_by_fee}")
else:
logger.info(f"[Excel] 无未匹配金额,跳过追加行")
for c, h in enumerate(HEADERS, 1): for c, h in enumerate(HEADERS, 1):
ws.column_dimensions[openpyxl.utils.get_column_letter(c)].width = column_widths.get(h, 12) ws.column_dimensions[openpyxl.utils.get_column_letter(c)].width = column_widths.get(h, 12)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!