Commit 4eae55d3 by 叶立庆

Merge remote-tracking branch 'origin/main' into v1.2

# Conflicts:
#	.workbuddy/memory/2026-09-28.md
#	data-process/.gitignore
#	data-process/config.py
2 parents 7b672fb2 b905a7d1
# 2026-09-29 工作日志
## 总看板「2.3交车数」口径核查(14487 vs 17513)
- 字段:`build_store_effect_board.py:810` `m['2.3交车数'] = fetch_extended_warranty_23_sum('delivery_cnt', period_start, period_end)` → `_lr_sum_one('warranty','delivery_cnt',...)`(line557)。
- 真实口径:`report_extended_warranty` 表 `task_id==max(周期匹配或最新task), is_deleted=0` 的 `delivery_cnt` 之和。**只汇总单个 task_id,非跨所有 task 全量**。
- 用户报:结果表显示 14487、DB 查汇总 17513。实测当前代码算当前 DB(仅 task_id=32 一个任务)=17513;三种 period 取值(None / 整月 / 子集)均 17513;task32 无 NULL 行、75 行 0 值。
- 结论:14487 是**旧结果表快照**,DB 已更新 → 重跑生成结果表即对齐 17513。差异=数据时效,非逻辑 bug。
- ⚠ 设计提醒:看板只取**单个** task_id(周期匹配优先,否则 max(task_id))。当前仅 task32 故与全量等价;若未来并存多月/多 task 延保数据,看板只取最新一个 task,与"不限 task_id 全量"查询将不一致。
## 总看板执行顺序闸门(必须等前4个sheet完成)
- 用户要求:总看板(第5 sheet)必须在前 4 张 sheet(warranty/equity/inshop/park)执行完才执行。
- 根因:5 个调度器(warranty/equity/inshop/park/store_effect_summary)各自独立扫描同一 PROCESSING 主任务并发执行;原 `scan_store_effect_summary` 在跑 `_process_summary`(读前 4 张表的 ORM 数据)**前无闸门** → 竞态,总看板读到未落库/旧前置数据。
- 修复:`store_effect_summary_processor.py`
- `process()` 顶部加两道闸:① 自身已 COMPLETED → 幂等跳过;② `_preceding_sheets_all_completed(task_id)` 检查 `PRECEDING_CATEGORIES=['warranty','equity','inshop','park']` 是否**全部 == SUBTASK_COMPLETED**,否则 `return`(自身子任务保持 PENDING,等下轮调度重试;不置 FAILED)。
- 新增模块常量 `PRECEDING_CATEGORIES` + 方法 `_preceding_sheets_all_completed`(返回 (all_done, pending_list),未就绪态 PENDING/PROCESSING/None/FAILED 均视为等待)。
- 闸门放在 `process()` 内部(而非仅 scan),同时覆盖**两条入口**:调度器 `StoreEffectSummaryScheduler.scan_store_effect_summary` 与手动"处理"按钮 `processor.py:1437` 路由,均调用 `StoreEffectSummaryProcessor.process(task)`。
- 注:某前置 FAILED 时,主任务会被 `promote_subtask_failure_to_main_task` 置 FAILED,调度器不再扫到;手动按钮也因闸门(FAILED≠COMPLETED)而等待,不 deadlock。
- 验证:`py_compile` 通过;monkeypatch 5 用例全过(全完成→True;inshop PENDING/park PROCESSING/equity FAILED/inshop None→均 False+对应 pending 列表)。
...@@ -5,10 +5,10 @@ ...@@ -5,10 +5,10 @@
# ============================================ # ============================================
# ---------- 数据库(MySQL) ---------- # ---------- 数据库(MySQL) ----------
MYSQL_HOST=192.168.3.227 MYSQL_HOST=192.168.1.228
MYSQL_PORT=3306 MYSQL_PORT=3307
MYSQL_USER=os_user MYSQL_USER=wechat_user
MYSQL_PASSWORD=os#123 MYSQL_PASSWORD=b4WRTkl
MYSQL_DB=data_report MYSQL_DB=data_report
# ---------- 阿里云 OSS ---------- # ---------- 阿里云 OSS ----------
...@@ -33,5 +33,5 @@ INIT_NICKNAME=系统管理员 ...@@ -33,5 +33,5 @@ INIT_NICKNAME=系统管理员
# ---------- 服务 ---------- # ---------- 服务 ----------
FLASK_HOST=0.0.0.0 FLASK_HOST=0.0.0.0
FLASK_PORT=5001 FLASK_PORT=5000
FLASK_DEBUG=true FLASK_DEBUG=true
...@@ -4,5 +4,8 @@ __pycache__/ ...@@ -4,5 +4,8 @@ __pycache__/
*.pyc *.pyc
uploads/ uploads/
data/ data/
.idea
.idea/*
.venv/ .venv/
/.scheduler.lock /.scheduler.lock
"""扫店中店模板 row1+row2 窗膜/车衣/精品/踏板 相关表头"""
from openpyxl import load_workbook
wb = load_workbook(r'f:\360MoveData\Users\11\Desktop\企微SAAS\2026\09\0921\data-report\data-process\exporttemplete\红黄门店盈利测算 轻改 .xlsx')
ws = wb['店中店汇总']
print("=== 店中店 col18~32 (品类成交数区域) row1+row2+row4 ===")
for col in range(18, 33):
h1 = ws.cell(1, col).value or ''
h2 = ws.cell(2, col).value or ''
h4 = ws.cell(4, col).value or ''
print(f" col{col:2d}: row1={h1.strip()!r:25s} row2={h2.strip()!r:30s} fmt_row4={str(h4)[:60]}")
wb.close()
...@@ -132,6 +132,11 @@ def parse_period(data, tcfg): ...@@ -132,6 +132,11 @@ def parse_period(data, tcfg):
if period_type not in ('month', 'week'): if period_type not in ('month', 'week'):
raise ValueError(f'period_type 仅支持 month / week,当前值:{period_type}') raise ValueError(f'period_type 仅支持 month / week,当前值:{period_type}')
# 校验:need_period=False 或 support_week=False 的类型不允许按周粒度
if period_type == 'week':
if not tcfg.get('need_period') or not tcfg.get('support_week'):
raise ValueError('该类型仅支持按月粒度,不可选择按周')
if period_type == 'week': if period_type == 'week':
# 按周:强校验 week_num,后端计算权威日期区间 # 按周:强校验 week_num,后端计算权威日期区间
try: try:
...@@ -257,7 +262,8 @@ def meta_task_types(): ...@@ -257,7 +262,8 @@ def meta_task_types():
"""数据表类型配置(含各类型所需表单类型清单、是否需要所属周期)""" """数据表类型配置(含各类型所需表单类型清单、是否需要所属周期)"""
data = [ data = [
{'code': k, 'name': v['name'], 'forms': v['forms'], {'code': k, 'name': v['name'], 'forms': v['forms'],
'need_period': v.get('need_period', False)} 'need_period': v.get('need_period', False),
'support_week': v.get('support_week', False)}
for k, v in Config.DATA_TABLE_TYPES.items() for k, v in Config.DATA_TABLE_TYPES.items()
] ]
return ok(data) return ok(data)
......
...@@ -910,12 +910,10 @@ def compute_metrics(src, period_start, period_end, month_start=None, month_end_e ...@@ -910,12 +910,10 @@ def compute_metrics(src, period_start, period_end, month_start=None, month_end_e
logger.warning(f"[指标] 拉取失败,产值/成交/触客置 0: {e}") logger.warning(f"[指标] 拉取失败,产值/成交/触客置 0: {e}")
def match_any(name, stores): def match_any(name, stores):
"""指标系统商户名 ↔ SAAS 门店名 匹配(精确优先,再双向包含)""" """指标系统商户名 ↔ SAAS 门店名 匹配(精确匹配,不使用包含)"""
if not name: if not name:
return False return False
if name in stores: return name in stores
return True
return any(s and (s in name or name in s) for s in stores)
def ind_sum(ind_map, stores, code): def ind_sum(ind_map, stores, code):
t = Decimal('0') t = Decimal('0')
...@@ -992,16 +990,14 @@ def compute_metrics(src, period_start, period_end, month_start=None, month_end_e ...@@ -992,16 +990,14 @@ def compute_metrics(src, period_start, period_end, month_start=None, month_end_e
m['全国直营店均人数'] = safe_div(m['全国直营营销人数'], m['全国直营门店总数']) m['全国直营店均人数'] = safe_div(m['全国直营营销人数'], m['全国直营门店总数'])
m['全国人均产值(w)'] = safe_div(m['全国经营总产值'], m['全国直营营销人数']) m['全国人均产值(w)'] = safe_div(m['全国经营总产值'], m['全国直营营销人数'])
# 豪华/非豪华:按「入驻门店」映射门店集合(精确优先,再包含匹配) # 豪华/非豪华:按「入驻门店」映射门店集合(精确匹配,不使用包含)
lux_stores = {r['store'] for r in allrows if r['category'] == '豪华'} lux_stores = {r['store'] for r in allrows if r['category'] == '豪华'}
nonlux_stores = {r['store'] for r in allrows if r['category'] != '豪华'} nonlux_stores = {r['store'] for r in allrows if r['category'] != '豪华'}
def in_stores(hs, stores): def in_stores(hs, stores):
if not hs: if not hs:
return False return False
if hs in stores: return hs in stores
return True
return any(s and (s in hs or hs in s) for s in stores)
lux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], lux_stores)} lux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], lux_stores)}
nonlux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], nonlux_stores)} nonlux_emp = {r['emp_no'] for r in not_left if in_stores(r['store'], nonlux_stores)}
...@@ -1202,7 +1198,7 @@ FIELD_NOTES = [ ...@@ -1202,7 +1198,7 @@ FIELD_NOTES = [
('全国经营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有门店明细按门店名称去重计算总数'), ('全国经营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有门店明细按门店名称去重计算总数'),
('经管预算目标', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(预算目标)"之和'), ('经管预算目标', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(预算目标)"之和'),
('全国经营总预算', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(纠偏)"之和'), ('全国经营总预算', '来源于saas+门店预算分解表sheet1+sheet2,所有明细的"预估产值(纠偏)"之和'),
('全国经营总产值', '指标系统 A0018(含二手车业务),不传bizs全量求和、不做门店匹配;2026-08=97,681,597.64'), ('全国经营总产值', '指标系统 A0018(含二手车业务),biz=None 不传bizs查全量、不做门店匹配;2026-08 全量(不传bizs)实测=98,255,112.51(注:97,681,597.64 为历史快照,数据随业务回写变动)'),
('全国直营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有驻店类型=直营 的门店明细去重计算总数'), ('全国直营门店总数', '来源于saas+门店预算分解表sheet1+sheet2,所有驻店类型=直营 的门店明细去重计算总数'),
('全国直营总人数', '人力成本表:AF列检核=TRUE、过滤岗位=离职,按工号去重【人力表加密无法读取,当前0】'), ('全国直营总人数', '人力成本表:AF列检核=TRUE、过滤岗位=离职,按工号去重【人力表加密无法读取,当前0】'),
('全国直营营销人数', '人力成本表:检核=TRUE、岗位=门店销售,按工号去重【人力表加密无法读取,当前0】'), ('全国直营营销人数', '人力成本表:检核=TRUE、岗位=门店销售,按工号去重【人力表加密无法读取,当前0】'),
......
...@@ -133,6 +133,7 @@ class Config: ...@@ -133,6 +133,7 @@ class Config:
'budget_achievement': { 'budget_achievement': {
'name': '预算达成数据', 'name': '预算达成数据',
'need_period': False, 'need_period': False,
'support_week': False,
'forms': [ 'forms': [
'结算数据汇总表', '结算数据汇总表',
'市场费总表', '市场费总表',
...@@ -146,6 +147,7 @@ class Config: ...@@ -146,6 +147,7 @@ class Config:
'store_effect_earnings': { 'store_effect_earnings': {
'name': '店效人效及盈利测算', 'name': '店效人效及盈利测算',
'need_period': True, 'need_period': True,
'support_week': False,
'forms': [ 'forms': [
'SAAS门店预算分解表', 'SAAS门店预算分解表',
'关系表', '关系表',
...@@ -163,16 +165,12 @@ class Config: ...@@ -163,16 +165,12 @@ class Config:
'output_value': { 'output_value': {
'name': '产值达成表', 'name': '产值达成表',
'need_period': True, 'need_period': True,
'support_week': False,
'forms': [ 'forms': [
'SAAS门店预算分解表', 'SAAS门店预算分解表',
'关系表', '关系表',
], ],
}, },
'future_expansion': {
'name': '未来拓展',
'need_period': False,
'forms': [],
},
# 阿维塔专项:当前仅需上传主机厂数据表(表名暂定,后续若改名只改下方 forms)。 # 阿维塔专项:当前仅需上传主机厂数据表(表名暂定,后续若改名只改下方 forms)。
# 注意:此「主机厂数据表」为阿维塔专项独立数据表,格式不保证与现有 # 注意:此「主机厂数据表」为阿维塔专项独立数据表,格式不保证与现有
# 「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,切勿复用 # 「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,切勿复用
...@@ -201,21 +199,24 @@ class Config: ...@@ -201,21 +199,24 @@ class Config:
'leapmotor_special': { 'leapmotor_special': {
'name': '零跑专项', 'name': '零跑专项',
'need_period': True, 'need_period': True,
'support_week': False,
'forms': [], 'forms': [],
}, },
'voyah_special': { 'voyah_special': {
'name': '岚图专项', 'name': '岚图专项',
'need_period': True, 'need_period': True,
'support_week': False,
'forms': [], 'forms': [],
}, },
# 通用+权益:支持按月/按周粒度,含 3 个附件 # 通用+权益:支持按月/按周粒度,含 3 个附件
'common_equity': { # 'common_equity': {
'name': '通用+权益', # 'name': '通用+权益',
'need_period': True, # 'need_period': True,
'forms': [ # 'support_week': True,
'区域维度数据', # 'forms': [
'汇总区数据', # '区域维度数据',
'红黄门店数据', # '汇总区数据',
], # '红黄门店数据',
}, # ],
# },
} }
...@@ -25,7 +25,7 @@ from report_utils import ( ...@@ -25,7 +25,7 @@ from report_utils import (
download_all_files, download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps, parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps,
parse_budget_achieve_excel, extract_budget_ratio, parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, exact_match_store,
fetch_indicator_data, fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio, safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
) )
...@@ -175,9 +175,10 @@ class WarrantyProcessor: ...@@ -175,9 +175,10 @@ class WarrantyProcessor:
indicator_data = {} indicator_data = {}
# ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ========== # ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
store_names_for_sql = [r.get('store_name', '') for r in base_records if r.get('store_name')] # 不传 store_names 过滤(419 个 OR LIKE 会导致 MySQL 优化器异常丢 50% 门店)
# 后续用 fuzzy_match_store 在 Python 层做精确模糊匹配
# BIZ_TYPE_WARRANTY='2.3' → scene_type=0, business_type=2 # BIZ_TYPE_WARRANTY='2.3' → scene_type=0, business_type=2
biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_WARRANTY, store_names_for_sql) biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_WARRANTY)
# ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ========== # ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========
...@@ -190,13 +191,12 @@ class WarrantyProcessor: ...@@ -190,13 +191,12 @@ class WarrantyProcessor:
resident_type = rec.get('resident_type', '') resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {}) ind = indicator_data.get(store_name, {})
# Excel 门店名 → 业务表 merchant_name 模糊匹配 # 业务系统 SQL — 精确匹配,避免模糊误匹配(如"广西河池中达"误匹配到其他"中达"门店)
biz_data = fuzzy_match_store(store_name, biz_sql_map) or {} biz_data = exact_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表"厅店名称"/"基础信息-门店名称" # 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表(两边都是 Excel,命名可能不同 → 模糊保留)
# Excel 未匹配时,系统日报 scene_type=0 兜底
delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0 delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0
if delivery_cnt == 0 and system_delivery_map: if delivery_cnt == 0 and system_delivery_map:
_sys_entry = fuzzy_match_store(store_name, system_delivery_map) or {} _sys_entry = exact_match_store(store_name, system_delivery_map) or {}
delivery_cnt = _sys_entry.get('delivery_cnt', 0) if isinstance(_sys_entry, dict) else 0 delivery_cnt = _sys_entry.get('delivery_cnt', 0) if isinstance(_sys_entry, dict) else 0
# 指标系统取值 # 指标系统取值
...@@ -218,9 +218,22 @@ class WarrantyProcessor: ...@@ -218,9 +218,22 @@ class WarrantyProcessor:
# —— 业务系统 SQL 取值(已在 L172 用 fuzzy_match_store 拿到 biz_data)—— # —— 业务系统 SQL 取值(已在 L172 用 fuzzy_match_store 拿到 biz_data)——
product_cost = biz_data.get('product_cost', Decimal('0')) product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', Decimal('0')) market_fee = biz_data.get('market_fee', Decimal('0'))
service_fee = Decimal('0') if resident_type == '直营' else biz_data.get('service_fee', Decimal('0')) service_fee = Decimal('0') if resident_type != '服务商' else biz_data.get('service_fee', Decimal('0'))
# 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录)
store_share = biz_data.get('shop_traffic_money', Decimal('0')) # —— 门店分成:普通品牌取系统流量费 shop_traffic_money;岚图按渗透率区间算比例 * 门店产值 ——
# penetration_rate 范围 0-100(safe_div_pct 已 ×100)
is_lantu = (brand or '') == '岚图'
if is_lantu:
pr = float(penetration_rate)
if pr < 30:
lantu_ratio = Decimal('0.88')
elif pr < 50:
lantu_ratio = Decimal('0.85')
else:
lantu_ratio = Decimal('0.80')
store_share = (store_output_value * lantu_ratio).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
else:
store_share = biz_data.get('shop_traffic_money', Decimal('0'))
guarantee_amount = Decimal('0') guarantee_amount = Decimal('0')
gl_share = store_output_value - product_cost - store_share - guarantee_amount gl_share = store_output_value - product_cost - store_share - guarantee_amount
......
...@@ -25,7 +25,7 @@ from report_utils import ( ...@@ -25,7 +25,7 @@ from report_utils import (
download_all_files, download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps, parse_saas_base, parse_region_map, parse_delivery_table, merge_delivery_maps,
parse_budget_achieve_excel, extract_budget_ratio, parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, fetch_biz_sql_aggregated, fetch_park_daily_report, fuzzy_match_store, exact_match_store,
fetch_indicator_data, fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio, safe_div, safe_div_pct, safe_div_pct_decimal, clamp_ratio,
) )
...@@ -177,9 +177,10 @@ class EquityProcessor: ...@@ -177,9 +177,10 @@ class EquityProcessor:
indicator_data = {} indicator_data = {}
# ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ========== # ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
store_names_for_sql = [r.get('store_name', '') for r in base_records if r.get('store_name')] # 不传 store_names 过滤(419 个 OR LIKE 会导致 MySQL 优化器异常丢 50% 门店)
# 后续用 fuzzy_match_store 在 Python 层做精确模糊匹配
# BIZ_TYPE_EQUITY='2.1' → scene_type=0, business_type=1 # BIZ_TYPE_EQUITY='2.1' → scene_type=0, business_type=1
biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_EQUITY, store_names_for_sql) biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_EQUITY)
# ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ========== # ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========
...@@ -192,14 +193,13 @@ class EquityProcessor: ...@@ -192,14 +193,13 @@ class EquityProcessor:
resident_type = rec.get('resident_type', '') resident_type = rec.get('resident_type', '')
ind = indicator_data.get(store_name, {}) ind = indicator_data.get(store_name, {})
# Excel 门店名 → 业务表 merchant_name 模糊匹配 # 业务系统 SQL — 精确匹配
biz_data = fuzzy_match_store(store_name, biz_sql_map) or {} biz_data = exact_match_store(store_name, biz_sql_map) or {}
# 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表"厅店名称"/"基础信息-门店名称" # 主机厂交车:SAAS表"门店名" 模糊匹配 主机厂表(Excel → Excel 保留模糊)
# Excel 未匹配时,系统日报 scene_type=0 兜底
delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0 delivery_cnt = fuzzy_match_store(store_name, delivery_map) or 0
if delivery_cnt == 0 and system_delivery_map: if delivery_cnt == 0 and system_delivery_map:
# system_delivery_map value 是 dict{delivery_cnt, equity_to_shop_count, ...} # system_delivery_map value 是 dict{delivery_cnt, equity_to_shop_count, ...}
_sys_entry = fuzzy_match_store(store_name, system_delivery_map) or {} _sys_entry = exact_match_store(store_name, system_delivery_map) or {}
delivery_cnt = _sys_entry.get('delivery_cnt', 0) if isinstance(_sys_entry, dict) else 0 delivery_cnt = _sys_entry.get('delivery_cnt', 0) if isinstance(_sys_entry, dict) else 0
# 指标系统取值 # 指标系统取值
...@@ -214,7 +214,7 @@ class EquityProcessor: ...@@ -214,7 +214,7 @@ class EquityProcessor:
# —— 业务系统 SQL 取值 —— # —— 业务系统 SQL 取值 ——
product_cost = biz_data.get('product_cost', Decimal('0')) product_cost = biz_data.get('product_cost', Decimal('0'))
market_fee = biz_data.get('market_fee', Decimal('0')) market_fee = biz_data.get('market_fee', Decimal('0'))
service_fee = Decimal('0') if resident_type == '直营' else biz_data.get('service_fee', Decimal('0')) service_fee = Decimal('0') if resident_type != '服务商' else biz_data.get('service_fee', Decimal('0'))
# 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录) # 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录)
store_share = biz_data.get('shop_traffic_money', Decimal('0')) store_share = biz_data.get('shop_traffic_money', Decimal('0'))
guarantee_amount = Decimal('0') guarantee_amount = Decimal('0')
......
...@@ -405,8 +405,9 @@ def _fix_number_format(fmt, attr_name): ...@@ -405,8 +405,9 @@ def _fix_number_format(fmt, attr_name):
if not fmt or '%' not in fmt: if not fmt or '%' not in fmt:
return fmt return fmt
if _is_ratio_field(attr_name): if _is_ratio_field(attr_name):
# 真正的比例字段 → 转字面百分号(DB 已存 1-100,不应再自动乘 100) # 真正的比例字段 → 统一保留 2 位小数 + 字面 "%"
return fmt.replace('%', '"%"') # 防模板整数百分比格式(0%)四舍五入:DB 存 1.5 显示成 2%
return '0.00"%"'
else: else:
# 金额/数值字段被误配 % → 去掉百分号字符,保留数字精度 # 金额/数值字段被误配 % → 去掉百分号字符,保留数字精度
cleaned = fmt.replace('%', '').strip() cleaned = fmt.replace('%', '').strip()
......
-- ============================================================
-- 红黄门店盈利测算 - 4 张输出表 DDL (MySQL 5.7+, utf8mb4)
-- 生成方式:由 SQLAlchemy ORM Model 反推,与 db.create_all() 等价
-- 使用:在目标库 data_process 中直接执行即可
-- ============================================================
-- ---------- 表 1:延保盈利测算表 ----------
DROP TABLE IF EXISTS `report_extended_warranty`;
CREATE TABLE `report_extended_warranty` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '所属任务单据ID',
`period_start` DATE DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` DATE DEFAULT NULL COMMENT '统计周期结束日期',
-- 门店基础维度(9 列)
`region_area` VARCHAR(50) DEFAULT '' COMMENT '片区',
`province` VARCHAR(50) DEFAULT '' COMMENT '省份',
`city` VARCHAR(50) DEFAULT '' COMMENT '城市',
`region_manager` VARCHAR(50) DEFAULT '' COMMENT '区域运营',
`training_supervisor` VARCHAR(50) DEFAULT '' COMMENT '培训督导',
`biz_manager` VARCHAR(50) DEFAULT '' COMMENT '业务经理',
`resident_type` VARCHAR(50) DEFAULT '' COMMENT '驻店类型',
`store_name` VARCHAR(200) DEFAULT '' COMMENT '门店名',
`brand` VARCHAR(50) DEFAULT '' COMMENT '品牌',
-- 触客/成交(3 列)
`delivery_cnt` INT DEFAULT 0 COMMENT '交车',
`touch_cnt` INT DEFAULT 0 COMMENT '触客',
`deal_cnt` INT DEFAULT 0 COMMENT '成交数',
-- 延保特有指标(8 列)
`penetration_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '渗透率',
`vehicle_warranty_cnt` INT DEFAULT 0 COMMENT '整车延保成交数',
`vehicle_warranty_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '整车延保渗透率',
`vehicle_warranty_touch_convert` DECIMAL(10,6) DEFAULT 0 COMMENT '整车延保触客成交率',
`battery_warranty_cnt` INT DEFAULT 0 COMMENT '电池成交数',
`battery_warranty_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '电池渗透率',
`easy_bag_cnt` INT DEFAULT 0 COMMENT '安心包成交数',
`easy_bag_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '安心包渗透率',
-- 产值/成本/费用/毛利(18 列)
`store_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '门店产值',
`upgrade_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '升级客单价',
`product_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '商品成本',
`store_share` DECIMAL(15,2) DEFAULT 0 COMMENT '门店分成',
`guarantee_amount` DECIMAL(15,2) DEFAULT 0 COMMENT '兜底金额',
`gl_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联分成',
`market_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '市场费',
`market_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '市场费占比',
`marketing_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '营销费用',
`marketing_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '营销费用占比',
`service_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '服务费用',
`service_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '服务费用占比',
`total_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '成本总计',
`cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '成本占比',
`gross_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '毛利测算',
`gross_profit_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '预估毛利率',
`gross_profit_status` VARCHAR(20) DEFAULT '' COMMENT '预估毛利情况',
`gross_profit_rank` INT DEFAULT 0 COMMENT '门店毛利排名',
-- 公共字段
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` INT NOT NULL DEFAULT 0 COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_warranty_period_store_brand`
(`task_id`, `period_start`, `period_end`, `store_name`, `brand`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-延保表';
-- ---------- 表 2:权益盈利测算表 ----------
DROP TABLE IF EXISTS `report_equity_service`;
CREATE TABLE `report_equity_service` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '所属任务单据ID',
`period_start` DATE DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` DATE DEFAULT NULL COMMENT '统计周期结束日期',
-- 门店基础维度(9 列)
`region_area` VARCHAR(50) DEFAULT '' COMMENT '片区',
`province` VARCHAR(50) DEFAULT '' COMMENT '省份',
`city` VARCHAR(50) DEFAULT '' COMMENT '城市',
`region_manager` VARCHAR(50) DEFAULT '' COMMENT '区域运营',
`training_supervisor` VARCHAR(50) DEFAULT '' COMMENT '培训督导',
`biz_manager` VARCHAR(50) DEFAULT '' COMMENT '业务经理',
`resident_type` VARCHAR(50) DEFAULT '' COMMENT '驻店类型',
`store_name` VARCHAR(200) DEFAULT '' COMMENT '门店名',
`brand` VARCHAR(50) DEFAULT '' COMMENT '品牌',
-- 触客/成交(4 列)
`delivery_cnt` INT DEFAULT 0 COMMENT '交车',
`touch_cnt` INT DEFAULT 0 COMMENT '触客',
`deal_cnt` INT DEFAULT 0 COMMENT '成交数',
`penetration_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '渗透率',
-- 产值/成本/费用/毛利(18 列,与延保表一致)
`store_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '门店产值',
`upgrade_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '升级客单价',
`product_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '商品成本',
`store_share` DECIMAL(15,2) DEFAULT 0 COMMENT '门店分成',
`guarantee_amount` DECIMAL(15,2) DEFAULT 0 COMMENT '兜底金额',
`gl_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联分成',
`market_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '市场费',
`market_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '市场费占比',
`marketing_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '营销费用',
`marketing_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '营销费用占比',
`service_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '服务费用',
`service_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '服务费用占比',
`total_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '成本总计',
`cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '成本占比',
`gross_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '毛利测算',
`gross_profit_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '预估毛利率',
`gross_profit_status` VARCHAR(20) DEFAULT '' COMMENT '预估毛利情况',
`gross_profit_rank` INT DEFAULT 0 COMMENT '门店毛利排名',
-- 公共字段
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` INT NOT NULL DEFAULT 0 COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_equity_period_store_brand`
(`task_id`, `period_start`, `period_end`, `store_name`, `brand`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-权益表';
-- ---------- 表 3:轻改-店中店汇总表 ----------
DROP TABLE IF EXISTS `report_light_reform_inshop`;
CREATE TABLE `report_light_reform_inshop` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '所属任务单据ID',
`period_start` DATE DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` DATE DEFAULT NULL COMMENT '统计周期结束日期',
-- 门店基础信息(13 列)
`region_area` VARCHAR(50) DEFAULT '' COMMENT '大区名称',
`province` VARCHAR(50) DEFAULT '' COMMENT '区域省',
`city` VARCHAR(50) DEFAULT '' COMMENT '区域市',
`park_type` VARCHAR(50) DEFAULT '' COMMENT '园区类型',
`biz_line` VARCHAR(50) DEFAULT '' COMMENT '业务线',
`operate_type` VARCHAR(50) DEFAULT '' COMMENT '经营属性',
`region_manager` VARCHAR(50) DEFAULT '' COMMENT '区域经理',
`park_name` VARCHAR(200) DEFAULT '' COMMENT '园区名称',
`store_name` VARCHAR(200) DEFAULT '' COMMENT '门店名称',
`brand` VARCHAR(50) DEFAULT '' COMMENT '品牌(问界/鸿蒙)',
`brand_category` VARCHAR(50) DEFAULT '' COMMENT '品牌分类(豪华/非豪华)',
`purchase_indicator` VARCHAR(200) DEFAULT '' COMMENT '采买/兜底指标',
-- 销售端口(3 列)
`sales_order_cnt` INT DEFAULT 0 COMMENT '销售大定数',
`sales_touch_cnt` INT DEFAULT 0 COMMENT '销售触客数',
`sales_touch_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '销售触客率',
-- 交付端口(3 列)
`delivery_cnt` INT DEFAULT 0 COMMENT '交车数',
`delivery_touch_cnt` INT DEFAULT 0 COMMENT '交付触客数',
`delivery_touch_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '交付触客率',
-- 售后端口(6 列)
`aftersales_baohui_cnt` INT DEFAULT 0 COMMENT '售后首保回厂数',
`aftersales_shigu_cnt` INT DEFAULT 0 COMMENT '售后事故回厂数',
`aftersales_touch_cnt` INT DEFAULT 0 COMMENT '售后触客数',
`aftersales_touch_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '售后触客率',
`total_touch_cnt` INT DEFAULT 0 COMMENT '总触客数',
`total_deal_cnt` INT DEFAULT 0 COMMENT '总成交数',
-- 窗膜/车衣/精品 原厂+副厂(12 列 + 踏板 1 列)
`window_film_oe_cnt` INT DEFAULT 0 COMMENT '窗膜成交数-原厂',
`window_film_nonoe_cnt` INT DEFAULT 0 COMMENT '窗膜成交数-副厂',
`car_wrap_oe_cnt` INT DEFAULT 0 COMMENT '车衣成交数-原厂',
`car_wrap_nonoe_cnt` INT DEFAULT 0 COMMENT '车衣成交数-副厂',
`premium_oe_cnt` INT DEFAULT 0 COMMENT '精品成交数-原厂',
`premium_nonoe_cnt` INT DEFAULT 0 COMMENT '精品成交数-副厂',
`pedal_cnt` INT DEFAULT 0 COMMENT '踏板',
-- 产值(5 列)
`store_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '门店总产值',
`internal_settle_value` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算产值',
`total_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '合计总产值',
`oe_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '原厂总产值',
`nonoe_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '副厂总产值',
-- 客单/渗透(9 列)
`avg_unit_price_delivery` DECIMAL(15,2) DEFAULT 0 COMMENT '平均客单价(交车)',
`avg_price_target` DECIMAL(15,2) DEFAULT 0 COMMENT '平客目标值',
`avg_price_diff` DECIMAL(15,2) DEFAULT 0 COMMENT '平客差值',
`delivery_touch_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '交付触客客单价',
`upgrade_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '升级客单价',
`total_penetration_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '总订单渗透率',
`window_film_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '窗膜渗透率',
`car_wrap_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '车衣渗透率',
`premium_penetration` DECIMAL(10,6) DEFAULT 0 COMMENT '精品渗透率',
-- 成本-产品(8 列)
`product_cost_finance` DECIMAL(15,2) DEFAULT 0 COMMENT '产品成本(财务列表)',
`internal_settle_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算成本(财务列表)',
`oe_product_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '原厂产品成本(财务列表)',
`nonoe_product_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '副厂产品成本(财务列表)',
`window_film_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '窗膜成本',
`car_wrap_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '车衣成本',
`premium_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '精品成本',
`product_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '产品总成本占比',
-- 施工/激励/进销差/分成(11 列)
`construction_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '施工成本',
`construction_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '施工成本占比',
`frontline_incentive` DECIMAL(15,2) DEFAULT 0 COMMENT '一线激励',
`frontline_incentive_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '一线激励占比',
`gross_profit_pre_share` DECIMAL(15,2) DEFAULT 0 COMMENT '进销差(未分成)',
`gross_profit_pre_share_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '进销差占比',
`store_share` DECIMAL(15,2) DEFAULT 0 COMMENT '门店分成',
`store_share_per_car` DECIMAL(15,2) DEFAULT 0 COMMENT '门店单车利润',
`guarantee_amount` DECIMAL(15,2) DEFAULT 0 COMMENT '兜底金额',
`gl_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联分成',
`gl_share_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '广联分成占比',
-- 广联总分成/内部结算/施工收入(3 列)
`construction_income` DECIMAL(15,2) DEFAULT 0 COMMENT '施工收入',
`internal_settle_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算',
`gl_total_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联总分成',
-- 营销/市场/装修/房租/耗材/服务商(9 列)
`marketing_personnel_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '营销人员成本',
`marketing_personnel_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '营销人员成本占比',
`market_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '市场费',
`market_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '市场费占比',
`renovation_amortization` DECIMAL(15,2) DEFAULT 0 COMMENT '装修分摊',
`rent_utilities` DECIMAL(15,2) DEFAULT 0 COMMENT '房租、水电费用',
`store_consumables` DECIMAL(15,2) DEFAULT 0 COMMENT '门店耗材',
`service_provider_share` DECIMAL(15,2) DEFAULT 0 COMMENT '服务商分成',
`service_provider_share_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '服务商分成占比',
-- 成本总计/毛利(6 列)
`total_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '成本总计',
`cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '总计占比',
`gross_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '毛利测算',
`gross_profit_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '毛利率',
`gross_profit_status` VARCHAR(20) DEFAULT '' COMMENT '毛利情况',
`gross_profit_rank` INT DEFAULT 0 COMMENT '门店毛利排名',
-- 公共字段
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT='创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT='最近更新时间',
`is_deleted` INT NOT NULL DEFAULT 0 COMMENT='是否删除:0正常 / 1已删除',
`deleted_at` DATETIME DEFAULT NULL COMMENT='删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_inshop_period_park_store`
(`task_id`, `period_start`, `period_end`, `park_name`, `store_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-轻改店中店汇总表';
-- ---------- 表 4:轻改-园区店汇总表 ----------
DROP TABLE IF EXISTS `report_light_reform_park`;
CREATE TABLE `report_light_reform_park` (
`id` INT NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` INT NOT NULL COMMENT '所属任务单据ID',
`period_start` DATE DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` DATE DEFAULT NULL COMMENT '统计周期结束日期',
-- 门店基础信息(12 列)
`region_area` VARCHAR(50) DEFAULT '' COMMENT '大区名称',
`province` VARCHAR(50) DEFAULT '' COMMENT '区域省',
`city` VARCHAR(50) DEFAULT '' COMMENT '区域市',
`park_type` VARCHAR(50) DEFAULT '' COMMENT '园区类型',
`operate_type` VARCHAR(50) DEFAULT '' COMMENT '经营属性',
`partner_store_cnt` INT DEFAULT 0 COMMENT '合作门店数量',
`region_manager` VARCHAR(50) DEFAULT '' COMMENT '区域经理',
`park_name` VARCHAR(200) DEFAULT '' COMMENT '园区名称',
`store_name` VARCHAR(200) DEFAULT '' COMMENT '门店名称',
`brand` VARCHAR(50) DEFAULT '' COMMENT '品牌',
`biz_type` VARCHAR(50) DEFAULT '' COMMENT '类型',
`purchase_indicator` VARCHAR(200) DEFAULT '' COMMENT '采买/兜底指标(流量费)',
-- 触客/交车/转化(7 列)
`delivery_cnt` INT DEFAULT 0 COMMENT '交车数',
`arrival_cnt` INT DEFAULT 0 COMMENT '到店数',
`arrival_invalid_cnt` INT DEFAULT 0 COMMENT '到店无效客户数',
`invalid_arrival_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '无效到店率',
`arrival_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '到店率',
`deal_cnt` INT DEFAULT 0 COMMENT '成交数',
`conversion_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '转化率',
-- 产值/客单(8 列)
`store_sales_output` DECIMAL(15,2) DEFAULT 0 COMMENT '门店销售产值',
`internal_settle_value` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算产值',
`total_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '合计总产值',
`output_progress` DECIMAL(10,6) DEFAULT 0 COMMENT '产值达成进度',
`avg_unit_price_arrival` DECIMAL(15,2) DEFAULT 0 COMMENT '平均客单价(到店)',
`avg_price_target` DECIMAL(15,2) DEFAULT 0 COMMENT '平客目标值',
`avg_price_diff` DECIMAL(15,2) DEFAULT 0 COMMENT '平客差值',
`upgrade_unit_price` DECIMAL(15,2) DEFAULT 0 COMMENT '升级客单价',
-- 窗膜/车衣/精品(6 列)
`window_film_cnt` INT DEFAULT 0 COMMENT '窗膜成交数',
`window_film_convert` DECIMAL(10,6) DEFAULT 0 COMMENT '窗膜转化率',
`car_wrap_cnt` INT DEFAULT 0 COMMENT '车衣成交数',
`car_wrap_convert` DECIMAL(10,6) DEFAULT 0 COMMENT '车衣转化率',
`premium_cnt` INT DEFAULT 0 COMMENT '精品成交数',
`premium_convert` DECIMAL(10,6) DEFAULT 0 COMMENT '精品转化率',
-- 预算(3 列)
`est_traffic` INT DEFAULT 0 COMMENT '商务上架预估流量',
`est_delivery_cnt` INT DEFAULT 0 COMMENT '预估交车数',
`est_output_value` DECIMAL(15,2) DEFAULT 0 COMMENT '预估总产值(预算目标)',
-- 成本/分成/毛利(38 列)
`product_cost_finance` DECIMAL(15,2) DEFAULT 0 COMMENT '产品成本(财务列表)',
`product_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '产品成本占比',
`internal_settle_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算成本(财务列表)',
`traffic_fee_finance` DECIMAL(15,2) DEFAULT 0 COMMENT '流量费(财务列表)',
`traffic_fee_per_car` DECIMAL(15,2) DEFAULT 0 COMMENT '按单台计算流量/台',
`traffic_fee_order` DECIMAL(15,2) DEFAULT 0 COMMENT '按台次计算流量费',
`store_traffic_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '门店流量费',
`traffic_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '流量费率(列表测算)',
`gl_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联分成',
`gl_share_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '广联分成占比',
`internal_settle_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '内部结算',
`gl_total_share` DECIMAL(15,2) DEFAULT 0 COMMENT '广联总分成',
`personnel_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '人员成本',
`personnel_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '常规人员费率(加权参考)',
`construction_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '施工成本',
`construction_cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '施工成本占比',
`market_fee_weighted` DECIMAL(15,2) DEFAULT 0 COMMENT '市场费(加权测算)',
`market_fee_weighted_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '市场费费率(加权参考)',
`service_fee` DECIMAL(15,2) DEFAULT 0 COMMENT '服务费(商务报表)',
`service_fee_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '服务费费率(加权参考)',
`renovation_amortization` DECIMAL(15,2) DEFAULT 0 COMMENT '装修分摊(商务报表)',
`renovation_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '装修占比',
`rent_utilities` DECIMAL(15,2) DEFAULT 0 COMMENT '房租、水电费用',
`rent_utilities_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '房租、水电占比',
`store_consumables` DECIMAL(15,2) DEFAULT 0 COMMENT '门店耗材',
`store_consumables_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '门店耗材占比',
`total_cost` DECIMAL(15,2) DEFAULT 0 COMMENT '成本总计',
`cost_ratio` DECIMAL(10,6) DEFAULT 0 COMMENT '总计占比',
`gross_profit` DECIMAL(15,2) DEFAULT 0 COMMENT '毛利测算',
`gross_profit_rate` DECIMAL(10,6) DEFAULT 0 COMMENT '毛利率',
`gross_profit_status` VARCHAR(20) DEFAULT '' COMMENT '毛利情况',
`gross_profit_rank` INT DEFAULT 0 COMMENT '门店毛利排名',
-- 公共字段
`created_at` DATETIME DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` DATETIME DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` INT NOT NULL DEFAULT 0 COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` DATETIME DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_park_period_park_store`
(`task_id`, `period_start`, `period_end`, `park_name`, `store_name`)
) ENGINE=InnoDB DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-轻改园区店汇总表';
-- ============================================================================
-- 增量 ALTER: 店中店新增 store_share_ratio (门店分成占比) 字段
-- 2026-09-10: col63 表头"门店分成(占比)"模板需要此列,但 ORM/DDL 均缺失
-- ============================================================================
ALTER TABLE report_light_reform_inshop
ADD COLUMN `store_share_ratio` DECIMAL(10, 6) DEFAULT 0
COMMENT '门店分成占比(门店分成/门店总产值)'
AFTER `store_share`;
-- ============================================================================
-- 增量 ALTER: 店中店新增后置施工成本 2 字段
-- DB 已有: construction_cost(总计), construction_cost_oe(前置原厂),
-- construction_cost_nonoe(前置副厂), construction_cost_ratio(总计占比)
-- 新增: construction_cost_post, construction_cost_post_ratio
-- construction_cost = oe + nonoe + post
-- ============================================================================
ALTER TABLE report_light_reform_inshop
ADD COLUMN `construction_cost_post` DECIMAL(15, 2) DEFAULT 0
COMMENT '后置施工成本(直营按商务政策, 服务商=0)'
AFTER `construction_cost_nonoe`,
ADD COLUMN `construction_cost_post_ratio` DECIMAL(10, 6) DEFAULT 0
COMMENT '后置施工成本占比(post/门店总产值)'
AFTER `construction_cost_post`;
-- data_report.luxury_brand_config definition
ALTER TABLE data_report.data_process_task ADD period_start date NULL COMMENT '所属周期-开始日期(need_period 类型使用,如 2026-08-01)';
ALTER TABLE data_report.data_process_task ADD period_end date NULL COMMENT '所属周期-结束日期(need_period 类型使用,如 2026-08-31)';
-- Step 1. 新增字段(period_type/week_num)
ALTER TABLE data_process_task
ADD COLUMN period_type VARCHAR(10) NOT NULL DEFAULT 'month'
COMMENT '周期粒度:month 按月 / week 按周' AFTER month,
ADD COLUMN week_num INT NULL
COMMENT '按周时的周序号 1-5;按月时为 NULL' AFTER period_type;
ALTER TABLE data_process_task DROP INDEX uq_task_type_month;
CREATE TABLE `luxury_brand_config` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`brand_name` varchar(100) COLLATE utf8mb4_unicode_ci NOT NULL COMMENT '品牌名称(如 问界/鸿蒙/奔驰/宝马 等)',
`is_luxury` int(11) NOT NULL COMMENT '是否豪华品牌:1豪华 / 0非豪华',
`remark` varchar(200) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '备注',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`is_deleted` int(11) NOT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_luxury_brand_name` (`brand_name`)
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='豪华品牌配置表';
-- data_report.data_process_subtask definition
CREATE TABLE `data_process_subtask` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '主任务ID(关联 data_process_task.id)',
`output_category` varchar(30) NOT NULL COMMENT '输出类别:warranty=延保 / equity=权益 / inshop=轻改店中店 / park=轻改园区店',
`status` varchar(20) NOT NULL DEFAULT 'PENDING' COMMENT '子任务状态:PENDING待处理 / PROCESSING处理中 / COMPLETED已完成 / FAILED失败',
`error_msg` varchar(500) DEFAULT '' COMMENT '失败时的错误信息',
`row_count` int(11) DEFAULT '0' COMMENT '实际写入行数(处理完成后更新)',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`),
UNIQUE KEY `uk_subtask_task_category` (`task_id`,`output_category`)
) ENGINE=InnoDB AUTO_INCREMENT=41 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-子任务表(追踪 4 张输出表的独立处理状态)';
-- data_report.report_equity_service definition
CREATE TABLE `report_equity_service` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`period_start` date DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` date DEFAULT NULL COMMENT '统计周期结束日期',
`region_area` varchar(50) DEFAULT '' COMMENT '片区',
`province` varchar(50) DEFAULT '' COMMENT '省份',
`city` varchar(50) DEFAULT '' COMMENT '城市',
`region_manager` varchar(50) DEFAULT '' COMMENT '区域运营',
`training_supervisor` varchar(50) DEFAULT '' COMMENT '培训督导',
`biz_manager` varchar(50) DEFAULT '' COMMENT '业务经理',
`resident_type` varchar(50) DEFAULT '' COMMENT '驻店类型',
`store_name` varchar(200) DEFAULT '' COMMENT '门店名',
`brand` varchar(50) DEFAULT '' COMMENT '品牌',
`delivery_cnt` int(11) DEFAULT '0' COMMENT '交车',
`touch_cnt` int(11) DEFAULT '0' COMMENT '触客',
`deal_cnt` int(11) DEFAULT '0' COMMENT '成交数',
`penetration_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '渗透率',
`store_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '门店产值',
`upgrade_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '升级客单价',
`product_cost` decimal(15,2) DEFAULT '0.00' COMMENT '商品成本',
`store_share` decimal(15,2) DEFAULT '0.00' COMMENT '门店分成',
`guarantee_amount` decimal(15,2) DEFAULT '0.00' COMMENT '兜底金额',
`gl_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联分成',
`market_fee` decimal(15,2) DEFAULT '0.00' COMMENT '市场费',
`market_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '市场费占比',
`marketing_fee` decimal(15,2) DEFAULT '0.00' COMMENT '营销费用',
`marketing_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '营销费用占比',
`service_fee` decimal(15,2) DEFAULT '0.00' COMMENT '服务费用',
`service_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '服务费用占比',
`total_cost` decimal(15,2) DEFAULT '0.00' COMMENT '成本总计',
`cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '成本占比',
`gross_profit` decimal(15,2) DEFAULT '0.00' COMMENT '毛利测算',
`gross_profit_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '预估毛利率',
`gross_profit_status` varchar(20) DEFAULT '' COMMENT '预估毛利情况',
`gross_profit_rank` int(11) DEFAULT '0' COMMENT '门店毛利排名',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=15232 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-权益表';
-- data_report.report_extended_warranty definition
CREATE TABLE `report_extended_warranty` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`period_start` date DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` date DEFAULT NULL COMMENT '统计周期结束日期',
`region_area` varchar(50) DEFAULT '' COMMENT '片区',
`province` varchar(50) DEFAULT '' COMMENT '省份',
`city` varchar(50) DEFAULT '' COMMENT '城市',
`region_manager` varchar(50) DEFAULT '' COMMENT '区域运营',
`training_supervisor` varchar(50) DEFAULT '' COMMENT '培训督导',
`biz_manager` varchar(50) DEFAULT '' COMMENT '业务经理',
`resident_type` varchar(50) DEFAULT '' COMMENT '驻店类型',
`store_name` varchar(200) DEFAULT '' COMMENT '门店名',
`brand` varchar(50) DEFAULT '' COMMENT '品牌',
`delivery_cnt` int(11) DEFAULT '0' COMMENT '交车',
`touch_cnt` int(11) DEFAULT '0' COMMENT '触客',
`deal_cnt` int(11) DEFAULT '0' COMMENT '成交数',
`penetration_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '渗透率',
`vehicle_warranty_cnt` int(11) DEFAULT '0' COMMENT '整车延保成交数',
`vehicle_warranty_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '整车延保渗透率',
`vehicle_warranty_touch_convert` decimal(10,6) DEFAULT '0.000000' COMMENT '整车延保触客成交率',
`battery_warranty_cnt` int(11) DEFAULT '0' COMMENT '电池成交数',
`battery_warranty_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '电池渗透率',
`easy_bag_cnt` int(11) DEFAULT '0' COMMENT '安心包成交数',
`easy_bag_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '安心包渗透率',
`store_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '门店产值',
`upgrade_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '升级客单价',
`product_cost` decimal(15,2) DEFAULT '0.00' COMMENT '商品成本',
`store_share` decimal(15,2) DEFAULT '0.00' COMMENT '门店分成',
`guarantee_amount` decimal(15,2) DEFAULT '0.00' COMMENT '兜底金额',
`gl_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联分成',
`market_fee` decimal(15,2) DEFAULT '0.00' COMMENT '市场费',
`market_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '市场费占比',
`marketing_fee` decimal(15,2) DEFAULT '0.00' COMMENT '营销费用',
`marketing_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '营销费用占比',
`service_fee` decimal(15,2) DEFAULT '0.00' COMMENT '服务费用',
`service_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '服务费用占比',
`total_cost` decimal(15,2) DEFAULT '0.00' COMMENT '成本总计',
`cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '成本占比',
`gross_profit` decimal(15,2) DEFAULT '0.00' COMMENT '毛利测算',
`gross_profit_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '预估毛利率',
`gross_profit_status` varchar(20) DEFAULT '' COMMENT '预估毛利情况',
`gross_profit_rank` int(11) DEFAULT '0' COMMENT '门店毛利排名',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=43461 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-延保表';
-- data_report.report_light_reform_inshop definition
CREATE TABLE `report_light_reform_inshop` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`period_start` date DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` date DEFAULT NULL COMMENT '统计周期结束日期',
`region_area` varchar(50) DEFAULT '' COMMENT '大区名称',
`province` varchar(50) DEFAULT '' COMMENT '区域省',
`city` varchar(50) DEFAULT '' COMMENT '区域市',
`park_type` varchar(50) DEFAULT '' COMMENT '园区类型',
`biz_line` varchar(50) DEFAULT '' COMMENT '业务线',
`operate_type` varchar(50) DEFAULT '' COMMENT '经营属性',
`region_manager` varchar(50) DEFAULT '' COMMENT '区域经理',
`park_name` varchar(200) DEFAULT '' COMMENT '园区名称',
`store_name` varchar(200) DEFAULT '' COMMENT '门店名称',
`brand` varchar(50) DEFAULT '' COMMENT '品牌(问界/鸿蒙)',
`brand_category` varchar(50) DEFAULT '' COMMENT '品牌分类(豪华/非豪华)',
`purchase_indicator` varchar(200) DEFAULT '' COMMENT '采买/兜底指标',
`sales_order_cnt` int(11) DEFAULT '0' COMMENT '销售大定数',
`sales_touch_cnt` int(11) DEFAULT '0' COMMENT '销售触客数',
`sales_touch_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '销售触客率',
`delivery_cnt` int(11) DEFAULT '0' COMMENT '交车数',
`delivery_touch_cnt` int(11) DEFAULT '0' COMMENT '交付触客数',
`delivery_touch_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '交付触客率',
`aftersales_baohui_cnt` int(11) DEFAULT '0' COMMENT '售后首保回厂数',
`aftersales_shigu_cnt` int(11) DEFAULT '0' COMMENT '售后事故回厂数',
`aftersales_touch_cnt` int(11) DEFAULT '0' COMMENT '售后触客数',
`aftersales_touch_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '售后触客率',
`total_touch_cnt` int(11) DEFAULT '0' COMMENT '总触客数',
`total_deal_cnt` int(11) DEFAULT '0' COMMENT '总成交数',
`window_film_oe_cnt` int(11) DEFAULT '0' COMMENT '窗膜成交数-原厂',
`window_film_nonoe_cnt` int(11) DEFAULT '0' COMMENT '窗膜成交数-副厂',
`car_wrap_oe_cnt` int(11) DEFAULT '0' COMMENT '车衣成交数-原厂',
`car_wrap_nonoe_cnt` int(11) DEFAULT '0' COMMENT '车衣成交数-副厂',
`premium_oe_cnt` int(11) DEFAULT '0' COMMENT '精品成交数-原厂',
`premium_nonoe_cnt` int(11) DEFAULT '0' COMMENT '精品成交数-副厂',
`pedal_cnt` int(11) DEFAULT '0' COMMENT '踏板',
`store_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '门店总产值',
`internal_settle_value` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算产值',
`total_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '合计总产值',
`oe_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '原厂总产值',
`nonoe_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '副厂总产值',
`avg_unit_price_delivery` decimal(15,2) DEFAULT '0.00' COMMENT '平均客单价(交车)',
`avg_price_target` decimal(15,2) DEFAULT '0.00' COMMENT '平客目标值',
`avg_price_diff` decimal(15,2) DEFAULT '0.00' COMMENT '平客差值',
`delivery_touch_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '交付触客客单价',
`upgrade_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '升级客单价',
`total_penetration_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '总订单渗透率',
`window_film_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '窗膜渗透率',
`car_wrap_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '车衣渗透率',
`premium_penetration` decimal(10,6) DEFAULT '0.000000' COMMENT '精品渗透率',
`product_cost_finance` decimal(15,2) DEFAULT '0.00' COMMENT '产品成本(财务列表)',
`internal_settle_cost` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算成本(财务列表)',
`oe_product_cost` decimal(15,2) DEFAULT '0.00' COMMENT '原厂产品成本(财务列表)',
`nonoe_product_cost` decimal(15,2) DEFAULT '0.00' COMMENT '副厂产品成本(财务列表)',
`window_film_cost` decimal(15,2) DEFAULT '0.00' COMMENT '窗膜成本',
`car_wrap_cost` decimal(15,2) DEFAULT '0.00' COMMENT '车衣成本',
`premium_cost` decimal(15,2) DEFAULT '0.00' COMMENT '精品成本',
`product_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '产品总成本占比',
`construction_cost` decimal(15,2) DEFAULT '0.00' COMMENT '施工成本',
`construction_cost_oe` decimal(15,2) DEFAULT '0.00' COMMENT '原厂施工成本',
`construction_cost_nonoe` decimal(15,2) DEFAULT '0.00' COMMENT '副厂施工成本',
`construction_cost_post` decimal(15,2) DEFAULT '0.00' COMMENT '后置施工成本(直营按商务政策, 服务商=0)',
`construction_cost_post_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '后置施工成本占比(post/门店总产值)',
`construction_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '施工成本占比',
`frontline_incentive` decimal(15,2) DEFAULT '0.00' COMMENT '一线激励',
`frontline_incentive_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '一线激励占比',
`gross_profit_pre_share` decimal(15,2) DEFAULT '0.00' COMMENT '进销差(未分成)',
`gross_profit_pre_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '进销差占比',
`store_share` decimal(15,2) DEFAULT '0.00' COMMENT '门店分成',
`store_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '门店分成占比',
`store_share_per_car` decimal(15,2) DEFAULT '0.00' COMMENT '门店单车利润',
`guarantee_amount` decimal(15,2) DEFAULT '0.00' COMMENT '兜底金额',
`gl_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联分成',
`gl_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '广联分成占比',
`construction_income` decimal(15,2) DEFAULT '0.00' COMMENT '施工收入',
`internal_settle_profit` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算',
`gl_total_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联总分成',
`marketing_personnel_cost` decimal(15,2) DEFAULT '0.00' COMMENT '营销人员成本',
`marketing_personnel_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '营销人员成本占比',
`market_fee` decimal(15,2) DEFAULT '0.00' COMMENT '市场费',
`market_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '市场费占比',
`renovation_amortization` decimal(15,2) DEFAULT '0.00' COMMENT '装修分摊',
`rent_utilities` decimal(15,2) DEFAULT '0.00' COMMENT '房租、水电费用',
`store_consumables` decimal(15,2) DEFAULT '0.00' COMMENT '门店耗材',
`service_provider_share` decimal(15,2) DEFAULT '0.00' COMMENT '服务商分成',
`service_provider_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '服务商分成占比',
`total_cost` decimal(15,2) DEFAULT '0.00' COMMENT '成本总计',
`cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '总计占比',
`gross_profit` decimal(15,2) DEFAULT '0.00' COMMENT '毛利测算',
`gross_profit_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '毛利率',
`gross_profit_status` varchar(20) DEFAULT '' COMMENT '毛利情况',
`gross_profit_rank` int(11) DEFAULT '0' COMMENT '门店毛利排名',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=4673 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-轻改店中店汇总表';
-- data_report.report_light_reform_park definition
CREATE TABLE `report_light_reform_park` (
`id` int(11) NOT NULL AUTO_INCREMENT COMMENT '主键ID',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`period_start` date DEFAULT NULL COMMENT '统计周期开始日期',
`period_end` date DEFAULT NULL COMMENT '统计周期结束日期',
`region_area` varchar(50) DEFAULT '' COMMENT '大区名称',
`province` varchar(50) DEFAULT '' COMMENT '区域省',
`city` varchar(50) DEFAULT '' COMMENT '区域市',
`park_type` varchar(50) DEFAULT '' COMMENT '园区类型',
`operate_type` varchar(50) DEFAULT '' COMMENT '经营属性',
`partner_store_cnt` int(11) DEFAULT '0' COMMENT '合作门店数量',
`region_manager` varchar(50) DEFAULT '' COMMENT '区域经理',
`park_name` varchar(200) DEFAULT '' COMMENT '园区名称',
`store_name` varchar(200) DEFAULT '' COMMENT '门店名称',
`brand` varchar(50) DEFAULT '' COMMENT '品牌',
`biz_type` varchar(50) DEFAULT '' COMMENT '类型',
`purchase_indicator` varchar(200) DEFAULT '' COMMENT '采买/兜底指标(流量费)',
`delivery_cnt` int(11) DEFAULT '0' COMMENT '交车数',
`arrival_cnt` int(11) DEFAULT '0' COMMENT '到店数',
`arrival_invalid_cnt` int(11) DEFAULT '0' COMMENT '到店无效客户数',
`invalid_arrival_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '无效到店率',
`arrival_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '到店率',
`deal_cnt` int(11) DEFAULT '0' COMMENT '成交数',
`conversion_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '转化率',
`store_sales_output` decimal(15,2) DEFAULT '0.00' COMMENT '门店销售产值',
`internal_settle_value` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算产值',
`total_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '合计总产值',
`output_progress` decimal(10,6) DEFAULT '0.000000' COMMENT '产值达成进度',
`avg_unit_price_arrival` decimal(15,2) DEFAULT '0.00' COMMENT '平均客单价(到店)',
`avg_price_target` decimal(15,2) DEFAULT '0.00' COMMENT '平客目标值',
`avg_price_diff` decimal(15,2) DEFAULT '0.00' COMMENT '平客差值',
`upgrade_unit_price` decimal(15,2) DEFAULT '0.00' COMMENT '升级客单价',
`window_film_cnt` int(11) DEFAULT '0' COMMENT '窗膜成交数',
`window_film_convert` decimal(10,6) DEFAULT '0.000000' COMMENT '窗膜转化率',
`car_wrap_cnt` int(11) DEFAULT '0' COMMENT '车衣成交数',
`car_wrap_convert` decimal(10,6) DEFAULT '0.000000' COMMENT '车衣转化率',
`premium_cnt` int(11) DEFAULT '0' COMMENT '精品成交数',
`premium_convert` decimal(10,6) DEFAULT '0.000000' COMMENT '精品转化率',
`est_traffic` int(11) DEFAULT '0' COMMENT '商务上架预估流量',
`est_delivery_cnt` int(11) DEFAULT '0' COMMENT '预估交车数',
`est_output_value` decimal(15,2) DEFAULT '0.00' COMMENT '预估总产值(预算目标)',
`product_cost_finance` decimal(15,2) DEFAULT '0.00' COMMENT '产品成本(财务列表)',
`product_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '产品成本占比',
`internal_settle_cost` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算成本(财务列表)',
`traffic_fee_finance` decimal(15,2) DEFAULT '0.00' COMMENT '流量费(财务列表)',
`traffic_fee_per_car` decimal(15,2) DEFAULT '0.00' COMMENT '按单台计算流量/台',
`traffic_fee_order` decimal(15,2) DEFAULT '0.00' COMMENT '按台次计算流量费',
`store_traffic_fee` decimal(15,2) DEFAULT '0.00' COMMENT '门店流量费',
`traffic_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '流量费率(列表测算)',
`gl_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联分成',
`gl_share_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '广联分成占比',
`internal_settle_profit` decimal(15,2) DEFAULT '0.00' COMMENT '内部结算',
`gl_total_share` decimal(15,2) DEFAULT '0.00' COMMENT '广联总分成',
`personnel_cost` decimal(15,2) DEFAULT '0.00' COMMENT '人员成本',
`personnel_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '常规人员费率(加权参考)',
`construction_cost` decimal(15,2) DEFAULT '0.00' COMMENT '施工成本',
`construction_cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '施工成本占比',
`market_fee_weighted` decimal(15,2) DEFAULT '0.00' COMMENT '市场费(加权测算)',
`market_fee_weighted_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '市场费费率(加权参考)',
`service_fee` decimal(15,2) DEFAULT '0.00' COMMENT '服务费(商务报表)',
`service_fee_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '服务费费率(加权参考)',
`renovation_amortization` decimal(15,2) DEFAULT '0.00' COMMENT '装修分摊(商务报表)',
`renovation_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '装修占比',
`rent_utilities` decimal(15,2) DEFAULT '0.00' COMMENT '房租、水电费用',
`rent_utilities_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '房租、水电占比',
`store_consumables` decimal(15,2) DEFAULT '0.00' COMMENT '门店耗材',
`store_consumables_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '门店耗材占比',
`total_cost` decimal(15,2) DEFAULT '0.00' COMMENT '成本总计',
`cost_ratio` decimal(10,6) DEFAULT '0.000000' COMMENT '总计占比',
`gross_profit` decimal(15,2) DEFAULT '0.00' COMMENT '毛利测算',
`gross_profit_rate` decimal(10,6) DEFAULT '0.000000' COMMENT '毛利率',
`gross_profit_status` varchar(20) DEFAULT '' COMMENT '毛利情况',
`gross_profit_rank` int(11) DEFAULT '0' COMMENT '门店毛利排名',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '最近更新时间',
`is_deleted` int(11) NOT NULL DEFAULT '0' COMMENT '是否删除:0正常 / 1已删除',
`deleted_at` datetime DEFAULT NULL COMMENT '删除时间',
PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=2081 DEFAULT CHARSET=utf8mb4 COMMENT='红黄门店盈利测算-轻改园区店汇总表';
-- data_report.report_store_effect_summary definition
CREATE TABLE `report_store_effect_summary` (
`id` int(11) NOT NULL AUTO_INCREMENT,
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`stat_month` varchar(7) COLLATE utf8mb4_unicode_ci DEFAULT NULL COMMENT '统计月份 YYYY-MM',
`period_start` date DEFAULT NULL COMMENT '统计周期开始',
`period_end` date DEFAULT NULL COMMENT '统计周期结束',
`store_count` int(11) DEFAULT NULL COMMENT '门店数(跨业务类型去重)',
`delivery_total` int(11) DEFAULT NULL COMMENT '交车数合计',
`touch_total` int(11) DEFAULT NULL COMMENT '触客数合计',
`deal_total` int(11) DEFAULT NULL COMMENT '成交数合计',
`output_value_total` decimal(15,2) DEFAULT NULL COMMENT '产值合计',
`cost_total` decimal(15,2) DEFAULT NULL COMMENT '成本合计',
`gross_profit_total` decimal(15,2) DEFAULT NULL COMMENT '毛利合计',
`gross_profit_rate` decimal(10,6) DEFAULT NULL COMMENT '毛利率',
`labor_cost_total` decimal(15,2) DEFAULT NULL COMMENT '人力成本合计',
`headcount_total` int(11) DEFAULT NULL COMMENT '人员数合计',
`per_capita_output` decimal(15,2) DEFAULT NULL COMMENT '人均产值',
`per_capita_profit` decimal(15,2) DEFAULT NULL COMMENT '人均毛利',
`created_at` datetime DEFAULT NULL,
`updated_at` datetime DEFAULT NULL,
`is_deleted` int(11) NOT NULL,
`deleted_at` datetime DEFAULT NULL,
PRIMARY KEY (`id`),
UNIQUE KEY `uk_store_effect_summary_task_period` (`task_id`,`period_start`,`period_end`)
) ENGINE=InnoDB AUTO_INCREMENT=318 DEFAULT CHARSET=utf8mb4 COLLATE=utf8mb4_unicode_ci COMMENT='门店店效人效汇总表(整体合计)';
-- data_report.saas_business_achievement definition
CREATE TABLE `saas_business_achievement` (
`id` int(10) unsigned NOT NULL AUTO_INCREMENT COMMENT '自增主键',
`task_id` int(11) NOT NULL COMMENT '所属任务单据ID',
`stat_month` char(7) NOT NULL COMMENT '统计月份,格式 YYYY-MM,如 2026-09',
`start_date` char(10) NOT NULL COMMENT '统计周期开始时间,如 2026-09-01',
`end_date` char(10) NOT NULL COMMENT '统计周期结束时间,如 2026-09-15',
`business_type` varchar(20) NOT NULL COMMENT '业务类型:2.1+2.3 或 1.1',
`manager` varchar(50) DEFAULT NULL COMMENT '大区经理(B列)',
`region_operator` varchar(50) NOT NULL COMMENT '区域运营负责人(B列)',
`online_operator` varchar(50) DEFAULT NULL COMMENT '线上运营(D列)',
`operated_stores` int(10) unsigned DEFAULT '0' COMMENT '运营门店数(E列)',
`direct_stores` int(10) unsigned DEFAULT '0' COMMENT '直营门店数(F列)',
`daily_new_gmv` decimal(15,2) DEFAULT '0.00' COMMENT '当日新增 GMV(G列)',
`existing_budget` decimal(15,2) DEFAULT '0.00' COMMENT '存量门店预算(H列)',
`existing_actual` decimal(15,2) DEFAULT '0.00' COMMENT '存量门店实际达成(I列)',
`existing_rate` decimal(5,2) DEFAULT '0.00' COMMENT '存量目标达成率(%)(J列)',
`new_budget` decimal(15,2) DEFAULT '0.00' COMMENT '新店预算(K列)',
`new_actual` decimal(15,2) DEFAULT '0.00' COMMENT '新店实际达成(L列)',
`new_rate` decimal(5,2) DEFAULT '0.00' COMMENT '新店目标达成率(%)(M列)',
`total_actual_gmv` decimal(15,2) DEFAULT '0.00' COMMENT '实际达成 GMV 合计(存量+新店)(N列)',
`total_rate` decimal(5,2) DEFAULT '0.00' COMMENT '总预算达成率(%)(O列)',
`created_at` datetime DEFAULT CURRENT_TIMESTAMP COMMENT '记录创建时间',
`updated_at` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP COMMENT '记录更新时间',
PRIMARY KEY (`id`),
KEY `idx_stat_month` (`stat_month`),
KEY `idx_business_type` (`business_type`),
KEY `idx_region_operator` (`region_operator`)
) ENGINE=InnoDB AUTO_INCREMENT=913 DEFAULT CHARSET=utf8mb4 COMMENT='产值达成表';
-- data_report.config_brand_category2 definition
CREATE TABLE `config_brand_category2` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`brand` varchar(200) NOT NULL COMMENT '品牌',
`category` varchar(50) NOT NULL DEFAULT '' COMMENT '品牌区分(如 豪华/非豪华)',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_brand` (`brand`(191))
) ENGINE=InnoDB AUTO_INCREMENT=19 DEFAULT CHARSET=utf8mb4 COMMENT='豪华品牌配置表';
-- data_report.config_brand_category definition
CREATE TABLE `config_brand_category` (
`id` bigint(20) NOT NULL AUTO_INCREMENT,
`brand` varchar(200) NOT NULL COMMENT '品牌',
`category` varchar(50) NOT NULL DEFAULT '' COMMENT '品牌区分(如 豪华/非豪华)',
`create_time` datetime DEFAULT CURRENT_TIMESTAMP,
`update_time` datetime DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
PRIMARY KEY (`id`),
UNIQUE KEY `uq_brand` (`brand`(191))
) ENGINE=InnoDB AUTO_INCREMENT=103 DEFAULT CHARSET=utf8mb4 COMMENT='豪华品牌配置表';
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(1, 'AITO', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(2, '鸿蒙智行', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(3, '奥迪', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(4, '腾势', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(5, '奔驰', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(6, '领克', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(7, 'AITO&鸿蒙', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(8, '宝马mini', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(9, '鸿蒙', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(10, '问界&鸿蒙', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(11, '问界', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(12, '腾势汽车', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(13, '红旗', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(14, '奔驰smart', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(15, '凯迪拉克', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(16, '尚界&问界', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(17, 'AITO&鸿蒙智行', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO luxury_brand_config
(id, brand_name, is_luxury, remark, created_at, updated_at, is_deleted)
VALUES(18, 'Smart', 1, '豪华品牌', NULL, NULL, 0);
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(1, 'AITO', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(2, '鸿蒙智行', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(3, '奥迪', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(4, '腾势', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(5, '奔驰', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(6, '领克', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(7, 'AITO&鸿蒙', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(8, '宝马mini', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(9, '鸿蒙', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(10, '问界&鸿蒙', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(11, '问界', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(12, '腾势汽车', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(13, '红旗', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(14, '奔驰smart', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(15, '凯迪拉克', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(16, '尚界&问界', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(17, 'AITO&鸿蒙智行', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category2
(id, brand, category, create_time, update_time)
VALUES(18, 'Smart', '豪华', '2026-09-03 11:53:39', '2026-09-03 11:53:39');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(33, 'AITO&鸿蒙智行', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(34, '鸿蒙智行', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(35, '北汽极狐', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(36, 'AITO', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(37, '极氪', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(38, '鸿蒙智行(含尚界)', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(39, '岚图', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(40, '奔驰', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(41, '极狐', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(42, '鸿蒙+尚界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(43, '阿维塔', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(44, '尚界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(45, '东风奕派', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(46, '奇瑞icar', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(47, '广汽丰田', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(48, '领克', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(49, '长安', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(50, '东风岚图', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(51, '奇瑞', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(52, '零跑', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(53, '腾势', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(54, '奥迪', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(55, '大众', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(56, '鸿蒙-尚界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(57, '东本', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(58, 'Smart', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(59, '比亚迪', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(60, '坦克', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(62, '吉利', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(63, '广汽传祺', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(64, '北京越野', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(65, '方程豹', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(66, '广汽埃安', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(67, '广汽本田', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(68, '吉利银河', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(69, '阿维塔、长安、长城、哈弗、欧拉、坦克', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(70, '银河', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(71, '上汽大众', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(72, '捷途纵横', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(73, '东风日产', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(74, '埃安', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(75, '星途', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(76, '比亚迪方程豹', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(77, '启源', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(78, '深蓝', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(79, '长安引力', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(80, 'AITO/鸿蒙智行', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(81, '智界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(82, '智已', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(83, '智己', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(84, 'AITO&鸿蒙', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(85, '鸿蒙', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(86, '捷途', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(87, '奔驰smart', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(88, '广爱埃安、广汽传祺', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(89, '鸿蒙智界', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(90, '长安汽车', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(91, '启境', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(92, '坦克,奇瑞', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(93, '长城', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(94, '欧拉', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(95, '福特', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(96, '领克、银河', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(97, '路虎', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(98, '广本', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(99, '广丰', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(100, '传祺', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(101, '品牌', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
INSERT INTO config_brand_category
(id, brand, category, create_time, update_time)
VALUES(102, '收尾接待', '豪华', '2026-09-08 09:56:53', '2026-09-08 09:56:53');
\ No newline at end of file \ No newline at end of file
...@@ -42,3 +42,8 @@ WHERE base_scene_code = '100101' ...@@ -42,3 +42,8 @@ WHERE base_scene_code = '100101'
AND deleted_flag = 'N' AND deleted_flag = 'N'
ORDER BY created_date DESC; ORDER BY created_date DESC;
-- =====================================================
-- 7. 查询园区店
-- 场景: base_scene_code='100101' 轻改
-- =====================================================
select traffic_party_name,parking_store_name from dj_car_life_merchant_store_info where base_scene_code ='100101' and deleted_flag ='N'
\ No newline at end of file \ No newline at end of file
...@@ -75,7 +75,7 @@ LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2 ...@@ -75,7 +75,7 @@ LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12) AND t2.status IN (4,6,12)
LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code LEFT JOIN `dj_car_life_pay_order` t3 ON t3.order_code=t1.order_code
WHERE t1.status = 1 WHERE t1.status = 1 and t1.del_flag='N'
AND t2.scene_type = 1 AND t2.scene_type = 1
AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59' AND t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6 and t1.dj_order_type !=6
......
...@@ -7,18 +7,25 @@ ...@@ -7,18 +7,25 @@
-- 关联表: -- 关联表:
-- gopa 利润分配主表 (子订单级, order_flag='N' 非汇总) -- gopa 利润分配主表 (子订单级, order_flag='N' 非汇总)
-- gopa2 利润分配汇总记录 (order_flag='Y', grain_size_type=1, 拿服务费/施工收入/产值) -- gopa2 利润分配汇总记录 (order_flag='Y', grain_size_type=1, 拿服务费/施工收入/产值)
-- gso 子订单表 (拿嘀加与第三方成本合计 = upgrade_dj_cost + upgrade_third_party_cost) -- gso 子订单表 (拿嘀加与第三方成本)
-- go 订单表 (scene_type / business_type / merchant_name) -- go 订单表 (scene_type / business_type / merchant_name)
-- po 支付单表 (success_date 周期过滤) -- po 支付单表 (success_date 周期过滤)
-- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901)) -- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901))
-- --
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY, order 级字段用 MAX 取单次值
-- 外层按 merchant_name GROUP BY, 全部 SUM 跨订单聚合
--
-- 字段口径: -- 字段口径:
-- 商品成本 = 嘀加与第三方成本合计 (upgrade_dj_cost + upgrade_third_party_cost) -- 商品成本 = upgrade_dj_cost + (shop_traffic_money_calculate_type=1 时才加 upgrade_third_party_cost)
-- 第三方成本仅在 GMV 口径算流量费时才计入
-- 门店分成/流量费 = shop_traffic_money (来自 gopa 主表) -- 门店分成/流量费 = shop_traffic_money (来自 gopa 主表)
-- 市场费 = 四项费用累计 (fee 子查询) -- 市场费 = 四项费用累计 (fee 子查询, 内层用 MAX 取单次值)
-- 服务费用 = 服务商金额 franchisee_profit_money (来自 gopa2 汇总记录) -- 服务费用 = 服务商金额 franchisee_profit_money (来自 gopa2, 内层用 MAX)
-- 门店产值 = total_price (来自 gopa2 汇总记录) -- 门店产值 = total_price (来自 gopa2, 内层用 MAX)
-- 其他费用 = custom_common_cost (来自 gopa2 汇总记录) -- 其他费用 = custom_common_cost (来自 gopa2, 内层用 MAX)
-- ============================================================================ -- ============================================================================
-- ========= 查询参数 ========= -- ========= 查询参数 =========
...@@ -28,62 +35,82 @@ SET @scene_type = 0; -- 固定: 0=延保/权益 ...@@ -28,62 +35,82 @@ SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 2; -- 2=延保 (1=权益, 另见 权益_财务成本分项.sql) SET @business_type = 2; -- 2=延保 (1=权益, 另见 权益_财务成本分项.sql)
SELECT SELECT
go.merchant_name AS `门店名称`, t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加与第三方成本合计 (子订单表) -- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(IFNULL(gso.upgrade_dj_cost, 0) + IFNULL(gso.upgrade_third_party_cost, 0)) SUM(t.product_cost) AS `商品成本`,
AS `商品成本`,
-- 门店分成/流量费 -- 门店分成/流量费
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS `门店分成`, SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计 (expense_category_id IN (706,808,809,901)) -- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
SUM(IFNULL(fee.total, 0)) AS `市场费`, SUM(t.market_fee) AS `市场费`,
-- 服务费用 = 服务商金额 (汇总记录) -- 服务费用 = 服务商金额
SUM(IFNULL(gopa2.franchisee_profit_money, 0)) AS `服务费用`, SUM(t.service_fee) AS `服务费用`,
-- 门店产值 (汇总记录) -- 门店产值
SUM(IFNULL(gopa2.total_price, 0)) AS `门店产值`, SUM(t.store_output_value) AS `门店产值`,
-- 其他费用 (汇总记录) -- 其他费用
SUM(IFNULL(gopa2.custom_common_cost, 0)) AS `其他费用` SUM(t.other_cost) AS `其他费用`
FROM dj_car_life_goods_order_profit_allocation gopa FROM (
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- 四项费用累计子查询: 日期 + scene_type + business_type 必须与外层同步!
SELECT SELECT
ecc.order_code, go.merchant_name,
SUM(ecc.expense_category_result) AS total gopa.order_code,
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code -- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code SUM(IFNULL(gso.upgrade_dj_cost, 0)
WHERE ecc.deleted_flag = 'N' + IF(gopa.shop_traffic_money_calculate_type = 1,
AND go.deleted_flag = 'N' IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901) SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
AND po.success_date >= @start_time
AND po.success_date <= @end_time -- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- 四项费用累计子查询: 日期 + scene_type + business_type 必须与外层同步!
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
AND go.business_type = @business_type AND go.business_type = @business_type
GROUP BY ecc.order_code AND po.success_date >= @start_time
) fee ON fee.order_code = gopa.order_code AND po.success_date <= @end_time
WHERE gopa.deleted_flag = 'N' GROUP BY go.merchant_name, gopa.order_code
AND gopa.order_flag = 'N' ) t
AND go.scene_type = @scene_type GROUP BY t.merchant_name;
AND go.business_type = @business_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name;
...@@ -6,6 +6,12 @@ ...@@ -6,6 +6,12 @@
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步) -- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- 关联表: 同 延保_财务成本分项.sql -- 关联表: 同 延保_财务成本分项.sql
-- --
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY, order 级字段用 MAX 取单次值
-- 外层按 merchant_name GROUP BY, 全部 SUM 跨订单聚合
--
-- 字段口径: 同延保 (仅 business_type 不同) -- 字段口径: 同延保 (仅 business_type 不同)
-- ============================================================================ -- ============================================================================
...@@ -16,62 +22,82 @@ SET @scene_type = 0; -- 固定: 0=延保/权益 ...@@ -16,62 +22,82 @@ SET @scene_type = 0; -- 固定: 0=延保/权益
SET @business_type = 1; -- 1=权益 (2=延保, 另见 延保_财务成本分项.sql) SET @business_type = 1; -- 1=权益 (2=延保, 另见 延保_财务成本分项.sql)
SELECT SELECT
go.merchant_name AS `门店名称`, t.merchant_name AS `门店名称`,
-- 商品成本 = 嘀加与第三方成本合计 -- 商品成本 = 嘀加成本 + 第三方成本(仅 GMV 口径 shop_traffic_money_calculate_type=1)
SUM(IFNULL(gso.upgrade_dj_cost, 0) + IFNULL(gso.upgrade_third_party_cost, 0)) SUM(t.product_cost) AS `商品成本`,
AS `商品成本`,
-- 门店分成/流量费 -- 门店分成/流量费
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS `门店分成`, SUM(t.shop_traffic_money) AS `门店分成`,
-- 市场费 = 四项费用累计 -- 市场费 = 四项费用累计 (内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合)
SUM(IFNULL(fee.total, 0)) AS `市场费`, SUM(t.market_fee) AS `市场费`,
-- 服务费用 = 服务商金额 -- 服务费用 = 服务商金额
SUM(IFNULL(gopa2.franchisee_profit_money, 0)) AS `服务费用`, SUM(t.service_fee) AS `服务费用`,
-- 门店产值 -- 门店产值
SUM(IFNULL(gopa2.total_price, 0)) AS `门店产值`, SUM(t.store_output_value) AS `门店产值`,
-- 其他费用 -- 其他费用
SUM(IFNULL(gopa2.custom_common_cost, 0)) AS `其他费用` SUM(t.other_cost) AS `其他费用`
FROM dj_car_life_goods_order_profit_allocation gopa FROM (
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type + business_type 与外层同步
SELECT SELECT
ecc.order_code, go.merchant_name,
SUM(ecc.expense_category_result) AS total gopa.order_code,
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code -- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code SUM(IFNULL(gso.upgrade_dj_cost, 0)
WHERE ecc.deleted_flag = 'N' + IF(gopa.shop_traffic_money_calculate_type = 1,
AND go.deleted_flag = 'N' IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901) SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
AND po.success_date >= @start_time
AND po.success_date <= @end_time -- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type + business_type 与外层同步
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
AND go.business_type = @business_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type AND go.scene_type = @scene_type
AND go.business_type = @business_type AND go.business_type = @business_type
GROUP BY ecc.order_code AND po.success_date >= @start_time
) fee ON fee.order_code = gopa.order_code AND po.success_date <= @end_time
WHERE gopa.deleted_flag = 'N' GROUP BY go.merchant_name, gopa.order_code
AND gopa.order_flag = 'N' ) t
AND go.scene_type = @scene_type GROUP BY t.merchant_name;
AND go.business_type = @business_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name;
...@@ -5,13 +5,21 @@ ...@@ -5,13 +5,21 @@
-- 业务: business_type = 1 OR 2 (轻改不区分) -- 业务: business_type = 1 OR 2 (轻改不区分)
-- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步) -- 日期: 支付成功时间 po.success_date BETWEEN :start AND :end (含 fee 子查询同步)
-- --
-- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积 (同店中店)
-- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY
-- - gopa/gso 级字段 → SUM(同订单多 sub_order_code 要累加)
-- - order 级字段(fee.total) → MAX(避免 JOIN 膨胀)
-- 外层按 merchant_name GROUP BY → 全部 SUM 跨订单聚合
--
-- 与"轻改店中店"的区别: -- 与"轻改店中店"的区别:
-- 园区店只消费 4 个字段 (不需要窗膜/车衣/精品/原厂/副厂/施工收入等): -- 园区店只消费 4 个字段 (不需要窗膜/车衣/精品/原厂/副厂/施工收入等):
-- 产品成本(财务列表) = dj_order_type != 6 -- 产品成本(财务列表) = dj_order_type != 6 → upgrade_shop_price - base_shop_price
-- 内部结算成本(财务列表) = dj_order_type = 6 -- 内部结算成本(财务列表) = dj_order_type = 6 → upgrade_shop_price - base_shop_price
-- 流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money -- 流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money
-- 市场费(加权测算) = 四项费用累计 -- 市场费(加权测算) = 四项费用累计 (fee 子查询, 内层用 MAX)
-- 字段口径/表关联/商品成本公式(upgrade_shop_price - base_shop_price)与店中店完全相同 -- 字段口径/表关联与店中店完全相同
-- ============================================================================ -- ============================================================================
-- ========= 查询参数 ========= -- ========= 查询参数 =========
...@@ -20,61 +28,77 @@ SET @end_time = '2026-08-31 23:59:59'; ...@@ -20,61 +28,77 @@ SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 1; -- 固定: 1=轻改 SET @scene_type = 1; -- 固定: 1=轻改
SELECT SELECT
go.merchant_name AS `门店名称`, t.merchant_name AS `门店名称`,
-- ===== 产品成本口径: upgrade_shop_price - base_shop_price ===== -- ===== 产品成本口径: upgrade_shop_price - base_shop_price =====
-- 外层 SUM 跨订单聚合, 内层已按 merchant_name + order_code 聚合好
-- 产品成本(财务列表) = 非内部结算 dj_order_type != 6 SUM(t.product_cost_finance) AS `产品成本(财务列表)`,
SUM(CASE WHEN gso.dj_order_type != 6 SUM(t.internal_settle_cost) AS `内部结算成本(财务列表)`,
THEN gso.upgrade_shop_price - gso.base_shop_price SUM(t.store_share) AS `流量费(财务列表)`,
ELSE 0 END) AS `产品成本(财务列表)`,
-- 内部结算成本(财务列表) = 内部结算 dj_order_type = 6 -- order 级字段: 内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合
SUM(CASE WHEN gso.dj_order_type = 6 SUM(t.market_fee) AS `市场费`
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `内部结算成本(财务列表)`,
-- 流量费(财务列表) = 非内部结算的 shop_traffic_money FROM (
SUM(CASE WHEN gso.dj_order_type != 6 SELECT
THEN IFNULL(gopa.shop_traffic_money, 0) go.merchant_name,
ELSE 0 END) AS `流量费(财务列表)`, gopa.order_code,
-- 市场费(加权测算) = 四项费用累计 (fee 子查询) -- ===== 内层: 按 merchant_name + order_code GROUP BY =====
SUM(IFNULL(fee.total, 0)) AS `市场费` -- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
FROM dj_car_life_goods_order_profit_allocation gopa SUM(CASE WHEN gso.dj_order_type != 6
INNER JOIN dj_car_life_goods_order go THEN gso.upgrade_shop_price - gso.base_shop_price
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N' ELSE 0 END) AS product_cost_finance,
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N' SUM(CASE WHEN gso.dj_order_type = 6
LEFT JOIN dj_car_life_goods_sub_order gso THEN gso.upgrade_shop_price - gso.base_shop_price
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N' ELSE 0 END) AS internal_settle_cost,
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code SUM(CASE WHEN gso.dj_order_type != 6
AND gopa2.order_flag = 'Y' THEN IFNULL(gopa.shop_traffic_money, 0)
AND gopa2.grain_size_type = 1 ELSE 0 END) AS store_share,
AND gopa2.deleted_flag = 'N'
LEFT JOIN ( -- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
-- fee 子查询: 日期 + scene_type 与外层同步 MAX(IFNULL(fee.total, 0)) AS market_fee
SELECT
ecc.order_code, FROM dj_car_life_goods_order_profit_allocation gopa
SUM(ecc.expense_category_result) AS total INNER JOIN dj_car_life_goods_order go
FROM dj_car_life_order_expense_category_calculated ecc ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code INNER JOIN dj_car_life_pay_order po
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code ON go.order_code = po.order_code AND po.deleted_flag = 'N'
WHERE ecc.deleted_flag = 'N' LEFT JOIN dj_car_life_goods_sub_order gso
AND go.deleted_flag = 'N' ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
AND po.deleted_flag = 'N' LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
AND ecc.expense_category_id IN (706, 808, 809, 901) ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND po.success_date >= @start_time AND po.success_date >= @start_time
AND po.success_date <= @end_time AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N' GROUP BY go.merchant_name, gopa.order_code
AND gopa.order_flag = 'N' ) t
AND go.scene_type = @scene_type GROUP BY t.merchant_name;
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name;
...@@ -12,21 +12,25 @@ ...@@ -12,21 +12,25 @@
-- po 支付单表 (success_date 周期过滤) -- po 支付单表 (success_date 周期过滤)
-- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901)) -- fee 子查询: 四项费用累计 (expense_category IN (706,808,809,901))
-- --
-- 关键差异 (与延保/权益对比): -- 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
-- 商品成本口径不同! 轻改用 upgrade_shop_price - base_shop_price -- gopa 是子订单级 (一个 order_code 多条 gopa 记录), fee/gopa2 是订单级
-- 延保/权益用 upgrade_dj_cost + upgrade_third_party_cost -- 直接 LEFT JOIN 会导致 fee.total / gopa2 字段被重复 SUM 多次
-- 内层按 merchant_name + order_code GROUP BY
-- - gopa/gso 级字段 → SUM(同订单多 sub_order_code 要累加)
-- - order 级字段(fee.total, gopa2.custom_common_cost) → MAX(避免 JOIN 膨胀)
-- 外层按 merchant_name GROUP BY → 全部 SUM 跨订单聚合
-- --
-- 字段口径 (店中店消费全部 10 项): -- 字段口径 (店中店消费全部 10 项):
-- 产品成本(财务列表) = dj_order_type != 6 (非内部结算) 的商品成本 -- 产品成本(财务列表) = dj_order_type != 6 (非内部结算) 的 upgrade_shop_price - base_shop_price
-- 内部结算成本(财务列表) = dj_order_type = 6 (内部结算) 的商品成本 -- 内部结算成本(财务列表) = dj_order_type = 6 (内部结算) 的 upgrade_shop_price - base_shop_price
-- 原厂产品成本(财务列表) = dj_order_type != 6 + goods_name LIKE '%AITO%' OR '%HIMA%' -- 原厂产品成本(财务列表) = dj_order_type != 6 + goods_name LIKE '%AITO%' OR '%HIMA%'
-- 副厂产品成本(财务列表) = dj_order_type != 6 + goods_name NOT LIKE '%AITO%' AND NOT LIKE '%HIMA%' -- 副厂产品成本(财务列表) = dj_order_type != 6 + goods_name NOT LIKE '%AITO%' AND NOT LIKE '%HIMA%'
-- 窗膜成本 = upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜') -- 窗膜成本 = upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
-- 车衣成本 = upgrade_goods_type_name IN ('车衣','改色膜') -- 车衣成本 = upgrade_goods_type_name IN ('车衣','改色膜')
-- 精品成本 = upgrade_goods_type_name NOT IN (窗膜/车衣 所有类型) -- 精品成本 = upgrade_goods_type_name NOT IN (窗膜/车衣 所有类型)
-- 门店分成/流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money -- 门店分成/流量费(财务列表) = dj_order_type != 6 的 shop_traffic_money
-- 施工收入 = custom_common_cost (汇总记录 gopa2) -- 施工收入 = custom_common_cost (汇总记录 gopa2, 内层用 MAX)
-- 市场费 = 四项费用累计 (fee 子查询) -- 市场费 = 四项费用累计 (fee 子查询, 内层用 MAX)
-- ============================================================================ -- ============================================================================
-- ========= 查询参数 ========= -- ========= 查询参数 =========
...@@ -35,93 +39,108 @@ SET @end_time = '2026-08-31 23:59:59'; ...@@ -35,93 +39,108 @@ SET @end_time = '2026-08-31 23:59:59';
SET @scene_type = 1; -- 固定: 1=轻改 SET @scene_type = 1; -- 固定: 1=轻改
SELECT SELECT
go.merchant_name AS `门店名称`, t.merchant_name AS `门店名称`,
-- ===== 产品成本口径: upgrade_shop_price - base_shop_price ===== -- ===== 产品成本口径: upgrade_shop_price - base_shop_price =====
-- 外层 SUM 跨订单聚合, 内层已按 merchant_name + order_code 聚合好
-- 产品成本(财务列表) = 非内部结算 dj_order_type != 6 SUM(t.product_cost_finance) AS `产品成本(财务列表)`,
SUM(CASE WHEN gso.dj_order_type != 6 SUM(t.internal_settle_cost) AS `内部结算成本(财务列表)`,
THEN gso.upgrade_shop_price - gso.base_shop_price SUM(t.oe_product_cost) AS `原厂产品成本(财务列表)`,
ELSE 0 END) AS `产品成本(财务列表)`, SUM(t.nonoe_product_cost) AS `副厂产品成本(财务列表)`,
SUM(t.window_film_cost) AS `窗膜成本`,
-- 内部结算成本(财务列表) = 内部结算 dj_order_type = 6 SUM(t.car_wrap_cost) AS `车衣成本`,
SUM(CASE WHEN gso.dj_order_type = 6 SUM(t.premium_cost) AS `精品成本`,
THEN gso.upgrade_shop_price - gso.base_shop_price SUM(t.store_share) AS `门店分成/流量费(财务列表)`,
ELSE 0 END) AS `内部结算成本(财务列表)`,
-- order 级字段: 内层 MAX 避免 JOIN 膨胀, 外层 SUM 跨订单聚合
-- 原厂产品成本(财务列表) = 非内部结算 + goods_name 含 AITO/HIMA SUM(t.construction_income) AS `施工收入`,
SUM(CASE WHEN gso.dj_order_type != 6 SUM(t.market_fee) AS `市场费`
AND (gso.upgrade_goods_name LIKE '%AITO%'
OR gso.upgrade_goods_name LIKE '%HIMA%') FROM (
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `原厂产品成本(财务列表)`,
-- 副厂产品成本(财务列表) = 非内部结算 + goods_name 不含 AITO/HIMA
SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `副厂产品成本(财务列表)`,
-- 窗膜成本 (品类 = 太阳膜/天窗冰甲)
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `窗膜成本`,
-- 车衣成本 (品类 = 车衣/改色膜)
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('车衣','改色膜')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `车衣成本`,
-- 精品成本 (排除所有已归类品类)
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN ('自建商品-太阳膜','天窗冰甲','太阳膜','车衣','改色膜','踏板','充电桩','验收一级类目')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS `精品成本`,
-- 门店分成/流量费(财务列表) = 非内部结算的 shop_traffic_money
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS `门店分成/流量费(财务列表)`,
-- 施工收入 = custom_common_cost (汇总记录 gopa2)
SUM(IFNULL(gopa2.custom_common_cost, 0)) AS `施工收入`,
-- 市场费 = 四项费用累计 (fee 子查询)
SUM(IFNULL(fee.total, 0)) AS `市场费`
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT SELECT
ecc.order_code, go.merchant_name,
SUM(ecc.expense_category_result) AS total gopa.order_code,
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code -- ===== 内层: 按 merchant_name + order_code GROUP BY =====
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code -- gopa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N' SUM(CASE WHEN gso.dj_order_type != 6
AND po.deleted_flag = 'N' THEN gso.upgrade_shop_price - gso.base_shop_price
AND ecc.expense_category_id IN (706, 808, 809, 901) ELSE 0 END) AS product_cost_finance,
SUM(CASE WHEN gso.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS internal_settle_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND (gso.upgrade_goods_name LIKE '%AITO%'
OR gso.upgrade_goods_name LIKE '%HIMA%')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS oe_product_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS nonoe_product_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('自建商品-太阳膜','天窗冰甲','太阳膜')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS window_film_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN ('车衣','改色膜')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS car_wrap_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN ('自建商品-太阳膜','天窗冰甲','太阳膜','车衣','改色膜','踏板','充电桩','验收一级类目')
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS premium_cost,
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS store_share,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS construction_income,
MAX(IFNULL(fee.total, 0)) AS market_fee
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
-- fee 子查询: 日期 + scene_type 与外层同步 (轻改无 business_type 过滤)
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
WHERE ecc.deleted_flag = 'N'
AND go.deleted_flag = 'N'
AND po.deleted_flag = 'N'
AND ecc.expense_category_id IN (706, 808, 809, 901)
AND po.success_date >= @start_time
AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND po.success_date >= @start_time AND po.success_date >= @start_time
AND po.success_date <= @end_time AND po.success_date <= @end_time
AND go.scene_type = @scene_type
GROUP BY ecc.order_code GROUP BY go.merchant_name, gopa.order_code
) fee ON fee.order_code = gopa.order_code ) t
GROUP BY t.merchant_name;
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = @scene_type
AND po.success_date >= @start_time
AND po.success_date <= @end_time
GROUP BY go.merchant_name;
...@@ -61,9 +61,10 @@ class IndicatorClient: ...@@ -61,9 +61,10 @@ class IndicatorClient:
参数: 参数:
- start_date: str 'YYYY-MM-DD' - start_date: str 'YYYY-MM-DD'
- end_date: str 'YYYY-MM-DD' - end_date: str 'YYYY-MM-DD'
- biz: int 单值(1=延保 2=轻改 3=权益) 或 list/tuple(如 [1,3] 多业务线); - biz: int 单值(1=延保 2=轻改 3=权益) 或 list/tuple(如 [1,3] 多业务线);
多值会序列化为逗号字符串 bizs="1,3"(与 itemCodes 风格一致); 多值会序列化为逗号字符串 bizs="1,3"(与 itemCodes 风格一致);
单值仍走原 "biz" 键,向后兼容现有调用方。 单值序列化为 bizs="N"(API 仅认 bizs 键,不再有 "biz" 单数形式);
None 表示不限定业务线 → 不传 bizs 键、查全量(A0018 全国经营总产值用此)。
- item_codes: list[str] 指标编码列表,如 ['A036', 'A075'] - item_codes: list[str] 指标编码列表,如 ['A036', 'A075']
- rate_codes: set[str] 率类指标编码,API 返回小数会 *100;None 则用 RATE_CODES 默认 - rate_codes: set[str] 率类指标编码,API 返回小数会 *100;None 则用 RATE_CODES 默认
...@@ -83,11 +84,13 @@ class IndicatorClient: ...@@ -83,11 +84,13 @@ class IndicatorClient:
"exts": "merchantIds", "exts": "merchantIds",
"itemCodes": ",".join(item_codes), "itemCodes": ",".join(item_codes),
} }
# biz 支持单值(int) / 多值(list):多业务线按约定序列化为逗号字符串 bizs="1,3" # biz=None 表示查全量:不要传 bizs 键,否则 API 把 "None" 当无效业务线过滤返回空
if isinstance(biz, (list, tuple, set)): if biz is None:
pass # 不传 bizs → 返回全业务线全量
elif isinstance(biz, (list, tuple, set)):
payload["bizs"] = ",".join(str(b) for b in biz) payload["bizs"] = ",".join(str(b) for b in biz)
else: else:
payload["biz"] = biz payload["bizs"] = str(biz)
last_err = None last_err = None
# 请求参数日志 # 请求参数日志
......
...@@ -25,7 +25,7 @@ from report_utils import ( ...@@ -25,7 +25,7 @@ from report_utils import (
parse_inshop_delivery_touch, parse_commerce_policy_inshop, parse_inshop_delivery_touch, parse_commerce_policy_inshop,
parse_labor_cost, is_luxury_brand, parse_labor_cost, is_luxury_brand,
parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period, parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats, fuzzy_match_store, fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats, fetch_park_name_map, fuzzy_match_store, exact_match_store,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal, get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
from models import ReportLightReformInshop, db from models import ReportLightReformInshop, db
...@@ -163,13 +163,13 @@ class LightReformInshopProcessor: ...@@ -163,13 +163,13 @@ class LightReformInshopProcessor:
goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end) goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end)
# 2d. 财务成本分项(店中店+园区店共用 SQL,按 dj_order_type + 品类 + 原厂/副厂切分) # 2d. 财务成本分项(店中店+园区店共用 SQL,按 dj_order_type + 品类 + 原厂/副厂切分)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1) finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 2b. 模糊匹配到门店 → 组装 sql_data dict(get_with_fallback 双优先用) # 2b. 精确匹配系统数据(系统 merchant_name 命名规范,精确避免误匹配)
biz_sql_data = {} biz_sql_data = {}
for rec in base_records: for rec in base_records:
sn = rec.get('store_name', '') sn = rec.get('store_name', '')
dr = fuzzy_match_store(sn, daily_report_map) or {} dr = exact_match_store(sn, daily_report_map) or {}
gs = fuzzy_match_store(sn, goods_stats_map) or {} gs = exact_match_store(sn, goods_stats_map) or {}
fs = fuzzy_match_store(sn, finance_map) or {} fs = exact_match_store(sn, finance_map) or {}
biz_sql_data[sn] = { biz_sql_data[sn] = {
# —— 日报类(来自 fetch_park_daily_report)—— # —— 日报类(来自 fetch_park_daily_report)——
'delivery_cnt': dr.get('delivery_cnt', 0), 'delivery_cnt': dr.get('delivery_cnt', 0),
...@@ -203,11 +203,26 @@ class LightReformInshopProcessor: ...@@ -203,11 +203,26 @@ class LightReformInshopProcessor:
'store_share': fs.get('store_share', Decimal('0')), 'store_share': fs.get('store_share', Decimal('0')),
'construction_income': fs.get('construction_income', Decimal('0')), 'construction_income': fs.get('construction_income', Decimal('0')),
'market_fee': fs.get('market_fee', Decimal('0')), 'market_fee': fs.get('market_fee', Decimal('0')),
'mgmt_market_fee': fs.get('mgmt_market_fee', Decimal('0')),
'sunshine_incentive_fee': fs.get('sunshine_incentive_fee', Decimal('0')),
} }
# ========== Step3: 上月预算明细(已在 Step1 从 Excel 解析) ========== # ========== Step3: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map prev_budget_map = budget_achieve_map
# ========== Step4.5: store_name → park_name 映射(系统表优先,与园区店同逻辑) ==========
park_name_sys_map = fetch_park_name_map(base_scene_code='100101')
store_to_park = {}
for rec in base_records:
sn = rec.get('store_name', '')
store_to_park[sn] = (
park_name_sys_map.get(sn) # 精确匹配
or rec.get('park_name', '') # Excel 原值兜底
)
_hit = sum(1 for v in store_to_park.values() if v)
logger.info(f"[park_name-inshop] store_to_park 映射 {_hit}/{len(store_to_park)} 有值, "
f"sample={list(store_to_park.items())[:5]}")
# ========== Step5: 逐行计算 ========== # ========== Step5: 逐行计算 ==========
rows_to_insert = [] rows_to_insert = []
for rec in base_records: for rec in base_records:
...@@ -267,7 +282,8 @@ class LightReformInshopProcessor: ...@@ -267,7 +282,8 @@ class LightReformInshopProcessor:
store_share = sql_data.get('store_share', Decimal('0')) store_share = sql_data.get('store_share', Decimal('0'))
construction_income = sql_data.get('construction_income', Decimal('0')) construction_income = sql_data.get('construction_income', Decimal('0'))
market_fee_raw = sql_data.get('market_fee', Decimal('0')) mgmt_market_fee = sql_data.get('mgmt_market_fee', Decimal('0'))
sunshine_incentive_fee = sql_data.get('sunshine_incentive_fee', Decimal('0'))
# —— 商务政策(店中店)—— # —— 商务政策(店中店)——
# 先精确匹配,失败则 fuzzy 包含匹配 # 先精确匹配,失败则 fuzzy 包含匹配
...@@ -299,8 +315,9 @@ class LightReformInshopProcessor: ...@@ -299,8 +315,9 @@ class LightReformInshopProcessor:
store_consumables = prorate_by_period( store_consumables = prorate_by_period(
extract_budget_ratio(prev_budget_map, sn, 'store_consumables'), extract_budget_ratio(prev_budget_map, sn, 'store_consumables'),
period_start, period_end) period_start, period_end)
# 服务费占比:直接取(比例值不摊销) # 服务费占比:直营店强制 0,服务商直接取(与 park_processor 对齐)
sp_ratio = extract_budget_ratio(prev_budget_map, sn, 'service_provider_share_ratio') sp_ratio = Decimal('0') if operate_type == '直营' else extract_budget_ratio(
prev_budget_map, sn, 'service_provider_share_ratio')
# —— 人力成本 —— # —— 人力成本 ——
headcount = labor_map.get(sn, 0) headcount = labor_map.get(sn, 0)
...@@ -377,16 +394,21 @@ class LightReformInshopProcessor: ...@@ -377,16 +394,21 @@ class LightReformInshopProcessor:
product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_output_value) product_cost_ratio = safe_div_pct_decimal(product_cost_finance, store_output_value)
# 市场费:若一线激励存在(不为 0),则只算管理层市场费1+2 # 市场费:若一线激励存在(> 0),则只算管理层市场费1+2;否则管理层+阳光激励全算
# 这里 market_fee_raw 已经是 TODO 占位值,先原样取 if frontline_incentive and frontline_incentive > 0:
market_fee = market_fee_raw market_fee = mgmt_market_fee
else:
market_fee = mgmt_market_fee + sunshine_incentive_fee
market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value) market_fee_ratio = safe_div_pct_decimal(market_fee, store_output_value)
# 营销人员成本 # 营销人员成本
marketing_personnel_cost = Decimal('0') marketing_personnel_cost = Decimal('0')
if operate_type == '直营': if operate_type == '直营':
# 底薪 3500 元/人/月,按统计周期天数折算:3500 * 周期天数 / 月份总天数
# (周期天数 = period_end - period_start + 1,含首尾;月份总天数 = period_start 所在月天数)
base_salary_prorated = prorate_by_period(Decimal('3500'), period_start, period_end)
marketing_personnel_cost = ( marketing_personnel_cost = (
Decimal(str(headcount)) * Decimal('3500') + Decimal(str(headcount)) * base_salary_prorated +
store_output_value * Decimal('0.04') store_output_value * Decimal('0.04')
) )
marketing_personnel_ratio = safe_div_pct_decimal(marketing_personnel_cost, store_output_value) marketing_personnel_ratio = safe_div_pct_decimal(marketing_personnel_cost, store_output_value)
...@@ -417,9 +439,9 @@ class LightReformInshopProcessor: ...@@ -417,9 +439,9 @@ class LightReformInshopProcessor:
task_id=task_id, period_start=period_start, period_end=period_end, task_id=task_id, period_start=period_start, period_end=period_end,
# 基础维度 # 基础维度
region_area=region_area, province=province, city=rec.get('city', ''), region_area=region_area, province=province, city=rec.get('city', ''),
park_type=rec.get('park_type', ''), biz_line=rec.get('biz_line', '1.12'), park_type=(rec.get('park_type') or '店中店'), biz_line=rec.get('biz_line', '1.12'),
operate_type=operate_type, region_manager=rec.get('region_manager', ''), operate_type=operate_type, region_manager=rec.get('region_manager', ''),
park_name=rec.get('park_name', ''), store_name=sn, brand=brand, park_name=store_to_park.get(sn, ''), store_name=sn, brand=brand,
brand_category=brand_category, purchase_indicator=purchase_indicator, brand_category=brand_category, purchase_indicator=purchase_indicator,
# 销售 # 销售
sales_order_cnt=sales_order_cnt, sales_touch_cnt=sales_touch_cnt, sales_order_cnt=sales_order_cnt, sales_touch_cnt=sales_touch_cnt,
......
...@@ -31,8 +31,8 @@ from report_utils import ( ...@@ -31,8 +31,8 @@ from report_utils import (
parse_park_delivery_touch, parse_commerce_policy_park, parse_park_delivery_touch, parse_commerce_policy_park,
parse_labor_cost, is_luxury_brand, parse_labor_cost, is_luxury_brand,
parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period, parse_budget_achieve_excel, extract_budget_ratio, prorate_by_period,
fetch_indicator_data, fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_indicator_data, fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats,
fetch_light_reform_finance_stats, fetch_est_delivery_count, fuzzy_match_store, fetch_est_delivery_count, fetch_park_name_map, fuzzy_match_store, exact_match_store,
get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal, get_with_fallback, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
from models import ReportLightReformPark, db from models import ReportLightReformPark, db
...@@ -168,13 +168,15 @@ class LightReformParkProcessor: ...@@ -168,13 +168,15 @@ class LightReformParkProcessor:
est_delivery_map = fetch_est_delivery_count(base_scene_code='100101') est_delivery_map = fetch_est_delivery_count(base_scene_code='100101')
# 3d. 财务成本分项(店中店+园区店共用 SQL,park 侧仅消费 4 项) # 3d. 财务成本分项(店中店+园区店共用 SQL,park 侧仅消费 4 项)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1) finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 3e. 模糊匹配到门店 → 组装 sql_data dict # 3e. 园区店名称(系统表 dj_car_life_merchant_store_info → parking_store_name)
park_name_sys_map = fetch_park_name_map(base_scene_code='100101')
# 3e. 精确匹配系统数据 → 组装 sql_data dict
biz_sql_data = {} biz_sql_data = {}
for rec in base_records: for rec in base_records:
sn = rec.get('store_name', '') sn = rec.get('store_name', '')
dr = fuzzy_match_store(sn, daily_report_map) or {} dr = exact_match_store(sn, daily_report_map) or {}
gs = fuzzy_match_store(sn, goods_stats_map) or {} gs = exact_match_store(sn, goods_stats_map) or {}
fs = fuzzy_match_store(sn, finance_map) or {} fs = exact_match_store(sn, finance_map) or {}
eq = dr.get('equity_to_shop_count', 0) eq = dr.get('equity_to_shop_count', 0)
af = dr.get('after_sale_equity_to_shop_count', 0) af = dr.get('after_sale_equity_to_shop_count', 0)
biz_sql_data[sn] = { biz_sql_data[sn] = {
...@@ -191,7 +193,7 @@ class LightReformParkProcessor: ...@@ -191,7 +193,7 @@ class LightReformParkProcessor:
'store_sales_output': gs.get('store_output_value', Decimal('0')), 'store_sales_output': gs.get('store_output_value', Decimal('0')),
'internal_settle_value': gs.get('internal_settle_value', Decimal('0')), 'internal_settle_value': gs.get('internal_settle_value', Decimal('0')),
# —— 预估交车数(来自 fetch_est_delivery_count)—— # —— 预估交车数(来自 fetch_est_delivery_count)——
'est_delivery_cnt': fuzzy_match_store(sn, est_delivery_map) or 0, 'est_delivery_cnt': exact_match_store(sn, est_delivery_map) or 0,
# —— 财务分项(park 仅消费产品成本/内部结算成本/流量费/市场费)—— # —— 财务分项(park 仅消费产品成本/内部结算成本/流量费/市场费)——
'product_cost_finance': fs.get('product_cost_finance', Decimal('0')), 'product_cost_finance': fs.get('product_cost_finance', Decimal('0')),
'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')), 'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')),
...@@ -203,36 +205,82 @@ class LightReformParkProcessor: ...@@ -203,36 +205,82 @@ class LightReformParkProcessor:
# ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ========== # ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map prev_budget_map = budget_achieve_map
# ========== Step5: 合作门店数量(按 park_name 聚合) ========== # ========== Step4.5: store_name → park_name 映射(系统表优先,用于 Step6 输出) ==========
from collections import Counter store_to_park = {}
park_counter = Counter(r.get('park_name', '') for r in base_records if r.get('park_name')) for rec in base_records:
sn = rec.get('store_name', '')
store_to_park[sn] = (
park_name_sys_map.get(sn) # 精确匹配
or rec.get('park_name', '') # Excel 原值兜底
)
_hit = sum(1 for v in store_to_park.values() if v)
logger.info(f"[park_name] store_to_park 映射 {_hit}/{len(store_to_park)} 有值, "
f"sample={list(store_to_park.items())[:5]}")
# ========== Step5.5: 预计算每个 park 的预估交车数合计(用于同 park 多门店分摊预估产值纠偏)========== # ========== Step5: 合作门店数量 + park 预估交车合计(保持原逻辑) ==========
# 分摊基数:Excel 第一优先,SQL/配置表回退(与循环内 est_delivery_cnt 取值逻辑一致) from collections import Counter
park_counter = Counter(p for p in store_to_park.values() if p)
park_est_delivery_total = {} park_est_delivery_total = {}
for rec in base_records: for rec in base_records:
pn = rec.get('park_name', '')
sn = rec.get('store_name', '') sn = rec.get('store_name', '')
pn = store_to_park.get(sn, '')
est = int(get_with_fallback( est = int(get_with_fallback(
rec.get('est_delivery_cnt', 0), rec.get('est_delivery_cnt', 0),
get_with_fallback( get_with_fallback(
fuzzy_match_store(sn, est_delivery_map) or 0, exact_match_store(sn, est_delivery_map) or 0,
fuzzy_match_store(sn, biz_sql_data).get('est_delivery_cnt', 0), biz_sql_data.get(sn, {}).get('est_delivery_cnt', 0),
), ),
) or 0) ) or 0)
park_est_delivery_total[pn] = park_est_delivery_total.get(pn, 0) + est park_est_delivery_total[pn] = park_est_delivery_total.get(pn, 0) + est
# ========== Step5.5: 识别合并组(Excel 合并单元格) ==========
# 按物理行顺序:est_output_value > 0 的行是"头行",后面连续 est=0 的行属于同一合并组
from decimal import Decimal as _D
merge_groups = []
cur_group = None
for rec in base_records:
sn = rec.get('store_name', '')
est_val = rec.get('est_output_value', _D('0')) or _D('0')
est_del = int(rec.get('est_delivery_cnt', 0) or 0)
if est_val > 0:
if cur_group is not None:
merge_groups.append(cur_group)
cur_group = {
'head_est': est_val,
'stores': [sn],
'deliveries': {sn: est_del},
}
else:
if cur_group is None:
cur_group = {'head_est': _D('0'), 'stores': [sn], 'deliveries': {sn: est_del}}
else:
cur_group['stores'].append(sn)
cur_group['deliveries'][sn] = est_del
if cur_group is not None:
merge_groups.append(cur_group)
store_to_group = {}
for g in merge_groups:
for sn in g['stores']:
store_to_group[sn] = g
multi_groups = [g for g in merge_groups if len(g['stores']) > 1]
logger.info(f"[合并行] 共 {len(merge_groups)} 个合并组, 其中 {len(multi_groups)} 个是多门店组:")
for g in multi_groups:
logger.info(f" head_est={g['head_est']}, stores={g['stores']}")
# ========== Step6: 逐行计算 ========== # ========== Step6: 逐行计算 ==========
rows_to_insert = [] rows_to_insert = []
for rec in base_records: for rec in base_records:
sn = rec.get('store_name', '') sn = rec.get('store_name', '')
province = rec.get('province', '') province = rec.get('province', '')
park_name = rec.get('park_name', '') park_name = store_to_park.get(sn, '')
operate_type = rec.get('operate_type', '') operate_type = rec.get('operate_type', '')
brand = rec.get('brand', '') brand = rec.get('brand', '')
region_area = region_map.get(('', province), '') region_area = region_map.get(('', province), '')
biz_type = is_luxury_brand(brand) # 类型=豪华/非豪华 biz_type = is_luxury_brand(brand)
partner_store_cnt = park_counter.get(park_name, 1) partner_store_cnt = park_counter.get(park_name, 1)
# —— Excel 第一优先 / SQL 回退 —— # —— Excel 第一优先 / SQL 回退 ——
...@@ -295,22 +343,18 @@ class LightReformParkProcessor: ...@@ -295,22 +343,18 @@ class LightReformParkProcessor:
total_output_value = store_sales_output + internal_settle_value total_output_value = store_sales_output + internal_settle_value
# 产值达成进度(预估总产值 = 预估产值纠偏按同 park 多门店的预估交车数占比分摊) # 产值达成进度:从合并组取头行预估产值,多门店合并组按预估交车数占比分摊
est_output_value_raw = rec.get('est_output_value', Decimal('0')) group = store_to_group.get(sn)
est_output_value = est_output_value_raw group_head_est = group['head_est'] if group else (rec.get('est_output_value', Decimal('0')) or Decimal('0'))
if est_output_value_raw and est_output_value_raw > 0: est_output_value = group_head_est
# 同 park 多门店共用一个纠偏值 → 按预估交车数占比分摊
park_total_est = park_est_delivery_total.get(park_name, 0) if group and len(group['stores']) > 1 and group_head_est > 0:
if partner_store_cnt > 1 and park_total_est > 0: # 多门店合并组 → 按预估交车数占比分摊
store_est_delivery = int(get_with_fallback( group_total_del = sum(group['deliveries'].values())
rec.get('est_delivery_cnt', 0), store_del = group['deliveries'].get(sn, 0)
get_with_fallback( if group_total_del > 0:
fuzzy_match_store(sn, est_delivery_map) or 0, est_output_value = (group_head_est
sql_data.get('est_delivery_cnt', 0), * Decimal(store_del) / Decimal(group_total_del)
),
) or 0)
est_output_value = (est_output_value_raw
* Decimal(store_est_delivery) / Decimal(park_total_est)
).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP) ).quantize(Decimal('0.01'), rounding=ROUND_HALF_UP)
output_progress = safe_div_pct_decimal(total_output_value, est_output_value) output_progress = safe_div_pct_decimal(total_output_value, est_output_value)
...@@ -346,8 +390,11 @@ class LightReformParkProcessor: ...@@ -346,8 +390,11 @@ class LightReformParkProcessor:
# 人员成本(直营才算) # 人员成本(直营才算)
personnel_cost = Decimal('0') personnel_cost = Decimal('0')
if operate_type == '直营': if operate_type == '直营':
# 底薪 3500 元/人/月,按统计周期天数折算:3500 * 周期天数 / 月份总天数
# (周期天数 = period_end - period_start + 1,含首尾;月份总天数 = period_start 所在月天数)
base_salary_prorated = prorate_by_period(Decimal('3500'), period_start, period_end)
personnel_cost = ( personnel_cost = (
Decimal(str(headcount)) * Decimal('3500') + Decimal(str(headcount)) * base_salary_prorated +
store_sales_output * Decimal('0.04') store_sales_output * Decimal('0.04')
) )
personnel_cost_ratio = safe_div_pct_decimal(personnel_cost, store_sales_output) personnel_cost_ratio = safe_div_pct_decimal(personnel_cost, store_sales_output)
......
...@@ -456,6 +456,8 @@ class OutputValueProcessor: ...@@ -456,6 +456,8 @@ class OutputValueProcessor:
""" """
task_id = task.id task_id = task.id
stat_month = task.month or '' stat_month = task.month or ''
today_str = datetime.now().strftime('%Y%m%d')
type_name = task.data_table_type_name or task.data_table_type or 'result'
# 统计周期起止(页面参数「所属周期」的起止时间) # 统计周期起止(页面参数「所属周期」的起止时间)
period_start = getattr(task, 'period_start', None) period_start = getattr(task, 'period_start', None)
...@@ -627,10 +629,10 @@ class OutputValueProcessor: ...@@ -627,10 +629,10 @@ class OutputValueProcessor:
# ---------- 保存 + 上传 ---------- # ---------- 保存 + 上传 ----------
tmp_dir = tempfile.mkdtemp(prefix=f'output_value_result_{task_id}_') tmp_dir = tempfile.mkdtemp(prefix=f'output_value_result_{task_id}_')
try: try:
excel_path = os.path.join(tmp_dir, f'产值达成表_{stat_month}.xlsx') excel_path = os.path.join(tmp_dir, f'{type_name}_{today_str}.xlsx')
wb.save(excel_path) wb.save(excel_path)
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}" object_key = (f"data-process/{today_str}"
f"/output_value_{stat_month}_{task_id}.xlsx") f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key) file_url = upload_file(excel_path, object_key)
logger.info(f"[产值达成] 结果表已生成并上传: {file_url}({len(rows)} 行明细)") logger.info(f"[产值达成] 结果表已生成并上传: {file_url}({len(rows)} 行明细)")
return file_url return file_url
......
...@@ -84,15 +84,17 @@ TITLE_TO_BIZ = { ...@@ -84,15 +84,17 @@ TITLE_TO_BIZ = {
# fee_col: 'market_fee' 表示取"市场费"列,'market_fee_total' 表示取"市场费总额"列 # fee_col: 'market_fee' 表示取"市场费"列,'market_fee_total' 表示取"市场费总额"列
SHEET_BIZ_MAP = [ SHEET_BIZ_MAP = [
# 1.1 业务:太阳膜、龙南系列 # 1.1 业务:太阳膜、龙南系列
{'pattern': '太阳膜-赛力斯', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'}, # 赛力斯用市场费总额 {'pattern': '太阳膜-赛力斯', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'}, # 赛力斯用市场费总额
{'pattern': '太阳膜', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'}, # 其他太阳膜用市场费 {'pattern': '太阳膜', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'}, # 其他太阳膜用市场费
{'pattern': '^龙南$', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'}, # 2.1 业务:权益、续保 —— 精确规则放前面,避免被模糊规则拦截
{'pattern': '龙南-', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'}, # 龙南-权益等 {'pattern': '龙南-权益', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'}, # 龙南下的权益=2.1+市场费
# 2.1 业务:权益、续保 {'pattern': '权益', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'}, # 权益默认取总额,Title行修正
{'pattern': '^权益$', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee_total'}, {'pattern': '续保', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'},
{'pattern': '续保', 'biz_type': BIZ_TYPE_2_1, 'fee_col': 'market_fee'}, # 2.3 业务:延保
# 2.3 业务:延保 {'pattern': '延保', 'biz_type': BIZ_TYPE_2_3, 'fee_col': 'market_fee'},
{'pattern': '延保', 'biz_type': BIZ_TYPE_2_3, 'fee_col': 'market_fee'}, # 1.1 业务:龙南系列(排除权益后)
{'pattern': '^龙南$', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee'},
{'pattern': '龙南-', 'biz_type': BIZ_TYPE_1_1, 'fee_col': 'market_fee_total'},
] ]
# 跳过的 Sheet 名称关键词 # 跳过的 Sheet 名称关键词
...@@ -1799,6 +1801,18 @@ class DataProcessor: ...@@ -1799,6 +1801,18 @@ class DataProcessor:
if not records: if not records:
return [] return []
# 预构建 2-tuple 索引:(flow_key, biz) → [(brand, gmv_ratio, GMV)]
# flow_key 同时存原始名和 to_standard 后的值,双向可查
flat_index = defaultdict(list)
for (sf, sb, sbr), data in settlement_map.items():
if not (sf and sb and sbr):
continue
entry = (sbr, data.get("gmv_ratio"), data["GMV"])
flat_index[(sf, sb)].append(entry)
std_f = to_standard(sf, '4s')
if std_f and std_f != sf:
flat_index[(std_f, sb)].append(entry)
# 按 (流量方, 业务类型) 分组 # 按 (流量方, 业务类型) 分组
groups = defaultdict(list) groups = defaultdict(list)
for r in records: for r in records:
...@@ -1807,9 +1821,17 @@ class DataProcessor: ...@@ -1807,9 +1821,17 @@ class DataProcessor:
result = [] result = []
for (flow, biz), group_records in groups.items(): for (flow, biz), group_records in groups.items():
# 取预构建的 flat_entries,并按品牌去重(to_standard 可能引入重复 brand)
raw_entries = flat_index.get((flow, biz), [])
seen_brands = set()
flat_entries = []
for e in raw_entries:
if e[0] not in seen_brands:
seen_brands.add(e[0])
flat_entries.append(e)
# 按品牌汇总费用 # 按品牌汇总费用
brand_fees = defaultdict(Decimal) # {品牌: 费用合计} brand_fees = defaultdict(Decimal) # {品牌: 费用合计}
brand_records = defaultdict(list) # {品牌: [原始记录列表]}
unknown_brand_fee = Decimal("0") # 未知品牌的费用总和 unknown_brand_fee = Decimal("0") # 未知品牌的费用总和
for r in group_records: for r in group_records:
...@@ -1819,7 +1841,6 @@ class DataProcessor: ...@@ -1819,7 +1841,6 @@ class DataProcessor:
unknown_brand_fee += fee unknown_brand_fee += fee
else: else:
brand_fees[brand] += fee brand_fees[brand] += fee
brand_records[brand].append(r)
# 诊断日志:分摊前的品牌费用(仅针对特定流量方) # 诊断日志:分摊前的品牌费用(仅针对特定流量方)
if "广西恒为" in flow or "恒为" in flow: if "广西恒为" in flow or "恒为" in flow:
...@@ -1830,14 +1851,17 @@ class DataProcessor: ...@@ -1830,14 +1851,17 @@ class DataProcessor:
# 如果有未知品牌费用且存在已知品牌,进行 GMV 分摊 # 如果有未知品牌费用且存在已知品牌,进行 GMV 分摊
if unknown_brand_fee > 0 and brand_fees: if unknown_brand_fee > 0 and brand_fees:
# 获取各品牌的 GMV # 获取各品牌的 GMV —— 只统计真能 3-tuple 匹配上的品牌
# 匹配不上的品牌(如 identify_brand 输出"赛力斯"但数据库没有)不纳入分母
brand_gmv = {} brand_gmv = {}
for brand in brand_fees.keys(): for brand in brand_fees.keys():
key = (flow, biz, brand) # 先试原始 flow,再试 to_standard 后的值(双向兼容)
if key in settlement_map: data = settlement_map.get((flow, biz, brand))
brand_gmv[brand] = settlement_map[key]["GMV"] if not data:
else: std_f = to_standard(flow, '4s')
brand_gmv[brand] = Decimal("0") if std_f and std_f != flow:
data = settlement_map.get((std_f, biz, brand))
brand_gmv[brand] = data["GMV"] if data else Decimal("0")
total_gmv = sum(brand_gmv.values()) total_gmv = sum(brand_gmv.values())
...@@ -1871,17 +1895,24 @@ class DataProcessor: ...@@ -1871,17 +1895,24 @@ class DataProcessor:
if "广西恒为" in flow or "恒为" in flow: if "广西恒为" in flow or "恒为" in flow:
logger.info(f"[市场费诊断] 尾差={diff}, 加到第一个品牌={first_brand}") logger.info(f"[市场费诊断] 尾差={diff}, 加到第一个品牌={first_brand}")
else: else:
# GMV 都为 0,平均分摊 # total_gmv=0 说明 brand_fees 里没有任何品牌能 3-tuple 匹配上
n = len(brand_fees) # 降级:用 2-tuple 查 settlement_map 全量,按 gmv_ratio 分摊
avg_fee = (unknown_brand_fee / n).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP) if flat_entries:
for brand in brand_fees.keys(): self._append_split_result(result, flow, biz, None, unknown_brand_fee, flat_entries)
brand_fees[brand] += avg_fee if "广西恒为" in flow or "恒为" in flow:
# 尾差归并 db_brands = [e[0] for e in flat_entries]
allocated_sum = avg_fee * n logger.info(f"[市场费诊断] 2-tuple降级分摊: flat_entries={db_brands}, fee={unknown_brand_fee}")
diff = unknown_brand_fee - allocated_sum else:
if diff != 0: # settlement_map 也没数据,真的只能平均分摊到 brand_fees
first_brand = list(brand_fees.keys())[0] n = len(brand_fees)
brand_fees[first_brand] += diff 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: if "广西恒为" in flow or "恒为" in flow:
...@@ -1898,18 +1929,93 @@ class DataProcessor: ...@@ -1898,18 +1929,93 @@ class DataProcessor:
"市场费": round_2(fee), "市场费": round_2(fee),
}) })
# 处理:如果所有记录都是未知品牌(无已知品牌可分摊),直接保留 # 处理:如果所有记录都是未知品牌(无已知品牌),用 2-tuple 查全量按 gmv_ratio 分摊
if not brand_fees and unknown_brand_fee > 0: if not brand_fees and unknown_brand_fee > 0:
result.append({ if flat_entries:
"流量方名称": flow, self._append_split_result(result, flow, biz, None, unknown_brand_fee, flat_entries)
"业务类型": biz, if "广西恒为" in flow or "恒为" in flow:
"品牌": "未知品牌", db_brands = [e[0] for e in flat_entries]
"市场费": round_2(unknown_brand_fee), logger.info(f"[市场费诊断] 全未知品牌, 2-tuple分摊: flat_entries={db_brands}, fee={unknown_brand_fee}")
}) else:
# settlement_map 也没数据,原样保留
result.append({
"流量方名称": flow,
"业务类型": biz,
"品牌": "未知品牌",
"市场费": round_2(unknown_brand_fee),
})
logger.info(f"[市场费分摊] GMV 分摊完成,共 {len(result)} 条记录") logger.info(f"[市场费分摊] GMV 分摊完成,共 {len(result)} 条记录")
return result return result
@staticmethod
def _append_split_result(result, flow, biz, fixed_brand, total_fee, entries):
"""
将 total_fee 按比例分摊到 entries 的各品牌,追加到 result。
比例优先级:gmv_ratio 归一化 → GMV 值归一化 → 平均分摊
Args:
result: 待追加的结果列表
flow: 流量方
biz: 业务类型
fixed_brand: 若不为 None,所有输出用这个品牌;若为 None 用 entries 里的品牌
total_fee: 待分摊的总费用
entries: [(brand, gmv_ratio_float_or_None, GMV_Decimal), ...]
"""
n = len(entries)
if n == 0:
return
# 判断是否有可用的 gmv_ratio(全部 None 就降级)
ratios = []
has_ratio = False
for (br, rt, gmv) in entries:
if rt is not None:
ratios.append(Decimal(str(rt)))
has_ratio = True
else:
ratios.append(Decimal("0"))
if has_ratio:
total_ratio = sum(ratios)
if total_ratio > 0:
for i, (br, rt, gmv) in enumerate(entries):
allocated = (total_fee * ratios[i] / total_ratio).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
out_brand = fixed_brand if fixed_brand is not None else br
result.append({"流量方名称": flow, "业务类型": biz,
"品牌": out_brand, "市场费": allocated})
# 尾差归并到最后一条
allocated_sum = sum(item["市场费"] for item in result[-n:])
diff = total_fee - allocated_sum
if diff != 0:
result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
return
# 降级:用 GMV 值
gmv_total = sum(gmv for (_, _, gmv) in entries)
if gmv_total > 0:
for (br, rt, gmv) in entries:
allocated = (total_fee * gmv / gmv_total).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
out_brand = fixed_brand if fixed_brand is not None else br
result.append({"流量方名称": flow, "业务类型": biz,
"品牌": out_brand, "市场费": allocated})
allocated_sum = sum(item["市场费"] for item in result[-n:])
diff = total_fee - allocated_sum
if diff != 0:
result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
return
# 最终降级:平均分摊
avg = (total_fee / n).quantize(Decimal("0.01"), rounding=ROUND_HALF_UP)
for (br, rt, gmv) in entries:
out_brand = fixed_brand if fixed_brand is not None else br
result.append({"流量方名称": flow, "业务类型": biz,
"品牌": out_brand, "市场费": avg})
allocated_sum = avg * n
diff = total_fee - allocated_sum
if diff != 0:
result[-1]["市场费"] = round_2(result[-1]["市场费"] + diff)
# ======================================================== # ========================================================
# 解析市场费表 # 解析市场费表
# ======================================================== # ========================================================
......
...@@ -267,7 +267,14 @@ def match_columns(columns, keywords_map): ...@@ -267,7 +267,14 @@ def match_columns(columns, keywords_map):
""" """
result = {} result = {}
# —— 先处理带 ordinal 的(返回 int 索引,因为列名相同无法区分)—— # —— 先处理直接传 int 索引的(比如 AF 列 = 31)——
for std, keywords in keywords_map.items():
for kw in keywords:
if isinstance(kw, int) and 0 <= kw < len(columns):
result[std] = kw
break
# —— 再处理带 ordinal 的(返回 int 索引,因为列名相同无法区分)——
for std, keywords in keywords_map.items(): for std, keywords in keywords_map.items():
for kw in keywords: for kw in keywords:
if isinstance(kw, tuple) and len(kw) == 2 and isinstance(kw[1], int): if isinstance(kw, tuple) and len(kw) == 2 and isinstance(kw[1], int):
...@@ -671,12 +678,16 @@ def parse_budget_achieve_excel(file_path, biz_type=None): ...@@ -671,12 +678,16 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
col_map = match_columns(df.columns, { col_map = match_columns(df.columns, {
'store_name': ['流量费名称', '流量方名称', '门店名', 'target_name'], 'store_name': ['流量费名称', '流量方名称', '门店名', 'target_name'],
'biz_type': ['业务类型', '业务线'], 'biz_type': ['业务类型', '业务线'],
# 人员工资占比 → 营销费用占比:Excel 有多个同名列 "本月占比",取第 4 个 # 人员工资占比 → 营销费用占比:Excel header=None row0 有 5 个同名"本月占比"
'labor_ratio': [("本月占比", 4), '人员工资占比', '人员工资', '人员成本占比', '营销费用占比'], # header=0 下 pandas 自动加后缀 .1~.4,ordinal 子串匹配能命中全部 5 个
# 第 1 个=成本占比(col11) / 第 2 个=流量费占比(col14) / 第 3 个=服务费占比(col17)
# 第 4 个=市场费占比(col23) / 第 5 个=营销团队工资占比(col31) ← 延保/权益要这个
'labor_ratio': [("本月占比", 5), '人员工资占比', '人员工资', '人员成本占比', '营销费用占比'],
'renovation_amortization': ['装修分摊', '装修费用', '装修摊销'], 'renovation_amortization': ['装修分摊', '装修费用', '装修摊销'],
'rent_utilities': ['房租水电', '房租、水电', '房租', '水电费'], 'rent_utilities': ['房租水电', '房租、水电', '房租', '水电费'],
'store_consumables': ['门店耗材', '耗材'], 'store_consumables': ['门店耗材', '耗材'],
'service_provider_share_ratio': ['服务费占比', '服务商分成占比', '服务费费率', ("本月占比", 5)], # 服务费占比 = 第 3 个本月占比(col17),与 labor_ratio(第5个) 不冲突
'service_provider_share_ratio': ['服务费占比', '服务商分成占比', '服务费费率', ("本月占比", 3)],
}) })
if 'store_name' not in col_map: if 'store_name' not in col_map:
...@@ -734,6 +745,7 @@ def parse_budget_achieve_excel(file_path, biz_type=None): ...@@ -734,6 +745,7 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
# 取平均 # 取平均
result = {} result = {}
multi_cnt_stores = [] # 收集多行平均的门店名
for (sn, _bt), fields in agg.items(): for (sn, _bt), fields in agg.items():
if sn not in result: if sn not in result:
result[sn] = { result[sn] = {
...@@ -743,11 +755,17 @@ def parse_budget_achieve_excel(file_path, biz_type=None): ...@@ -743,11 +755,17 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
'store_consumables': Decimal('0'), 'store_consumables': Decimal('0'),
'service_provider_share_ratio': Decimal('0'), 'service_provider_share_ratio': Decimal('0'),
} }
# 检查这个门店是否有任何字段 cnt > 1(多行被平均)
max_cnt = max((cnt for (_, cnt) in fields.values()), default=1)
if max_cnt > 1:
multi_cnt_stores.append((sn, {f: c for f, (_, c) in fields.items() if c > 1}))
for field, (total, cnt) in fields.items(): for field, (total, cnt) in fields.items():
if cnt > 0: if cnt > 0:
result[sn][field] = (total / Decimal(str(cnt))).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP) result[sn][field] = (total / Decimal(str(cnt))).quantize(Decimal('0.0001'), rounding=ROUND_HALF_UP)
logger.info(f"[预算达成Excel] {len(result)} 个门店匹配") logger.info(f"[预算达成Excel] biz_type={biz_type} {len(result)} 个门店匹配")
if multi_cnt_stores:
logger.info(f"[预算达成Excel] biz_type={biz_type} {len(multi_cnt_stores)} 个门店有多行→取平均: {multi_cnt_stores[:10]}")
return result return result
...@@ -755,18 +773,14 @@ def extract_budget_ratio(budget_map, store_name, field='labor_ratio'): ...@@ -755,18 +773,14 @@ def extract_budget_ratio(budget_map, store_name, field='labor_ratio'):
""" """
从 parse_budget_achieve_excel 返回值中安全取单个字段。 从 parse_budget_achieve_excel 返回值中安全取单个字段。
匹配逻辑:先精确匹配 store_name → budget_map key,失败则用 fuzzy_match_store 模糊包含匹配。 匹配逻辑:只做门店名**精确匹配**,取不到返回 Decimal('0')。
模糊匹配兼容"门店名"(SAAS表) vs "流量费名称"(预算表) 命名差异。 营销费用/服务费等占比必须精准对应门店,避免模糊匹配串店。
返回 Decimal,取不到返回 Decimal('0')。
""" """
if not budget_map or not store_name: if not budget_map or not store_name:
return Decimal('0') return Decimal('0')
# 1. 精确匹配
entry = budget_map.get(store_name) entry = budget_map.get(store_name)
if entry is None: if entry is None:
# 2. 模糊包含匹配 return Decimal('0')
entry = fuzzy_match_store(store_name, budget_map) or {}
val = entry.get(field, Decimal('0')) if isinstance(entry, dict) else Decimal('0') val = entry.get(field, Decimal('0')) if isinstance(entry, dict) else Decimal('0')
return val or Decimal('0') return val or Decimal('0')
...@@ -1046,10 +1060,10 @@ def _aggregate_by_biz_type(df, col_map, store_name_col, numeric_fields, text_fie ...@@ -1046,10 +1060,10 @@ def _aggregate_by_biz_type(df, col_map, store_name_col, numeric_fields, text_fie
result[sn] = {} result[sn] = {}
for f, v in fields.items(): for f, v in fields.items():
if isinstance(v, list): if isinstance(v, list):
# 数值 [sum, count] → 取平均 # 数值 [sum, count] → 取平均(高精度保留,避免 0.015 被 quantize(0.01) 提前四舍五入成 0.02)
total, cnt = v total, cnt = v
result[sn][f] = (total / Decimal(str(cnt))).quantize( result[sn][f] = (total / Decimal(str(cnt))).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP) if cnt > 0 else Decimal('0') Decimal('0.000001'), rounding=ROUND_HALF_UP) if cnt > 0 else Decimal('0')
else: else:
result[sn][f] = v result[sn][f] = v
return result return result
...@@ -1184,6 +1198,13 @@ def parse_commerce_policy_inshop(file_path, biz_type='1.1'): ...@@ -1184,6 +1198,13 @@ def parse_commerce_policy_inshop(file_path, biz_type='1.1'):
default = {f: Decimal('0') for f in numeric_fields} default = {f: Decimal('0') for f in numeric_fields}
# 百分比字段:Excel 里写 1.5% → pandas 读 0.015,需要 ×100 存 1-100 # 百分比字段:Excel 里写 1.5% → pandas 读 0.015,需要 ×100 存 1-100
pct_fields = {'frontline_incentive_ratio'} pct_fields = {'frontline_incentive_ratio'}
# === 诊断:打印 raw 原始值(×100 之前)===
if raw:
sample_sn = list(raw.keys())[:2]
logger.info(f"[商务政策-店中店] 诊断 raw 值: ")
for sn in sample_sn:
fr_val = raw.get(sn, {}).get('frontline_incentive_ratio', 'MISSING')
logger.info(f" {sn}: frontline_incentive_ratio raw={fr_val} type={type(fr_val).__name__}")
for sn, v in raw.items(): for sn, v in raw.items():
merged = dict(default) merged = dict(default)
merged.update({k: v[k] for k in numeric_fields if k in v}) merged.update({k: v[k] for k in numeric_fields if k in v})
...@@ -1249,7 +1270,7 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'): ...@@ -1249,7 +1270,7 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'):
df.columns = [str(c).strip() if c else '' for c in df.columns] df.columns = [str(c).strip() if c else '' for c in df.columns]
col_map = match_columns(df.columns, { col_map = match_columns(df.columns, {
'store_name': ['入驻门店', '门店名称', '门店名'], 'store_name': ['入驻门店', '门店名称', '门店名'],
'verify': ['检核业务线'], 'verify': [31], # AF 列,直接按索引取
'biz_type': ['人员业务归属', '业务类型', '业务线'], 'biz_type': ['人员业务归属', '业务类型', '业务线'],
'position': ['岗位', '职位'], 'position': ['岗位', '职位'],
}) })
...@@ -1266,16 +1287,18 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'): ...@@ -1266,16 +1287,18 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'):
result = {} result = {}
skip_verify = skip_biz = skip_pos = 0 skip_verify = skip_biz = skip_pos = 0
for _, row in df.iterrows(): for _, row in df.iterrows():
# 检核业务线 = True # 检核列:truthy = True / 1 / '1' / '是' / 'TRUE' / 'TUER'(兼容各种 Excel 值)
if verify_col: # verify_col 可能是 int(按索引取)或 str(按列名取)
v = row.get(verify_col) if verify_col is not None:
if v is not True: v = row.iloc[verify_col] if isinstance(verify_col, int) else row.get(verify_col)
v_norm = str(v).strip().upper() if v is not None else ''
if v is None or v_norm in ('', '0', '否', 'FALSE', 'NAN', 'NONE'):
skip_verify += 1 skip_verify += 1
continue continue
# 人员业务归属 = biz_type # 人员业务归属 = biz_type
if biz_col: if biz_col is not None:
bt_raw = row.get(biz_col) bt_raw = row.iloc[biz_col] if isinstance(biz_col, int) else row.get(biz_col)
bt = str(bt_raw).strip() if bt_raw is not None else '' bt = str(bt_raw).strip() if bt_raw is not None else ''
# pandas 可能把 '1.1' 读成 float 1.1 # pandas 可能把 '1.1' 读成 float 1.1
try: try:
...@@ -1288,13 +1311,15 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'): ...@@ -1288,13 +1311,15 @@ def parse_labor_cost(file_path, biz_type='1.1', password='2026'):
continue continue
# 岗位筛选 # 岗位筛选
if pos_col: if pos_col is not None:
pos = str(row.get(pos_col, '')).strip() pos_raw = row.iloc[pos_col] if isinstance(pos_col, int) else row.get(pos_col)
pos = str(pos_raw).strip() if pos_raw is not None else ''
if pos and not any(t in pos for t in target_positions): if pos and not any(t in pos for t in target_positions):
skip_pos += 1 skip_pos += 1
continue continue
sn = str(row.get(col_map['store_name'], '')).strip() sn_raw = row.iloc[col_map['store_name']] if isinstance(col_map['store_name'], int) else row.get(col_map['store_name'], '')
sn = str(sn_raw).strip() if sn_raw is not None else ''
if not sn or sn in ('nan', 'None', ''): if not sn or sn in ('nan', 'None', ''):
continue continue
result[sn] = result.get(sn, 0) + 1 result[sn] = result.get(sn, 0) + 1
...@@ -1486,7 +1511,8 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1486,7 +1511,8 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
一条 SQL 批量查出商品成本 / 市场费 / 服务费 / 流量费 / 产值,避免 N+1 和多表 LEFT JOIN 笛卡尔乘积。 一条 SQL 批量查出商品成本 / 市场费 / 服务费 / 流量费 / 产值,避免 N+1 和多表 LEFT JOIN 笛卡尔乘积。
字段口径(与 Java 财务测算保持一致): 字段口径(与 Java 财务测算保持一致):
- product_cost = upgrade_dj_cost + upgrade_third_party_cost(嘀加与第三方成本合计,子订单表 gso) - product_cost = upgrade_dj_cost + (shop_traffic_money_calculate_type=1 时才加 upgrade_third_party_cost)
即第三方成本仅在按 GMV 口径算流量费时才计入商品成本
- market_fee = 四项费用累计(expense_category IN (706,808,809,901),子查询 GROUP BY order_code 避免重复行) - market_fee = 四项费用累计(expense_category IN (706,808,809,901),子查询 GROUP BY order_code 避免重复行)
- service_fee = franchisee_profit_money(服务商金额,主汇总记录 gopa2) - service_fee = franchisee_profit_money(服务商金额,主汇总记录 gopa2)
- shop_traffic_money = shop_traffic_money(流量费,来自主表 gopa 不是 gopa2) - shop_traffic_money = shop_traffic_money(流量费,来自主表 gopa 不是 gopa2)
...@@ -1526,8 +1552,6 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1526,8 +1552,6 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
end_str = end_date.strftime('%Y-%m-%d 23:59:59') if end_date else '' end_str = end_date.strftime('%Y-%m-%d 23:59:59') if end_date else ''
# —— SQL 构造 —— # —— SQL 构造 ——
# 子查询 fee:四项费用累计,INNER JOIN go+po 下推过滤避免笛卡尔乘积
# 外层:主表 gopa(子订单级) JOIN go+po+gso(子订单) + LEFT JOIN gopa2(主汇总 order_flag='Y') + LEFT JOIN fee
where_parts = [ where_parts = [
"gopa.deleted_flag = 'N'", "gopa.deleted_flag = 'N'",
"gopa.order_flag = 'N'", "gopa.order_flag = 'N'",
...@@ -1557,46 +1581,66 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1557,46 +1581,66 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
if business_type is not None: if business_type is not None:
fee_where.append(f"go.business_type = {business_type}") fee_where.append(f"go.business_type = {business_type}")
# 一条 SQL 搞定: 驱动表 gopa(order_flag='N' 子订单级) + LEFT JOIN gopa2(order_flag='Y' 主汇总级)
# product_cost → SUM(gso 子订单字段)
# shop_traffic_money/service_fee/store_output_value/other_cost → MAX(gopa2 主汇总字段)
# market_fee → MAX(fee 子查询)
sql = f""" sql = f"""
SELECT SELECT
go.merchant_name AS merchant_name, t.merchant_name AS merchant_name,
SUM(IFNULL(gso.upgrade_dj_cost, 0) + IFNULL(gso.upgrade_third_party_cost, 0)) SUM(t.product_cost) AS product_cost,
AS product_cost, SUM(t.market_fee) AS market_fee,
SUM(IFNULL(fee.total, 0)) AS market_fee, SUM(t.service_fee) AS service_fee,
SUM(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee, SUM(t.store_output_value) AS store_output_value,
SUM(IFNULL(gopa2.total_price, 0)) AS store_output_value, SUM(t.shop_traffic_money) AS shop_traffic_money,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money, SUM(t.other_cost) AS other_cost
SUM(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost FROM (
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
SELECT SELECT
ecc.order_code, go.merchant_name,
SUM(ecc.expense_category_result) AS total gopa.order_code,
FROM dj_car_life_order_expense_category_calculated ecc -- 商品成本: 子订单级 gso 字段, 同订单多 sub_order → SUM
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code SUM(IFNULL(gso.upgrade_dj_cost, 0)
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code + IF(gopa.shop_traffic_money_calculate_type = 1,
WHERE {' AND '.join(fee_where)} IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
GROUP BY ecc.order_code -- shop_traffic_money: 主汇总级字段, 从 gopa2(order_flag='Y') 取, MAX 防 LEFT JOIN 放大
) fee ON fee.order_code = gopa.order_code MAX(IFNULL(gopa2.shop_traffic_money, 0)) AS shop_traffic_money,
WHERE {' AND '.join(where_parts)} -- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
GROUP BY go.merchant_name MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
MAX(IFNULL(gopa2.total_price, 0)) AS store_output_value,
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
SELECT
ecc.order_code,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code AND po.deleted_flag = 'N'
WHERE {' AND '.join(fee_where)}
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE {' AND '.join(where_parts)}
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name
""" """
try: try:
from sqlalchemy import text as sa_text from sqlalchemy import text as sa_text
_sql_preview = sql.strip().replace('\n', ' ')[:500] _sql_preview = sql.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_biz_sql_aggregated] biz_type={biz_type} dates={start_str}~{end_str} scene_type={scene_type} business_type={business_type} store_cnt={len(store_names) if store_names else 'all'} SQL={_sql_preview}...") logger.info(f"[BizSQL-fetch_biz_sql_aggregated] biz_type={biz_type} SQL={_sql_preview}...")
result = conn.execute(sa_text(sql)) result = conn.execute(sa_text(sql))
rows = result.mappings().all() rows = result.mappings().all()
out = {} out = {}
...@@ -1605,47 +1649,14 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1605,47 +1649,14 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
if not mn: if not mn:
continue continue
out[mn] = { out[mn] = {
'product_cost': Decimal(str(r['product_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'product_cost': Decimal(str(r['product_cost'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'market_fee': Decimal(str(r['market_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'market_fee': Decimal(str(r['market_fee'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'service_fee': Decimal(str(r['service_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'service_fee': Decimal(str(r['service_fee'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'store_output_value': Decimal(str(r['store_output_value'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'store_output_value': Decimal(str(r['store_output_value'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'shop_traffic_money': Decimal(str(r['shop_traffic_money'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'shop_traffic_money': Decimal(str(r['shop_traffic_money'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
'other_cost': Decimal(str(r['other_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'other_cost': Decimal(str(r['other_cost'] or 0)).quantize(Decimal('0.01'), ROUND_HALF_UP),
} }
logger.info(f"[BizSQL-延保权益财务] biz_type={biz_type} 聚合完成, {len(out)} 个门店") logger.info(f"[BizSQL-延保权益财务] biz_type={biz_type} 完成, {len(out)} 个门店")
# === 诊断:带 store_names 过滤返回 0 时,自动再跑一次不带过滤的全量 ===
if store_names and len(out) == 0:
logger.warning(f"[BizSQL-延保权益财务] store_cnt={len(store_names)} 过滤后返回 0,诊断全量...")
# 构造不带 store_names LIKE 条件的全量 SQL
diag_where_parts = [w for w in where_parts if 'LIKE' not in w]
diag_sql = sql.split("WHERE")[0] + "WHERE " + " AND ".join(diag_where_parts) + " GROUP BY go.merchant_name"
try:
_diag_preview = diag_sql.strip().replace('\n', ' ')[:400]
logger.info(f"[BizSQL-诊断] 全量 SQL={_diag_preview}...")
diag_rows = conn.execute(sa_text(diag_sql)).mappings().all()
logger.info(f"[BizSQL-诊断] 全量返回 {len(diag_rows)} 个门店")
if diag_rows:
diag_names = [r['merchant_name'] for r in diag_rows[:15]]
logger.info(f"[BizSQL-诊断] merchant_name 样本: {diag_names}")
# 比较 store_names 和 merchant_name 的交集
store_set = set(store_names)
name_set = {r['merchant_name'] for r in diag_rows}
exact_match = store_set & name_set
logger.info(f"[BizSQL-诊断] Excel store_names={len(store_set)}, DB merchant_name={len(name_set)}, 精确匹配={len(exact_match)}")
if exact_match:
logger.info(f"[BizSQL-诊断] 精确匹配样本: {list(exact_match)[:5]}")
# 模糊包含检查
fuzzy_hits = []
for sn in store_set:
for mn in name_set:
if sn and mn and (sn in mn or mn in sn):
fuzzy_hits.append((sn, mn))
break
logger.info(f"[BizSQL-诊断] 模糊包含匹配={len(fuzzy_hits)}")
if fuzzy_hits:
logger.info(f"[BizSQL-诊断] 模糊匹配样本: {fuzzy_hits[:5]}")
except Exception as de:
logger.error(f"[BizSQL-诊断] 全量查询也失败: {de}")
return out return out
except Exception as e: except Exception as e:
logger.error(f"[BizSQL-延保权益财务] 查询异常: {e}") logger.error(f"[BizSQL-延保权益财务] 查询异常: {e}")
...@@ -1659,6 +1670,17 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1659,6 +1670,17 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
pass pass
def exact_match_store(store_name, store_map):
"""
系统数据源精确匹配 — 门店名必须完全一致才返回。
用于 biz_sql_map / system_delivery_map / indicator_data 等系统数据源,
避免模糊匹配导致"广西河池中达"误匹配到其他含"中达"的门店。
"""
if not store_name or not store_map:
return None
return store_map.get(store_name)
def fuzzy_match_store(store_name, biz_sql_map, return_key=False): def fuzzy_match_store(store_name, biz_sql_map, return_key=False):
""" """
Excel 门店名 ↔ 业务表 merchant_name 模糊匹配。 Excel 门店名 ↔ 业务表 merchant_name 模糊匹配。
...@@ -1943,9 +1965,12 @@ def fetch_light_reform_goods_stats(start_date, end_date): ...@@ -1943,9 +1965,12 @@ def fetch_light_reform_goods_stats(start_date, end_date):
LEFT JOIN dj_car_life_goods_order t2 LEFT JOIN dj_car_life_goods_order t2
ON t2.order_code = t1.order_code ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12) AND t2.status IN (4,6,12)
AND t2.deleted_flag = 'N'
LEFT JOIN dj_car_life_pay_order t3 LEFT JOIN dj_car_life_pay_order t3
ON t3.order_code = t1.order_code ON t3.order_code = t1.order_code
AND t3.deleted_flag = 'N'
WHERE t1.status = 1 WHERE t1.status = 1
AND t1.deleted_flag = 'N'
AND t2.scene_type = 1 AND t2.scene_type = 1
AND t3.success_date BETWEEN '{start_str}' AND '{end_str}' AND t3.success_date BETWEEN '{start_str}' AND '{end_str}'
GROUP BY t2.merchant_name GROUP BY t2.merchant_name
...@@ -2011,14 +2036,17 @@ def fetch_est_delivery_count(base_scene_code='100101'): ...@@ -2011,14 +2036,17 @@ def fetch_est_delivery_count(base_scene_code='100101'):
return {} return {}
sql = f""" sql = f"""
SELECT traffic_party_name, SELECT t3.merchant_name AS traffic_party_name,
IF(estimated_delivery_count_per_month IS NULL, IF(t1.estimated_delivery_count_per_month IS NULL,
delivery_count, t1.delivery_count,
estimated_delivery_count_per_month) AS final_delivery_count t1.estimated_delivery_count_per_month) AS final_delivery_count
FROM dj_car_life_merchant_store_info FROM dj_car_life_merchant_store_info t1
WHERE base_scene_code = '{base_scene_code}' LEFT JOIN dj_car_life_service_merchant t3
AND deleted_flag = 'N' ON t1.traffic_party_id = t3.merchant_id
ORDER BY created_date DESC AND t3.deleted_flag = 'N'
WHERE t1.base_scene_code = '{base_scene_code}'
AND t1.deleted_flag = 'N'
ORDER BY t1.created_date DESC
""" """
out = {} out = {}
...@@ -2047,6 +2075,68 @@ def fetch_est_delivery_count(base_scene_code='100101'): ...@@ -2047,6 +2075,68 @@ def fetch_est_delivery_count(base_scene_code='100101'):
pass pass
def fetch_park_name_map(base_scene_code='100101'):
"""
园区店名称批量查询(静态配置表,无日期参数)。
数据源:dj_car_life_merchant_store_info(门店流量方配置表)
取值逻辑:traffic_party_name(流量方门店名)→ parking_store_name(园区店名称)
过滤条件:base_scene_code = '100101'(轻改), deleted_flag = 'N'
:param base_scene_code: 业务场景编码,默认 '100101' 轻改
:return: dict[traffic_party_name] = parking_store_name (str)
"""
from config import Config
if not Config.BIZ_SQL_ENABLED:
logger.warning("[BizSQL-园区名称] BIZ_SQL_ENABLED=false,跳过查询")
return {}
conn = _get_biz_sql_conn()
if conn is None:
return {}
sql = f"""
SELECT t3.merchant_name AS traffic_party_name,
t2.merchant_name AS parking_store_name
FROM dj_car_life_merchant_store_info t1
LEFT JOIN dj_car_life_service_merchant t2
ON t1.parking_store_id = t2.merchant_id
AND t2.deleted_flag = 'N'
LEFT JOIN dj_car_life_service_merchant t3
ON t1.traffic_party_id = t3.merchant_id
AND t3.deleted_flag = 'N'
WHERE t1.base_scene_code = '{base_scene_code}'
AND t1.deleted_flag = 'N'
AND t2.merchant_name IS NOT NULL
AND t3.merchant_name IS NOT NULL
ORDER BY t1.created_date DESC
"""
out = {}
try:
from sqlalchemy import text as sa_text
_sql_preview = sql.strip().replace('\n', ' ')[:500]
logger.info(f"[BizSQL-fetch_park_name_map] base_scene_code={base_scene_code} SQL={_sql_preview}...")
for r in conn.execute(sa_text(sql)).mappings().all():
tp = r['traffic_party_name']
ps = r['parking_store_name']
# ORDER BY created_date DESC → 同 traffic_party 多条时只取最新一条
if tp and tp not in out:
out[tp] = ps
logger.info(f"[BizSQL-园区名称] 完成, {len(out)} 个门店")
return out
except Exception as e:
logger.error(f"[BizSQL-园区名称] 查询异常: {e}")
import traceback
logger.error(traceback.format_exc())
return {}
finally:
try:
conn.close()
except Exception:
pass
def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1): def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
""" """
轻改 店中店 + 园区店 共用:财务成本分项批量查询(scene_type=1)。 轻改 店中店 + 园区店 共用:财务成本分项批量查询(scene_type=1)。
...@@ -2103,86 +2193,103 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1): ...@@ -2103,86 +2193,103 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
sql = f""" sql = f"""
SELECT SELECT
go.merchant_name AS merchant_name, t.merchant_name AS merchant_name,
-- 产品成本(财务列表)= 非内部结算 dj_order_type != 6 -- 内层已按 merchant_name + order_code 聚合好, 外层全部 SUM 跨订单
SUM(CASE WHEN gso.dj_order_type != 6 SUM(t.product_cost_finance) AS product_cost_finance,
THEN gso.upgrade_shop_price - gso.base_shop_price SUM(t.internal_settle_cost) AS internal_settle_cost,
ELSE 0 END) AS product_cost_finance, SUM(t.oe_product_cost) AS oe_product_cost,
SUM(t.nonoe_product_cost) AS nonoe_product_cost,
-- 内部结算成本(财务列表)= 内部结算 dj_order_type = 6 SUM(t.window_film_cost) AS window_film_cost,
SUM(CASE WHEN gso.dj_order_type = 6 SUM(t.car_wrap_cost) AS car_wrap_cost,
THEN gso.upgrade_shop_price - gso.base_shop_price SUM(t.premium_cost) AS premium_cost,
ELSE 0 END) AS internal_settle_cost, SUM(t.store_share) AS store_share,
SUM(t.construction_income) AS construction_income,
-- 原厂产品成本(非内部结算 + 名称含 AITO/HIMA) SUM(t.market_fee) AS market_fee,
SUM(CASE WHEN gso.dj_order_type != 6 SUM(t.mgmt_market_fee) AS mgmt_market_fee,
AND (gso.upgrade_goods_name LIKE '%AITO%' SUM(t.sunshine_incentive_fee) AS sunshine_incentive_fee
OR gso.upgrade_goods_name LIKE '%HIMA%')
THEN gso.upgrade_shop_price - gso.base_shop_price FROM (
ELSE 0 END) AS oe_product_cost,
-- 副厂产品成本(非内部结算 + 名称不含 AITO/HIMA)
SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS nonoe_product_cost,
-- 窗膜成本
SUM(CASE WHEN gso.upgrade_goods_type_name IN {FILM_TYPES}
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS window_film_cost,
-- 车衣成本
SUM(CASE WHEN gso.upgrade_goods_type_name IN {CAR_WRAP_TYPES}
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS car_wrap_cost,
-- 精品成本(排除所有已归类品类)
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN {PREMIUM_EXCLUDE}
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS premium_cost,
-- 门店分成/流量费(财务列表)= 非内部结算 shop_traffic_money
SUM(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa.shop_traffic_money, 0)
ELSE 0 END) AS store_share,
-- 施工收入 = custom_common_cost(来自主汇总记录 gopa2)
SUM(IFNULL(gopa2.custom_common_cost, 0)) AS construction_income,
-- 市场费 = 四项费用累计(子查询 fee.total)
SUM(IFNULL(fee.total, 0)) AS market_fee
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
SELECT SELECT
ecc.order_code, go.merchant_name,
SUM(ecc.expense_category_result) AS total gopa.order_code,
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code -- gpa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code SUM(CASE WHEN gso.dj_order_type != 6
WHERE {' AND '.join(fee_where)} THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
GROUP BY ecc.order_code ELSE 0 END) AS product_cost_finance,
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N' SUM(CASE WHEN gso.dj_order_type = 6
AND gopa.order_flag = 'N' THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
AND go.scene_type = {scene_type} ELSE 0 END) AS internal_settle_cost,
AND po.success_date >= '{start_str}'
AND po.success_date <= '{end_str}' SUM(CASE WHEN gso.dj_order_type != 6
GROUP BY go.merchant_name AND (gso.upgrade_goods_name LIKE '%AITO%'
OR gso.upgrade_goods_name LIKE '%HIMA%')
THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS oe_product_cost,
SUM(CASE WHEN gso.dj_order_type != 6
AND gso.upgrade_goods_name NOT LIKE '%AITO%'
AND gso.upgrade_goods_name NOT LIKE '%HIMA%'
THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS nonoe_product_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN {FILM_TYPES}
THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS window_film_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name IN {CAR_WRAP_TYPES}
THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS car_wrap_cost,
SUM(CASE WHEN gso.upgrade_goods_type_name NOT IN {PREMIUM_EXCLUDE}
THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS premium_cost,
-- store_share: shop_traffic_money 来自主汇总级 gopa2(order_flag='Y'), MAX 防 LEFT JOIN 放大
MAX(CASE WHEN gso.dj_order_type != 6
THEN IFNULL(gopa2.shop_traffic_money, 0)
ELSE 0 END) AS store_share,
-- construction_income / market_fee: MAX 取单次值
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS construction_income,
MAX(IFNULL(fee.total, 0)) AS market_fee,
MAX(IFNULL(fee.mgmt_fee, 0)) AS mgmt_market_fee,
MAX(IFNULL(fee.sunshine_fee, 0)) AS sunshine_incentive_fee
FROM dj_car_life_goods_order_profit_allocation gopa
INNER JOIN dj_car_life_goods_order go
ON go.order_code = gopa.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po
ON go.order_code = po.order_code AND po.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_sub_order gso
ON gopa.sub_order_code = gso.sub_order_code AND gso.deleted_flag = 'N'
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N'
LEFT JOIN (
SELECT
ecc.order_code,
SUM(IF(ecc.expense_category_id IN (706, 808), ecc.expense_category_result, 0)) AS mgmt_fee,
SUM(IF(ecc.expense_category_id IN (809, 901), ecc.expense_category_result, 0)) AS sunshine_fee,
SUM(ecc.expense_category_result) AS total
FROM dj_car_life_order_expense_category_calculated ecc
INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code AND go.deleted_flag = 'N'
INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code AND po.deleted_flag = 'N'
WHERE {' AND '.join(fee_where)}
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'N'
AND go.scene_type = {scene_type}
AND po.success_date >= '{start_str}'
AND po.success_date <= '{end_str}'
GROUP BY go.merchant_name, gopa.order_code
) t
GROUP BY t.merchant_name
""" """
try: try:
...@@ -2208,6 +2315,8 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1): ...@@ -2208,6 +2315,8 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
'store_share': Decimal(str(r['store_share'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'store_share': Decimal(str(r['store_share'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'construction_income': Decimal(str(r['construction_income'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'construction_income': Decimal(str(r['construction_income'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'market_fee': Decimal(str(r['market_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP), 'market_fee': Decimal(str(r['market_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'mgmt_market_fee': Decimal(str(r.get('mgmt_market_fee', Decimal('0')))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'sunshine_incentive_fee': Decimal(str(r.get('sunshine_incentive_fee', Decimal('0')))).quantize(Decimal('0.01'), ROUND_HALF_UP),
} }
logger.info(f"[BizSQL-轻改财务] 完成, {len(out)} 个门店") logger.info(f"[BizSQL-轻改财务] 完成, {len(out)} 个门店")
return out return out
......
...@@ -13,6 +13,7 @@ ...@@ -13,6 +13,7 @@
作者:数据处理引擎 作者:数据处理引擎
""" """
import os
import threading import threading
import logging import logging
import sys import sys
...@@ -56,6 +57,56 @@ class TaskScheduler: ...@@ -56,6 +57,56 @@ class TaskScheduler:
self._is_processing = False self._is_processing = False
self._last_run_time = None self._last_run_time = None
self._last_run_result = None self._last_run_result = None
# 跨进程互斥: 文件锁 (Windows 用 msvcrt, Linux 用 fcntl)
self._lock_path = os.path.join(os.path.dirname(os.path.abspath(__file__)), '.scheduler.lock')
self._lock_file = None
def _acquire_file_lock(self):
"""
尝试获取跨进程文件锁。
返回 True = 获取成功 (本进程可以启动调度器)
返回 False = 另一个进程已持有锁
"""
try:
self._lock_file = open(self._lock_path, 'w')
if sys.platform.startswith('win'):
import msvcrt
msvcrt.locking(self._lock_file.fileno(), msvcrt.LK_NBLCK, 1)
else:
import fcntl
fcntl.flock(self._lock_file.fileno(), fcntl.LOCK_EX | fcntl.LOCK_NB)
self._lock_file.write(str(os.getpid()))
self._lock_file.flush()
return True
except (IOError, OSError) as e:
logger.warning(f"[调度器] 跨进程锁获取失败 (另一实例已在运行): {e}")
if self._lock_file:
self._lock_file.close()
self._lock_file = None
return False
def _release_file_lock(self):
"""释放跨进程文件锁。"""
if self._lock_file:
try:
import sys as _sys
if _sys.platform.startswith('win'):
import msvcrt
msvcrt.locking(self._lock_file.fileno(), msvcrt.LK_UNLCK, 1)
else:
import fcntl
fcntl.flock(self._lock_file.fileno(), fcntl.LOCK_UN)
except Exception:
pass
try:
self._lock_file.close()
except Exception:
pass
self._lock_file = None
try:
os.remove(self._lock_path)
except Exception:
pass
def start(self): def start(self):
""" """
...@@ -70,6 +121,12 @@ class TaskScheduler: ...@@ -70,6 +121,12 @@ class TaskScheduler:
logger.info("[调度器] 定时任务未启用 (SCHEDULER_ENABLED=false),跳过启动") logger.info("[调度器] 定时任务未启用 (SCHEDULER_ENABLED=false),跳过启动")
return return
# ===== 跨进程互斥: 文件锁 =====
# 多人同时启动 Flask 时, 只有第一个能拿到文件锁, 其余直接跳过
if not self._acquire_file_lock():
logger.warning("[调度器] ⚠️ 另一个调度器实例已在运行 (PID 见 .scheduler.lock),本实例跳过启动")
return
interval = Config.SCHEDULER_INTERVAL_SECONDS interval = Config.SCHEDULER_INTERVAL_SECONDS
try: try:
...@@ -113,6 +170,9 @@ class TaskScheduler: ...@@ -113,6 +170,9 @@ class TaskScheduler:
except Exception as e: except Exception as e:
logger.error(f"[调度器] 停止 APScheduler 时出错: {str(e)}") logger.error(f"[调度器] 停止 APScheduler 时出错: {str(e)}")
# ===== 释放跨进程文件锁 =====
self._release_file_lock()
logger.info("[调度器] 调度器已完全停止") logger.info("[调度器] 调度器已完全停止")
def get_status(self): def get_status(self):
......
...@@ -245,6 +245,7 @@ ...@@ -245,6 +245,7 @@
function onTypeChange() { function onTypeChange() {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; }); var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
renderFileInputs(cfg ? cfg.forms : []); renderFileInputs(cfg ? cfg.forms : []);
togglePeriodTypeRow(cfg); // 按 support_week 控制粒度切换行显示
togglePeriodRow(cfg); togglePeriodRow(cfg);
} }
...@@ -381,10 +382,18 @@ ...@@ -381,10 +382,18 @@
modalWeekNum = weekNum; modalWeekNum = weekNum;
} }
// 周期粒度行:始终显示(所有类型都支持按月/按周切换) // 周期粒度行:仅 support_week=true 的类型(通用+权益)才显示
function togglePeriodTypeRow() { // 其他类型(整月、月份+自定义日期)统一隐藏,用户不可切换按月/按周
function togglePeriodTypeRow(cfg) {
var row = document.getElementById('mPeriodTypeRow'); var row = document.getElementById('mPeriodTypeRow');
row.style.display = ''; var show = cfg && cfg.support_week;
row.style.display = show ? '' : 'none';
// 防御:若当前 period_type 为 week 但新类型不支持,强制重置为 month
if (!show && modalPeriodType === 'week') {
modalPeriodType = 'month';
modalWeekNum = null;
document.getElementById('mWeekSelect').style.display = 'none';
}
} }
// 周期提示:结束日期 ≤ 月份最后一天;开始默认1号 // 周期提示:结束日期 ≤ 月份最后一天;开始默认1号
function updatePeriodHint() { function updatePeriodHint() {
...@@ -426,9 +435,14 @@ ...@@ -426,9 +435,14 @@
mMonth.disabled = locked; mMonth.disabled = locked;
// 周期框 disabled 由 togglePeriodRow 统一控制(按周时 disabled,按月时 need_period=True 可编辑) // 周期框 disabled 由 togglePeriodRow 统一控制(按周时 disabled,按月时 need_period=True 可编辑)
var cfg = typeConfigs.find(function (t) { return t.code === (task ? task.data_table_type : ''); }); var cfg = typeConfigs.find(function (t) { return t.code === (task ? task.data_table_type : ''); });
// 防御:若原 task 的 period_type 为 week 但当前类型不支持,强制重置
if (cfg && !cfg.support_week && modalPeriodType === 'week') {
modalPeriodType = 'month';
modalWeekNum = null;
}
renderFileInputs(cfg ? cfg.forms : []); renderFileInputs(cfg ? cfg.forms : []);
togglePeriodTypeRow(); // 显示粒度切换行 togglePeriodTypeRow(cfg); // 按 support_week 控制粒度切换行显示
togglePeriodRow(cfg); // 根据粒度 + need_period 控制周期行显示/disabled togglePeriodRow(cfg); // 根据粒度 + need_period 控制周期行显示/disabled
updatePeriodHint(); updatePeriodHint();
// 初始化粒度按钮组 active 状态 // 初始化粒度按钮组 active 状态
...@@ -656,6 +670,9 @@ ...@@ -656,6 +670,9 @@
// ---------- 弹窗:周期粒度切换 ---------- // ---------- 弹窗:周期粒度切换 ----------
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (btn) { document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (btn) {
btn.addEventListener('click', function () { btn.addEventListener('click', function () {
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
// 防御:当前类型不支持按周时忽略点击(理论上行已隐藏,用户不可达)
if (!cfg || !cfg.support_week) return;
modalPeriodType = btn.dataset.type; modalPeriodType = btn.dataset.type;
// 更新按钮组 active 状态 // 更新按钮组 active 状态
document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (b) { document.querySelectorAll('#mPeriodTypeGroup .seg-btn').forEach(function (b) {
...@@ -664,7 +681,6 @@ ...@@ -664,7 +681,6 @@
}); });
// 切换粒度时重置 weekNum // 切换粒度时重置 weekNum
modalWeekNum = null; modalWeekNum = null;
var cfg = typeConfigs.find(function (t) { return t.code === mType.value; });
if (modalPeriodType === 'week') { if (modalPeriodType === 'week') {
// 按周:渲染周下拉 + 自动计算日期 // 按周:渲染周下拉 + 自动计算日期
document.getElementById('mWeekSelect').style.display = ''; document.getElementById('mWeekSelect').style.display = '';
......
...@@ -39,13 +39,14 @@ from report_utils import ( ...@@ -39,13 +39,14 @@ from report_utils import (
STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_WARRANTY, BIZ_TYPE_EQUITY, INDICATOR_BIZ_MAP, STORE_EFFECT_EARNINGS_TYPE, BIZ_TYPE_WARRANTY, BIZ_TYPE_EQUITY, INDICATOR_BIZ_MAP,
mark_task_failed, cleanup_tmp_dir, mark_task_failed, cleanup_tmp_dir,
update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task, update_subtask, is_subtask_completed, promote_subtask_failure_to_main_task,
get_subtask_status,
SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED, SUBTASK_PROCESSING, SUBTASK_COMPLETED, SUBTASK_FAILED,
download_all_files, download_all_files,
parse_saas_base, parse_saas_base_sheet2, parse_saas_base_sheet2_exclude, parse_saas_base, parse_saas_base_sheet2, parse_saas_base_sheet2_exclude,
parse_region_map, parse_delivery_table, parse_region_map, parse_delivery_table,
parse_budget_achieve_excel, extract_budget_ratio, parse_labor_cost, parse_budget_achieve_excel, extract_budget_ratio, parse_labor_cost,
fetch_biz_sql_aggregated, fetch_park_daily_report, fetch_biz_sql_aggregated, fetch_park_daily_report,
fetch_indicator_data, fuzzy_match_store, safe_div_pct_decimal, prorate_by_period, fetch_indicator_data, fuzzy_match_store, exact_match_store, safe_div_pct_decimal, prorate_by_period,
) )
from models import ReportStoreEffectSummary, DataProcessTask, db from models import ReportStoreEffectSummary, DataProcessTask, db
...@@ -53,6 +54,10 @@ logger = logging.getLogger('StoreEffectSummaryProcessor') ...@@ -53,6 +54,10 @@ logger = logging.getLogger('StoreEffectSummaryProcessor')
SUMMARY_CATEGORY = 'store_effect_summary' SUMMARY_CATEGORY = 'store_effect_summary'
# 总看板(第5个 sheet)必须在以下前 4 张 sheet 全部 COMPLETED 后才能执行,
# 否则读到的源数据不全(前 4 张表尚未落库或仍是旧快照)。
PRECEDING_CATEGORIES = ['warranty', 'equity', 'inshop', 'park']
# 各业务类型 → (解析函数, 文件/sheet 参数, 指标 biz 键, 指标编码) # 各业务类型 → (解析函数, 文件/sheet 参数, 指标 biz 键, 指标编码)
BIZ_PLAN = [ BIZ_PLAN = [
('warranty', BIZ_TYPE_WARRANTY, INDICATOR_BIZ_MAP.get('warranty'), ('warranty', BIZ_TYPE_WARRANTY, INDICATOR_BIZ_MAP.get('warranty'),
...@@ -104,8 +109,39 @@ class StoreEffectSummaryProcessor: ...@@ -104,8 +109,39 @@ class StoreEffectSummaryProcessor:
logger.info(f"[店效人效汇总] 完成, 成功 {success_count}, 失败 {fail_count}") logger.info(f"[店效人效汇总] 完成, 成功 {success_count}, 失败 {fail_count}")
return {'success': success_count, 'failed': fail_count} return {'success': success_count, 'failed': fail_count}
def _preceding_sheets_all_completed(self, task_id):
"""总看板闸门:前 4 张 sheet(warranty/equity/inshop/park)是否全部 COMPLETED。
返回 (all_completed, pending_list):
- all_completed=True → 总看板可以执行;
- all_completed=False → pending_list 列出尚未就绪的 category=status,
供日志提示。任一未 COMPLETED(PENDING/PROCESSING/None/FAILED)都视为未就绪,
总看板返回等待,自身子任务保持 PENDING,由下一轮调度重试。
"""
pending = []
for cat in PRECEDING_CATEGORIES:
st = get_subtask_status(task_id, cat)
if st != SUBTASK_COMPLETED:
pending.append(f"{cat}={st}")
return (len(pending) == 0, pending)
def process(self, task): def process(self, task):
task_id = task.id task_id = task.id
# 幂等:自身子任务已 COMPLETED 则跳过(防止调度器重复扫描重算)
if is_subtask_completed(task_id, SUMMARY_CATEGORY):
logger.info(f"[店效人效汇总] 任务 {task_id} 子任务已 COMPLETED,跳过")
return
# 闸门:总看板必须在前 4 张 sheet(延保/权益/店中店/园区店)全部 COMPLETED 后执行,
# 否则读到的是未落库/旧的前置数据(如 2.3交车数会偏旧)。
# 前置未就绪时直接返回(自身子任务保持 PENDING,等下一轮调度重试),不置 FAILED。
all_done, pending = self._preceding_sheets_all_completed(task_id)
if not all_done:
logger.info(f"[店效人效汇总] 任务 {task_id} 前 4 张 sheet 尚未全部完成,"
f"总看板暂缓执行,等待下一轮:未完成任务={pending}")
return
update_subtask(task_id, SUMMARY_CATEGORY, SUBTASK_PROCESSING) update_subtask(task_id, SUMMARY_CATEGORY, SUBTASK_PROCESSING)
db.session.commit() db.session.commit()
...@@ -302,12 +338,12 @@ class StoreEffectSummaryProcessor: ...@@ -302,12 +338,12 @@ class StoreEffectSummaryProcessor:
if biz_tag in ('warranty', 'equity'): if biz_tag in ('warranty', 'equity'):
if biz_tag == 'warranty': if biz_tag == 'warranty':
ind = ind_warranty.get(store_name) or fuzzy_match_store(store_name, ind_warranty) or {} ind = ind_warranty.get(store_name) or exact_match_store(store_name, ind_warranty) or {}
biz = fuzzy_match_store(store_name, biz_sql_warranty) or {} biz = exact_match_store(store_name, biz_sql_warranty) or {}
budget_ratio_map = budget_warranty budget_ratio_map = budget_warranty
else: # equity else: # equity
ind = ind_equity.get(store_name) or fuzzy_match_store(store_name, ind_equity) or {} ind = ind_equity.get(store_name) or exact_match_store(store_name, ind_equity) or {}
biz = fuzzy_match_store(store_name, biz_sql_equity) or {} biz = exact_match_store(store_name, biz_sql_equity) or {}
budget_ratio_map = budget_equity budget_ratio_map = budget_equity
output_value = Decimal(str(ind.get('A036', 0))) output_value = Decimal(str(ind.get('A036', 0)))
...@@ -327,9 +363,9 @@ class StoreEffectSummaryProcessor: ...@@ -327,9 +363,9 @@ class StoreEffectSummaryProcessor:
labor_cost = Decimal('0') labor_cost = Decimal('0')
headcount = 0 headcount = 0
else: # 轻改 inshop / park else: # 轻改 inshop / park
ind = ind_light.get(store_name) or fuzzy_match_store(store_name, ind_light) or {} ind = ind_light.get(store_name) or exact_match_store(store_name, ind_light) or {}
biz1 = fuzzy_match_store(store_name, biz_sql_light) or {} biz1 = exact_match_store(store_name, biz_sql_light) or {}
park_dr = fuzzy_match_store(store_name, park_daily) or {} park_dr = exact_match_store(store_name, park_daily) or {}
output_value = Decimal(str(biz1.get('store_output_value', 0))) output_value = Decimal(str(biz1.get('store_output_value', 0)))
deal = int(Decimal(str(ind.get('A075', 0)))) deal = int(Decimal(str(ind.get('A075', 0))))
...@@ -429,6 +465,8 @@ class StoreEffectSummaryProcessor: ...@@ -429,6 +465,8 @@ class StoreEffectSummaryProcessor:
def generate_result_excel(self, task, row, board_metrics=None, local_only=False): def generate_result_excel(self, task, row, board_metrics=None, local_only=False):
stat_month = task.month or '' stat_month = task.month or ''
today_str = datetime.now().strftime('%Y%m%d')
type_name = task.data_table_type_name or task.data_table_type or 'result'
period_end = getattr(task, 'period_end', None) period_end = getattr(task, 'period_end', None)
period_start = getattr(task, 'period_start', None) period_start = getattr(task, 'period_start', None)
end_date_str = period_end.strftime('%Y-%m-%d') if period_end else '' end_date_str = period_end.strftime('%Y-%m-%d') if period_end else ''
...@@ -448,14 +486,14 @@ class StoreEffectSummaryProcessor: ...@@ -448,14 +486,14 @@ class StoreEffectSummaryProcessor:
out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)), out_dir = os.path.join(os.path.dirname(os.path.abspath(__file__)),
'outputs', 'store_effect_summary') 'outputs', 'store_effect_summary')
os.makedirs(out_dir, exist_ok=True) os.makedirs(out_dir, exist_ok=True)
final_path = os.path.join(out_dir, f'红黄门店盈利测算_{stat_month}.xlsx') final_path = os.path.join(out_dir, f'{type_name}_{today_str}.xlsx')
import shutil import shutil
shutil.copy2(local_path, final_path) shutil.copy2(local_path, final_path)
logger.info(f"[店效人效汇总] 6 sheet 本地文件: {final_path}") logger.info(f"[店效人效汇总] 6 sheet 本地文件: {final_path}")
return final_path return final_path
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}" object_key = (f"data-process/{today_str}"
f"/red_yellow_report_{stat_month}_{task.id}.xlsx") f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(local_path, object_key) file_url = upload_file(local_path, object_key)
logger.info(f"[店效人效汇总] 6 sheet 已上传 OSS: {file_url}") logger.info(f"[店效人效汇总] 6 sheet 已上传 OSS: {file_url}")
return file_url return file_url
...@@ -530,10 +568,10 @@ class StoreEffectSummaryProcessor: ...@@ -530,10 +568,10 @@ class StoreEffectSummaryProcessor:
tmp_dir = tempfile.mkdtemp(prefix=f'store_effect_result_{task.id}_') tmp_dir = tempfile.mkdtemp(prefix=f'store_effect_result_{task.id}_')
try: try:
excel_path = os.path.join(tmp_dir, f'门店店效人效汇总表_{stat_month}.xlsx') excel_path = os.path.join(tmp_dir, f'{type_name}_{today_str}.xlsx')
wb.save(excel_path) wb.save(excel_path)
object_key = (f"data-process/{datetime.now().strftime('%Y%m%d')}" object_key = (f"data-process/{today_str}"
f"/store_effect_summary_{stat_month}_{task.id}.xlsx") f"/{type_name}_{today_str}.xlsx")
file_url = upload_file(excel_path, object_key) file_url = upload_file(excel_path, object_key)
logger.info(f"[店效人效汇总] 回退单行已上传: {file_url}") logger.info(f"[店效人效汇总] 回退单行已上传: {file_url}")
return file_url return file_url
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!