Commit 315f21a5 by zhouhaibao

refactor(data-process): 优化业务SQL查询逻辑并移除未来拓展配置

- 将Flask端口从5001改为5000
- 移除config.py中的future_expansion配置项
- 在report_utils.py中添加多行平均门店收集功能用于调试
- 修改fetch_biz_sql_aggregated方法的SQL逻辑,将order_flag条件从'Y'改为'N'
- 更新SQL注释说明双层查询结构变化
- 简化日志输出信息
- 移除诊断查询相关代码
- 在exporttemplete的SQL模板中添加删除标记过滤条件
- 优化数值计算中的空值处理逻辑
1 parent dec4f00d
......@@ -33,5 +33,5 @@ INIT_NICKNAME=系统管理员
# ---------- 服务 ----------
FLASK_HOST=0.0.0.0
FLASK_PORT=5001
FLASK_PORT=5000
FLASK_DEBUG=true
......@@ -168,11 +168,6 @@ class Config:
'关系表',
],
},
'future_expansion': {
'name': '未来拓展',
'need_period': False,
'forms': [],
},
# 阿维塔专项:当前仅需上传主机厂数据表(表名暂定,后续若改名只改下方 forms)。
# 注意:此「主机厂数据表」为阿维塔专项独立数据表,格式不保证与现有
# 「鸿蒙主机厂数据表」/「广联主机厂数据表」一致,切勿复用
......
......@@ -75,7 +75,7 @@ LEFT JOIN dj_smartcarlife.dj_car_life_goods_order t2
ON t2.order_code = t1.order_code
AND t2.status IN (4,6,12)
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 t3.success_date BETWEEN '2026-08-01 00:00:00' AND '2026-08-31 23:59:59'
and t1.dj_order_type !=6
......
......@@ -738,6 +738,7 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
# 取平均
result = {}
multi_cnt_stores = [] # 收集多行平均的门店名
for (sn, _bt), fields in agg.items():
if sn not in result:
result[sn] = {
......@@ -747,11 +748,17 @@ def parse_budget_achieve_excel(file_path, biz_type=None):
'store_consumables': 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():
if cnt > 0:
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
......@@ -1527,12 +1534,9 @@ 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 ''
# —— SQL 构造 ——
# 子查询 fee:四项费用累计,INNER JOIN go+po 下推过滤避免笛卡尔乘积
# 外层:主表 gopa(子订单级) JOIN go+po+gso(子订单) + LEFT JOIN gopa2(主汇总 order_flag='Y') + LEFT JOIN fee
where_parts = [
"gopa.deleted_flag = 'N'",
"gopa.order_flag = 'Y'",
"gopa.grain_size_type = 1",
"gopa.order_flag = 'N'",
f"go.scene_type = {scene_type}",
f"po.success_date >= '{start_str}'",
f"po.success_date <= '{end_str}'",
......@@ -1559,11 +1563,10 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
if business_type is not None:
fee_where.append(f"go.business_type = {business_type}")
# 关键: 两层 GROUP BY 避免 JOIN 笛卡尔乘积
# 内层: 按 merchant_name + order_code GROUP BY
# - gopa/gso 级字段(product_cost, shop_traffic_money) → SUM(同订单多 sub_order 要累加)
# - order 级字段(fee.total, gopa2 各字段) → MAX(LEFT JOIN 被 gopa 多行放大,取单次值)
# 外层: 按 merchant_name GROUP BY → 全部 SUM(跨订单聚合)
# 一条 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"""
SELECT
t.merchant_name AS merchant_name,
......@@ -1577,12 +1580,13 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
SELECT
go.merchant_name,
gopa.order_code,
-- gopa/gso 子订单级:同订单多 sub_order_code → SUM 累加
-- 商品成本: 子订单级 gso 字段, 同订单多 sub_order → SUM
SUM(IFNULL(gso.upgrade_dj_cost, 0)
+ IF(gopa.shop_traffic_money_calculate_type = 1,
IFNULL(gso.upgrade_third_party_cost, 0), 0)) AS product_cost,
SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
-- order 级:LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
-- shop_traffic_money: 主汇总级字段, 从 gopa2(order_flag='Y') 取, MAX 防 LEFT JOIN 放大
MAX(IFNULL(gopa2.shop_traffic_money, 0)) AS shop_traffic_money,
-- 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,
......@@ -1618,7 +1622,7 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
try:
from sqlalchemy import text as sa_text
_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))
rows = result.mappings().all()
out = {}
......@@ -1627,47 +1631,14 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
if not mn:
continue
out[mn] = {
'product_cost': Decimal(str(r['product_cost'] 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),
'service_fee': Decimal(str(r['service_fee'] or Decimal('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),
'shop_traffic_money': Decimal(str(r['shop_traffic_money'] or Decimal('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),
'product_cost': Decimal(str(r['product_cost'] or 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 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 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)} 个门店")
# === 诊断:带 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}")
logger.info(f"[BizSQL-延保权益财务] biz_type={biz_type} 完成, {len(out)} 个门店")
return out
except Exception as e:
logger.error(f"[BizSQL-延保权益财务] 查询异常: {e}")
......@@ -2215,42 +2186,43 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
-- gpa/gso 子订单级: 同订单多 sub_order_code → SUM 累加
SUM(CASE WHEN gso.dj_order_type != 6
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
ELSE 0 END) AS product_cost_finance,
SUM(CASE WHEN gso.dj_order_type = 6
THEN (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
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) * gso.number
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 (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
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 (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
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 (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
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 (gso.upgrade_shop_price - gso.base_shop_price) * gso.number
THEN (IFNULL(gso.upgrade_shop_price, 0) - IFNULL(gso.base_shop_price, 0)) * IFNULL(gso.number, 1)
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,
-- 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,
-- order 级: LEFT JOIN 被 gopa 多行放大 → MAX 取单次值
-- construction_income / market_fee: MAX 取单次值
MAX(IFNULL(gopa2.custom_common_cost, 0)) AS construction_income,
MAX(IFNULL(fee.total, 0)) AS market_fee
......@@ -2260,7 +2232,7 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
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'
ON gopa.sub_order_code = gso.sub_order_code
LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y'
......@@ -2277,7 +2249,7 @@ def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
GROUP BY ecc.order_code
) fee ON fee.order_code = gopa.order_code
WHERE gopa.deleted_flag = 'N'
AND gopa.order_flag = 'Y' and gopa.grain_size_type = 1
AND gopa.order_flag = 'N'
AND go.scene_type = {scene_type}
AND po.success_date >= '{start_str}'
AND po.success_date <= '{end_str}'
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!