import { describe, it, expect } from "vitest" import { Shrimp, ShrimpTableModule, MemoryShrimpCrud, ShrimpFieldTypes } from "../src/main" import type { IShrimpSheets } from "../src/main" type Row = { _id: string; name: string } function makeModule() { const shrimp = new Shrimp() const crud = new MemoryShrimpCrud() const mod = new ShrimpTableModule(shrimp, "tag", crud, [ { key: "name", label: "名称", type: ShrimpFieldTypes.String }, ], "标签") mod.initCrud() return { crud, mod } } describe("导入导出的 sheet 契约", () => { it("export 返回以 moduleKey 命名的单张 sheet", async () => { const { crud, mod } = makeModule() await crud.add({ name: "热门" } as any) const sheets = await mod.export({}) expect(Object.keys(sheets)).toEqual(["tag"]) expect(sheets.tag.map(r => r.name)).toEqual(["热门"]) }) it("import 认同名 sheet", async () => { const { crud, mod } = makeModule() await mod.import({ other: [{ name: "别人的" }], tag: [{ name: "热门" }] }) const all = await crud.list({}) expect(all.list.map(r => r.name)).toEqual(["热门"]) }) it("没有同名 sheet 时退回第一张(手工 Excel 的 Sheet1)", async () => { const { crud, mod } = makeModule() await mod.import({ Sheet1: [{ name: "热门" }] }) expect((await crud.list({})).list.map(r => r.name)).toEqual(["热门"]) }) it("老版本前端发的裸数组仍然能导", async () => { const { crud, mod } = makeModule() await mod.import([{ name: "热门" }] as any) expect((await crud.list({})).list.map(r => r.name)).toEqual(["热门"]) }) it("多 sheet 由模块重写 export/import 自行分派", async () => { const shrimp = new Shrimp() const goods = new MemoryShrimpCrud() const shops = new MemoryShrimpCrud() class ShopModule extends ShrimpTableModule { async export(): Promise { return { goods: (await goods.list({})).list, shop: (await shops.list({})).list } } async import(data?: IShrimpSheets): Promise { for (const row of data?.goods ?? []) await goods.add(row as any) for (const row of data?.shop ?? []) await shops.add(row as any) } } const mod = new ShopModule(shrimp, "shop", shops, [ { key: "name", label: "名称", type: ShrimpFieldTypes.String }, ], "商店") await mod.import({ goods: [{ name: "木剑" }], shop: [{ name: "杂货铺" }] }) const sheets = await mod.export() expect(sheets.goods.map(r => r.name)).toEqual(["木剑"]) expect(sheets.shop.map(r => r.name)).toEqual(["杂货铺"]) }) })