import { readFile } from "node:fs/promises"; import path from "node:path"; import { strToU8, zipSync, type Zippable } from "fflate"; import { beforeEach, expect, it } from "vitest"; import { buildExport, importBook, readImportFile } from "@/lib/book-transfer"; import { UPLOAD_DIR, saveImageBytes } from "@/lib/files"; import { nextMapCode, nextMarkerCode, nextScheduleCode } from "@/lib/ids"; import { entityRow, makeImage, validExport } from "../helpers/fixtures"; import { describeDb, filesIn, makeBook, makeEntity, makeRelation, makeUser, prisma, resetAll } from "../helpers/db"; /** Skickar exporten genom samma zip-format som exportknappen och läser tillbaka den. */ function viaZip(exported: Awaited>) { const entries: Zippable = { "book.json": strToU8(JSON.stringify(exported.data)) }; for (const [name, bytes] of exported.files) entries[`files/${name}`] = [bytes, { level: 0 }]; return readImportFile(zipSync(entries)); } describeDb("export och import", () => { let ownerId: string; let bookId: string; const ids = {} as Record<"anna" | "erik" | "cafe" | "firma" | "relation" | "map", string>; /** En bok med allt: bilder, relation med deltagare, kopplingsfält, scheman, kartor och mall. */ beforeEach(async () => { await resetAll(); ownerId = (await makeUser("Ägare")).id; bookId = (await makeBook(ownerId, "Testbok")).id; const portrait = await saveImageBytes(await makeImage(120, 80, "png")); const anna = await makeEntity(bookId, "CHARACTER", "Anna", { imageFile: portrait, tags: ["huvud"], summary: "Huvudperson", data: { age: 30 } }); const erik = await makeEntity(bookId, "CHARACTER", "Erik"); const cafe = await makeEntity(bookId, "PREMISES", "Café Lund"); const firma = await makeEntity(bookId, "COMPANY", "Lunds Kaffe", { data: { industry: "Kaffe", premises: cafe.id } }); const relation = await makeRelation(bookId, anna.id, erik.id, "Vänner", [cafe.id]); const scheduleCode = await nextScheduleCode(bookId); await prisma.shift.createMany({ data: [0, 1].map((weekday) => ({ bookId, personId: erik.id, workplaceId: cafe.id, weekday, startTime: "08:00", endTime: "16:00", scheduleCode })), }); const mapImage = await saveImageBytes(await makeImage(200, 100, "png"), "map"); const geo = await prisma.bookMap.create({ data: { bookId, name: "Lund", kind: "GEO", code: await nextMapCode(bookId, "GEO"), centerLat: 55.7, centerLng: 13.19, zoom: 14 } }); await prisma.bookMap.create({ data: { bookId, name: "Egen", kind: "IMAGE", code: await nextMapCode(bookId, "IMAGE"), imageFile: mapImage } }); await prisma.marker.create({ data: { mapId: geo.id, entityId: cafe.id, label: "Café", code: await nextMarkerCode(bookId), lat: 55.7047, lng: 13.191, color: "orange", note: "Hörnet" } }); await prisma.template.create({ data: { bookId, kind: "CHARACTER", fields: [{ key: "mood", label: "Läge", type: "text" }] } }); Object.assign(ids, { anna: anna.id, erik: erik.id, cafe: cafe.id, firma: firma.id, relation: relation.id, map: geo.id }); }); it("en export som importeras igen blir en likadan bok med nya id", async () => { const exported = await buildExport(bookId, true); const { data, files } = viaZip(exported); const result = await importBook(ownerId, data, files); expect(result).toMatchObject({ entities: 4, relations: 1, maps: 2, markers: 1, shifts: 2, skippedImages: 0, skippedLinks: 0 }); expect(result.bookId).not.toBe(bookId); const copy = await prisma.book.findUniqueOrThrow({ where: { id: result.bookId }, include: { entities: true, relations: { include: { members: true } }, shifts: true, maps: { include: { markers: true } }, templates: true, counters: true }, }); // Samma titel får ett tillägg så att böckerna går att skilja åt expect(copy.title).toBe("Testbok (import)"); // Poster: nya id, men samma namn, ID-nummer, taggar och mallfält const byName = Object.fromEntries(copy.entities.map((e) => [e.name, e])); expect(Object.keys(byName).sort()).toEqual(["Anna", "Café Lund", "Erik", "Lunds Kaffe"]); expect(byName.Anna).toMatchObject({ code: "KI-0001", tags: ["huvud"], summary: "Huvudperson", data: { age: 30 } }); expect(byName["Café Lund"].code).toBe("LI-0001"); for (const old of Object.values(ids)) expect(copy.entities.map((e) => e.id)).not.toContain(old); // Kopplingsfältet pekar på den nya lokalen, inte den gamla expect((byName["Lunds Kaffe"].data as { premises: string }).premises).toBe(byName["Café Lund"].id); // Relationen och dess extra deltagare pekar på de nya posterna const [relation] = copy.relations; expect(relation).toMatchObject({ code: "REI-0001", type: "Vänner", fromId: byName.Anna.id, toId: byName.Erik.id }); expect(relation.members.map((m) => m.entityId)).toEqual([byName["Café Lund"].id]); // Scheman delar schema-ID och pekar på nya poster expect(copy.shifts).toHaveLength(2); expect(new Set(copy.shifts.map((s) => s.scheduleCode))).toEqual(new Set(["SCI-0001"])); expect(copy.shifts.every((s) => s.personId === byName.Erik.id && s.workplaceId === byName["Café Lund"].id)).toBe(true); // Kartor och markeringar const geo = copy.maps.find((m) => m.kind === "GEO")!; expect(geo).toMatchObject({ code: "KD-R_0001", zoom: 14, centerLat: 55.7 }); expect(geo.markers[0]).toMatchObject({ code: "PI-0001", label: "Café", color: "orange", note: "Hörnet", entityId: byName["Café Lund"].id }); expect(copy.maps.find((m) => m.kind === "IMAGE")?.code).toBe("KD-E_0001"); // Mall och räknare expect(copy.templates).toHaveLength(1); const counter = Object.fromEntries(copy.counters.map((c) => [c.key, c.next])); expect(counter).toMatchObject({ KI: 2, LI: 1, FI: 1, REI: 1, SCI: 1, PI: 1, "KD-R": 1, "KD-E": 1 }); }); it("bilderna kopieras till nya filer", async () => { const before = await filesIn(UPLOAD_DIR); expect(before).toHaveLength(2); const { data, files } = viaZip(await buildExport(bookId, true)); const result = await importBook(ownerId, data, files); const after = await filesIn(UPLOAD_DIR); expect(after).toHaveLength(4); const copy = await prisma.entity.findFirstOrThrow({ where: { bookId: result.bookId, name: "Anna" } }); expect(copy.imageFile).toBeTruthy(); expect(before).not.toContain(copy.imageFile); expect((await readFile(path.join(UPLOAD_DIR, copy.imageFile!))).length).toBeGreaterThan(0); }); it("nya poster fortsätter numreringen efter importen", async () => { const { data, files } = viaZip(await buildExport(bookId, true)); const { bookId: copyId } = await importBook(ownerId, data, files); const next = await makeEntity(copyId, "CHARACTER", "Ny"); expect(next.code).toBe("KI-0003"); }); it("JSON utan bilder går att importera", async () => { const { data } = await buildExport(bookId, false); const result = await importBook(ownerId, data, new Map()); expect(result.entities).toBe(4); expect(result.skippedImages).toBe(0); expect((await prisma.entity.findFirstOrThrow({ where: { bookId: result.bookId, name: "Anna" } })).imageFile).toBeNull(); }); it("kan importeras till en annan användare utan tillägg i titeln", async () => { const other = await makeUser("Annan"); const { data, files } = viaZip(await buildExport(bookId, true)); const result = await importBook(other.id, data, files); const copy = await prisma.book.findUniqueOrThrow({ where: { id: result.bookId } }); expect(copy.ownerId).toBe(other.id); expect(copy.title).toBe("Testbok"); }); it("saknade bilder och trasiga kopplingar hoppas över och räknas", async () => { const data = validExport({ entities: [entityRow("a", "CHARACTER", "Anna", { image: "saknas.png" }), entityRow("b", "CHARACTER", "Bo", { image: "skräp.png" })], relations: [ { id: "r1", code: null, fromId: "a", toId: "b", type: "Vänner", description: null, data: {}, members: ["finns-inte"] }, { id: "r2", code: null, fromId: "a", toId: "okänd", type: "Fiende", description: null, data: {}, members: [] }, { id: "r3", code: null, fromId: "a", toId: "a", type: "Självrelation", description: null, data: {}, members: [] }, ], shifts: [{ personId: "okänd", workplaceId: null, weekday: 0, startTime: "08:00", endTime: "16:00", weeks: "ALL", label: null, scheduleCode: null }], }); const files = new Map([["skräp.png", new TextEncoder().encode("det här är ingen bild")]]); const result = await importBook(ownerId, data, files); expect(result).toMatchObject({ entities: 2, relations: 1, shifts: 0, skippedImages: 2, skippedLinks: 3 }); const relations = await prisma.relation.findMany({ where: { bookId: result.bookId }, include: { members: true } }); expect(relations).toHaveLength(1); expect(relations[0].members).toHaveLength(0); }); it("behåller giltiga ID men ger nya åt dubbletter och felaktiga", async () => { const data = validExport({ entities: [ entityRow("a", "CHARACTER", "Anna", { code: "KI-0007" }), entityRow("b", "CHARACTER", "Bo", { code: "KI-0007" }), // dubblett entityRow("c", "CHARACTER", "Cia", { code: "FEL-1" }), // fel format entityRow("d", "CHARACTER", "Dan", { code: "FI-0002" }), // fel prefix för en karaktär entityRow("e", "CHARACTER", "Eva", { code: null }), entityRow("f", "APP", "En app", { code: "KI-0001" }), // appar har inget ID ], }); const result = await importBook(ownerId, data, new Map()); const rows = await prisma.entity.findMany({ where: { bookId: result.bookId }, orderBy: { name: "asc" } }); const code = (name: string) => rows.find((e) => e.name === name)!.code; expect(code("Anna")).toBe("KI-0007"); expect(code("En app")).toBeNull(); const assigned = ["Bo", "Cia", "Dan", "Eva"].map(code); expect(new Set([...assigned, "KI-0007"]).size).toBe(5); // alla unika expect(assigned.every((c) => /^KI-\d{4}$/.test(c!))).toBe(true); // Nya nummer fortsätter efter det högsta som användes expect(assigned.sort()).toEqual(["KI-0008", "KI-0009", "KI-0010", "KI-0011"]); }); it("tar bort de sparade bilderna igen om importen misslyckas", async () => { const image = await makeImage(40, 40, "png"); const before = await filesIn(UPLOAD_DIR); // Samma id två gånger gör att databasen avvisar raderna (unik nyckel) efter att bilderna sparats const data = validExport({ entities: [entityRow("dubbel", "CHARACTER", "A", { image: "a.png" }), entityRow("dubbel", "CHARACTER", "B", { image: "b.png" })], }); await expect(importBook(ownerId, data, new Map([["a.png", image], ["b.png", image]]))).rejects.toThrow(); expect(await filesIn(UPLOAD_DIR)).toEqual(before); expect(await prisma.book.count({ where: { title: "Testbok (import)" } })).toBe(0); }); });