Commit a8264da7 by 江名洋

feat(sub-brand): Enhance file upload handling and preview rendering

- Added functionality to display the save button when a file is selected.
- Included start and end date fields in the form data for uploads.
- Refactored the preview rendering logic to utilize a dedicated function for improved clarity and maintainability.
1 parent 4ef9c531
{
"主机厂数据-鸿蒙子品牌-模板001.xlsx": {
"sheets": [
"主机厂-子品牌(7.1-7.19)"
],
"主机厂-子品牌(7.1-7.19)": {
"shape": [
134,
15
],
"rows": [
[
"总交付数",
"尊界",
"尊界",
"尚界",
"尚界",
"智界",
"智界",
"享界",
"享界"
],
[
"省份",
"城市",
"门店编号",
"用户中心门店名称",
"门店",
"交付",
"出单",
"交付",
"出单",
"交付",
"出单",
"交付",
"出单",
"交付",
"出单"
],
[
"省份",
"城市",
"门店编号",
"用户中心门店名称",
"对应门店名称",
"总交付",
"总出单",
"交付",
"出单",
"交付",
"出单",
"交付",
"出单",
"交付",
"出单"
],
[
"安徽省",
"合肥市",
"CNSCN317902",
"鸿蒙智行授权用户中心•合肥蒙城北路",
"14",
"4",
"0",
"1",
"0",
"0",
"12",
"2",
"2",
"1"
],
[
"安徽省",
"六安市",
"CNSCN315745",
"鸿蒙智行授权用户中心•六安东方汽车城",
"10",
"3",
"0",
"0",
"0",
"0",
"7",
"2",
"3",
"1"
],
[
"安徽省",
"宿州市",
"CNSCN325151",
"鸿蒙智行授权用户中心•宿州城东汽车城",
"5",
"1",
"0",
"0",
"1",
"0",
"2",
"0",
"2",
"1"
],
[
"北京市",
"北京",
"CNSCN330472",
"鸿蒙智行授权用户中心•北京姚家园",
"23",
"32",
"1",
"1",
"0",
"0",
"19",
"23",
"3",
"8"
],
[
"北京市",
"北京",
"CNSCN332567",
"鸿蒙智行智界用户中心•北京通州博瑞汽车园",
"10",
"9",
"0",
"0",
"0",
"0",
"10",
"9",
"0",
"0"
],
[
"北京市",
"北京",
"CNSCN329512",
"鸿蒙智行尚界用户中心•北京安宁庄东路",
"13",
"9",
"0",
"0",
"13",
"9",
"0",
"0",
"0",
"0"
],
[
"北京市",
"北京",
"CNSCN309446",
"鸿蒙智行授权用户中心•北京玉泉路",
"22",
"14",
"1",
"0",
"1",
"1",
"15",
"10",
"5",
"3"
],
[
"北京市",
"北京",
"CNSCN310748",
"鸿蒙智行授权用户中心•北京首钢园",
"93",
"53",
"2",
"1",
"45",
"27",
"35",
"18",
"11",
"7"
],
[
"北京市",
"北京",
"CNSCN333012",
"鸿蒙智行尚界用户中心•北京首都机场",
"26",
"13",
"0",
"0",
"26",
"13",
"0",
"0",
"0",
"0"
]
]
}
},
"输出模板-鸿蒙子品牌-模板001.xlsx": {
"sheets": [
"模板"
],
"模板": {
"shape": [
3,
38
],
"rows": [
[
"基础门店信息",
"主机厂交付数",
"产值表数据",
"是否触发兜底",
"当前转化率",
"需达标转化率",
"需达标订单差额",
"赔付金额",
"总赔付金额"
],
[
"门店",
"品牌",
"兜底指标",
"区域(省)",
"直营与否",
"区域运营",
"飞行督导",
"线上运营",
"特殊情况",
"复合交付数",
"主机厂交付数",
"产值交付数",
"主机厂跟产值表差距",
"门店触客数",
"触客率"
],
[
"示例门店(尊界)",
"尊界",
"兜底:触客渗透率60%",
"广东省",
"直营",
"区域运营",
"飞行督导",
"线上运营",
"10",
"10",
"10",
"8",
"5",
"2",
"1"
]
]
}
}
}
\ No newline at end of file
{"error": "Length mismatch: Expected axis has 15 elements, new values have 19 elements"}
\ No newline at end of file
......@@ -89,6 +89,27 @@ def _parse_target_value(val):
return v / 100.0 if v > 1 else v
def _normalize_sub_brand(brand_str) -> str:
"""从门店配置品牌字段提取子品牌名(尊界/尚界/智界/享界)"""
if brand_str is None or (isinstance(brand_str, float) and pd.isna(brand_str)):
return ""
s = str(brand_str).strip()
if not s or s in ("/", "nan", "None"):
return ""
for name in SUB_BRAND_NAMES:
if name in s:
return name
return s
def _normalize_store_key(name: str) -> str:
"""统一门店名称中的分隔符,便于用户中心名匹配"""
s = str(name or "").strip()
for ch in ("•", "·", "・", "●", "∙"):
s = s.replace(ch, "•")
return s
class HarmonyAnalysisService:
"""鸿蒙生态分析服务"""
......@@ -736,12 +757,78 @@ class HarmonyAnalysisService:
return df
@staticmethod
def _load_user_center_legal_map() -> dict:
"""用户中心门店名称 → 法人门店名称(来自鸿蒙主机厂数据)"""
mapping = {}
file_path = None
try:
from app.services.upload_service import get_upload_history
rows = get_upload_history(brand="鸿蒙", data_type="oem_delivery")
if rows:
remark = (rows[0].get("remark") or "").strip()
if remark and os.path.exists(remark):
file_path = remark
if not file_path:
file_path = _find_latest_template("主机厂数据-鸿蒙-模板")
df = HarmonyAnalysisService.read_factory_data(file_path)
if df.empty or "用户中心门店名" not in df.columns:
return mapping
for _, row in df.iterrows():
uc = _normalize_store_key(row.get("用户中心门店名", ""))
legal = str(row.get("门店名", "")).strip()
if uc and legal:
mapping[uc] = legal
except Exception as e:
logger.warning(f"加载用户中心→法人门店映射失败: {e}")
return mapping
@staticmethod
def _prepare_sub_brand_store_df(store_df: pd.DataFrame) -> pd.DataFrame:
"""标准化门店兜底配置,便于与子品牌 OEM 数据按法人名+子品牌合并"""
cfg = store_df.copy()
cfg["法人门店名"] = cfg["门店名"].astype(str).str.strip()
cfg["子品牌"] = cfg["品牌"].apply(_normalize_sub_brand)
cfg = cfg[cfg["法人门店名"].notna() & (cfg["法人门店名"] != "")]
return cfg.drop_duplicates(subset=["法人门店名", "子品牌"], keep="first")
@staticmethod
def _fill_sub_brand_store_fallback(merged: pd.DataFrame, store_cfg: pd.DataFrame, base_cols: list) -> pd.DataFrame:
"""对未精确匹配子品牌的行,回退使用「鸿蒙智行」或未标注品牌的门店兜底条款"""
generic = store_cfg[store_cfg["子品牌"].isin(["", "鸿蒙智行"])].drop_duplicates(
subset=["法人门店名"], keep="first"
)
if generic.empty:
return merged
generic_map = generic.set_index("法人门店名")
for idx, row in merged.iterrows():
guarantee = str(row.get("兜底指标", "") or "").strip()
if guarantee and guarantee not in ("nan", "None"):
continue
legal = str(row.get("法人门店名", "") or "").strip()
if not legal or legal not in generic_map.index:
continue
src = generic_map.loc[legal]
for col in base_cols:
if col in src.index:
merged.at[idx, col] = src[col]
return merged
@staticmethod
def _merge_sub_brand_oem_with_store(oem_df: pd.DataFrame, store_df: pd.DataFrame) -> pd.DataFrame:
"""合并主机厂子品牌 OEM 数据与门店兜底配置"""
if store_df is None or store_df.empty:
store_df = HarmonyAnalysisService.load_latest_harmony_store_df()
if store_df.empty:
base_cols = [
"兜底指标", "区域(省)", "直营与否", "区域运营", "飞行督导", "线上运营",
"兜底类型", "特殊情况",
"需达标转化率_整车延保", "需达标转化率_安心包", "需达标转化率_电池延保",
"预计赔付金额_整车", "预计赔付金额_安心包", "预计赔付金额_电池",
]
def _empty_merge_result() -> pd.DataFrame:
logger.warning("未找到鸿蒙门店兜底配置,子品牌报表将缺少兜底条款")
out = pd.DataFrame()
out["门店名"] = oem_df["门店名"]
......@@ -760,32 +847,51 @@ class HarmonyAnalysisService:
out["整车延保成交数"] = oem_df["主机厂出单数"]
out["安心包达成数量"] = 0
out["电池延保成交数"] = 0
out["需达标转化率_整车延保"] = 0
out["需达标转化率_安心包"] = 0
out["需达标转化率_电池延保"] = 0
out["预计赔付金额_整车"] = 0
out["预计赔付金额_安心包"] = 0
out["预计赔付金额_电池"] = 0
for c in base_cols[7:]:
out[c] = 0 if "转化率" in c or "赔付" in c else ""
return out
merged = oem_df.merge(store_df, on=["门店名", "品牌"], how="left")
if store_df.empty:
return _empty_merge_result()
uc_map = HarmonyAnalysisService._load_user_center_legal_map()
oem = oem_df.copy()
oem["门店名"] = oem["门店名"].astype(str).str.strip()
oem["子品牌"] = oem["品牌"].apply(_normalize_sub_brand)
def _resolve_legal(row):
mapped = str(row.get("对应门店名称", "")).strip()
if mapped and mapped not in ("nan", "None"):
return mapped
uc_key = _normalize_store_key(row.get("门店名", ""))
return uc_map.get(uc_key, "")
oem["法人门店名"] = oem.apply(_resolve_legal, axis=1)
store_cfg = HarmonyAnalysisService._prepare_sub_brand_store_df(store_df)
specific_cfg = store_cfg[~store_cfg["子品牌"].isin(["", "鸿蒙智行"])]
cfg_cols = ["法人门店名", "子品牌"] + [c for c in base_cols if c in store_cfg.columns]
merged = oem.merge(specific_cfg[cfg_cols], on=["法人门店名", "子品牌"], how="left")
merged = HarmonyAnalysisService._fill_sub_brand_store_fallback(merged, store_cfg, base_cols)
matched = merged["兜底指标"].astype(str).str.strip().replace("nan", "").ne("")
logger.info(
f"Sub-brand store merge: {matched.sum()}/{len(merged)} rows matched "
f"(legal mapped={oem['法人门店名'].ne('').sum()}/{len(oem)})"
)
merged["区域(省)"] = merged["区域(省)"].fillna(merged["省份"])
for col in [
"兜底指标", "直营与否", "区域运营", "飞行督导", "线上运营",
"兜底类型", "特殊情况",
"需达标转化率_整车延保", "需达标转化率_安心包", "需达标转化率_电池延保",
"预计赔付金额_整车", "预计赔付金额_安心包", "预计赔付金额_电池",
]:
for col in base_cols:
if col not in merged.columns:
merged[col] = ""
merged[col] = merged[col].fillna("")
merged["产值表交付数"] = 0
merged["触客数"] = 0
merged["整车延保成交数"] = merged["主机厂出单数"].fillna(0).astype(int)
merged["主机厂交付数"] = oem["主机厂交付数"]
merged["整车延保成交数"] = oem["主机厂出单数"].fillna(0).astype(int)
merged["安心包达成数量"] = 0
merged["电池延保成交数"] = 0
return merged
return merged.drop(columns=["法人门店名", "子品牌"], errors="ignore")
@staticmethod
def _read_sub_brand_legacy(file_path: str) -> pd.DataFrame:
......
......@@ -276,9 +276,14 @@
const name = file.name;
document.getElementById('sb-file-name').textContent = '\u2705 ' + name;
document.getElementById('sb-drop-zone').classList.add('has-file');
document.getElementById('btn-save-sb-batch').style.display = 'block';
const formData = new FormData();
formData.append('data_file', file);
const sd = document.getElementById('sb-start-date').value;
const ed = document.getElementById('sb-end-date').value;
if (sd) formData.append('start_date', sd);
if (ed) formData.append('end_date', ed);
try {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty">正在解析数据...</div>';
......@@ -287,41 +292,7 @@
if (data.status !== 'success') {
throw new Error(data.detail || '上传失败');
}
const reader = new FileReader();
reader.onload = function(e) {
try {
const wb = XLSX.read(e.target.result, {type: 'array'});
const sheetName = wb.SheetNames.find(s => s.includes('子品牌')) || wb.SheetNames[0];
const ws = wb.Sheets[sheetName];
const rows = XLSX.utils.sheet_to_json(ws, {header: 1, defval: ''});
const dataRows = rows.slice(7).filter(r => r[0] && String(r[0]).trim());
const headers = ['门店','品牌','区域','直营','主机厂交付','产值交付','触客数','整车延保成交','安心包','电池','兜底指标'];
let html = '<table class="preview-table"><thead><tr><th>#</th>';
headers.forEach(h => html += '<th>' + escapeHtml(h) + '</th>');
html += '</tr></thead><tbody>';
dataRows.slice(0, 100).forEach((row, i) => {
html += '<tr><td style="text-align:center;color:#999;">' + (i+1) + '</td>';
html += '<td>' + escapeHtml(String(row[0]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[7]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[2]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[3]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[8]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[9]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[10]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[12]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[15]||'')) + '</td>';
html += '<td>' + escapeHtml(String(row[17]||'')) + '</td>';
html += '<td style="max-width:200px;overflow:hidden;text-overflow:ellipsis;">' + escapeHtml(String(row[1]||'')) + '</td>';
html += '</tr>';
});
html += '</tbody></table>';
document.getElementById('sb-preview-body').innerHTML = html;
} catch(ex) {
document.getElementById('sb-preview-body').innerHTML =
'<div class="right-panel-empty" style="color:#f5222d;">解析预览失败: ' + ex.message + '</div>';
}
};
reader.readAsArrayBuffer(file);
renderSubBrandPreview(data.data || {});
} catch(e) {
console.error('子品牌上传失败:', e);
document.getElementById('sb-preview-body').innerHTML =
......
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!