Commit 70371d95 by 周立明

订单数,GMV,收入,成本(GMV口径),本月占比,上月占比 字段解析及入库

1 parent fc351f49
...@@ -21,3 +21,17 @@ ...@@ -21,3 +21,17 @@
数据库:MySQL 192.168.3.227/data_report。注意 `biz_budget_achieve`(utf8mb4_general_ci) 与 数据库:MySQL 192.168.3.227/data_report。注意 `biz_budget_achieve`(utf8mb4_general_ci) 与
`biz_budget_achieve_temp_main`(utf8mb4_unicode_ci) 排序规则不同,直接 UNION 会报 1271,需 CONVERT 或在 Python 侧比对。 `biz_budget_achieve_temp_main`(utf8mb4_unicode_ci) 排序规则不同,直接 UNION 会报 1271,需 CONVERT 或在 Python 侧比对。
## 第二步:补齐金额指标 6 列(order_count / gmv / revenue / cost_gmv / cost_gmv_ratio_current / cost_gmv_ratio_previous)
- `settlement_parser.py` 新增 `generate_budget_metrics(prev_metrics=None)`:按同维度累计 J升级数量、K订单金额、AF总应收、N总成本;
本月占比=成本(GMV口径)/GMV×100 四舍五入 2 位(用 Decimal ROUND_HALF_UP);上月占比取 `prev_metrics`(按 6 维匹配,缺失写 None)。
新增 `_to_num`(去千分位/货币符号)、`_ratio` 辅助函数。
- `clean_budget_achievement.py`:`save_budget_rows` 改为全量写 13 列(维度 7+金额 6,DELETE+INSERT 幂等);
新增 `prev_month_str(month)` 与 `query_previous_month_metrics(conn, prev_month)`(按 stat_month 上一月聚合 cost_gmv/gmv)。
- 修复 `config.py` 环境变量回写 bug:原 `_env_values.update(os.environ)` 后 `os.environ.update` 会把超长环境变量(沙箱注入)写回触发
Windows 32767 上限报错;改为仅把 .env 中真实环境未设置且长度≤32767 的项写回 os.environ,行为等价且更安全。
验证(2026-06):654 行全量重写;订单数合计 23326 与 Excel 明细累计精确一致;GMV/成本/收入与原始明细累计一致(仅 decimal(15,2) 逐行舍入 <0.02 偏差);
本月占比 651 行非空、3 组 GMV=0 写 NULL;上月占比 654 行全 NULL(2026-05 未处理,待跑完 2026-05 后重跑 2026-06 自动回填)。
比值抽查与 ROUND(成本/GMV×100,2) 精确一致。
...@@ -9,9 +9,17 @@ ...@@ -9,9 +9,17 @@
→ 解析并按维度分组 → 解析并按维度分组
→ 写入 biz_budget_achieve → 写入 biz_budget_achieve
本期只写入以下字段,其余指标字段留待后续步骤补齐: 本期写入字段(维度 7 个 + 金额 6 个,共 13 个):
task_id、stat_month、is_multi_category、traffic_name、 task_id、stat_month、is_multi_category、traffic_name、business_type、
business_type、entity、brand、park_store、service_provider entity、brand、park_store、service_provider、
order_count、gmv、revenue、cost_gmv、
cost_gmv_ratio_current、cost_gmv_ratio_previous
说明:
- 金额指标按「业务类型+主体+流量方+品牌+园区店+服务商」维度累计汇总;
- cost_gmv_ratio_current = 成本(GMV口径)/GMV*100(保留 2 位);
- cost_gmv_ratio_previous = 上月同维度比值,取自 biz_budget_achieve 中上一统计月的数据,
若上月数据尚未处理则写 NULL,待上月跑完后重跑本脚本即可自动回填。
用法: 用法:
python clean_budget_achievement.py --data-table-type budget_achievement --month 2026-06 python clean_budget_achievement.py --data-table-type budget_achievement --month 2026-06
...@@ -99,13 +107,59 @@ def update_clean_status(conn, file_id, status): ...@@ -99,13 +107,59 @@ def update_clean_status(conn, file_id, status):
conn.commit() conn.commit()
def prev_month_str(month):
"""'YYYY-MM' → 上一统计月字符串(如 2026-01 → 2025-12)。"""
year, mon = month.split('-')
year, mon = int(year), int(mon)
if mon == 1:
year, mon = year - 1, 12
else:
mon -= 1
return f'{year:04d}-{mon:02d}'
def query_previous_month_metrics(conn, prev_month):
"""查询上一统计月 biz_budget_achieve 中各维度组的成本(GMV口径)与 GMV 累计值。
用于计算 cost_gmv_ratio_previous(上月占比)。按 6 维度聚合,
返回 dict:key=(traffic_name, business_type, entity, brand, park_store, service_provider),
value={'cost_gmv':float, 'gmv':float}。
若上月数据尚未处理(查无记录),返回空 dict,对应比值写 None。
"""
sql = (
'SELECT traffic_name, business_type, entity, brand, park_store, service_provider, '
'SUM(cost_gmv) AS cost_gmv, SUM(gmv) AS gmv '
'FROM biz_budget_achieve '
'WHERE stat_month = %s '
'GROUP BY traffic_name, business_type, entity, brand, park_store, service_provider'
)
result = {}
with conn.cursor() as cur:
cur.execute(sql, (prev_month,))
for r in cur.fetchall():
key = (r['traffic_name'], r['business_type'], r['entity'],
r['brand'], r['park_store'], r['service_provider'])
result[key] = {
'cost_gmv': float(r['cost_gmv'] or 0),
'gmv': float(r['gmv'] or 0),
}
return result
def save_budget_rows(conn, task_id, stat_month, rows): def save_budget_rows(conn, task_id, stat_month, rows):
"""写入预算达成数据表:同一任务重跑先清空旧数据,再批量插入(单事务)。""" """写入预算达成数据表:同一任务重跑先清空旧数据,再批量插入(单事务)。
写入字段:维度 7 个 + 金额 6 个(order_count/gmv/revenue/cost_gmv/
cost_gmv_ratio_current/cost_gmv_ratio_previous)。
"""
insert_sql = ( insert_sql = (
f'INSERT INTO {TARGET_TABLE} ' f'INSERT INTO {TARGET_TABLE} '
'(task_id, stat_month, is_multi_category, traffic_name, business_type, ' '(task_id, stat_month, is_multi_category, traffic_name, business_type, '
' entity, brand, park_store, service_provider) ' ' entity, brand, park_store, service_provider, '
'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s)' ' order_count, gmv, revenue, cost_gmv, '
' cost_gmv_ratio_current, cost_gmv_ratio_previous) '
'VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)'
) )
params = [ params = [
( (
...@@ -118,6 +172,12 @@ def save_budget_rows(conn, task_id, stat_month, rows): ...@@ -118,6 +172,12 @@ def save_budget_rows(conn, task_id, stat_month, rows):
r['brand'] or None, r['brand'] or None,
r['park_store'] or None, r['park_store'] or None,
r['service_provider'] or None, r['service_provider'] or None,
r['order_count'],
r['gmv'],
r['revenue'],
r['cost_gmv'],
r['cost_gmv_ratio_current'],
r['cost_gmv_ratio_previous'],
) )
for r in rows for r in rows
] ]
...@@ -169,6 +229,13 @@ def process_task(conn, task, dry_run=False): ...@@ -169,6 +229,13 @@ def process_task(conn, task, dry_run=False):
file_row = files[0] file_row = files[0]
log(f' 附件 #{file_row["id"]}:{file_row["file_name"]}') log(f' 附件 #{file_row["id"]}:{file_row["file_name"]}')
# 上月数据(用于计算 cost_gmv_ratio_previous),写库阶段才查库
prev_month = prev_month_str(stat_month)
prev_metrics = query_previous_month_metrics(conn, prev_month) if not dry_run else {}
if not dry_run:
log(f' 上月统计月 {prev_month}:命中维度组 {len(prev_metrics)} 个'
f'(缺失则该组上月占比写 NULL)')
if not dry_run: if not dry_run:
update_clean_status(conn, file_row['id'], CLEAN_RUNNING) update_clean_status(conn, file_row['id'], CLEAN_RUNNING)
...@@ -177,7 +244,7 @@ def process_task(conn, task, dry_run=False): ...@@ -177,7 +244,7 @@ def process_task(conn, task, dry_run=False):
local_path = download_file(file_row['file_url'], tmp) local_path = download_file(file_row['file_url'], tmp)
parser = SettlementSummaryParser(local_path) parser = SettlementSummaryParser(local_path)
records = parser.parse() records = parser.parse()
rows = parser.generate_budget_first7() rows = parser.generate_budget_metrics(prev_metrics=prev_metrics)
log(f' 解析明细 {len(records)} 行 → 分组后 {len(rows)} 行' log(f' 解析明细 {len(records)} 行 → 分组后 {len(rows)} 行'
f'(多品类 {sum(1 for r in rows if r["is_multi_category"] == "是")} 行)') f'(多品类 {sum(1 for r in rows if r["is_multi_category"] == "是")} 行)')
...@@ -188,7 +255,8 @@ def process_task(conn, task, dry_run=False): ...@@ -188,7 +255,8 @@ def process_task(conn, task, dry_run=False):
return len(rows) return len(rows)
deleted, inserted = save_budget_rows(conn, task_id, stat_month, rows) deleted, inserted = save_budget_rows(conn, task_id, stat_month, rows)
log(f' 写入 {TARGET_TABLE}:清理旧数据 {deleted} 行,新增 {inserted} 行') log(f' 写入 {TARGET_TABLE}:清理旧数据 {deleted} 行,新增 {inserted} 行'
f'(含金额指标 6 列,本月占比非空 {sum(1 for r in rows if r["cost_gmv_ratio_current"] is not None)} 行)')
update_clean_status(conn, file_row['id'], CLEAN_DONE) update_clean_status(conn, file_row['id'], CLEAN_DONE)
return inserted return inserted
except Exception: except Exception:
......
...@@ -28,8 +28,15 @@ for _file in (BASE_DIR / '.env', BASE_DIR / f'.env.{APP_ENV}'): ...@@ -28,8 +28,15 @@ for _file in (BASE_DIR / '.env', BASE_DIR / f'.env.{APP_ENV}'):
for _k, _v in dotenv_values(_file).items(): for _k, _v in dotenv_values(_file).items():
if _v is not None: if _v is not None:
_env_values[_k] = _v _env_values[_k] = _v
_env_values.update({_k: _v for _k, _v in os.environ.items()}) # 真实环境变量优先级最高:仅在未设置时才用 .env 值
os.environ.update(_env_values) for _k, _v in os.environ.items():
_env_values.setdefault(_k, _v)
# 仅把 .env 中真实环境未设置的项写回 os.environ;
# 跳过超长值(Windows 环境变量长度上限 32767),避免 os.environ.update 因个别超大变量而失败
_ENV_MAX_LEN = 32767
for _k, _v in _env_values.items():
if _k not in os.environ and isinstance(_v, str) and len(_v) <= _ENV_MAX_LEN:
os.environ[_k] = _v
class Config: class Config:
......
...@@ -24,7 +24,9 @@ ...@@ -24,7 +24,9 @@
- 其他品牌 → 按原品牌信息取数汇总 - 其他品牌 → 按原品牌信息取数汇总
""" """
import os import os
import re
from collections import OrderedDict, defaultdict from collections import OrderedDict, defaultdict
from decimal import Decimal, ROUND_HALF_UP
import openpyxl import openpyxl
...@@ -110,6 +112,34 @@ def normalize_brand(brand): ...@@ -110,6 +112,34 @@ def normalize_brand(brand):
return brand_str return brand_str
def _to_num(value):
"""单元格数值归一:None/空 → None;数字原样;字符串去千分位与货币符号后转 float。"""
if value is None:
return None
if isinstance(value, bool):
return None
if isinstance(value, (int, float)):
return float(value)
s = str(value).strip().replace(',', '')
if not s:
return None
s = re.sub(r'[^\d.\-]', '', s) # 去掉 ¥、空格等非数字字符
if s in ('', '.', '-'):
return None
try:
return float(s)
except ValueError:
return None
def _ratio(cost, gmv):
"""成本(GMV口径)/GMV*100,四舍五入保留 2 位;分母为 0 返回 None。"""
if not gmv:
return None
return float((Decimal(str(cost)) / Decimal(str(gmv)) * 100).quantize(
Decimal('0.01'), rounding=ROUND_HALF_UP))
class SettlementSummaryParser: class SettlementSummaryParser:
"""结算数据汇总表解析器。""" """结算数据汇总表解析器。"""
...@@ -239,6 +269,87 @@ class SettlementSummaryParser: ...@@ -239,6 +269,87 @@ class SettlementSummaryParser:
self.budget_rows = rows self.budget_rows = rows
return rows return rows
def generate_budget_metrics(self, prev_metrics=None):
"""生成「预算达成数据表」维度 + 金额指标(维度同前 7 列,金额列累计汇总)。
金额指标来源(模板 I~N 列定义):
- order_count 订单数 ← 结算数据「升级数量」按维度累计
- gmv GMV ← 结算数据「订单金额」按维度累计
- revenue 收入 ← 结算数据「应收-总应收(按对账)」按维度累计
- cost_gmv 成本(GMV口径) ← 结算数据「商品成本-总成本」按维度累计
- cost_gmv_ratio_current 本月占比 ← 成本(GMV口径)/GMV*100,保留 2 位
- cost_gmv_ratio_previous 上月占比 ← 上月「成本(GMV口径)/GMV*100」,
prev_metrics 提供(key = 6 维),
缺失则写 None(待上月数据处理后重跑回填)
Args:
prev_metrics: dict,key=(traffic_name, business_type, entity, brand,
park_store, service_provider),value={'cost_gmv':float,'gmv':float}。
Returns:
list[dict]: 含 13 个字段的明细行。
"""
if not self.records:
self.parse()
groups = OrderedDict()
sums = {}
for rec in self.records:
if rec['brand'] == _EXCLUDED_BRAND: # 捷通达不纳入统计
continue
key = (
rec['business_type'],
rec['entity'],
rec['traffic_party'],
normalize_brand(rec['brand']),
rec['park_store'],
rec['service_provider'],
)
if key not in groups:
groups[key] = []
sums[key] = {'order_count': 0.0, 'gmv': 0.0, 'revenue': 0.0, 'cost_gmv': 0.0}
groups[key].append(rec)
m = sums[key]
m['order_count'] += _to_num(rec['upgrade_count']) or 0.0
m['gmv'] += _to_num(rec['order_amount']) or 0.0
m['revenue'] += _to_num(rec['receivable_total']) or 0.0
m['cost_gmv'] += _to_num(rec['cost_total']) or 0.0
traffic_business_types = defaultdict(set)
for business_type, _entity, traffic_party, _brand, _park, _sp in groups:
traffic_business_types[traffic_party].add(business_type)
rows = []
for business_type, entity, traffic_party, brand, park_store, sp in groups:
m = sums[(business_type, entity, traffic_party, brand, park_store, sp)]
order_count = int(round(m['order_count']))
gmv = round(m['gmv'], 2)
revenue = round(m['revenue'], 2)
cost_gmv = round(m['cost_gmv'], 2)
ratio_current = _ratio(cost_gmv, gmv)
ratio_previous = None
if prev_metrics:
pv = prev_metrics.get(
(traffic_party, business_type, entity, brand, park_store, sp))
if pv:
ratio_previous = _ratio(pv['cost_gmv'], pv['gmv'])
rows.append({
'is_multi_category': '是' if len(traffic_business_types[traffic_party]) > 1 else '否',
'traffic_name': traffic_party,
'business_type': business_type,
'entity': entity,
'brand': brand,
'park_store': park_store,
'service_provider': sp,
'order_count': order_count,
'gmv': gmv,
'revenue': revenue,
'cost_gmv': cost_gmv,
'cost_gmv_ratio_current': ratio_current,
'cost_gmv_ratio_previous': ratio_previous,
})
return rows
def get_titles(self): def get_titles(self):
"""返回预算达成数据前 7 个 title 名称列表。""" """返回预算达成数据前 7 个 title 名称列表。"""
return list(BUDGET_FIRST_7_TITLES) return list(BUDGET_FIRST_7_TITLES)
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!