|
|
export function scoreExcelColumns(metrics) {
|
|
|
return [
|
|
|
{ key: "channel", label: "渠道" },
|
|
|
...metrics.map((metric) => ({ key: metric.key, label: `${metric.dimension}得分`, alias: metric.label })),
|
|
|
{ key: "weightedScore", label: "加权得分" },
|
|
|
];
|
|
|
}
|
|
|
|
|
|
const headerName = (value) => String(value ?? "").replace(/\s/g, "");
|
|
|
const hasValue = (row) => Array.isArray(row) && row.some((value) => String(value ?? "").trim());
|
|
|
|
|
|
export function parseScoreExcelRows(sheetRows, metrics, channels) {
|
|
|
const headerIndex = sheetRows.findIndex(hasValue);
|
|
|
if (headerIndex < 0) throw new Error("Excel 中没有数据,请按模板填写后导入");
|
|
|
const columns = scoreExcelColumns(metrics);
|
|
|
const headers = sheetRows[headerIndex].map(headerName);
|
|
|
const indexes = columns.map((column) => {
|
|
|
const matches = headers.map((name, index) => [name, index]).filter(([name]) => name === headerName(column.label) || (column.alias && name === headerName(column.alias)));
|
|
|
if (!matches.length) throw new Error(`Excel 缺少表头:${column.label}`);
|
|
|
if (matches.length > 1) throw new Error(`Excel 表头重复:${column.label}`);
|
|
|
return matches[0][1];
|
|
|
});
|
|
|
const allowedChannels = new Set(channels.map((channel) => String(channel ?? "").trim()));
|
|
|
if (allowedChannels.size !== channels.length || allowedChannels.has("")) throw new Error("第二步渠道名称为空或重复,请先修正渠道数据");
|
|
|
const seen = new Set();
|
|
|
const rows = sheetRows.slice(headerIndex + 1).map((values, index) => ({ values, line: headerIndex + index + 2 })).filter(({ values }) => hasValue(values));
|
|
|
if (!rows.length) throw new Error("Excel 只有表头,没有可导入的渠道得分");
|
|
|
return rows.map(({ values, line }) => Object.fromEntries(columns.map((column, index) => {
|
|
|
const value = String(values[indexes[index]] ?? "").trim();
|
|
|
const field = `Excel 第 ${line} 行「${column.label}」`;
|
|
|
if (column.key === "channel") {
|
|
|
if (!value) throw new Error(`${field}不能为空`);
|
|
|
if (!allowedChannels.has(value)) throw new Error(`${field}“${value}”不存在,请先在第二步添加该渠道`);
|
|
|
if (seen.has(value)) throw new Error(`${field}“${value}”重复`);
|
|
|
seen.add(value);
|
|
|
return [column.key, value];
|
|
|
}
|
|
|
if (!value) return [column.key, undefined];
|
|
|
if (!/^(?:\d+(?:\.\d*)?|\.\d+)$/.test(value) || !Number.isFinite(Number(value))) throw new Error(`${field}请填写非负数字`);
|
|
|
const weighted = column.key === "weightedScore";
|
|
|
if (!weighted && Number(value) > 10) throw new Error(`${field}必须在 0–10 之间`);
|
|
|
const fraction = value.split(".")[1]?.replace(/0+$/, "") || "";
|
|
|
if (fraction.length > (weighted ? 2 : 1)) throw new Error(`${field}最多保留 ${weighted ? 2 : 1} 位小数`);
|
|
|
return [column.key, Number(value)];
|
|
|
})));
|
|
|
}
|