Commit 7ad208b5 by zhouhaibao

feat(data-process): 实现嘀加业务系统SQL数据源集成

- 配置文件中启用BIZ_SQL并设置嘀加数据库连接串
- 新增fetch_biz_sql_aggregated函数实现批量聚合查询
- 添加fuzzy_match_store函数实现门店名模糊匹配
- 在收益报告处理器中集成延保业务SQL数据查询
- 在权益处理器中集成权益业务SQL数据查询
- 替换原有的占位逻辑为实际的SQL数据获取
- 实现门店分成字段从store_share改为shop_traffic_money
- 新增订单分润导出分页查询脚本list_for_export_by_order.py
1 parent 9abd5db8
...@@ -94,10 +94,12 @@ class Config: ...@@ -94,10 +94,12 @@ class Config:
INDICATOR_BIZ_LIGHT_REFORM = 2 INDICATOR_BIZ_LIGHT_REFORM = 2
INDICATOR_BIZ_EQUITY = 3 INDICATOR_BIZ_EQUITY = 3
# ---------- 业务系统 SQL 数据源(占位,待后续完善连接串和查询)---------- # ---------- 业务系统 SQL 数据源(嘀加 dj_smartcarlife 库)----------
# 连接串示例:mysql+pymysql://user:pwd@host:port/db?charset=utf8mb4 BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'true').lower() == 'true'
BIZ_SQL_ENABLED = os.getenv('BIZ_SQL_ENABLED', 'false').lower() == 'true' BIZ_SQL_DATABASE_URL = os.getenv(
BIZ_SQL_DATABASE_URL = os.getenv('BIZ_SQL_DATABASE_URL', '') 'BIZ_SQL_DATABASE_URL',
'mysql+pymysql://wechat_user:b4WRTkl@192.168.1.228:3307/dj_smartcarlife?charset=utf8mb4'
)
# ---------- 文件上传 ---------- # ---------- 文件上传 ----------
MAX_CONTENT_LENGTH = 100 * 1024 * 1024 # 单文件最大 100M MAX_CONTENT_LENGTH = 100 * 1024 * 1024 # 单文件最大 100M
......
...@@ -25,6 +25,7 @@ from report_utils import ( ...@@ -25,6 +25,7 @@ from report_utils import (
download_all_files, download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, parse_saas_base, parse_region_map, parse_delivery_table,
parse_budget_achieve_excel, extract_budget_ratio, parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fuzzy_match_store,
fetch_indicator_data, fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
...@@ -151,14 +152,10 @@ class WarrantyProcessor: ...@@ -151,14 +152,10 @@ class WarrantyProcessor:
finally: finally:
cleanup_tmp_dir(tmp_dir) cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统(biz=1 延保) ========== # ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
warranty_codes = ['A084', 'A075', 'A066', 'A070', 'A086', 'A036'] store_names_for_sql = [r.get('store_name', '') for r in base_records if r.get('store_name')]
indicator_data = fetch_indicator_data( # BIZ_TYPE_WARRANTY='2.3' → scene_type=0, business_type=2
start_str, end_str, INDICATOR_BIZ_MAP['warranty'], warranty_codes) biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_WARRANTY, store_names_for_sql)
# ========== Step3: 业务系统 SQL(TODO 占位) ==========
biz_sql_data = {}
logger.warning("[延保] Step3 业务系统 SQL 暂未实现")
# ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ========== # ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========
...@@ -171,6 +168,8 @@ class WarrantyProcessor: ...@@ -171,6 +168,8 @@ 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 模糊匹配
biz_data = fuzzy_match_store(store_name, biz_sql_map) or {}
delivery_cnt = delivery_map.get(store_name, 0) delivery_cnt = delivery_map.get(store_name, 0)
# 指标系统取值 # 指标系统取值
...@@ -189,11 +188,12 @@ class WarrantyProcessor: ...@@ -189,11 +188,12 @@ class WarrantyProcessor:
easy_bag_penetration = safe_div_pct(easy_bag_cnt, delivery_cnt) easy_bag_penetration = safe_div_pct(easy_bag_cnt, delivery_cnt)
upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2) upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2)
biz_data = biz_sql_data.get(store_name, {}) # —— 业务系统 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'))
store_share = biz_data.get('store_share', Decimal('0')) # 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录)
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,6 +25,7 @@ from report_utils import ( ...@@ -25,6 +25,7 @@ from report_utils import (
download_all_files, download_all_files,
parse_saas_base, parse_region_map, parse_delivery_table, parse_saas_base, parse_region_map, parse_delivery_table,
parse_budget_achieve_excel, extract_budget_ratio, parse_budget_achieve_excel, extract_budget_ratio,
fetch_biz_sql_aggregated, fuzzy_match_store,
fetch_indicator_data, fetch_indicator_data,
safe_div, safe_div_pct, safe_div_pct_decimal, safe_div, safe_div_pct, safe_div_pct_decimal,
) )
...@@ -153,14 +154,10 @@ class EquityProcessor: ...@@ -153,14 +154,10 @@ class EquityProcessor:
finally: finally:
cleanup_tmp_dir(tmp_dir) cleanup_tmp_dir(tmp_dir)
# ========== Step2: 指标系统(biz=3 权益) ========== # ========== Step3: 业务系统 SQL(嘀加 dj_smartcarlife 库,批量一次查全) ==========
equity_codes = ['A084', 'A075', 'A036'] # 触客 / 成交 / 产值 store_names_for_sql = [r.get('store_name', '') for r in base_records if r.get('store_name')]
indicator_data = fetch_indicator_data( # BIZ_TYPE_EQUITY='2.1' → scene_type=0, business_type=1
start_str, end_str, INDICATOR_BIZ_MAP['equity'], equity_codes) biz_sql_map = fetch_biz_sql_aggregated(period_start, period_end, BIZ_TYPE_EQUITY, store_names_for_sql)
# ========== Step3: 业务系统 SQL(TODO 占位) ==========
biz_sql_data = {}
logger.warning("[权益] Step3 业务系统 SQL 暂未实现")
# ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ========== # ========== Step4: 上月营销费用占比(已在 Step1 从 Excel 解析) ==========
...@@ -173,6 +170,8 @@ class EquityProcessor: ...@@ -173,6 +170,8 @@ 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 模糊匹配
biz_data = fuzzy_match_store(store_name, biz_sql_map) or {}
delivery_cnt = delivery_map.get(store_name, 0) delivery_cnt = delivery_map.get(store_name, 0)
# 指标系统取值 # 指标系统取值
...@@ -184,11 +183,12 @@ class EquityProcessor: ...@@ -184,11 +183,12 @@ class EquityProcessor:
penetration_rate = safe_div_pct(deal_cnt, delivery_cnt) penetration_rate = safe_div_pct(deal_cnt, delivery_cnt)
upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2) upgrade_unit_price = safe_div(store_output_value, deal_cnt, 2)
biz_data = biz_sql_data.get(store_name, {}) # —— 业务系统 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'))
store_share = biz_data.get('store_share', Decimal('0')) # 门店分成 = 流量费累计 = shop_traffic_money(来自主汇总记录)
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
......
...@@ -1132,3 +1132,197 @@ def parse_commerce_policy_park(file_path, biz_type='1.1'): ...@@ -1132,3 +1132,197 @@ def parse_commerce_policy_park(file_path, biz_type='1.1'):
result[sn] = {f: v.get(f, Decimal('0')) for f in numeric} result[sn] = {f: v.get(f, Decimal('0')) for f in numeric}
logger.info(f"[商务政策-园区店] {len(result)} 个门店") logger.info(f"[商务政策-园区店] {len(result)} 个门店")
return result return result
# ============================================================
# 嘀加 dj_smartcarlife 业务系统 SQL 批量聚合查询
# ============================================================
# biz_type → 嘀加 scene_type / business_type 映射
# 1.1 → scene_type=1(轻改,无 business_type)
# 2.1 → scene_type=0, business_type=1(权益)
# 2.3 → scene_type=0, business_type=2(延保)
BIZ_TYPE_TO_SMARTCARLIFE = {
'1.1': {'scene_type': 1},
'2.1': {'scene_type': 0, 'business_type': 1},
'2.3': {'scene_type': 0, 'business_type': 2},
}
def _get_biz_sql_conn():
"""从 config.BIZ_SQL_DATABASE_URL 创建 SQLAlchemy engine + pymysql 连接。"""
from config import Config
try:
from sqlalchemy import create_engine, text
engine = create_engine(Config.BIZ_SQL_DATABASE_URL, echo=False, pool_pre_ping=True)
return engine.connect()
except Exception as e:
logger.error(f"[BizSQL] 连接 dj_smartcarlife 失败: {e}")
return None
def fetch_biz_sql_aggregated(start_date, end_date, biz_type, store_names=None):
"""
**一条聚合 SQL** 批量查商品成本 / 市场费 / 服务费 / 产值 / 门店流量费。
一次 DB I/O 拿到所有门店的汇总值,避免 N+1。
:param start_date: date 对象
:param end_date: date 对象
:param biz_type: '1.1' / '2.1' / '2.3'
:param store_names: list[str] 门店名列表(可选,不传则全量查该 biz_type 的所有门店)
:return: dict[merchant_name] = {
product_cost, # Decimal 商品成本(dj_cost + 条件第三方成本)
market_fee, # Decimal 市场费(管理层市场费1+2 + 阳光激励费1+2)
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
if not Config.BIZ_SQL_ENABLED:
logger.warning("[BizSQL] BIZ_SQL_ENABLED=false,跳过查询")
return {}
mapping = BIZ_TYPE_TO_SMARTCARLIFE.get(biz_type)
if not mapping:
logger.warning(f"[BizSQL] 未知 biz_type={biz_type}")
return {}
scene_type = mapping['scene_type']
business_type = mapping.get('business_type') # 1=权益, 2=延保; None=轻改
conn = _get_biz_sql_conn()
if conn is None:
return {}
# —— SQL 构造 ——
# 主表:dj_car_life_goods_order_profit_allocation (gopa) 子订单级
# 关联:主订单 go + 支付单 po + 主汇总记录 gopa2(order_flag='Y' grain_size_type=1)
# 左连子查询:费用类目累计(expense_category 表按 order_code + 类目 sum)
# 左连子查询:服务商分账累计(merchant_distribution 表)
where_parts = [
"gopa.deleted_flag = 'N'",
"gopa.order_flag = 'N'",
"go.deleted_flag = 'N'",
"po.deleted_flag = 'N'",
f"go.scene_type = {scene_type}",
f"po.success_date >= '{start_date} 00:00:00'",
f"po.success_date <= '{end_date} 23:59:59'",
]
if business_type is not None:
where_parts.append(f"go.business_type = {business_type}")
if store_names:
# 门店名模糊匹配(IN 太严,用 OR LIKE)
name_conds = []
for n in store_names[:200]: # 防止 SQL 过长
safe_n = n.replace("'", "''")
name_conds.append("go.merchant_name LIKE '%" + safe_n + "%'")
where_parts.append(f"({' OR '.join(name_conds)})")
sql = f"""
SELECT
go.merchant_name AS merchant_name,
SUM(gopa.dj_cost) AS product_cost_dj,
SUM(CASE
WHEN md_owning.division_money IS NOT NULL
THEN gopa.third_party_cost
ELSE 0
END) AS product_cost_conditional_third_party,
SUM(CASE WHEN ec1.expense_category_result IS NOT NULL THEN ec1.expense_category_result ELSE 0 END)
+ 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
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 po.order_code = go.order_code AND po.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'
-- 费用类目(4 种市场费):id=706/808/809/901
LEFT JOIN dj_car_life_order_expense_category_calculated ec1
ON ec1.order_code = gopa.order_code AND ec1.expense_category_id = 706 AND ec1.deleted_flag = 'N'
LEFT JOIN dj_car_life_order_expense_category_calculated ec2
ON ec2.order_code = gopa.order_code AND ec2.expense_category_id = 808 AND ec2.deleted_flag = 'N'
LEFT JOIN dj_car_life_order_expense_category_calculated ec3
ON ec3.order_code = gopa.order_code AND ec3.expense_category_id = 809 AND ec3.deleted_flag = 'N'
LEFT JOIN dj_car_life_order_expense_category_calculated ec4
ON ec4.order_code = gopa.order_code AND ec4.expense_category_id = 901 AND ec4.deleted_flag = 'N'
-- 服务商分账(实际分账 RULE_ACTUAL_DISTRIBUTE=2)
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)}
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
pc = (r['product_cost_dj'] or Decimal('0')) + (r['product_cost_conditional_third_party'] or Decimal('0'))
out[mn] = {
'product_cost': Decimal(str(pc)).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),
}
logger.info(f"[BizSQL] biz_type={biz_type} 聚合完成, {len(out)} 个门店")
return out
except Exception as e:
logger.error(f"[BizSQL] 查询异常: {e}")
return {}
finally:
try:
conn.close()
except Exception:
pass
def fuzzy_match_store(store_name, biz_sql_map):
"""
Excel 门店名 ↔ 业务表 merchant_name 模糊匹配。
规则:store_name in merchant_name 或 merchant_name in store_name。
精确匹配优先,否则取第一个包含关系匹配。
"""
if not store_name or not biz_sql_map:
return None
# 精确
if store_name in biz_sql_map:
return biz_sql_map[store_name]
# 模糊
for mn, val in biz_sql_map.items():
if store_name in mn or mn in store_name:
return val
return None
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!