展开查看
import base64
from io import BytesIO
from datetime import datetime
import html
import pandas as pd
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
from matplotlib import font_manager
# =========================
# 字体设置:避免中文显示为方框
# =========================
font_candidates = [
"PingFang SC",
"PingFang HK",
"Heiti SC",
"Heiti TC",
"STHeiti",
"Microsoft YaHei",
"SimHei",
"Arial Unicode MS"
]
available_fonts = {f.name for f in font_manager.fontManager.ttflist}
for name in font_candidates:
if name in available_fonts:
plt.rcParams["font.family"] = name
break
plt.rcParams["axes.unicode_minus"] = False
# =========================
# ROI 模型参数(可根据业务调整)
# =========================
# 固定预算:每个渠道在统计周期内的固定投放成本(单位:元)
BUDGET_PER_CHANNEL = {
"自然流量": 15000,
"搜索广告": 80000,
"直播": 120000,
"推荐": 60000,
"老客回访": 20000
}
# CAC:每个渠道的获客成本(按订单计,单位:元/单)
CAC_PER_ORDER = {
"自然流量": 2,
"搜索广告": 35,
"直播": 45,
"推荐": 20,
"老客回访": 8
}
# 广告费率:广告费用占 GMV 的比例(无单位,如 0.08 表示 8%)
AD_SPEND_RATE = {
"自然流量": 0.00,
"搜索广告": 0.08,
"直播": 0.10,
"推荐": 0.06,
"老客回访": 0.03
}
# 毛利率(用于 ROI 的毛利口径对比)
DEFAULT_MARGIN_RATE = 0.25
CATEGORY_MARGIN_RATE = {
"电脑": 0.15,
"手机": 0.10,
"家电": 0.18,
"服饰": 0.45,
"美妆": 0.55,
"食品": 0.25
}
# =========================
# 读取数据
# =========================
# 读取清洗后的订单数据
raw_df = pd.read_csv("data/orders_clean.csv")
# 解析订单时间为 datetime,便于按月/周统计
raw_df["order_time"] = pd.to_datetime(raw_df["order_time"])
# 全量订单:包含取消/退款,但净额与件数需置 0,避免被计入成交
all_df = raw_df.copy()
mask_cancel = all_df["status"].isin(["cancelled", "refunded"])
all_df.loc[mask_cancel, "net"] = 0
all_df.loc[mask_cancel, "qty"] = 0
# 有效订单:排除取消/退款
valid_df = all_df[~mask_cancel].copy()
# =========================
# 工具函数:将图表转为 base64
# =========================
# 这样 HTML 可单文件直接打开,无需外部图片文件
def fig_to_base64(fig):
# 创建内存缓冲区
buf = BytesIO()
# 将图表写入缓冲区
fig.savefig(buf, format="png", bbox_inches="tight")
# 关闭图表,释放内存
plt.close(fig)
# 把图片字节转为 base64 字符串
return base64.b64encode(buf.getvalue()).decode("utf-8")
# =========================
# 计算某个统计口径的数据(有效订单 / 全量订单)
# =========================
def compute_scope(df_scope, df_all, scope_key):
"""
df_scope: 当前口径数据(有效订单 or 全量订单)
df_all: 全量订单(用于计算退款率等)
scope_key: 标识(valid / all)
"""
# -------------------------
# 核心 KPI
# -------------------------
total_orders = len(df_scope)
valid_orders = len(df_scope[~df_scope["status"].isin(["cancelled", "refunded"])])
gmv = df_scope["net"].sum()
aov = gmv / total_orders if total_orders else 0
users = df_scope["user_id"].nunique()
items = df_scope["qty"].sum()
member_rate = df_scope["is_member"].mean() if total_orders else 0
kpi = {
"total_orders": total_orders,
"valid_orders": valid_orders,
"gmv": gmv,
"aov": aov,
"users": users,
"items": items,
"member_rate": member_rate
}
# -------------------------
# 月度汇总
# -------------------------
df_scope = df_scope.copy()
df_scope["month"] = df_scope["order_time"].dt.to_period("M").astype(str)
monthly = df_scope.groupby("month").agg(
orders=("order_id", "count"),
gmv=("net", "sum"),
items=("qty", "sum")
).reset_index()
monthly["aov"] = (monthly["gmv"] / monthly["orders"]).round(2)
monthly = monthly.sort_values("month")
# -------------------------
# 周度汇总(ISO 周)
# -------------------------
iso = df_scope["order_time"].dt.isocalendar()
df_scope["week"] = iso["year"].astype(str) + "-W" + iso["week"].astype(str).str.zfill(2)
weekly = df_scope.groupby("week").agg(
orders=("order_id", "count"),
gmv=("net", "sum")
).reset_index().sort_values("week")
# -------------------------
# 类目汇总
# -------------------------
category = df_scope.groupby("category").agg(
orders=("order_id", "count"),
gmv=("net", "sum"),
items=("qty", "sum")
).reset_index()
category["aov"] = (category["gmv"] / category["orders"]).round(2)
# -------------------------
# 价格区间(按四分位切分)
# -------------------------
q25 = df_scope["net"].quantile(0.25)
q75 = df_scope["net"].quantile(0.75)
def price_band(x):
# 低于 25% 分位:低客单
if x <= q25:
return "低客单"
# 高于 75% 分位:高客单
if x >= q75:
return "高客单"
# 其余:中客单
return "中客单"
df_scope["price_band"] = df_scope["net"].apply(price_band)
price_band_summary = df_scope.groupby("price_band").agg(
orders=("order_id", "count"),
users=("user_id", "nunique"),
gmv=("net", "sum"),
items=("qty", "sum"),
member_rate=("is_member", "mean")
).reset_index()
price_band_summary["aov"] = (price_band_summary["gmv"] / price_band_summary["orders"]).round(2)
price_band_summary["member_rate"] = (price_band_summary["member_rate"] * 100).round(2)
price_band_summary["order_share"] = (price_band_summary["orders"] / price_band_summary["orders"].sum() * 100).round(2)
price_band_summary["gmv_share"] = (price_band_summary["gmv"] / price_band_summary["gmv"].sum() * 100).round(2)
# -------------------------
# 用户画像(按用户客单价分层)
# -------------------------
user_aov = df_scope.groupby("user_id").agg(
user_orders=("order_id", "count"),
user_gmv=("net", "sum"),
member=("is_member", "mean")
).reset_index()
user_aov["user_aov"] = (user_aov["user_gmv"] / user_aov["user_orders"]).round(2)
u25 = user_aov["user_aov"].quantile(0.25)
u75 = user_aov["user_aov"].quantile(0.75)
def user_band(x):
# 低于 25% 分位:低客单用户
if x <= u25:
return "低客单用户"
# 高于 75% 分位:高客单用户
if x >= u75:
return "高客单用户"
# 其余:中客单用户
return "中客单用户"
user_aov["user_band"] = user_aov["user_aov"].apply(user_band)
user_band_summary = user_aov.groupby("user_band").agg(
users=("user_id", "count"),
avg_orders=("user_orders", "mean"),
avg_gmv=("user_gmv", "mean"),
avg_aov=("user_aov", "mean"),
member_rate=("member", "mean")
).reset_index()
user_band_summary["member_rate"] = (user_band_summary["member_rate"] * 100).round(2)
user_band_summary = user_band_summary.round(2)
# -------------------------
# 新客 / 老客结构(按月)
# -------------------------
user_first_month = df_scope.groupby("user_id")["month"].min()
df_scope["first_month"] = df_scope["user_id"].map(user_first_month)
df_scope["is_new_order"] = df_scope["month"] == df_scope["first_month"]
new_old = df_scope.groupby("month").agg(
orders=("order_id", "count"),
new_orders=("is_new_order", "sum")
).reset_index().sort_values("month")
new_old["old_orders"] = new_old["orders"] - new_old["new_orders"]
new_old["new_rate"] = (new_old["new_orders"] / new_old["orders"] * 100).round(2)
# -------------------------
# 渠道 ROI(GMV 口径 + 毛利口径)
# -------------------------
roi_base = df_scope.copy()
roi_base["margin_rate"] = roi_base["category"].map(CATEGORY_MARGIN_RATE).fillna(DEFAULT_MARGIN_RATE)
roi_base["gross_profit"] = (roi_base["net"] * roi_base["margin_rate"]).round(2)
channel = roi_base.groupby("channel").agg(
orders=("order_id", "count"),
gmv=("net", "sum"),
gross_profit=("gross_profit", "sum")
).reset_index()
channel["budget"] = channel["channel"].map(BUDGET_PER_CHANNEL).fillna(0)
channel["cac"] = channel["channel"].map(CAC_PER_ORDER).fillna(0)
channel["ad_rate"] = channel["channel"].map(AD_SPEND_RATE).fillna(0)
channel["ad_spend"] = (channel["gmv"] * channel["ad_rate"]).round(2)
channel["spend"] = (channel["budget"] + channel["orders"] * channel["cac"] + channel["ad_spend"]).round(2)
channel["roi_gmv"] = ((channel["gmv"] - channel["spend"]) / channel["spend"]).round(2)
channel["roi_margin"] = ((channel["gross_profit"] - channel["spend"]) / channel["spend"]).round(2)
channel_sorted = channel.sort_values("roi_gmv", ascending=False)
# -------------------------
# 渠道质量画像(AOV / 退款率 / 复购率)
# -------------------------
quality = df_scope.groupby("channel").agg(
orders=("order_id", "count"),
gmv=("net", "sum")
).reset_index()
quality["aov"] = (quality["gmv"] / quality["orders"]).round(2)
# 退款率:基于全量订单
refund_counts = df_all[df_all["status"].isin(["cancelled", "refunded"])].groupby("channel").size()
total_counts = df_all.groupby("channel").size()
refund_rate = (refund_counts / total_counts * 100).fillna(0).round(2)
quality["refund_rate"] = quality["channel"].map(refund_rate).fillna(0)
# 复购率:按渠道统计用户是否有 2 笔及以上订单
user_orders = df_scope.groupby(["channel", "user_id"]).size().reset_index(name="order_cnt")
repeat_users = user_orders[user_orders["order_cnt"] >= 2].groupby("channel")["user_id"].nunique()
total_users = user_orders.groupby("channel")["user_id"].nunique()
repeat_rate = (repeat_users / total_users * 100).fillna(0).round(2)
quality["repeat_rate"] = quality["channel"].map(repeat_rate).fillna(0)
# -------------------------
# 图表生成(转成 base64)
# -------------------------
# 月度 GMV(单位:万元)
fig1 = plt.figure(figsize=(7, 3.5))
monthly_gmv_10k = monthly["gmv"] / 10000
plt.plot(monthly["month"], monthly_gmv_10k, marker="o")
plt.title("月度 GMV / Monthly GMV")
plt.xlabel("月份 / Month")
plt.ylabel("GMV(万元)")
plt.xticks(rotation=45)
monthly_b64 = fig_to_base64(fig1)
# 周度 GMV(单位:万元)
fig_week = plt.figure(figsize=(7, 3.5))
weekly_gmv_10k = weekly["gmv"] / 10000
plt.plot(weekly["week"], weekly_gmv_10k, marker="o")
plt.title("周度 GMV / Weekly GMV")
plt.xlabel("周 / Week")
plt.ylabel("GMV(万元)")
plt.xticks(rotation=45)
weekly_b64 = fig_to_base64(fig_week)
# 类目 GMV(单位:万元)
fig2 = plt.figure(figsize=(7, 3.5))
category_sorted = category.sort_values("gmv", ascending=False)
category_gmv_10k = category_sorted["gmv"] / 10000
plt.bar(category_sorted["category"], category_gmv_10k)
plt.title("类目 GMV / GMV by Category")
plt.xlabel("类目 / Category")
plt.ylabel("GMV(万元)")
category_b64 = fig_to_base64(fig2)
# 价格区间 GMV(单位:万元)
fig3 = plt.figure(figsize=(6, 3.5))
price_gmv_10k = price_band_summary["gmv"] / 10000
plt.bar(price_band_summary["price_band"], price_gmv_10k)
plt.title("价格区间 GMV / GMV by Price Band")
plt.xlabel("价格区间 / Price Band")
plt.ylabel("GMV(万元)")
price_b64 = fig_to_base64(fig3)
# 价格区间渗透率(订单占比 + GMV 占比)
fig_pen = plt.figure(figsize=(6, 3.5))
x = range(len(price_band_summary["price_band"]))
plt.bar([i - 0.2 for i in x], price_band_summary["order_share"], width=0.4, label="订单占比")
plt.bar([i + 0.2 for i in x], price_band_summary["gmv_share"], width=0.4, label="GMV占比")
plt.xticks(list(x), price_band_summary["price_band"])
plt.title("价格区间渗透率 / Price Band Penetration")
plt.xlabel("价格区间 / Price Band")
plt.ylabel("占比(%)")
plt.legend()
pen_b64 = fig_to_base64(fig_pen)
# 新客占比趋势
fig_new = plt.figure(figsize=(7, 3.5))
plt.plot(new_old["month"], new_old["new_rate"], marker="o")
plt.title("新客订单占比 / New Customer Share")
plt.xlabel("月份 / Month")
plt.ylabel("新客占比(%)")
plt.xticks(rotation=45)
new_b64 = fig_to_base64(fig_new)
# 渠道 ROI(GMV 口径)
fig4 = plt.figure(figsize=(7, 3.5))
plt.bar(channel_sorted["channel"], channel_sorted["roi_gmv"])
plt.title("渠道 ROI / ROI by Channel")
plt.xlabel("渠道 / Channel")
plt.ylabel("ROI")
roi_b64 = fig_to_base64(fig4)
# -------------------------
# 关键发现(用于报告摘要)
# -------------------------
top_category = category_sorted.iloc[0]
best_month = monthly.sort_values("gmv", ascending=False).iloc[0]
top_channel = channel_sorted.iloc[0] if not channel_sorted.empty else None
# -------------------------
# 表格列名:中英文双语(用于表头)
# -------------------------
price_band_display = price_band_summary.rename(columns={
"price_band": "价格区间<br><span class='th-en'>Price Band</span>",
"orders": "订单数<br><span class='th-en'>Orders</span>",
"users": "用户数<br><span class='th-en'>Users</span>",
"gmv": "GMV 成交额<br><span class='th-en'>GMV</span>",
"items": "销量<br><span class='th-en'>Items</span>",
"member_rate": "会员占比<br><span class='th-en'>Member Rate</span>",
"aov": "客单价<br><span class='th-en'>AOV</span>",
"order_share": "订单占比<br><span class='th-en'>Order Share</span>",
"gmv_share": "GMV占比<br><span class='th-en'>GMV Share</span>"
})
user_band_display = user_band_summary.rename(columns={
"user_band": "用户分层<br><span class='th-en'>User Band</span>",
"users": "用户数<br><span class='th-en'>Users</span>",
"avg_orders": "均订单数<br><span class='th-en'>Avg Orders</span>",
"avg_gmv": "均 GMV<br><span class='th-en'>Avg GMV</span>",
"avg_aov": "均客单价<br><span class='th-en'>Avg AOV</span>",
"member_rate": "会员占比<br><span class='th-en'>Member Rate</span>"
})
channel_display = channel_sorted.rename(columns={
"channel": "渠道<br><span class='th-en'>Channel</span>",
"orders": "订单数<br><span class='th-en'>Orders</span>",
"gmv": "GMV 成交额<br><span class='th-en'>GMV</span>",
"gross_profit": "毛利<br><span class='th-en'>Gross Profit</span>",
"budget": "固定预算<br><span class='th-en'>Budget</span>",
"cac": "CAC 获客成本<br><span class='th-en'>CAC</span>",
"ad_rate": "广告费率<br><span class='th-en'>Ad Rate</span>",
"ad_spend": "广告费<br><span class='th-en'>Ad Spend</span>",
"spend": "投放成本<br><span class='th-en'>Total Spend</span>",
"roi_gmv": "ROI 回报率<br><span class='th-en'>ROI (GMV)</span>",
"roi_margin": "ROI 毛利<br><span class='th-en'>ROI (Margin)</span>"
})
quality_display = quality.rename(columns={
"channel": "渠道<br><span class='th-en'>Channel</span>",
"orders": "订单数<br><span class='th-en'>Orders</span>",
"gmv": "GMV 成交额<br><span class='th-en'>GMV</span>",
"aov": "客单价<br><span class='th-en'>AOV</span>",
"refund_rate": "退款率<br><span class='th-en'>Refund Rate</span>",
"repeat_rate": "复购率<br><span class='th-en'>Repeat Rate</span>"
})
new_old_display = new_old.rename(columns={
"month": "月份<br><span class='th-en'>Month</span>",
"orders": "订单数<br><span class='th-en'>Orders</span>",
"new_orders": "新客订单<br><span class='th-en'>New Orders</span>",
"old_orders": "老客订单<br><span class='th-en'>Returning Orders</span>",
"new_rate": "新客占比<br><span class='th-en'>New Share</span>"
})
return {
"kpi": kpi,
"monthly_b64": monthly_b64,
"weekly_b64": weekly_b64,
"category_b64": category_b64,
"price_b64": price_b64,
"pen_b64": pen_b64,
"new_b64": new_b64,
"roi_b64": roi_b64,
"top_category": top_category,
"best_month": best_month,
"top_channel": top_channel,
"price_band_display": price_band_display,
"user_band_display": user_band_display,
"channel_display": channel_display,
"quality_display": quality_display,
"new_old_display": new_old_display
}
# =========================
# 生成两套口径数据
# =========================
valid_scope = compute_scope(valid_df, all_df, "valid")
all_scope = compute_scope(all_df, all_df, "all")
# =========================
# 生成单个口径的 HTML 内容
# =========================
def render_scope(scope, scope_key, scope_label):
k = scope["kpi"]
return f"""
<div class="scope-section" data-scope="{scope_key}">
<section class="section">
<div class="section-header">
<h2>核心指标</h2>
<div class="muted">当前口径:{scope_label}</div>
</div>
<div class="kpi">
<div class="kpi-card">总订单数<br><b>{k['total_orders']}</b><span>包含取消/退款</span></div>
<div class="kpi-card">有效订单数<br><b>{k['valid_orders']}</b><span>排除取消/退款</span></div>
<div class="kpi-card">销量(件)<br><b>{k['items']}</b><span>订单件数</span></div>
<div class="kpi-card">独立用户数<br><b>{k['users']}</b><span>订单用户数</span></div>
<div class="kpi-card">会员占比<br><b>{k['member_rate']:.2%}</b><span>会员订单比</span></div>
<div class="kpi-card">客单价(净)<br><b>{k['aov']:.2f}</b><span>GMV / 订单数</span></div>
<div class="kpi-card">GMV(净额成交)<br><b>{k['gmv']:.2f}</b><span>净额成交</span></div>
</div>
<div class="kpi-note">
口径说明:有效订单数 = 总订单数 − 取消/退款订单数;销量(件) = 有效订单 qty(每个订单包含商品数量)之和;
独立用户数 = 有效订单去重用户数;会员占比 = 会员订单数 ÷ 有效订单数;
GMV(净额成交)= 有效订单 net 之和(net = price × qty − discount + shipping(price 单价,qty 件数,discount 折扣额,shipping 运费),取消/退款记为 0);
客单价(净) = GMV ÷ 有效订单数。
</div>
</section>
<section class="section">
<div class="section-header">
<h2>关键发现</h2>
<div class="muted">优先级最高的业务洞察</div>
</div>
<ul class="insights">
<li>GMV(成交额)最高类目:{scope['top_category']['category']}({scope['top_category']['gmv']:.2f})</li>
<li>GMV(成交额)最高月份:{scope['best_month']['month']}({scope['best_month']['gmv']:.2f})</li>
<li>ROI(回报率)最高渠道:{scope['top_channel']['channel']}(ROI {scope['top_channel']['roi_gmv']:.2f})</li>
</ul>
</section>
<section class="section">
<div class="section-header">
<h2>趋势与结构</h2>
<div class="muted">月度/周度变化与类目贡献</div>
</div>
<div class="chart-grid">
<div class="chart-card">
<h3>月度 GMV <span class="en-inline">Monthly GMV</span></h3>
<img src="data:image/png;base64,{scope['monthly_b64']}" />
</div>
<div class="chart-card">
<h3>周度 GMV <span class="en-inline">Weekly GMV</span></h3>
<img src="data:image/png;base64,{scope['weekly_b64']}" />
</div>
<div class="chart-card">
<h3>类目 GMV <span class="en-inline">GMV by Category</span></h3>
<img src="data:image/png;base64,{scope['category_b64']}" />
</div>
</div>
</section>
<section class="section">
<div class="section-header">
<h2>价格区间分析</h2>
<div class="muted">高/中/低客单贡献与渗透率</div>
</div>
<div class="chart-grid">
<div class="chart-card">
<h3>价格区间 GMV <span class="en-inline">GMV by Price Band</span></h3>
<img src="data:image/png;base64,{scope['price_b64']}" />
</div>
<div class="chart-card">
<h3>价格区间渗透率 <span class="en-inline">Penetration</span></h3>
<img src="data:image/png;base64,{scope['pen_b64']}" />
</div>
</div>
{scope['price_band_display'].to_html(index=False, escape=False)}
<h3>用户画像 <span class="en-inline">User Profile</span></h3>
{scope['user_band_display'].to_html(index=False, escape=False)}
</section>
<section class="section">
<div class="section-header">
<h2>新客 / 老客结构</h2>
<div class="muted">新客订单占比趋势</div>
</div>
<div class="chart-grid">
<div class="chart-card">
<h3>新客占比 <span class="en-inline">New Customer Share</span></h3>
<img src="data:image/png;base64,{scope['new_b64']}" />
</div>
</div>
{scope['new_old_display'].to_html(index=False, escape=False)}
</section>
<section class="section">
<div class="section-header">
<h2>渠道 ROI(行业常用 GMV 口径)</h2>
<div class="muted">预算结构下的回报对比(含 ROI 双口径)</div>
</div>
<div class="note">
<div class="label">口径说明:</div>
<div>ROI(GMV) = (GMV - 投放成本) / 投放成本</div>
<div>ROI(毛利) = (毛利 - 投放成本) / 投放成本</div>
<div>投放成本 = 固定预算 + 订单数 × CAC(获客成本)+ 广告费(GMV × 广告费率)</div>
<div>统计范围:{scope_label}</div>
</div>
<div class="chart-grid">
<div class="chart-card">
<h3>渠道 ROI <span class="en-inline">ROI by Channel</span></h3>
<img src="data:image/png;base64,{scope['roi_b64']}" />
</div>
</div>
{scope['channel_display'].to_html(index=False, escape=False)}
</section>
<section class="section">
<div class="section-header">
<h2>渠道质量画像</h2>
<div class="muted">客单价 / 退款率 / 复购率</div>
</div>
{scope['quality_display'].to_html(index=False, escape=False)}
</section>
</div>
"""
valid_html = render_scope(valid_scope, "valid", "有效订单")
all_html = render_scope(all_scope, "all", "全量订单")
# =========================
# 附件功能:复制 / 下载按钮(内联脚本)
# =========================
script = """
<script>
function setScope(scope) {
document.querySelectorAll(".scope-section").forEach(function(el) {
if (el.getAttribute("data-scope") === scope) {
el.style.display = "block";
} else {
el.style.display = "none";
}
});
document.querySelectorAll(".scope-panel").forEach(function(el) {
if (el.getAttribute("data-scope") === scope) {
el.style.display = "grid";
} else {
el.style.display = "none";
}
});
document.querySelectorAll(".toggle-btn").forEach(function(btn) {
var isActive = btn.getAttribute("data-scope") === scope;
btn.classList.toggle("active", isActive);
});
}
document.addEventListener("DOMContentLoaded", function() {
setScope("valid");
document.querySelectorAll(".toggle-btn").forEach(function(btn) {
btn.addEventListener("click", function() {
setScope(btn.getAttribute("data-scope"));
});
});
});
// 复制附件代码到剪贴板
function copyAttachmentCode() {
var el = document.getElementById("attachment-code");
if (!el) return;
var text = el.innerText;
// 优先使用现代 Clipboard API
if (navigator.clipboard && navigator.clipboard.writeText) {
navigator.clipboard.writeText(text);
return;
}
// 兼容旧浏览器:使用选区 + execCommand
var range = document.createRange();
range.selectNodeContents(el);
var selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
try {
document.execCommand("copy");
} catch (e) {}
selection.removeAllRanges();
}
// 下载附件代码为本地文件
function downloadAttachmentCode() {
var el = document.getElementById("attachment-code");
if (!el) return;
var text = el.innerText;
// 创建临时 Blob 并触发下载
var blob = new Blob([text], { type: "text/plain;charset=utf-8" });
var url = URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = "analysis_11_report_html.py";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
URL.revokeObjectURL(url);
}
</script>
""".strip()
# =========================
# 组装 HTML 报告(单文件)
# =========================
html_output = f"""
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8"/>
<title>电商订单分析报告</title>
<style>
:root {{
--bg: #f4f7fb;
--bg-2: #eef2f7;
--surface: #ffffff;
--ink: #0f172a;
--muted: #5b6470;
--accent: #1d4ed8;
--accent-2: #0f766e;
--border: #d7dee8;
--shadow: 0 10px 24px rgba(15, 23, 42, 0.08);
}}
* {{ box-sizing: border-box; }}
body {{
margin: 0;
color: var(--ink);
background: linear-gradient(180deg, var(--bg) 0%, var(--bg-2) 100%);
font-family: "PingFang HK", "PingFang SC", "Heiti TC", "Heiti SC", "STHeiti",
"Arial Unicode MS", "Helvetica Neue", Arial, sans-serif;
}}
.page {{
max-width: 1100px;
margin: 0 auto;
padding: 32px 20px 56px;
}}
h1, h2, h3 {{ margin: 0; font-weight: 700; letter-spacing: 0.2px; }}
h1 {{ font-size: 30px; }}
h2 {{ font-size: 22px; }}
h3 {{ font-size: 16px; color: var(--muted); text-transform: uppercase; letter-spacing: 0.12em; }}
p {{ color: var(--muted); margin: 6px 0 0; }}
.hero {{
display: flex;
gap: 24px;
align-items: stretch;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 20px;
padding: 24px;
box-shadow: var(--shadow);
}}
.hero-text {{
flex: 1.2;
display: flex;
flex-direction: column;
gap: 8px;
align-items: center;
text-align: center;
}}
.eyebrow {{
font-size: 12px;
text-transform: uppercase;
letter-spacing: 0.2em;
color: var(--accent);
}}
.en-tag {{
display: inline-block;
margin-left: 6px;
padding: 2px 6px;
border-radius: 999px;
background: rgba(29, 78, 216, 0.12);
color: var(--accent);
font-size: 11px;
letter-spacing: 0.04em;
}}
.en-inline {{
margin-left: 6px;
color: var(--muted);
font-size: 12px;
font-weight: 500;
}}
.subtitle {{
font-size: 14px;
color: var(--muted);
}}
.pill {{
display: inline-flex;
align-items: center;
gap: 6px;
padding: 6px 12px;
border-radius: 999px;
background: rgba(29, 78, 216, 0.12);
color: var(--accent);
font-size: 12px;
justify-content: center;
}}
.scope-toggle {{
display: flex;
gap: 12px;
margin-top: 16px;
width: 100%;
}}
.toggle-btn {{
border: 1px solid var(--border);
background: #ffffff;
color: var(--ink);
padding: 12px 16px;
border-radius: 8px;
font-size: 12px;
cursor: pointer;
flex: 1 1 0;
}}
.scope-section {{
display: none;
}}
.scope-panel {{
display: none;
}}
.toggle-btn.active {{
border-color: var(--accent);
color: var(--accent);
background: rgba(29, 78, 216, 0.08);
}}
.hero-panel {{
width: 100%;
display: grid;
grid-template-columns: repeat(4, minmax(0, 1fr));
gap: 12px;
margin-top: 12px;
}}
.mini-card {{
background: #f8fafc;
border: 1px solid var(--border);
border-radius: 14px;
padding: 12px 14px;
text-align: center;
}}
.mini-card span {{
display: block;
font-size: 12px;
color: var(--muted);
}}
.mini-card b {{
font-size: 18px;
color: var(--ink);
}}
.section {{
margin-top: 28px;
background: var(--surface);
border: 1px solid var(--border);
border-radius: 18px;
padding: 20px;
box-shadow: 0 6px 16px rgba(33, 39, 46, 0.06);
}}
.section-header {{
display: flex;
justify-content: space-between;
align-items: baseline;
gap: 12px;
margin-bottom: 16px;
}}
.kpi {{
display: flex;
flex-wrap: wrap;
gap: 12px;
}}
.kpi-card {{
border: 1px solid var(--border);
border-radius: 14px;
padding: 12px 14px;
background: #f8fafc;
flex: 1 1 240px;
text-align: center;
}}
.kpi-card b {{
font-size: 18px;
color: var(--accent);
}}
.kpi-card span {{
display: block;
font-size: 12px;
color: var(--muted);
margin-top: 4px;
}}
.insights {{
list-style: none;
padding: 0;
margin: 0;
display: grid;
gap: 10px;
}}
.insights li {{
position: relative;
padding-left: 18px;
color: var(--ink);
}}
.insights li::before {{
content: "";
position: absolute;
left: 0;
top: 7px;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--accent-2);
}}
.chart-grid {{
display: grid;
grid-template-columns: repeat(auto-fit, minmax(280px, 1fr));
gap: 16px;
}}
.chart-card {{
border: 1px solid var(--border);
border-radius: 16px;
padding: 12px;
background: #fbfdff;
}}
img {{
max-width: 100%;
border-radius: 12px;
border: 1px solid #dfe6ef;
background: #fff;
display: block;
margin: 0 auto;
}}
.dataframe {{
width: 100%;
border-collapse: collapse;
margin-top: 10px;
font-size: 13px;
}}
.dataframe th {{
background: #f7f2ea;
border: 1px solid var(--border);
padding: 8px 10px;
text-align: center;
}}
.dataframe td {{
border: 1px solid var(--border);
padding: 8px 10px;
text-align: center;
}}
.dataframe .th-en {{
display: block;
font-size: 12px;
color: var(--muted);
margin-top: 2px;
}}
.muted {{ color: var(--muted); }}
.note {{
margin: 8px 0 0;
padding: 10px 12px;
border-radius: 10px;
background: #f3f6fb;
border: 1px solid #d9e2ee;
line-height: 1.6;
letter-spacing: 0.2px;
}}
.note .label {{
font-weight: 600;
color: var(--ink);
}}
.kpi-note {{
margin-top: 10px;
font-size: 12px;
color: var(--muted);
line-height: 1.6;
}}
.code-block {{
font-family: ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace;
font-size: 11px;
color: #6b7280;
background: #f8fafc;
border: 1px solid var(--border);
border-radius: 12px;
padding: 12px;
max-height: 360px;
overflow: auto;
line-height: 1.5;
white-space: pre-wrap;
}}
details.attachment {{
margin-top: 12px;
}}
details.attachment > summary {{
cursor: pointer;
color: var(--accent);
font-weight: 600;
}}
.attachment-head {{
display: flex;
align-items: center;
justify-content: space-between;
gap: 12px;
}}
.attachment-actions {{
display: flex;
gap: 8px;
}}
.attachment-actions button {{
border: 1px solid var(--border);
background: #ffffff;
color: var(--ink);
padding: 6px 10px;
border-radius: 8px;
font-size: 12px;
cursor: pointer;
}}
.attachment-actions button:hover {{
border-color: var(--accent);
color: var(--accent);
}}
@media (max-width: 900px) {{
.hero {{ flex-direction: column; }}
.hero-panel {{ grid-template-columns: repeat(2, minmax(0, 1fr)); }}
.kpi-card {{ flex: 1 1 calc((100% - 12px) / 2); }}
}}
@media (max-width: 600px) {{
.hero-panel {{ grid-template-columns: 1fr; }}
.kpi-card {{ flex: 1 1 100%; }}
}}
</style>
</head>
<body>
<div class="page">
<header class="hero">
<div class="hero-text">
<div class="eyebrow">电商分析<span class="en-tag">E-commerce Analytics</span></div>
<h1>电商订单分析报告</h1>
<p class="subtitle">一页概览关键指标、趋势结构与渠道 ROI(行业常用口径:GMV - 投放成本)</p>
<div class="pill">生成时间:{datetime.now().strftime("%Y-%m-%d %H:%M:%S")}</div>
</div>
</header>
<div class="scope-toggle">
<button class="toggle-btn active" data-scope="valid">以有效订单计算</button>
<button class="toggle-btn" data-scope="all">以全量订单计算</button>
</div>
{valid_html}
{all_html}
<section class="section">
<div class="section-header attachment-head">
<h2>附件:生成代码</h2>
<div class="attachment-actions">
<button type="button" onclick="copyAttachmentCode()">复制</button>
<button type="button" onclick="downloadAttachmentCode()">下载</button>
</div>
</div>
<div class="muted">用于复现本报告的脚本(可折叠查看)</div>
<details class="attachment">
<summary>展开查看</summary>
<pre id="attachment-code" class="code-block">{html.escape(open(__file__, "r", encoding="utf-8").read())}</pre>
</details>
</section>
</div>
{script}
</body>
</html>
"""
# 写出 HTML 文件
with open("data/report.html", "w", encoding="utf-8") as f:
f.write(html_output)
# 终端提示
print("已生成:data/report.html")