You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
dianshang-qianduan/tests/category-optimization-impor...

150 lines
9.0 KiB
JavaScript

const test = require("node:test");
const assert = require("node:assert/strict");
const fs = require("node:fs");
const path = require("node:path");
const vm = require("node:vm");
const Vue = require("vue");
const XLSX = require("xlsx");
const { parse, compileScript, compileTemplate } = require("@vue/compiler-sfc");
const { compile } = require("@vue/compiler-dom");
const { renderToString } = require("@vue/server-renderer");
const sourcePath = path.resolve(__dirname, "../src/views/assessment/optimization.vue");
const source = fs.readFileSync(sourcePath, "utf8");
const helpersSource = fs.readFileSync(path.resolve(__dirname, "../src/views/assessment/categoryOptimizationExcel.js"), "utf8");
function helpers() {
const context = {};
vm.runInNewContext(helpersSource.replace(/export /g, "") + "\nglobalThis.exports={CATEGORY_EXCEL_COLUMNS,sanitizeCategoryNumber,parseCategoryExcelRows};", context);
return context.exports;
}
const plain = (value) => JSON.parse(JSON.stringify(value));
function workbookBytes(rows, bookType = "xlsx") {
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, XLSX.utils.aoa_to_sheet(rows), "品类数据");
return XLSX.write(workbook, { type: "buffer", bookType });
}
function fileEvent(bytes, name = "品类数据.xlsx") {
const target = { value: name, files: [{ name, arrayBuffer: async () => bytes.buffer.slice(bytes.byteOffset, bytes.byteOffset + bytes.byteLength) }] };
return { target };
}
function pageHarness(confirm = true) {
const messages = [], saved = [], downloads = [];
const context = { ...Vue, ...helpers(), onMounted() {}, defineAsyncComponent: () => ({}),
ElMessage: { success: (value) => messages.push(value), error: (value) => messages.push(value) },
ElMessageBox: { confirm: async () => { if (!confirm) throw new Error("cancel"); } },
parseTrainingArray: (value, fallback = []) => Array.isArray(value) ? value : fallback,
XLSX_IMPORT: { ...XLSX, writeFile: (workbook, filename) => downloads.push({ workbook, filename }) },
saveStudentTrainingAnswer: async (taskKey, payload) => saved.push({ taskKey, payload }),
};
const script = parse(source).descriptor.scriptSetup.content.replace(/^import .*\r?\n/gm, "").replaceAll('await import("xlsx")', "XLSX_IMPORT");
vm.runInNewContext(script + "\nglobalThis.page={categoryRows,importCategoryExcel,downloadCategoryTemplate,saveCurrentProgress,importingCategories};", context);
return { ...context.page, messages, saved, downloads };
}
test("numeric inputs ignore non numeric characters and preserve decimal editing", () => {
const { sanitizeCategoryNumber: clean, CATEGORY_EXCEL_COLUMNS: columns } = helpers();
for (const { key } of columns.slice(1)) {
assert.equal(clean("abc中文$%+-", key), "");
assert.equal(clean("1a2.3$4", key), "12.34");
assert.equal(clean("1.2.3", key), "1.23");
assert.equal(clean("0.", key), "0.");
assert.equal(clean(".5", key), "0.5");
assert.equal(clean(null, key), "");
}
assert.equal(clean("101.25", "capitalOccupancyRate"), "100");
assert.equal(clean("12.345", "sellThroughRate"), "12.34");
assert.equal(clean("12345.678", "revenue"), "12345.678");
});
test("xls and xlsx imports map reordered headers and Excel percentages correctly", () => {
const { CATEGORY_EXCEL_COLUMNS: columns, parseCategoryExcelRows: parseRows } = helpers();
for (const bookType of ["xlsx", "xls"]) {
const headers = Array.from(columns, (column) => column.label);
const sheet = XLSX.utils.aoa_to_sheet([headers, ["ABC品类", 600, 0.6, 0.6, 1250, 0.25, 0.75, 0.3]]);
for (const cell of ["C2", "D2", "F2", "G2", "H2"]) sheet[cell].z = "0.00%";
sheet.E2.z = "#,##0.00";
const workbook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(workbook, sheet, "数据");
const parsed = XLSX.read(XLSX.write(workbook, { type: "buffer", bookType }), { type: "buffer" });
const rows = XLSX.utils.sheet_to_json(parsed.Sheets[parsed.SheetNames[0]], { header: 1, defval: "", raw: false });
const result = plain(parseRows(rows.map((row) => row.slice().reverse())));
assert.deepEqual(result, [{ categoryName: "ABC品类", revenue: "600", revenueShare: "60.00", cumulativeShare: "60.00", inventoryCapital: "1250.00", capitalOccupancyRate: "25.00", sellThroughRate: "75.00", grossMargin: "30.00" }]);
}
});
test("invalid Excel rows fail as a batch while optional columns stay blank", () => {
const { parseCategoryExcelRows: parseRows } = helpers();
const headers = ["品类名称", "近12个月营收(万元)"];
assert.throws(() => parseRows([]), /没有数据/);
assert.throws(() => parseRows([headers]), /没有可导入/);
assert.throws(() => parseRows([["品类名称"], ["测试"]]), /缺少表头/);
assert.throws(() => parseRows([[...headers, "近12个月营收"], ["A", 1, 1]]), /表头重复/);
assert.throws(() => parseRows([headers, ["A", 1], ["B", "12abc"]]), /第 3 行/);
assert.throws(() => parseRows([headers, ["A", -1]]), /只接受数字/);
assert.throws(() => parseRows([headers, ...Array.from({ length: 31 }, () => ["A", 1])]), /最多导入 30 行/);
assert.throws(() => parseRows([[...headers, "资金占用率(%)"], ["A", 1, "101%"]]), /不能超过 100/);
const [row] = plain(parseRows([[], headers, [], ["A", 0]]));
assert.equal(row.revenue, "0");
assert.equal(row.inventoryCapital, "");
assert.equal(row.capitalOccupancyRate, "");
});
test("page import preserves current work on invalid files or cancellation and saves accepted data", async () => {
const { CATEGORY_EXCEL_COLUMNS: columns } = helpers();
const headers = Array.from(columns, (column) => column.label);
const valid = workbookBytes([headers, ["导入品类", 100, 100, 100, 20, 25, 75, 30]]);
const page = pageHarness();
page.categoryRows.value = [{ id: "old-row", categoryName: "原有品类", revenue: "60" }];
await page.importCategoryExcel(fileEvent(workbookBytes([headers, ["错误数据", "abc"]])));
assert.equal(page.categoryRows.value[0].id, "old-row");
assert.match(page.messages.at(-1), /只接受数字/);
assert.equal(page.importingCategories.value, false);
const cancelled = pageHarness(false);
cancelled.categoryRows.value = [{ id: "keep-me" }];
await cancelled.importCategoryExcel(fileEvent(valid));
assert.equal(cancelled.categoryRows.value[0].id, "keep-me");
const event = fileEvent(valid);
await page.importCategoryExcel(event);
assert.equal(event.target.value, "");
assert.equal(page.categoryRows.value.length, 1);
assert.equal(page.categoryRows.value[0].categoryName, "导入品类");
assert.equal(page.categoryRows.value[0].abcClassification, "");
await page.saveCurrentProgress();
const payload = page.saved[0].payload;
assert.equal(payload.saveAction, "SAVE");
assert.equal(JSON.parse(payload.step1Answer).categoryRows[0].revenue, "100");
assert.equal(JSON.parse(payload.step1Answer).categoryRows[0].capitalOccupancyRate, 25);
});
test("template download contains the page columns without importing sample answers", async () => {
const page = pageHarness();
await page.downloadCategoryTemplate();
const { workbook, filename } = page.downloads[0];
assert.match(filename, /\.xlsx$/);
const rows = XLSX.utils.sheet_to_json(workbook.Sheets[workbook.SheetNames[0]], { header: 1 });
assert.equal(rows.length, 1);
assert.equal(rows[0].length, 8);
assert.equal(rows[0][0], "品类名称");
assert.equal(workbook.SheetNames[1], "填写说明");
});
test("all seven numeric template bindings filter pasted text while category names remain text", async () => {
const { descriptor, errors } = parse(source);
assert.deepEqual(errors, []);
compileScript(descriptor, { id: "category-import" });
assert.deepEqual(compileTemplate({ source: descriptor.template.content, filename: sourcePath, id: "category-import" }).errors, []);
const rowTemplate = source.match(/<tr v-for="\(row, index\) in categoryRows"[\s\S]*?<\/tr>/)[0];
const render = new Function("Vue", compile(rowTemplate, { prefixIdentifiers: true }).code)(Vue);
const row = Vue.reactive({ categoryName: "ABC品类", revenue: "", revenueShare: "", cumulativeShare: "", inventoryCapital: "", capitalOccupancyRate: null, sellThroughRate: null, grossMargin: "" });
const handlers = [];
const app = Vue.createSSRApp({ setup: () => ({ categoryRows: [row], sanitizeCategoryNumber: helpers().sanitizeCategoryNumber }), render });
app.component("el-input", { props: ["modelValue"], setup: (props, { attrs }) => { handlers.push({ label: attrs["aria-label"], update: attrs["onUpdate:modelValue"] }); return () => Vue.h("input", { value: props.modelValue }); } });
await renderToString(app);
assert.equal(handlers.length, 8);
for (const handler of handlers.slice(1)) handler.update("1a2.3#4");
for (const key of Object.keys(row).filter((key) => key !== "categoryName")) assert.equal(row[key], "12.34", key);
assert.equal(row.categoryName, "ABC品类");
for (const handler of handlers.slice(1)) handler.update("ABC@中文");
for (const key of Object.keys(row).filter((key) => key !== "categoryName")) assert.equal(row[key], "", key);
});