Delning av böcker, skydd mot kolliderande ändringar och import från Word
Böcker kan delas med roller (läsare, redaktör, administratör), och behörigheten kontrolleras på servern. Formulär för poster, relationer och händelser skickar med version, och en krock visar vad som skiljer och låter användaren spara ändå eller ladda om. Ifyllda Word-mallar kan importeras med förhandsgranskning. Importerade ID flyttar nu räknaren. Migrering 0007. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
bd269d70a5
commit
86fd435438
64 files changed
+4796
-235
No files matched your search
@@ -0,0 +1,242 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { UPLOAD_DIR, saveImageBytes } from "@/lib/files";
|
||||
import { MAX_VERSIONS } from "@/lib/history";
|
||||
import { isStale, versionOf, type ConflictInfo, type SaveResult } from "@/lib/conflict";
|
||||
import { makeImage } from "../helpers/fixtures";
|
||||
import { describeDb, filesIn, makeBook, makeEntity, makeEvent, makeRelation, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
const login = vi.hoisted(() => ({ userId: "" as string }));
|
||||
vi.mock("@/auth", () => ({ auth: async () => (login.userId ? { user: { id: login.userId } } : null) }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: () => undefined }));
|
||||
vi.mock("next/navigation", () => ({
|
||||
redirect: (to: string) => {
|
||||
throw new Error(`REDIRECT:${to}`);
|
||||
},
|
||||
notFound: () => {
|
||||
throw new Error("NOT_FOUND");
|
||||
},
|
||||
}));
|
||||
vi.mock("@/i18n/server", async () => {
|
||||
const core = await import("@/i18n/core");
|
||||
return { getLocale: async () => "sv", getT: async () => ({ locale: "sv", t: core.makeT(core.dictionaries.sv) }) };
|
||||
});
|
||||
|
||||
import { saveEntity } from "@/actions/entities";
|
||||
import { saveEvent } from "@/actions/events";
|
||||
import { saveRelation } from "@/actions/relations";
|
||||
|
||||
const form = (fields: Record<string, string | string[] | Blob>) => {
|
||||
const data = new FormData();
|
||||
for (const [key, value] of Object.entries(fields)) {
|
||||
if (value instanceof Blob) data.append(key, value, "bild.png");
|
||||
else for (const v of Array.isArray(value) ? value : [value]) data.append(key, v);
|
||||
}
|
||||
return data;
|
||||
};
|
||||
|
||||
/** Kör en sparåtgärd. Antingen omdirigerar den (sparat) eller svarar med en krock. */
|
||||
async function save(run: () => Promise<SaveResult>): Promise<{ saved: true; to: string } | { saved: false; conflict: ConflictInfo }> {
|
||||
try {
|
||||
const result = await run();
|
||||
if (result?.conflict) return { saved: false, conflict: result.conflict };
|
||||
throw new Error("Åtgärden svarade varken med omdirigering eller krock");
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : "";
|
||||
if (message.startsWith("REDIRECT:")) return { saved: true, to: message.slice(9) };
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
describe("isStale", () => {
|
||||
const now = new Date("2026-01-01T12:00:00.000Z");
|
||||
it("jämför versionen som formuläret öppnades med", () => {
|
||||
expect(isStale(versionOf(now), now)).toBe(false);
|
||||
expect(isStale(versionOf(new Date(now.getTime() - 1)), now)).toBe(true);
|
||||
});
|
||||
it("kontrollerar inget när versionen saknas", () => {
|
||||
expect(isStale("", now)).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
describeDb("skydd mot kolliderande ändringar", () => {
|
||||
let ownerId: string;
|
||||
let otherId: string;
|
||||
let bookId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
const owner = await makeUser("Ägare");
|
||||
const other = await makeUser("Kollega", "kollega@example.com");
|
||||
ownerId = owner.id;
|
||||
otherId = other.id;
|
||||
bookId = (await makeBook(ownerId)).id;
|
||||
await prisma.bookMember.create({ data: { bookId, userId: otherId, role: "EDITOR" } });
|
||||
login.userId = ownerId;
|
||||
});
|
||||
|
||||
describe("poster", () => {
|
||||
const edit = (id: string, version: string, fields: Record<string, string> = {}) =>
|
||||
save(() => saveEntity(form({ bookId, id, name: "Anna", version, ...fields })));
|
||||
|
||||
it("sparar när versionen stämmer, och ger en ny version", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
const result = await edit(anna.id, versionOf(anna.updatedAt), { summary: "Ny" });
|
||||
expect(result).toMatchObject({ saved: true });
|
||||
const after = await prisma.entity.findUniqueOrThrow({ where: { id: anna.id } });
|
||||
expect(after.summary).toBe("Ny");
|
||||
expect(after.updatedById).toBe(ownerId);
|
||||
expect(versionOf(after.updatedAt)).not.toBe(versionOf(anna.updatedAt));
|
||||
});
|
||||
|
||||
it("sparar ingenting när någon annan hunnit före, och visar vad som skiljer", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna", { summary: "Från början", data: { nickname: "Ann" } });
|
||||
const opened = versionOf(anna.updatedAt);
|
||||
|
||||
// Kollegan sparar först
|
||||
login.userId = otherId;
|
||||
await edit(anna.id, opened, { summary: "Kollegans text", f_nickname: "Ann" });
|
||||
|
||||
// Sedan sparar den första med den gamla versionen
|
||||
login.userId = ownerId;
|
||||
const result = await edit(anna.id, opened, { summary: "Min text", f_nickname: "Annie" });
|
||||
expect(result.saved).toBe(false);
|
||||
if (result.saved) return;
|
||||
|
||||
expect(result.conflict.by).toBe("Kollega");
|
||||
expect(result.conflict.changes).toEqual(
|
||||
expect.arrayContaining([
|
||||
{ label: "Sammanfattning", before: "Kollegans text", after: "Min text" },
|
||||
{ label: "Smeknamn", before: "Ann", after: "Annie" },
|
||||
]),
|
||||
);
|
||||
const stored = await prisma.entity.findUniqueOrThrow({ where: { id: anna.id } });
|
||||
expect(stored.summary).toBe("Kollegans text");
|
||||
expect(stored.updatedById).toBe(otherId);
|
||||
});
|
||||
|
||||
it("att spara ändå med den nya versionen skriver över, och den andras version hamnar i historiken", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna", { summary: "Från början" });
|
||||
const opened = versionOf(anna.updatedAt);
|
||||
login.userId = otherId;
|
||||
await edit(anna.id, opened, { summary: "Kollegans text" });
|
||||
|
||||
login.userId = ownerId;
|
||||
const conflict = await edit(anna.id, opened, { summary: "Min text" });
|
||||
if (conflict.saved) throw new Error("Väntade en krock");
|
||||
const forced = await edit(anna.id, conflict.conflict.version, { summary: "Min text" });
|
||||
expect(forced.saved).toBe(true);
|
||||
|
||||
expect((await prisma.entity.findUniqueOrThrow({ where: { id: anna.id } })).summary).toBe("Min text");
|
||||
const versions = await prisma.entityVersion.findMany({ where: { entityId: anna.id }, orderBy: { createdAt: "asc" } });
|
||||
const summaries = versions.map((v) => (v.snapshot as { summary: string }).summary);
|
||||
expect(summaries).toEqual(["Från början", "Kollegans text"]);
|
||||
expect(versions[1].userId).toBe(ownerId);
|
||||
});
|
||||
|
||||
it("tre samtidiga redigerare: bara en kommer igenom med samma version", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
const opened = versionOf(anna.updatedAt);
|
||||
const results = await Promise.all([1, 2, 3].map((n) => edit(anna.id, opened, { summary: `Text ${n}` }).catch((e) => ({ error: String(e) }))));
|
||||
const saved = results.filter((r) => "saved" in r && r.saved).length;
|
||||
const conflicts = results.filter((r) => "saved" in r && !r.saved).length;
|
||||
expect(saved).toBe(1);
|
||||
expect(conflicts).toBe(2);
|
||||
});
|
||||
|
||||
it("en ny bild läggs inte kvar som skräp när sparningen avbryts av en krock", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
const opened = versionOf(anna.updatedAt);
|
||||
await edit(anna.id, opened, { summary: "Först" });
|
||||
|
||||
const before = await filesIn(UPLOAD_DIR);
|
||||
const png = new Blob([(await makeImage(50, 50, "png")) as BlobPart], { type: "image/png" });
|
||||
const result = await save(() => saveEntity(form({ bookId, id: anna.id, name: "Anna", version: opened, image: png })));
|
||||
expect(result.saved).toBe(false);
|
||||
expect(await filesIn(UPLOAD_DIR)).toEqual(before);
|
||||
});
|
||||
|
||||
it("en bild som byts ut tar bort den gamla först när sparningen lyckats", async () => {
|
||||
const old = await saveImageBytes(await makeImage(40, 40, "png"));
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna", { imageFile: old });
|
||||
const png = new Blob([(await makeImage(50, 50, "png")) as BlobPart], { type: "image/png" });
|
||||
const result = await edit(anna.id, versionOf(anna.updatedAt), { image: png as unknown as string });
|
||||
expect(result.saved).toBe(true);
|
||||
const after = await prisma.entity.findUniqueOrThrow({ where: { id: anna.id } });
|
||||
expect(after.imageFile).toBeTruthy();
|
||||
expect(after.imageFile).not.toBe(old);
|
||||
expect(await filesIn(UPLOAD_DIR)).not.toContain(old);
|
||||
});
|
||||
|
||||
it("formulär utan version sparas som förut", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
expect((await save(() => saveEntity(form({ bookId, id: anna.id, name: "Anna", summary: "Utan version" })))).saved).toBe(true);
|
||||
});
|
||||
|
||||
it("nya poster behöver ingen version", async () => {
|
||||
const result = await save(() => saveEntity(form({ bookId, kind: "CHARACTER", name: "Ny", version: "" })));
|
||||
expect(result.saved).toBe(true);
|
||||
expect((await prisma.entity.findFirstOrThrow({ where: { name: "Ny" } })).updatedById).toBe(ownerId);
|
||||
});
|
||||
|
||||
it("historiken håller sig inom gränsen även med många krockar", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
let version = versionOf(anna.updatedAt);
|
||||
for (let i = 0; i < MAX_VERSIONS + 3; i++) {
|
||||
await edit(anna.id, version, { summary: `v${i}` });
|
||||
version = versionOf((await prisma.entity.findUniqueOrThrow({ where: { id: anna.id } })).updatedAt);
|
||||
}
|
||||
expect(await prisma.entityVersion.count({ where: { entityId: anna.id } })).toBe(MAX_VERSIONS);
|
||||
});
|
||||
});
|
||||
|
||||
describe("relationer", () => {
|
||||
it("kan inte skriva över en relation som ändrats av någon annan", async () => {
|
||||
const a = await makeEntity(bookId, "CHARACTER", "A");
|
||||
const b = await makeEntity(bookId, "CHARACTER", "B");
|
||||
const relation = await makeRelation(bookId, a.id, b.id, "Vänner");
|
||||
const opened = versionOf(relation.updatedAt);
|
||||
const edit = (type: string, version: string) => save(() => saveRelation(form({ bookId, id: relation.id, type, version })));
|
||||
|
||||
login.userId = otherId;
|
||||
expect((await edit("Bästa vänner", opened)).saved).toBe(true);
|
||||
login.userId = ownerId;
|
||||
const result = await edit("Ovänner", opened);
|
||||
expect(result.saved).toBe(false);
|
||||
if (result.saved) return;
|
||||
expect(result.conflict.by).toBe("Kollega");
|
||||
expect((await prisma.relation.findUniqueOrThrow({ where: { id: relation.id } })).type).toBe("Bästa vänner");
|
||||
|
||||
expect((await edit("Ovänner", result.conflict.version)).saved).toBe(true);
|
||||
expect((await prisma.relation.findUniqueOrThrow({ where: { id: relation.id } })).type).toBe("Ovänner");
|
||||
});
|
||||
|
||||
it("deltagarna behålls när en sparning avvisas", async () => {
|
||||
const a = await makeEntity(bookId, "CHARACTER", "A");
|
||||
const b = await makeEntity(bookId, "CHARACTER", "B");
|
||||
const c = await makeEntity(bookId, "CHARACTER", "C");
|
||||
const relation = await makeRelation(bookId, a.id, b.id, "Grupp", [c.id]);
|
||||
const opened = versionOf(relation.updatedAt);
|
||||
await save(() => saveRelation(form({ bookId, id: relation.id, type: "Grupp 2", version: opened, memberIds: [c.id] })));
|
||||
const result = await save(() => saveRelation(form({ bookId, id: relation.id, type: "Grupp 3", version: opened })));
|
||||
expect(result.saved).toBe(false);
|
||||
expect(await prisma.relationMember.count({ where: { relationId: relation.id } })).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("händelser", () => {
|
||||
it("kan inte skriva över en händelse som ändrats av någon annan", async () => {
|
||||
const a = await makeEntity(bookId, "CHARACTER", "A");
|
||||
const event = await makeEvent(bookId, "Fest", "2000", [a.id]);
|
||||
const opened = versionOf(event.updatedAt);
|
||||
const edit = (title: string, version: string) => save(() => saveEvent(form({ bookId, id: event.id, title, date: "2000", version, participantIds: [a.id] })));
|
||||
|
||||
login.userId = otherId;
|
||||
expect((await edit("Stor fest", opened)).saved).toBe(true);
|
||||
login.userId = ownerId;
|
||||
const result = await edit("Liten fest", opened);
|
||||
expect(result.saved).toBe(false);
|
||||
expect((await prisma.storyEvent.findUniqueOrThrow({ where: { id: event.id } })).title).toBe("Stor fest");
|
||||
expect(await prisma.eventParticipant.count({ where: { eventId: event.id } })).toBe(1);
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,327 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { UPLOAD_DIR, saveImageBytes } from "@/lib/files";
|
||||
import { makeImage } from "../helpers/fixtures";
|
||||
import { describeDb, filesIn, makeBook, makeEntity, makeEvent, makeRelation, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
// Här används den riktiga inloggningskontrollen (session.ts). Bara själva inloggningen, cache och
|
||||
// omdirigeringar ersätts, så att åtgärderna kan köras utan webbserver.
|
||||
const login = vi.hoisted(() => ({ userId: "" as string }));
|
||||
vi.mock("@/auth", () => ({ auth: async () => (login.userId ? { user: { id: login.userId } } : null) }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: () => undefined }));
|
||||
vi.mock("next/navigation", () => ({
|
||||
redirect: (to: string) => {
|
||||
throw new Error(`REDIRECT:${to}`);
|
||||
},
|
||||
notFound: () => {
|
||||
throw new Error("NOT_FOUND");
|
||||
},
|
||||
}));
|
||||
vi.mock("@/i18n/server", async () => {
|
||||
const core = await import("@/i18n/core");
|
||||
return { getLocale: async () => "sv", getT: async () => ({ locale: "sv", t: core.makeT(core.dictionaries.sv) }) };
|
||||
});
|
||||
|
||||
import { deleteBook, updateBook } from "@/actions/books";
|
||||
import { deleteEntity, saveEntity } from "@/actions/entities";
|
||||
import { addEvent } from "@/actions/events";
|
||||
import { addRelation } from "@/actions/relations";
|
||||
import { changeMemberRole, leaveSharedBook, removeBookMember, shareBook } from "@/actions/sharing";
|
||||
import { emptyTrash, purgeTrash, restoreTrashEntity } from "@/actions/trash";
|
||||
import { saveTemplate } from "@/actions/templates";
|
||||
import { GET as exportBook } from "@/app/api/books/[bookId]/export/route";
|
||||
import { GET as searchBook } from "@/app/api/books/[bookId]/search/route";
|
||||
import { bookAccess } from "@/lib/book-access";
|
||||
import { listMembers } from "@/lib/sharing";
|
||||
|
||||
const form = (fields: Record<string, string | string[]>) => {
|
||||
const data = new FormData();
|
||||
for (const [key, value] of Object.entries(fields)) for (const v of Array.isArray(value) ? value : [value]) data.append(key, v);
|
||||
return data;
|
||||
};
|
||||
|
||||
/** Kör en åtgärd. Returnerar "ok" om den gick igenom, annars vad som hände (omdirigering eller 404). */
|
||||
async function attempt(run: () => Promise<unknown>): Promise<string> {
|
||||
try {
|
||||
await run();
|
||||
return "ok";
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (message.startsWith("REDIRECT:") || message === "NOT_FOUND") return message;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
describeDb("delning av böcker", () => {
|
||||
let owner: { id: string };
|
||||
let admin: { id: string };
|
||||
let editor: { id: string };
|
||||
let viewer: { id: string };
|
||||
let stranger: { id: string };
|
||||
let bookId: string;
|
||||
|
||||
const as = (user: { id: string }) => {
|
||||
login.userId = user.id;
|
||||
};
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
owner = await makeUser("Ägare");
|
||||
admin = await makeUser("Admin");
|
||||
editor = await makeUser("Redaktör");
|
||||
viewer = await makeUser("Läsare");
|
||||
stranger = await makeUser("Obehörig");
|
||||
bookId = (await makeBook(owner.id, "Delad bok")).id;
|
||||
await prisma.bookMember.createMany({
|
||||
data: [
|
||||
{ bookId, userId: admin.id, role: "ADMIN" },
|
||||
{ bookId, userId: editor.id, role: "EDITOR" },
|
||||
{ bookId, userId: viewer.id, role: "VIEWER" },
|
||||
],
|
||||
});
|
||||
});
|
||||
|
||||
describe("åtkomst", () => {
|
||||
it("ger rätt roll åt ägare, medlemmar och ingen alls åt andra", async () => {
|
||||
expect((await bookAccess(bookId, owner.id))?.role).toBe("OWNER");
|
||||
expect((await bookAccess(bookId, admin.id))?.role).toBe("ADMIN");
|
||||
expect((await bookAccess(bookId, editor.id))?.role).toBe("EDITOR");
|
||||
expect((await bookAccess(bookId, viewer.id))?.role).toBe("VIEWER");
|
||||
expect(await bookAccess(bookId, stranger.id)).toBeNull();
|
||||
expect(await bookAccess("finns-inte", owner.id)).toBeNull();
|
||||
});
|
||||
|
||||
it("boken ligger kvar hos ägaren och medlemskapet försvinner med boken eller användaren", async () => {
|
||||
await prisma.user.delete({ where: { id: editor.id } });
|
||||
expect(await prisma.bookMember.count({ where: { bookId } })).toBe(2);
|
||||
await prisma.book.delete({ where: { id: bookId } });
|
||||
expect(await prisma.bookMember.count()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("vad varje roll får göra", () => {
|
||||
const create = (name: string) => saveEntity(form({ bookId, kind: "CHARACTER", name }));
|
||||
|
||||
it("läsare kan läsa men inte skriva", async () => {
|
||||
as(viewer);
|
||||
expect(await attempt(() => create("Ny"))).toBe("NOT_FOUND");
|
||||
expect(await attempt(() => addRelation(form({ bookId, fromId: "a", toId: "b", type: "x" })))).toBe("NOT_FOUND");
|
||||
expect(await attempt(() => addEvent(form({ bookId, title: "x", date: "2000" })))).toBe("NOT_FOUND");
|
||||
expect(await prisma.entity.count()).toBe(0);
|
||||
// Läsning och export fungerar
|
||||
const res = await exportBook(new Request("http://x/api"), { params: Promise.resolve({ bookId }) });
|
||||
expect(res.status).toBe(200);
|
||||
});
|
||||
|
||||
it("redaktörer skriver som ägaren men administrerar inte", async () => {
|
||||
as(editor);
|
||||
expect(await attempt(() => create("Anna"))).toMatch(/^REDIRECT:/);
|
||||
const anna = await prisma.entity.findFirstOrThrow({ where: { bookId } });
|
||||
expect(anna.updatedById).toBe(editor.id);
|
||||
expect(await attempt(() => updateBook(form({ bookId, title: "Ny titel" })))).toBe("NOT_FOUND");
|
||||
expect(await attempt(() => saveTemplate(form({ bookId, kind: "CHARACTER", fields: "[]" })))).toBe("NOT_FOUND");
|
||||
expect(await attempt(() => shareBook(form({ bookId, email: "x@example.com", role: "VIEWER" })))).toBe("NOT_FOUND");
|
||||
expect(await attempt(() => deleteBook(form({ bookId })))).toBe("NOT_FOUND");
|
||||
expect((await prisma.book.findUniqueOrThrow({ where: { id: bookId } })).title).toBe("Delad bok");
|
||||
});
|
||||
|
||||
it("administratörer ändrar bokens uppgifter och delar den, men tar inte bort den", async () => {
|
||||
as(admin);
|
||||
expect(await attempt(() => updateBook(form({ bookId, title: "Nytt namn" })))).toBe("ok");
|
||||
expect((await prisma.book.findUniqueOrThrow({ where: { id: bookId } })).title).toBe("Nytt namn");
|
||||
expect(await attempt(() => deleteBook(form({ bookId })))).toBe("NOT_FOUND");
|
||||
expect(await prisma.book.count()).toBe(1);
|
||||
});
|
||||
|
||||
it("bara ägaren tar bort boken, och den hamnar i ägarens papperskorg", async () => {
|
||||
as(owner);
|
||||
expect(await attempt(() => deleteBook(form({ bookId })))).toBe("REDIRECT:/");
|
||||
expect(await prisma.book.count()).toBe(0);
|
||||
expect(await prisma.trashItem.count({ where: { ownerId: owner.id, kind: "book" } })).toBe(1);
|
||||
});
|
||||
|
||||
it("obehöriga får 404 överallt, även för export och sök", async () => {
|
||||
as(stranger);
|
||||
expect(await attempt(() => create("Intrång"))).toBe("NOT_FOUND");
|
||||
expect(await attempt(() => updateBook(form({ bookId, title: "x" })))).toBe("NOT_FOUND");
|
||||
expect((await exportBook(new Request("http://x/api"), { params: Promise.resolve({ bookId }) })).status).toBe(404);
|
||||
expect((await searchBook(new Request("http://x/api?q=anna"), { params: Promise.resolve({ bookId }) })).status).toBe(404);
|
||||
});
|
||||
|
||||
it("sök fungerar för medlemmar", async () => {
|
||||
await makeEntity(bookId, "CHARACTER", "Annika");
|
||||
as(viewer);
|
||||
const res = await searchBook(new Request("http://x/api?q=anni"), { params: Promise.resolve({ bookId }) });
|
||||
expect(res.status).toBe(200);
|
||||
expect(((await res.json()) as { results: unknown[] }).results).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("inloggning krävs", async () => {
|
||||
login.userId = "";
|
||||
expect(await attempt(() => create("Anonym"))).toBe("REDIRECT:/login");
|
||||
expect((await exportBook(new Request("http://x/api"), { params: Promise.resolve({ bookId }) })).status).toBe(401);
|
||||
});
|
||||
});
|
||||
|
||||
describe("hantera delningen", () => {
|
||||
it("ägaren delar med e-postadress, oavsett stora och små bokstäver", async () => {
|
||||
const friend = await makeUser("Vän", "Vän@Example.com");
|
||||
as(owner);
|
||||
expect(await attempt(() => shareBook(form({ bookId, email: " vän@example.COM ", role: "EDITOR" })))).toBe("REDIRECT:" + `/books/${bookId}/settings?share=ok`);
|
||||
expect((await prisma.bookMember.findFirstOrThrow({ where: { userId: friend.id } })).role).toBe("EDITOR");
|
||||
});
|
||||
|
||||
it("ger tydliga svar när delningen inte går", async () => {
|
||||
as(owner);
|
||||
const share = (email: string, role = "EDITOR") => attempt(() => shareBook(form({ bookId, email, role })));
|
||||
expect(await share("ingen@example.com")).toContain("share=not-found");
|
||||
expect(await share("ägare@example.com")).toContain("share=owner");
|
||||
expect(await share("redaktör@example.com")).toContain("share=already");
|
||||
expect(await share("inte-en-adress")).toContain("share=invalid");
|
||||
expect(await share("läsare@example.com", "SUPER")).toContain("share=invalid");
|
||||
expect(await prisma.bookMember.count()).toBe(3);
|
||||
});
|
||||
|
||||
it("en administratör kan dela som redaktör eller läsare men inte utse administratörer", async () => {
|
||||
const friend = await makeUser("Vän");
|
||||
as(admin);
|
||||
expect(await attempt(() => shareBook(form({ bookId, email: "vän@example.com", role: "ADMIN" })))).toContain("share=forbidden");
|
||||
expect(await attempt(() => shareBook(form({ bookId, email: "vän@example.com", role: "VIEWER" })))).toContain("share=ok");
|
||||
expect((await prisma.bookMember.findFirstOrThrow({ where: { userId: friend.id } })).role).toBe("VIEWER");
|
||||
});
|
||||
|
||||
it("en administratör kan inte röra en annan administratör, ägaren kan", async () => {
|
||||
const second = await makeUser("Admin två");
|
||||
await prisma.bookMember.create({ data: { bookId, userId: second.id, role: "ADMIN" } });
|
||||
as(admin);
|
||||
expect(await attempt(() => changeMemberRole(form({ bookId, userId: second.id, role: "VIEWER" })))).toContain("share=forbidden");
|
||||
expect(await attempt(() => removeBookMember(form({ bookId, userId: second.id })))).toContain("share=forbidden");
|
||||
expect(await prisma.bookMember.count({ where: { userId: second.id } })).toBe(1);
|
||||
as(owner);
|
||||
expect(await attempt(() => changeMemberRole(form({ bookId, userId: second.id, role: "VIEWER" })))).toContain("share=ok");
|
||||
expect(await attempt(() => removeBookMember(form({ bookId, userId: second.id })))).toContain("share=ok");
|
||||
expect(await prisma.bookMember.count({ where: { userId: second.id } })).toBe(0);
|
||||
});
|
||||
|
||||
it("redaktörer och läsare kan inte hantera delningen", async () => {
|
||||
for (const user of [editor, viewer]) {
|
||||
as(user);
|
||||
expect(await attempt(() => removeBookMember(form({ bookId, userId: viewer.id })))).toBe("NOT_FOUND");
|
||||
expect(await attempt(() => changeMemberRole(form({ bookId, userId: viewer.id, role: "ADMIN" })))).toBe("NOT_FOUND");
|
||||
}
|
||||
expect(await prisma.bookMember.count()).toBe(3);
|
||||
});
|
||||
|
||||
it("en medlem kan lämna boken, och ägaren kan inte lämna sin egen", async () => {
|
||||
as(viewer);
|
||||
expect(await attempt(() => leaveSharedBook(form({ bookId })))).toBe("REDIRECT:/");
|
||||
expect(await bookAccess(bookId, viewer.id)).toBeNull();
|
||||
as(owner);
|
||||
await attempt(() => leaveSharedBook(form({ bookId })));
|
||||
expect((await bookAccess(bookId, owner.id))?.role).toBe("OWNER");
|
||||
});
|
||||
|
||||
it("listar ägare och medlemmar", async () => {
|
||||
const { owner: o, members } = await listMembers(bookId);
|
||||
expect(o.id).toBe(owner.id);
|
||||
expect(members.map((m) => [m.user.name, m.role])).toEqual([
|
||||
["Admin", "ADMIN"],
|
||||
["Redaktör", "EDITOR"],
|
||||
["Läsare", "VIEWER"],
|
||||
]);
|
||||
});
|
||||
|
||||
it("tar bort en delning utan att röra bokens innehåll", async () => {
|
||||
await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
as(owner);
|
||||
await attempt(() => removeBookMember(form({ bookId, userId: editor.id })));
|
||||
expect(await prisma.entity.count({ where: { bookId } })).toBe(1);
|
||||
});
|
||||
});
|
||||
|
||||
describe("papperskorgen i en delad bok", () => {
|
||||
it("en redaktör flyttar en post dit under ägarens namn, och återställer den", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
as(editor);
|
||||
expect(await attempt(() => deleteEntity(form({ bookId, id: anna.id })))).toMatch(/^REDIRECT:/);
|
||||
const item = await prisma.trashItem.findFirstOrThrow();
|
||||
expect(item).toMatchObject({ ownerId: owner.id, bookId, kind: "entity" });
|
||||
|
||||
expect(await attempt(() => restoreTrashEntity(form({ bookId, id: item.id })))).toContain(`/entity/${anna.id}`);
|
||||
expect(await prisma.entity.count({ where: { id: anna.id } })).toBe(1);
|
||||
});
|
||||
|
||||
it("läsare kan inte ta bort eller återställa", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
as(viewer);
|
||||
expect(await attempt(() => deleteEntity(form({ bookId, id: anna.id })))).toBe("NOT_FOUND");
|
||||
expect(await prisma.entity.count()).toBe(1);
|
||||
});
|
||||
|
||||
it("bara administratörer rensar papperskorgen", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
as(editor);
|
||||
await attempt(() => deleteEntity(form({ bookId, id: anna.id })));
|
||||
const item = await prisma.trashItem.findFirstOrThrow();
|
||||
|
||||
expect(await attempt(() => purgeTrash(form({ bookId, id: item.id })))).toBe("NOT_FOUND");
|
||||
expect(await attempt(() => emptyTrash(form({ bookId })))).toBe("NOT_FOUND");
|
||||
expect(await prisma.trashItem.count()).toBe(1);
|
||||
|
||||
as(admin);
|
||||
expect(await attempt(() => purgeTrash(form({ bookId, id: item.id })))).toBe("ok");
|
||||
expect(await prisma.trashItem.count()).toBe(0);
|
||||
});
|
||||
|
||||
it("en annan boks papperskorg går inte att återställa eller rensa", async () => {
|
||||
const otherBook = await makeBook(stranger.id, "Annans bok");
|
||||
const secret = await makeEntity(otherBook.id, "CHARACTER", "Hemlig");
|
||||
const { trashEntity } = await import("@/lib/trash");
|
||||
await trashEntity(stranger.id, otherBook.id, secret.id);
|
||||
const item = await prisma.trashItem.findFirstOrThrow();
|
||||
|
||||
as(editor);
|
||||
// Rätt bok i formuläret men en annan boks post: ingenting återställs
|
||||
expect(await attempt(() => restoreTrashEntity(form({ bookId, id: item.id })))).toContain("restore=failed");
|
||||
expect(await attempt(() => purgeTrash(form({ bookId, id: item.id })))).toBe("NOT_FOUND");
|
||||
expect(await prisma.trashItem.count()).toBe(1);
|
||||
expect(await prisma.entity.count({ where: { id: secret.id } })).toBe(0);
|
||||
});
|
||||
|
||||
it("borttagna böcker går bara att återställa och rensa för ägaren", async () => {
|
||||
as(owner);
|
||||
await attempt(() => deleteBook(form({ bookId })));
|
||||
const item = await prisma.trashItem.findFirstOrThrow({ where: { kind: "book" } });
|
||||
as(admin);
|
||||
await attempt(() => purgeTrash(form({ id: item.id })));
|
||||
expect(await prisma.trashItem.count()).toBe(1);
|
||||
as(owner);
|
||||
await attempt(() => purgeTrash(form({ id: item.id })));
|
||||
expect(await prisma.trashItem.count()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("lagring", () => {
|
||||
it("bilder som en redaktör laddar upp räknas på ägaren", async () => {
|
||||
const image = await saveImageBytes(await makeImage(60, 40, "png"));
|
||||
await makeEntity(bookId, "CHARACTER", "Anna", { imageFile: image });
|
||||
const { userStorageBytes } = await import("@/lib/storage");
|
||||
expect(await userStorageBytes(owner.id)).toBeGreaterThan(0);
|
||||
expect(await userStorageBytes(editor.id)).toBe(0);
|
||||
expect(await filesIn(UPLOAD_DIR)).toContain(image);
|
||||
});
|
||||
});
|
||||
|
||||
describe("relationer och händelser skrivs av redaktörer", () => {
|
||||
it("sparar vem som gjorde ändringen", async () => {
|
||||
const a = await makeEntity(bookId, "CHARACTER", "A");
|
||||
const b = await makeEntity(bookId, "CHARACTER", "B");
|
||||
as(editor);
|
||||
await attempt(() => addEvent(form({ bookId, title: "Möte", date: "2001" })));
|
||||
expect((await prisma.storyEvent.findFirstOrThrow()).updatedById).toBe(editor.id);
|
||||
await attempt(() => addRelation(form({ bookId, fromId: a.id, toId: b.id, type: "Vänner" })));
|
||||
expect(await prisma.relation.count()).toBe(1);
|
||||
expect(await makeRelation(bookId, a.id, b.id)).toBeTruthy();
|
||||
expect(await makeEvent(bookId, "x", "2000")).toBeTruthy();
|
||||
});
|
||||
});
|
||||
});
|
||||
@@ -0,0 +1,276 @@
|
||||
import { beforeEach, describe, expect, it, vi } from "vitest";
|
||||
import { makeDocx, para, table } from "../helpers/docx";
|
||||
import { describeDb, makeBook, makeEntity, makeUser, prisma, resetAll } from "../helpers/db";
|
||||
|
||||
const login = vi.hoisted(() => ({ userId: "" as string }));
|
||||
vi.mock("@/auth", () => ({ auth: async () => (login.userId ? { user: { id: login.userId } } : null) }));
|
||||
vi.mock("next/cache", () => ({ revalidatePath: () => undefined }));
|
||||
vi.mock("next/navigation", () => ({
|
||||
redirect: (to: string) => {
|
||||
throw new Error(`REDIRECT:${to}`);
|
||||
},
|
||||
notFound: () => {
|
||||
throw new Error("NOT_FOUND");
|
||||
},
|
||||
}));
|
||||
vi.mock("@/i18n/server", async () => {
|
||||
const core = await import("@/i18n/core");
|
||||
return { getLocale: async () => "sv", getT: async () => ({ locale: "sv", t: core.makeT(core.dictionaries.sv) }) };
|
||||
});
|
||||
|
||||
import { previewWordImport, saveWordImport } from "@/actions/word-import";
|
||||
import { MAX_DOCX_BYTES } from "@/lib/word-docx";
|
||||
import { commitWordImport, previewWordFiles, type CommitItem } from "@/lib/word-import-db";
|
||||
|
||||
const character = (name: string, extra: string[][] = [], code = "KI-0001") =>
|
||||
makeDocx([table(["Karaktärs ID:", code], ["Förnamn:", name], ["Efternamn:", "Test"], ...extra), para("Övrigt:"), para("Anteckning.")]);
|
||||
|
||||
const bytes = (doc: Uint8Array) => ({ name: "doc.docx", bytes: doc });
|
||||
|
||||
async function attempt(run: () => Promise<unknown>): Promise<string> {
|
||||
try {
|
||||
await run();
|
||||
return "ok";
|
||||
} catch (error) {
|
||||
const message = error instanceof Error ? error.message : String(error);
|
||||
if (message === "NOT_FOUND" || message.startsWith("REDIRECT:")) return message;
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
describeDb("import från Word", () => {
|
||||
let ownerId: string;
|
||||
let bookId: string;
|
||||
|
||||
beforeEach(async () => {
|
||||
await resetAll();
|
||||
ownerId = (await makeUser()).id;
|
||||
bookId = (await makeBook(ownerId)).id;
|
||||
login.userId = ownerId;
|
||||
});
|
||||
|
||||
describe("förhandsgranskning", () => {
|
||||
it("tolkar dokumentet mot bokens poster och markerar dubbletter", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna Test");
|
||||
const [doc] = await previewWordFiles(bookId, [bytes(character("Anna", [["Anställd hos:", "Okänd"]]))]);
|
||||
expect(doc.error).toBeNull();
|
||||
expect(doc.kind).toBe("CHARACTER");
|
||||
expect(doc.items[0]).toMatchObject({ name: "Anna Test", code: "KI-0001" });
|
||||
expect(doc.items[0].duplicates).toEqual([{ id: anna.id, name: "Anna Test", code: anna.code }]);
|
||||
expect(doc.items[0].links).toEqual([{ type: "Jobbar på", toDocument: false, entityId: null, text: "Okänd", note: "" }]);
|
||||
});
|
||||
|
||||
it("hittar poster i boken på ID och namn, men inte i en annan bok", async () => {
|
||||
const company = await makeEntity(bookId, "COMPANY", "Lunds skola");
|
||||
const otherBook = await makeBook(ownerId, "Annan bok");
|
||||
await makeEntity(otherBook.id, "COMPANY", "Främmande AB");
|
||||
const [doc] = await previewWordFiles(bookId, [
|
||||
bytes(character("Eva", [["Anställd hos:", `Lunds skola ${company.code}, Främmande AB`]])),
|
||||
]);
|
||||
expect(doc.items[0].links.map((l) => [l.text, l.entityId])).toEqual([
|
||||
[`Lunds skola ${company.code}`, company.id],
|
||||
["Främmande AB", null],
|
||||
]);
|
||||
});
|
||||
|
||||
it("använder bokens egen mall, med ändrade etiketter", async () => {
|
||||
await prisma.template.create({ data: { bookId, kind: "CHARACTER", fields: [{ key: "job", label: "Arbete", type: "text" }, { key: "notes", label: "Övrigt", type: "textarea" }] } });
|
||||
const [doc] = await previewWordFiles(bookId, [bytes(character("Eva", [["Arbete:", "Snickare"]]))]);
|
||||
expect(doc.items[0].data).toEqual({ job: "Snickare", notes: "Anteckning." });
|
||||
});
|
||||
|
||||
it("rapporterar filer som inte går att läsa, och läser de andra", async () => {
|
||||
const docs = await previewWordFiles(bookId, [
|
||||
{ name: "text.docx", bytes: new TextEncoder().encode("bara text") },
|
||||
bytes(character("Eva")),
|
||||
{ name: "stor.docx", bytes: new Uint8Array(MAX_DOCX_BYTES + 1) },
|
||||
]);
|
||||
expect(docs.map((d) => d.error)).toEqual(["not-docx", null, "too-large"]);
|
||||
expect(docs[1].items).toHaveLength(1);
|
||||
});
|
||||
|
||||
it("låter användaren byta dokumenttyp", async () => {
|
||||
const [doc] = await previewWordFiles(bookId, [bytes(makeDocx([table(["Namn:", "Rex"], ["Ras:", "Boxer"])]))], ["PET"]);
|
||||
expect(doc).toMatchObject({ kind: "PET" });
|
||||
expect(doc.items[0]).toMatchObject({ name: "Rex", data: { breed: "Boxer" } });
|
||||
});
|
||||
|
||||
it("sparar ingenting", async () => {
|
||||
await previewWordFiles(bookId, [bytes(character("Eva"))]);
|
||||
expect(await prisma.entity.count()).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe("sparande", () => {
|
||||
const item = (overrides: Partial<CommitItem> = {}): CommitItem => ({
|
||||
include: true,
|
||||
entityKind: "CHARACTER",
|
||||
name: "Eva Test",
|
||||
code: "KI-0007",
|
||||
data: { occupation: "Lärare" },
|
||||
links: [],
|
||||
unmatched: [],
|
||||
...overrides,
|
||||
});
|
||||
const commit = (items: CommitItem[], appendUnmatched = true) => commitWordImport(bookId, ownerId, items, { appendUnmatched });
|
||||
|
||||
it("skapar poster med dokumentets ID när det är ledigt, annars ett nytt", async () => {
|
||||
await makeEntity(bookId, "CHARACTER", "Redan"); // tar KI-0001
|
||||
const result = await commit([item(), item({ name: "Två", code: "KI-0001" }), item({ name: "Tre", code: null }), item({ name: "Fyra", code: "FEL-1" })]);
|
||||
expect(result).toMatchObject({ created: 4, skipped: 0 });
|
||||
const codes = Object.fromEntries((await prisma.entity.findMany({ where: { bookId } })).map((e) => [e.name, e.code]));
|
||||
expect(codes["Eva Test"]).toBe("KI-0007");
|
||||
expect(new Set(Object.values(codes)).size).toBe(5); // alla ID är unika
|
||||
expect(codes["Två"]).not.toBe("KI-0001");
|
||||
});
|
||||
|
||||
it("nya poster fortsätter numreringen efter importerade ID", async () => {
|
||||
await commit([item({ code: "KI-0020" })]);
|
||||
expect((await makeEntity(bookId, "CHARACTER", "Nästa")).code).toBe("KI-0021");
|
||||
});
|
||||
|
||||
it("hoppar över poster som användaren valt bort, och poster utan namn", async () => {
|
||||
const result = await commit([item({ include: false }), item({ name: " " }), item({ name: "Behåll", code: null })]);
|
||||
expect(result).toMatchObject({ created: 1, skipped: 2 });
|
||||
expect((await prisma.entity.findMany({ where: { bookId } })).map((e) => e.name)).toEqual(["Behåll"]);
|
||||
});
|
||||
|
||||
it("lägger det som inte tolkats i Övrigt, om användaren vill", async () => {
|
||||
await commit([item({ data: { notes: "Först." }, unmatched: [{ label: "Relationer", value: "Vän med Bo." }] })]);
|
||||
const [saved] = await prisma.entity.findMany({ where: { bookId } });
|
||||
expect((saved.data as { notes: string }).notes).toBe("Först.\n\nRelationer: Vän med Bo.");
|
||||
|
||||
const other = await makeBook(ownerId, "Utan tillägg");
|
||||
await commitWordImport(other.id, ownerId, [item({ unmatched: [{ label: "Relationer", value: "Vän med Bo." }] })], { appendUnmatched: false });
|
||||
expect((await prisma.entity.findFirstOrThrow({ where: { bookId: other.id } })).data).toEqual({ occupation: "Lärare" });
|
||||
});
|
||||
|
||||
it("skapar relationer åt rätt håll med anteckning", async () => {
|
||||
const anna = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
const company = await makeEntity(bookId, "COMPANY", "Firma");
|
||||
await commit([
|
||||
item({ name: "Eva", links: [{ type: "Jobbar på", toDocument: false, entityId: company.id, text: "Firma", note: "" }] }),
|
||||
item({
|
||||
entityKind: "COMPANY",
|
||||
name: "Kaffe AB",
|
||||
code: null,
|
||||
data: {},
|
||||
links: [
|
||||
{ type: "Jobbar på", toDocument: true, entityId: anna.id, text: "Anna", note: "Barista" },
|
||||
{ type: "Jobbar på", toDocument: true, entityId: null, text: "Okänd", note: "" },
|
||||
],
|
||||
}),
|
||||
]);
|
||||
const relations = await prisma.relation.findMany({ include: { from: true, to: true }, orderBy: { createdAt: "asc" } });
|
||||
expect(relations.map((r) => [r.from.name, r.type, r.to.name, r.description])).toEqual([
|
||||
["Eva", "Jobbar på", "Firma", null],
|
||||
["Anna", "Jobbar på", "Kaffe AB", "Barista"],
|
||||
]);
|
||||
expect(relations.every((r) => r.code && r.updatedById === ownerId)).toBe(true);
|
||||
});
|
||||
|
||||
it("kopplingar till poster i en annan bok och till sig själv ignoreras", async () => {
|
||||
const otherBook = await makeBook(ownerId, "Annan");
|
||||
const foreign = await makeEntity(otherBook.id, "CHARACTER", "Främling");
|
||||
await commit([item({ links: [{ type: "Vän till", toDocument: false, entityId: foreign.id, text: "Främling", note: "" }] })]);
|
||||
expect(await prisma.relation.count()).toBe(0);
|
||||
});
|
||||
|
||||
it("rensar värden som inte hör hemma i mallen, och kopplingsfält till fel typ eller bok", async () => {
|
||||
const otherBook = await makeBook(ownerId, "Annan");
|
||||
const foreign = await makeEntity(otherBook.id, "PREMISES", "Främmande lokal");
|
||||
const own = await makeEntity(bookId, "CHARACTER", "Anna");
|
||||
await commit([
|
||||
item({
|
||||
entityKind: "COMPANY",
|
||||
name: "Firma",
|
||||
code: null,
|
||||
data: { industry: "Kaffe", premises: foreign.id, sketch: own.id, hotelRooms: "tio", okänt: "x", satisfaction: "Fantastisk", hasSketches: true },
|
||||
}),
|
||||
]);
|
||||
expect((await prisma.entity.findFirstOrThrow({ where: { bookId, name: "Firma" } })).data).toEqual({ industry: "Kaffe", hasSketches: true });
|
||||
});
|
||||
|
||||
it("okända dokumenttyper och trasiga poster hoppas över utan att stoppa resten", async () => {
|
||||
const result = await commit([item({ entityKind: "FINNS_INTE" }), null as unknown as CommitItem, item({ name: "Ok", code: null })]);
|
||||
expect(result.created).toBe(1);
|
||||
});
|
||||
|
||||
it("en relation kräver två deltagare i boken och sätter släktband för partner", async () => {
|
||||
const a = await makeEntity(bookId, "CHARACTER", "A");
|
||||
const b = await makeEntity(bookId, "CHARACTER", "B");
|
||||
const c = await makeEntity(bookId, "CHARACTER", "C");
|
||||
const relation = (participants: string[], category: string): CommitItem =>
|
||||
item({ entityKind: "RELATION", name: category, code: null, data: { category, healthy: true }, participants });
|
||||
|
||||
expect(await commit([relation([a.id], "Partner")])).toMatchObject({ relations: 0, skipped: 1 });
|
||||
expect(await commit([relation([a.id, "finns-inte"], "Partner")])).toMatchObject({ relations: 0 });
|
||||
|
||||
await commit([relation([a.id, b.id, c.id], "Partner"), relation([a.id, c.id], "Vännergrupp")]);
|
||||
const relations = await prisma.relation.findMany({ include: { members: true }, orderBy: { createdAt: "asc" } });
|
||||
expect(relations.map((r) => [r.type, r.bond, r.members.length])).toEqual([
|
||||
["Partner till", "PARTNER", 1],
|
||||
["Vänner", null, 0],
|
||||
]);
|
||||
expect(relations[0]).toMatchObject({ fromId: a.id, toId: b.id, data: { category: "Partner", healthy: true } });
|
||||
});
|
||||
|
||||
it("sparar allt eller inget om något går fel", async () => {
|
||||
const result = commit([item({ name: "Bra", code: null }), item({ name: "x".repeat(10), code: null, data: { nickname: "y".repeat(30000) } })]);
|
||||
await expect(result).resolves.toMatchObject({ created: 2 });
|
||||
// För långa värden kortas i stället för att avvisas
|
||||
const long = await prisma.entity.findFirstOrThrow({ where: { bookId, name: "xxxxxxxxxx" } });
|
||||
expect(((long.data as { nickname: string }).nickname ?? "").length).toBeLessThanOrEqual(20000);
|
||||
});
|
||||
});
|
||||
|
||||
describe("åtgärderna", () => {
|
||||
const formWith = (docs: { name: string; bytes: Uint8Array }[], kinds: string[] = []) => {
|
||||
const data = new FormData();
|
||||
data.set("bookId", bookId);
|
||||
for (const d of docs) data.append("files", new File([d.bytes as BlobPart], d.name));
|
||||
for (const k of kinds) data.append("kinds", k);
|
||||
return data;
|
||||
};
|
||||
|
||||
it("förhandsgranskar och sparar för redaktörer", async () => {
|
||||
const response = await previewWordImport(formWith([bytes(character("Eva"))]));
|
||||
if (!("docs" in response)) throw new Error("Väntade förhandsgranskning");
|
||||
expect(response.docs[0].items[0].name).toBe("Eva Test");
|
||||
|
||||
const result = await saveWordImport({ bookId, appendUnmatched: true, items: [{ include: true, entityKind: "CHARACTER", name: "Eva Test", code: null, data: {}, links: [], unmatched: [] }] });
|
||||
expect(result.created).toBe(1);
|
||||
});
|
||||
|
||||
it("kräver minst en fil och högst 20", async () => {
|
||||
expect(await previewWordImport(formWith([]))).toEqual({ error: "no-files" });
|
||||
expect(await previewWordImport(formWith(Array.from({ length: 21 }, () => bytes(character("Eva")))))).toEqual({ error: "limit" });
|
||||
});
|
||||
|
||||
it("stora filer läses inte alls", async () => {
|
||||
const response = await previewWordImport(formWith([{ name: "stor.docx", bytes: new Uint8Array(MAX_DOCX_BYTES + 10) }]));
|
||||
if (!("docs" in response)) throw new Error("Väntade svar");
|
||||
expect(response.docs[0].error).toBe("too-large");
|
||||
});
|
||||
|
||||
it("läsare och obehöriga får inte importera", async () => {
|
||||
const viewer = await makeUser("Läsare");
|
||||
const stranger = await makeUser("Obehörig");
|
||||
await prisma.bookMember.create({ data: { bookId, userId: viewer.id, role: "VIEWER" } });
|
||||
const editor = await makeUser("Redaktör");
|
||||
await prisma.bookMember.create({ data: { bookId, userId: editor.id, role: "EDITOR" } });
|
||||
|
||||
for (const user of [viewer, stranger]) {
|
||||
login.userId = user.id;
|
||||
expect(await attempt(() => previewWordImport(formWith([bytes(character("Eva"))])))).toBe("NOT_FOUND");
|
||||
expect(await attempt(() => saveWordImport({ bookId, appendUnmatched: false, items: [] }))).toBe("NOT_FOUND");
|
||||
}
|
||||
expect(await prisma.entity.count()).toBe(0);
|
||||
|
||||
login.userId = editor.id;
|
||||
const result = await saveWordImport({ bookId, appendUnmatched: false, items: [{ include: true, entityKind: "CHARACTER", name: "Av redaktör", code: null, data: {}, links: [], unmatched: [] }] });
|
||||
expect(result.created).toBe(1);
|
||||
expect((await prisma.entity.findFirstOrThrow()).updatedById).toBe(editor.id);
|
||||
});
|
||||
});
|
||||
});
|
||||
Reference in new issue
Block a user