Commit 3dfa6639 by zhouhaibao

feat(data-process): 新增轻改财务成本分项统计功能

- 在 light_reform_inshop_processor.py 中引入 fetch_light_reform_finance_stats 函数
- 在 light_reform_park_processor.py 中集成财务成本分项查询功能
- 新增 10 个财务成本字段包括产品成本、内部结算成本、原厂/副厂成本等
- 重构 report_utils.py 中的财务统计数据查询逻辑
- 优化 SQL 查询性能,使用单次聚合查询替代多次数据库访问
- 实现店中店和园区店共用财务成本统计,支持按订单类型和品类切分
1 parent 97f07f16
...@@ -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, fuzzy_match_store, fetch_park_daily_report, fetch_light_reform_goods_stats, fetch_light_reform_finance_stats, fuzzy_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
...@@ -158,14 +158,15 @@ class LightReformInshopProcessor: ...@@ -158,14 +158,15 @@ class LightReformInshopProcessor:
daily_report_map = fetch_park_daily_report(period_start, period_end, scene_type=1) daily_report_map = fetch_park_daily_report(period_start, period_end, scene_type=1)
# 2c. 品类成交数 + 产值(店中店+园区店共用 SQL,按 dj_order_type + AITO/HIMA 关键字聚合) # 2c. 品类成交数 + 产值(店中店+园区店共用 SQL,按 dj_order_type + AITO/HIMA 关键字聚合)
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 + 品类 + 原厂/副厂切分)
finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 2b. 模糊匹配到门店 → 组装 sql_data dict(get_with_fallback 双优先用) # 2b. 模糊匹配到门店 → 组装 sql_data dict(get_with_fallback 双优先用)
# 店中店:delivery_cnt→交车;equity→交付触客;after_sale→售后触客;
# 售后首保/事故回厂数 → 无 SQL,默认 0
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 = fuzzy_match_store(sn, daily_report_map) or {}
gs = fuzzy_match_store(sn, goods_stats_map) or {} gs = fuzzy_match_store(sn, goods_stats_map) or {}
fs = fuzzy_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),
...@@ -175,7 +176,7 @@ class LightReformInshopProcessor: ...@@ -175,7 +176,7 @@ class LightReformInshopProcessor:
'aftersales_shigu_cnt': 0, # 无 SQL 'aftersales_shigu_cnt': 0, # 无 SQL
'sales_order_cnt': 0, # 无 SQL(销售大定数) 'sales_order_cnt': 0, # 无 SQL(销售大定数)
'sales_touch_cnt': 0, # 无 SQL(销售触客数) 'sales_touch_cnt': 0, # 无 SQL(销售触客数)
# —— 品类成交数 + 产值(来自 fetch_inshop_goods_stats)—— # —— 品类成交数 + 产值(来自 fetch_light_reform_goods_stats)——
'total_deal_cnt': gs.get('total_deal_cnt', 0), 'total_deal_cnt': gs.get('total_deal_cnt', 0),
'window_film_oe_cnt': gs.get('window_film_oe_cnt', 0), 'window_film_oe_cnt': gs.get('window_film_oe_cnt', 0),
'window_film_nonoe_cnt': gs.get('window_film_nonoe_cnt', 0), 'window_film_nonoe_cnt': gs.get('window_film_nonoe_cnt', 0),
...@@ -188,6 +189,17 @@ class LightReformInshopProcessor: ...@@ -188,6 +189,17 @@ class LightReformInshopProcessor:
'internal_settle_value': gs.get('internal_settle_value', Decimal('0')), 'internal_settle_value': gs.get('internal_settle_value', Decimal('0')),
'oe_output_value': gs.get('oe_output_value', Decimal('0')), 'oe_output_value': gs.get('oe_output_value', Decimal('0')),
'nonoe_output_value': gs.get('nonoe_output_value', Decimal('0')), 'nonoe_output_value': gs.get('nonoe_output_value', Decimal('0')),
# —— 财务成本分项(来自 fetch_light_reform_finance_stats)——
'product_cost_finance': fs.get('product_cost_finance', Decimal('0')),
'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')),
'oe_product_cost': fs.get('oe_product_cost', Decimal('0')),
'nonoe_product_cost': fs.get('nonoe_product_cost', Decimal('0')),
'window_film_cost': fs.get('window_film_cost', Decimal('0')),
'car_wrap_cost': fs.get('car_wrap_cost', Decimal('0')),
'premium_cost': fs.get('premium_cost', Decimal('0')),
'store_share': fs.get('store_share', Decimal('0')),
'construction_income': fs.get('construction_income', Decimal('0')),
'market_fee': fs.get('market_fee', Decimal('0')),
} }
# ========== Step3: 上月预算明细(已在 Step1 从 Excel 解析) ========== # ========== Step3: 上月预算明细(已在 Step1 从 Excel 解析) ==========
......
...@@ -32,7 +32,7 @@ from report_utils import ( ...@@ -32,7 +32,7 @@ from report_utils import (
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_est_delivery_count, fuzzy_match_store, fetch_light_reform_finance_stats, fetch_est_delivery_count, fuzzy_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
...@@ -166,13 +166,15 @@ class LightReformParkProcessor: ...@@ -166,13 +166,15 @@ class LightReformParkProcessor:
goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end) goods_stats_map = fetch_light_reform_goods_stats(period_start, period_end)
# 3c. 预估交车数(静态配置表,无日期参数,traffic_party_name 即门店名) # 3c. 预估交车数(静态配置表,无日期参数,traffic_party_name 即门店名)
est_delivery_map = fetch_est_delivery_count(base_scene_code='100101') est_delivery_map = fetch_est_delivery_count(base_scene_code='100101')
# 3d. 模糊匹配到门店 → 组装 sql_data dict # 3d. 财务成本分项(店中店+园区店共用 SQL,park 侧仅消费 4 项)
# 园区店:delivery_cnt → 交车;equity + after_sale → 到店数;无效到店无 SQL → 0 finance_map = fetch_light_reform_finance_stats(period_start, period_end, scene_type=1)
# 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 = fuzzy_match_store(sn, daily_report_map) or {}
gs = fuzzy_match_store(sn, goods_stats_map) or {} gs = fuzzy_match_store(sn, goods_stats_map) or {}
fs = fuzzy_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] = {
...@@ -188,10 +190,15 @@ class LightReformParkProcessor: ...@@ -188,10 +190,15 @@ class LightReformParkProcessor:
# —— 产值(来自 fetch_light_reform_goods_stats)—— # —— 产值(来自 fetch_light_reform_goods_stats)——
'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,traffic_party_name 即门店名)—— # —— 预估交车数(来自 fetch_est_delivery_count)——
'est_delivery_cnt': fuzzy_match_store(sn, est_delivery_map) or 0, 'est_delivery_cnt': fuzzy_match_store(sn, est_delivery_map) or 0,
# —— 财务分项(park 仅消费产品成本/内部结算成本/流量费/市场费)——
'product_cost_finance': fs.get('product_cost_finance', Decimal('0')),
'internal_settle_cost': fs.get('internal_settle_cost', Decimal('0')),
'traffic_fee_finance': fs.get('store_share', Decimal('0')), # 流量费 = gopa.shop_traffic_money (dj_order_type!=6)
'market_fee_weighted': fs.get('market_fee', Decimal('0')), # 市场费加权测算 = fee 四项费用累计
} }
# 3e. 其他聚合 SQL(成本/市场费/流量费等)后续接入,当前保持默认 0 # 3f. 其他字段(service_fee / construction_cost 等) park 从 Excel 或公式取,保持 0
# ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ========== # ========== Step4: 上月预算明细(已在 Step1 从 Excel 解析) ==========
prev_budget_map = budget_achieve_map prev_budget_map = budget_achieve_map
......
...@@ -1164,33 +1164,37 @@ def _get_biz_sql_conn(): ...@@ -1164,33 +1164,37 @@ def _get_biz_sql_conn():
def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
""" """
**一条聚合 SQL** 批量查商品成本 / 市场费 / 服务费 / 产值 / 门店流量费。 延保/权益 轻改共用的财务类聚合 SQL(scene_type/business_type 由 biz_type 自动映射)。
一次 DB I/O 拿到所有门店的汇总值,避免 N+1。 一条 SQL 批量查出商品成本 / 市场费 / 服务费 / 流量费 / 产值,避免 N+1 和多表 LEFT JOIN 笛卡尔乘积。
字段口径(与 Java 财务测算保持一致):
- product_cost = upgrade_dj_cost + upgrade_third_party_cost(嘀加与第三方成本合计,子订单表 gso)
- market_fee = 四项费用累计(expense_category IN (706,808,809,901),子查询 GROUP BY order_code 避免重复行)
- service_fee = franchisee_profit_money(服务商金额,主汇总记录 gopa2)
- shop_traffic_money = shop_traffic_money(流量费,来自主表 gopa 不是 gopa2)
- store_output_value = total_price(门店产值分账金额,主汇总记录 gopa2)
- other_cost = custom_common_cost(其他费用,主汇总记录 gopa2)
调用方:warranty_processor(延保 biz_type=2.3)、equity_processor(权益 biz_type=2.1)
注:两个处理器的 store_output_value 都从指标系统 A036 取,这里 SQL 取的作为备用。
:param start_date: date 对象 :param start_date: date 对象
:param end_date: date 对象 :param end_date: date 对象
:param biz_type: '1.1' / '2.1' / '2.3' :param biz_type: '2.1' / '2.3'(延保权益才有财务 SQL;'1.1' 轻改已由 fetch_light_reform_goods_stats 接管)
:param store_names: list[str] 门店名列表(可选,不传则全量查该 biz_type 的所有门店) :param store_names: list[str] 门店名列表(可选,不传则全量查该 biz_type 的所有门店)
:return: dict[merchant_name] = { :return: dict[merchant_name] = {
product_cost, # Decimal 商品成本(dj_cost + 条件第三方成本) product_cost, market_fee, service_fee, store_output_value,
market_fee, # Decimal 市场费(管理层市场费1+2 + 阳光激励费1+2) shop_traffic_money, other_cost
service_fee, # Decimal 服务商总金额
store_output_value, # Decimal 门店产值(分账金额合计)
shop_traffic_money, # Decimal 门店流量费(来自主汇总记录)
} }
条件第三方成本说明(与 Java 代码一致):
- 按毛利分润(rule_type=1/RULE_OWNING_DISTRIBUTE) 时 = third_party_cost
- 按其他分润模式时 = 0
""" """
from config import Config from config import Config
if not Config.BIZ_SQL_ENABLED: if not Config.BIZ_SQL_ENABLED:
logger.warning("[BizSQL] BIZ_SQL_ENABLED=false,跳过查询") logger.warning("[BizSQL-延保权益财务] BIZ_SQL_ENABLED=false,跳过查询")
return {} return {}
mapping = BIZ_TYPE_TO_SMARTCARLIFE.get(biz_type) mapping = BIZ_TYPE_TO_SMARTCARLIFE.get(biz_type)
if not mapping: if not mapping:
logger.warning(f"[BizSQL] 未知 biz_type={biz_type}") logger.warning(f"[BizSQL-延保权益财务] 未知 biz_type={biz_type}")
return {} return {}
scene_type = mapping['scene_type'] scene_type = mapping['scene_type']
...@@ -1200,84 +1204,73 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1200,84 +1204,73 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
if conn is None: if conn is None:
return {} return {}
start_str = start_date.strftime('%Y-%m-%d 00:00:00') if start_date else ''
end_str = end_date.strftime('%Y-%m-%d 23:59:59') if end_date else ''
# —— SQL 构造 —— # —— SQL 构造 ——
# 主表:dj_car_life_goods_order_profit_allocation (gopa) 子订单级 # 子查询 fee:四项费用累计,INNER JOIN go+po 下推过滤避免笛卡尔乘积
# 关联:主订单 go + 支付单 po + 主汇总记录 gopa2(order_flag='Y' grain_size_type=1) # 外层:主表 gopa(子订单级) JOIN go+po+gso(子订单) + LEFT JOIN gopa2(主汇总 order_flag='Y') + LEFT JOIN fee
# 左连子查询:费用类目累计(expense_category 表按 order_code + 类目 sum)
# 左连子查询:服务商分账累计(merchant_distribution 表)
where_parts = [ where_parts = [
"gopa.deleted_flag = 'N'", "gopa.deleted_flag = 'N'",
"gopa.order_flag = 'N'", "gopa.order_flag = 'N'",
"go.deleted_flag = 'N'",
"po.deleted_flag = 'N'",
f"go.scene_type = {scene_type}", f"go.scene_type = {scene_type}",
f"po.success_date >= '{start_date} 00:00:00'", f"po.success_date >= '{start_str}'",
f"po.success_date <= '{end_date} 23:59:59'", f"po.success_date <= '{end_str}'",
] ]
if business_type is not None: if business_type is not None:
where_parts.append(f"go.business_type = {business_type}") where_parts.append(f"go.business_type = {business_type}")
if store_names: if store_names:
# 门店名模糊匹配(IN 太严,用 OR LIKE)
name_conds = [] name_conds = []
for n in store_names[:200]: # 防止 SQL 过长 for n in store_names[:200]:
safe_n = n.replace("'", "''") safe_n = n.replace("'", "''")
name_conds.append("go.merchant_name LIKE '%" + safe_n + "%'") name_conds.append("go.merchant_name LIKE '%" + safe_n + "%'")
where_parts.append(f"({' OR '.join(name_conds)})") where_parts.append(f"({' OR '.join(name_conds)})")
# 子查询 fee 的条件(日期/scene_type/business_type 必须与外层同步!)
fee_where = [
"ecc.deleted_flag = 'N'",
"go.deleted_flag = 'N'",
"po.deleted_flag = 'N'",
"ecc.expense_category_id IN (706, 808, 809, 901)",
f"po.success_date >= '{start_str}'",
f"po.success_date <= '{end_str}'",
f"go.scene_type = {scene_type}",
]
if business_type is not None:
fee_where.append(f"go.business_type = {business_type}")
sql = f""" sql = f"""
SELECT SELECT
go.merchant_name AS merchant_name, go.merchant_name AS merchant_name,
SUM(gopa.dj_cost) AS product_cost_dj, SUM(IFNULL(gso.upgrade_dj_cost, 0) + IFNULL(gso.upgrade_third_party_cost, 0))
SUM(CASE AS product_cost,
WHEN md_owning.division_money IS NOT NULL SUM(IFNULL(fee.total, 0)) AS market_fee,
THEN gopa.third_party_cost SUM(IFNULL(gopa2.franchisee_profit_money, 0)) AS service_fee,
ELSE 0 SUM(IFNULL(gopa2.total_price, 0)) AS store_output_value,
END) AS product_cost_conditional_third_party, SUM(IFNULL(gopa.shop_traffic_money, 0)) AS shop_traffic_money,
SUM(CASE WHEN ec1.expense_category_result IS NOT NULL THEN ec1.expense_category_result ELSE 0 END) SUM(IFNULL(gopa2.custom_common_cost, 0)) AS other_cost
+ SUM(CASE WHEN ec2.expense_category_result IS NOT NULL THEN ec2.expense_category_result ELSE 0 END)
+ SUM(CASE WHEN ec3.expense_category_result IS NOT NULL THEN ec3.expense_category_result ELSE 0 END)
+ SUM(CASE WHEN ec4.expense_category_result IS NOT NULL THEN ec4.expense_category_result ELSE 0 END)
AS market_fee,
SUM(CASE WHEN partner_actual.division_money IS NOT NULL THEN partner_actual.division_money ELSE 0 END)
+ SUM(CASE WHEN partner_owning.division_money IS NOT NULL THEN partner_owning.division_money ELSE 0 END)
AS service_fee,
SUM(gopa2.total_price) AS store_output_value,
SUM(gopa2.shop_traffic_money) AS shop_traffic_money
FROM dj_car_life_goods_order_profit_allocation gopa 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_goods_order go
INNER JOIN dj_car_life_pay_order po ON po.order_code = go.order_code AND po.deleted_flag = 'N' 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 LEFT JOIN dj_car_life_goods_order_profit_allocation gopa2
ON gopa2.order_code = gopa.order_code ON gopa2.order_code = gopa.order_code
AND gopa2.order_flag = 'Y' AND gopa2.order_flag = 'Y'
AND gopa2.grain_size_type = 1 AND gopa2.grain_size_type = 1
AND gopa2.deleted_flag = 'N' AND gopa2.deleted_flag = 'N'
-- 费用类目(4 种市场费):id=706/808/809/901 LEFT JOIN (
LEFT JOIN dj_car_life_order_expense_category_calculated ec1 SELECT
ON ec1.order_code = gopa.order_code AND ec1.expense_category_id = 706 AND ec1.deleted_flag = 'N' ecc.order_code,
LEFT JOIN dj_car_life_order_expense_category_calculated ec2 SUM(ecc.expense_category_result) AS total
ON ec2.order_code = gopa.order_code AND ec2.expense_category_id = 808 AND ec2.deleted_flag = 'N' FROM dj_car_life_order_expense_category_calculated ecc
LEFT JOIN dj_car_life_order_expense_category_calculated ec3 INNER JOIN dj_car_life_goods_order go ON ecc.order_code = go.order_code
ON ec3.order_code = gopa.order_code AND ec3.expense_category_id = 809 AND ec3.deleted_flag = 'N' INNER JOIN dj_car_life_pay_order po ON go.order_code = po.order_code
LEFT JOIN dj_car_life_order_expense_category_calculated ec4 WHERE {' AND '.join(fee_where)}
ON ec4.order_code = gopa.order_code AND ec4.expense_category_id = 901 AND ec4.deleted_flag = 'N' GROUP BY ecc.order_code
-- 服务商分账(实际分账 RULE_ACTUAL_DISTRIBUTE=2) ) fee ON fee.order_code = gopa.order_code
LEFT JOIN dj_car_life_merchant_distribution partner_actual
ON partner_actual.order_code = gopa.order_code
AND partner_actual.target_merchant_type = 2
AND partner_actual.rule_type = 2
AND partner_actual.deleted_flag = 'N'
-- 服务商费用归属(RULE_OWNING_DISTRIBUTE=1,用于判断条件第三方成本)
LEFT JOIN dj_car_life_merchant_distribution md_owning
ON md_owning.order_code = gopa.order_code
AND md_owning.target_merchant_type = 2
AND md_owning.rule_type = 1
AND md_owning.deleted_flag = 'N'
-- 服务商费用归属(平台方配置了归属规则 → 服务商应付)
LEFT JOIN dj_car_life_merchant_distribution partner_owning
ON partner_owning.order_code = gopa.order_code
AND partner_owning.target_merchant_type = 2
AND partner_owning.rule_type = 1
AND partner_owning.deleted_flag = 'N'
WHERE {' AND '.join(where_parts)} WHERE {' AND '.join(where_parts)}
GROUP BY go.merchant_name GROUP BY go.merchant_name
""" """
...@@ -1291,18 +1284,20 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None): ...@@ -1291,18 +1284,20 @@ def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
mn = r['merchant_name'] mn = r['merchant_name']
if not mn: if not mn:
continue continue
pc = (r['product_cost_dj'] or Decimal('0')) + (r['product_cost_conditional_third_party'] or Decimal('0'))
out[mn] = { out[mn] = {
'product_cost': Decimal(str(pc)).quantize(Decimal('0.01'), ROUND_HALF_UP), '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), '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), '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), '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), '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),
} }
logger.info(f"[BizSQL] biz_type={biz_type} 聚合完成, {len(out)} 个门店") logger.info(f"[BizSQL-延保权益财务] biz_type={biz_type} 聚合完成, {len(out)} 个门店")
return out return out
except Exception as e: except Exception as e:
logger.error(f"[BizSQL] 查询异常: {e}") logger.error(f"[BizSQL-延保权益财务] 查询异常: {e}")
import traceback
logger.error(traceback.format_exc())
return {} return {}
finally: finally:
try: try:
...@@ -1638,10 +1633,11 @@ def fetch_est_delivery_count(base_scene_code='100101'): ...@@ -1638,10 +1633,11 @@ def fetch_est_delivery_count(base_scene_code='100101'):
""" """
预估交车数批量查询(静态配置表,无日期参数)。 预估交车数批量查询(静态配置表,无日期参数)。
数据源:dj_car_life_merchant_store_info(门店流量方配置表) 数据源:dj_car_life_merchant_store_info(门店流量方配置表)
取值逻辑:estimated_delivery_count_per_month 为空时回退 delivery_count(IF 表达式)。
过滤条件:base_scene_code = '100101'(轻改), deleted_flag = 'N' 过滤条件:base_scene_code = '100101'(轻改), deleted_flag = 'N'
:param base_scene_code: 业务场景编码,默认 '100101' 轻改 :param base_scene_code: 业务场景编码,默认 '100101' 轻改
:return: dict[traffic_party_name] = estimated_delivery_count_per_month (int) :return: dict[traffic_party_name] = final_delivery_count (int)
""" """
from config import Config from config import Config
if not Config.BIZ_SQL_ENABLED: if not Config.BIZ_SQL_ENABLED:
...@@ -1653,11 +1649,14 @@ def fetch_est_delivery_count(base_scene_code='100101'): ...@@ -1653,11 +1649,14 @@ def fetch_est_delivery_count(base_scene_code='100101'):
return {} return {}
sql = f""" sql = f"""
SELECT traffic_party_name, estimated_delivery_count_per_month SELECT traffic_party_name,
IF(estimated_delivery_count_per_month IS NULL,
delivery_count,
estimated_delivery_count_per_month) AS final_delivery_count
FROM dj_car_life_merchant_store_info FROM dj_car_life_merchant_store_info
WHERE base_scene_code = '{base_scene_code}' WHERE base_scene_code = '{base_scene_code}'
AND deleted_flag = 'N' AND deleted_flag = 'N'
AND estimated_delivery_count_per_month IS NOT NULL ORDER BY created_date DESC
""" """
out = {} out = {}
...@@ -1666,8 +1665,9 @@ def fetch_est_delivery_count(base_scene_code='100101'): ...@@ -1666,8 +1665,9 @@ def fetch_est_delivery_count(base_scene_code='100101'):
for r in conn.execute(sa_text(sql)).mappings().all(): for r in conn.execute(sa_text(sql)).mappings().all():
tn = r['traffic_party_name'] tn = r['traffic_party_name']
if tn: # ORDER BY created_date DESC → 同门店多条时只取最新一条(先遍历到的就是最新)
out[tn] = int(r['estimated_delivery_count_per_month'] or 0) if tn and tn not in out:
out[tn] = int(r['final_delivery_count'] or 0)
logger.info(f"[BizSQL-预估交车数] 完成, {len(out)} 个门店") logger.info(f"[BizSQL-预估交车数] 完成, {len(out)} 个门店")
return out return out
...@@ -1683,6 +1683,179 @@ def fetch_est_delivery_count(base_scene_code='100101'): ...@@ -1683,6 +1683,179 @@ def fetch_est_delivery_count(base_scene_code='100101'):
pass pass
def fetch_light_reform_finance_stats(start_date, end_date, scene_type=1):
"""
轻改 店中店 + 园区店 共用:财务成本分项批量查询(scene_type=1)。
一条条件聚合 SQL 一次性查出所有门店的全部成本分项,供两个处理器按需消费。
核心公式(**注意与延保/权益不同!**):
商品成本 = SUM(upgrade_shop_price - base_shop_price)
(延保/权益用的是 upgrade_dj_cost + upgrade_third_party_cost,别搞混)
分项口径(全部用 CASE WHEN 按 dj_order_type + 品类 + 原厂/副厂 关键字切分):
- product_cost_finance 产品成本(dj_order_type != 6 非内部结算)
- internal_settle_cost 内部结算成本(dj_order_type = 6)
- oe_product_cost / nonoe_product_cost 原厂/副厂产品成本(dj_order_type != 6 + AITO/HIMA 关键字)
- window_film_cost / car_wrap_cost / premium_cost 品类产品成本(upgrade_goods_type_name 分类)
- store_share 门店分成/流量费(dj_order_type != 6 的 shop_traffic_money)
- construction_income 施工收入(custom_common_cost)
- market_fee 市场费(fee 子查询的四项费用累计:706/808/809/901)
数据源表:dj_car_life_goods_order_profit_allocation(gopa) + gopa2 + sub_order(gso) + order(go) + pay_order(po)
过滤条件:gopa.deleted_flag='N', gopa.order_flag='N', go.scene_type=scene_type, po.success_date BETWEEN ...
business_type **不限制**(1 或 2 都算轻改业务)
调用方说明:
- 店中店 inshop:消费全部 10 个字段
- 园区店 park:仅消费 product_cost_finance / internal_settle_cost / store_share(=traffic_fee_finance) / market_fee(=market_fee_weighted)
"""
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 {}
start_str = start_date.strftime('%Y-%m-%d 00:00:00') if start_date else ''
end_str = end_date.strftime('%Y-%m-%d 23:59:59') if end_date else ''
# 轻改品类常量(与 goods_stats 里的分类逻辑保持一致)
FILM_TYPES = "('自建商品-太阳膜','天窗冰甲','太阳膜')"
CAR_WRAP_TYPES = "('车衣','改色膜')"
PREMIUM_EXCLUDE = "('自建商品-太阳膜','天窗冰甲','车衣','改色膜','踏板','充电桩','验收一级类目','太阳膜')"
# 子查询 fee(四项费用累计)— 日期 + scene_type 与外层同步
fee_where = [
"ecc.deleted_flag = 'N'",
"go.deleted_flag = 'N'",
"po.deleted_flag = 'N'",
"ecc.expense_category_id IN (706, 808, 809, 901)",
f"po.success_date >= '{start_str}'",
f"po.success_date <= '{end_str}'",
f"go.scene_type = {scene_type}",
]
sql = f"""
SELECT
go.merchant_name AS merchant_name,
-- 产品成本(财务列表)= 非内部结算 dj_order_type != 6
SUM(CASE WHEN gopa.dj_order_type != 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS product_cost_finance,
-- 内部结算成本(财务列表)= 内部结算 dj_order_type = 6
SUM(CASE WHEN gopa.dj_order_type = 6
THEN gso.upgrade_shop_price - gso.base_shop_price
ELSE 0 END) AS internal_settle_cost,
-- 原厂产品成本(非内部结算 + 名称含 AITO/HIMA)
SUM(CASE WHEN gopa.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,
-- 副厂产品成本(非内部结算 + 名称不含 AITO/HIMA)
SUM(CASE WHEN gopa.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 gopa.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
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 {' 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
"""
try:
from sqlalchemy import text as sa_text
result = conn.execute(sa_text(sql))
rows = result.mappings().all()
out = {}
for r in rows:
mn = r['merchant_name']
if not mn:
continue
out[mn] = {
'product_cost_finance': Decimal(str(r['product_cost_finance'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'internal_settle_cost': Decimal(str(r['internal_settle_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'oe_product_cost': Decimal(str(r['oe_product_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'nonoe_product_cost': Decimal(str(r['nonoe_product_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'window_film_cost': Decimal(str(r['window_film_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'car_wrap_cost': Decimal(str(r['car_wrap_cost'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
'premium_cost': Decimal(str(r['premium_cost'] 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),
'market_fee': Decimal(str(r['market_fee'] or Decimal('0'))).quantize(Decimal('0.01'), ROUND_HALF_UP),
}
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 parse_saas_achieve_details(file_path, sheet_keywords, fallback_index=0): def parse_saas_achieve_details(file_path, sheet_keywords, fallback_index=0):
""" """
解析 SAAS门店预算分解表 的指定 sheet,返回门店明细列表。 解析 SAAS门店预算分解表 的指定 sheet,返回门店明细列表。
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!