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()
......
...@@ -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;
...@@ -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
......
...@@ -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!