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:
bobbanandClaude Sonnet 5.5 committed 2026-11-04 23:53:33 +01:00
1 parent bd269d70a5
commit 86fd435438
64 files changed
+4796 -235

No files matched your search

+2 -2
View File
@@ -25,7 +25,7 @@ export async function createBook(formData: FormData) {
}
export async function updateBook(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "ADMIN");
const title = str(formData, "title", 200);
if (!title) return;
await prisma.book.update({
@@ -42,7 +42,7 @@ export async function updateBook(formData: FormData) {
}
export async function deleteBook(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "OWNER");
// Boken flyttas till papperskorgen (som zip med bilder) och kan återställas i 30 dagar
await trashBook(book.ownerId, book.id);
revalidatePath("/");
+58 -35
View File
@@ -1,10 +1,11 @@
"use server";
import type { Prisma } from "@prisma/client";
import { Prisma } from "@prisma/client";
import { redirect } from "next/navigation";
import { prisma } from "@/lib/db";
import { conflictInfo, isStale, type SaveResult } from "@/lib/conflict";
import { deleteImage, isUpload, saveImage } from "@/lib/files";
import { recordVersion, sameSnapshot, snapshotOf } from "@/lib/history";
import { diffSnapshots, recordVersion, sameSnapshot, snapshotOf } from "@/lib/history";
import { optStr, parseTags, revalidateBook, str } from "@/lib/form";
import { collectFieldData } from "@/lib/field-values";
import { KIND_INFO, parseKind } from "@/lib/kinds";
@@ -13,12 +14,12 @@ import { requireBook, requireEntity } from "@/lib/session";
import { withinQuota } from "@/lib/storage";
import { trashEntity } from "@/lib/trash";
import { getTemplate } from "@/lib/templates";
import { getLocale } from "@/i18n/server";
import { getLocale, getT } from "@/i18n/server";
export async function saveEntity(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
export async function saveEntity(formData: FormData): Promise<SaveResult> {
const book = await requireBook(str(formData, "bookId"), "EDITOR");
const id = str(formData, "id");
const existing = id ? await requireEntity(book.id, id) : null;
const existing = id ? await requireEntity(book.id, id, "EDITOR") : null;
const kind = existing?.kind ?? parseKind(str(formData, "kind"));
if (!kind) throw new Error("Invalid kind");
@@ -27,49 +28,71 @@ export async function saveEntity(formData: FormData) {
const { fields } = await getTemplate(book.id, kind, await getLocale());
const data = await collectFieldData(book.id, fields, formData, (existing?.data as Record<string, unknown> | null) ?? null);
let imageFile = existing?.imageFile ?? null;
const upload = formData.get("image");
if (isUpload(upload)) {
if (!(await withinQuota(book.ownerId, upload.size))) {
redirect(existing ? `/books/${book.id}/entity/${existing.id}/edit?error=quota` : `/books/${book.id}/e/${KIND_INFO[kind].slug}/new?error=quota`);
}
const saved = await saveImage(upload);
await deleteImage(imageFile);
imageFile = saved;
} else if (formData.has("removeImage")) {
await deleteImage(imageFile);
imageFile = null;
}
const values = {
name,
summary: optStr(formData, "summary"),
tags: parseTags(str(formData, "tags", 1000)),
data: data as Prisma.InputJsonObject,
imageFile,
};
// ID skapas automatiskt vid första sparningen och ändras aldrig därefter
const saved = await prisma.$transaction(async (tx) => {
if (existing) {
// Den tidigare versionen sparas bara om något faktiskt ändrats
const before = snapshotOf(existing);
if (!sameSnapshot(before, snapshotOf(values))) await recordVersion(tx, book.id, existing.id, book.ownerId, before);
const code = existing.code ?? (await nextEntityCode(book.id, kind, tx));
return tx.entity.update({ where: { id: existing.id }, data: { ...values, code } });
// Har någon annan sparat posten sedan formuläret öppnades? Då sparas ingenting förrän användaren väljer det.
const conflict = async (current: NonNullable<typeof existing>): Promise<SaveResult> => {
const { t } = await getT();
const changes = diffSnapshots(snapshotOf(current), snapshotOf(values), fields, {
name: t("common.name"),
summary: t("common.summary"),
tags: t("common.tags"),
});
return { conflict: await conflictInfo(current, changes) };
};
if (existing && isStale(str(formData, "version", 30), existing.updatedAt)) return conflict(existing);
let imageFile = existing?.imageFile ?? null;
let replaced: string | null = null; // den gamla bilden, som tas bort först när posten har sparats
const upload = formData.get("image");
if (isUpload(upload)) {
if (!(await withinQuota(book.ownerId, upload.size))) {
redirect(existing ? `/books/${book.id}/entity/${existing.id}/edit?error=quota` : `/books/${book.id}/e/${KIND_INFO[kind].slug}/new?error=quota`);
}
const code = await nextEntityCode(book.id, kind, tx);
return tx.entity.create({ data: { ...values, code, bookId: book.id, kind } });
});
replaced = imageFile;
imageFile = await saveImage(upload);
} else if (formData.has("removeImage")) {
replaced = imageFile;
imageFile = null;
}
// ID skapas automatiskt vid första sparningen och ändras aldrig därefter
let saved: { id: string };
try {
saved = await prisma.$transaction(async (tx) => {
if (existing) {
// Den tidigare versionen sparas bara om något faktiskt ändrats
const before = snapshotOf(existing);
if (!sameSnapshot(before, snapshotOf(values))) await recordVersion(tx, book.id, existing.id, book.userId, before);
const code = existing.code ?? (await nextEntityCode(book.id, kind, tx));
// Villkoret på updatedAt gör att en samtidig sparning av någon annan ger ett fel i stället för att skrivas över
return tx.entity.update({ where: { id: existing.id, updatedAt: existing.updatedAt }, data: { ...values, imageFile, code, updatedById: book.userId } });
}
const code = await nextEntityCode(book.id, kind, tx);
return tx.entity.create({ data: { ...values, imageFile, code, bookId: book.id, kind, updatedById: book.userId } });
});
} catch (error) {
if (existing && error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2025") {
if (imageFile !== existing.imageFile) await deleteImage(imageFile);
const current = await prisma.entity.findUnique({ where: { id: existing.id } });
if (current) return conflict(current);
}
throw error;
}
if (replaced) await deleteImage(replaced);
revalidateBook(book.id);
redirect(`/books/${book.id}/entity/${saved.id}`);
}
export async function deleteEntity(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const entity = await requireEntity(book.id, str(formData, "id"));
const book = await requireBook(str(formData, "bookId"), "EDITOR");
const entity = await requireEntity(book.id, str(formData, "id"), "EDITOR");
// Posten flyttas till papperskorgen och kan återställas i 30 dagar
await trashEntity(book.ownerId, book.id, entity.id);
revalidateBook(book.id);
+32 -18
View File
@@ -1,6 +1,8 @@
"use server";
import { Prisma } from "@prisma/client";
import { redirect } from "next/navigation";
import { conflictInfo, isStale, type SaveResult } from "@/lib/conflict";
import { prisma } from "@/lib/db";
import { optStr, revalidateBook, str } from "@/lib/form";
import { requireBook } from "@/lib/session";
@@ -28,7 +30,7 @@ async function readEvent(bookId: string, formData: FormData) {
}
export async function addEvent(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "EDITOR");
const event = await readEvent(book.id, formData);
if (!event.title) return;
if (event.badDate) redirect(`/books/${book.id}/timeline?error=date`);
@@ -40,6 +42,7 @@ export async function addEvent(formData: FormData) {
date: event.date,
endDate: event.endDate,
description: event.description,
updatedById: book.userId,
participants: { create: event.participantIds.map((entityId) => ({ entityId })) },
},
});
@@ -47,35 +50,46 @@ export async function addEvent(formData: FormData) {
redirect(`/books/${book.id}/timeline`);
}
export async function saveEvent(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
export async function saveEvent(formData: FormData): Promise<SaveResult> {
const book = await requireBook(str(formData, "bookId"), "EDITOR");
const id = str(formData, "id");
const existing = await prisma.storyEvent.findFirst({ where: { id, bookId: book.id }, select: { id: true } });
const existing = await prisma.storyEvent.findFirst({ where: { id, bookId: book.id } });
if (!existing) throw new Error("Event not found");
if (isStale(str(formData, "version", 30), existing.updatedAt)) return { conflict: await conflictInfo(existing) };
const event = await readEvent(book.id, formData);
if (!event.title) return;
if (event.badDate) redirect(`/books/${book.id}/timeline/${id}?error=date`);
await prisma.$transaction([
prisma.eventParticipant.deleteMany({ where: { eventId: id } }),
prisma.storyEvent.update({
where: { id },
data: {
title: event.title,
date: event.date,
endDate: event.endDate,
description: event.description,
participants: { create: event.participantIds.map((entityId) => ({ entityId })) },
},
}),
]);
try {
await prisma.$transaction([
prisma.eventParticipant.deleteMany({ where: { eventId: id } }),
prisma.storyEvent.update({
// Villkoret på updatedAt gör att en samtidig sparning av någon annan ger ett fel i stället för att skrivas över
where: { id, updatedAt: existing.updatedAt },
data: {
title: event.title,
date: event.date,
endDate: event.endDate,
description: event.description,
updatedById: book.userId,
participants: { create: event.participantIds.map((entityId) => ({ entityId })) },
},
}),
]);
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2025") {
const current = await prisma.storyEvent.findUnique({ where: { id } });
if (current) return { conflict: await conflictInfo(current) };
}
throw error;
}
revalidateBook(book.id);
redirect(`/books/${book.id}/timeline/${id}?saved=1`);
}
export async function deleteEvent(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "EDITOR");
await prisma.storyEvent.deleteMany({ where: { id: str(formData, "id"), bookId: book.id } });
revalidateBook(book.id);
redirect(`/books/${book.id}/timeline`);
+3 -3
View File
@@ -10,15 +10,15 @@ import { requireBook, requireEntity } from "@/lib/session";
/** Återställer en tidigare version. Den nuvarande versionen sparas först i historiken, så åtgärden kan ångras. */
export async function restoreVersion(formData: FormData) {
const bookId = str(formData, "bookId");
const book = await requireBook(bookId);
const entity = await requireEntity(bookId, str(formData, "entityId"));
const book = await requireBook(bookId, "EDITOR");
const entity = await requireEntity(bookId, str(formData, "entityId"), "EDITOR");
const version = await prisma.entityVersion.findFirst({ where: { id: str(formData, "versionId"), entityId: entity.id, bookId } });
if (!version) redirect(`/books/${bookId}/entity/${entity.id}/history`);
const target = version.snapshot as unknown as Snapshot;
const current = snapshotOf(entity);
await prisma.$transaction(async (tx) => {
if (!sameSnapshot(current, target)) await recordVersion(tx, bookId, entity.id, book.ownerId, current);
if (!sameSnapshot(current, target)) await recordVersion(tx, bookId, entity.id, book.userId, current);
await tx.entity.update({
where: { id: entity.id },
data: { name: target.name, summary: target.summary, tags: target.tags, data: (target.data ?? {}) as Prisma.InputJsonObject },
+2 -2
View File
@@ -10,14 +10,14 @@ import { requireBook } from "@/lib/session";
import { withinQuota } from "@/lib/storage";
async function requireMap(bookId: string, mapId: string) {
const book = await requireBook(bookId);
const book = await requireBook(bookId, "EDITOR");
const map = await prisma.bookMap.findFirst({ where: { id: mapId, bookId: book.id } });
if (!map) throw new Error("Map not found");
return { book, map };
}
export async function createMap(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "EDITOR");
const name = str(formData, "name", 200);
const kind = str(formData, "kind") === "IMAGE" ? "IMAGE" : "GEO";
if (!name) return;
+32 -20
View File
@@ -1,7 +1,8 @@
"use server";
import type { Prisma } from "@prisma/client";
import { Prisma } from "@prisma/client";
import { redirect } from "next/navigation";
import { conflictInfo, isStale, type SaveResult } from "@/lib/conflict";
import { prisma } from "@/lib/db";
import { parseBond } from "@/lib/family";
import { optStr, revalidateBook, str } from "@/lib/form";
@@ -35,7 +36,7 @@ async function bondAndDates(formData: FormData) {
}
export async function addRelation(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "EDITOR");
const fromId = str(formData, "fromId");
const toId = str(formData, "toId");
const { ok, bond, startDate, endDate, type } = await bondAndDates(formData);
@@ -65,10 +66,11 @@ export async function addRelation(formData: FormData) {
revalidateBook(book.id);
}
export async function saveRelation(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
export async function saveRelation(formData: FormData): Promise<SaveResult> {
const book = await requireBook(str(formData, "bookId"), "EDITOR");
const relation = await prisma.relation.findFirst({ where: { id: str(formData, "id"), bookId: book.id } });
if (!relation) throw new Error("Relation not found");
if (isStale(str(formData, "version", 30), relation.updatedAt)) return { conflict: await conflictInfo(relation) };
const { ok, bond, startDate, endDate, type } = await bondAndDates(formData);
if (!type || !ok) return;
@@ -76,27 +78,37 @@ export async function saveRelation(formData: FormData) {
const data = await collectFieldData(book.id, fields, formData, (relation.data as Record<string, unknown> | null) ?? null);
const memberIds = await cleanMemberIds(book.id, formData, [relation.fromId, relation.toId]);
await prisma.$transaction([
prisma.relationMember.deleteMany({ where: { relationId: relation.id } }),
prisma.relation.update({
where: { id: relation.id },
data: {
type,
bond,
startDate,
endDate,
description: optStr(formData, "description", 2000),
data: data as Prisma.InputJsonObject,
members: { create: memberIds.map((entityId) => ({ entityId })) },
},
}),
]);
try {
await prisma.$transaction([
prisma.relationMember.deleteMany({ where: { relationId: relation.id } }),
prisma.relation.update({
// Villkoret på updatedAt gör att en samtidig sparning av någon annan ger ett fel i stället för att skrivas över
where: { id: relation.id, updatedAt: relation.updatedAt },
data: {
type,
bond,
startDate,
endDate,
description: optStr(formData, "description", 2000),
data: data as Prisma.InputJsonObject,
updatedById: book.userId,
members: { create: memberIds.map((entityId) => ({ entityId })) },
},
}),
]);
} catch (error) {
if (error instanceof Prisma.PrismaClientKnownRequestError && error.code === "P2025") {
const current = await prisma.relation.findUnique({ where: { id: relation.id } });
if (current) return { conflict: await conflictInfo(current) };
}
throw error;
}
revalidateBook(book.id);
redirect(`/books/${book.id}/relations/${relation.id}?saved=1`);
}
export async function deleteRelation(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "EDITOR");
await prisma.relation.deleteMany({ where: { id: str(formData, "id"), bookId: book.id } });
revalidateBook(book.id);
if (formData.get("redirect") === "list") redirect(`/books/${book.id}/relations`);
+43
View File
@@ -0,0 +1,43 @@
"use server";
import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";
import { parseMemberRole } from "@/lib/access";
import { str } from "@/lib/form";
import { requireBook, requireUser } from "@/lib/session";
import { addMember, leaveBook, removeMember, setMemberRole, type ShareResult } from "@/lib/sharing";
const back = (bookId: string, result: ShareResult) => redirect(`/books/${bookId}/settings?share=${result}`);
export async function shareBook(formData: FormData) {
const book = await requireBook(str(formData, "bookId"), "ADMIN");
const role = parseMemberRole(str(formData, "role"));
if (!role) return back(book.id, "invalid");
const result = await addMember(book.id, book.role, str(formData, "email", 200), role);
revalidatePath(`/books/${book.id}/settings`);
back(book.id, result);
}
export async function changeMemberRole(formData: FormData) {
const book = await requireBook(str(formData, "bookId"), "ADMIN");
const role = parseMemberRole(str(formData, "role"));
if (!role) return back(book.id, "invalid");
const result = await setMemberRole(book.id, book.role, str(formData, "userId"), role);
revalidatePath(`/books/${book.id}/settings`);
back(book.id, result);
}
export async function removeBookMember(formData: FormData) {
const book = await requireBook(str(formData, "bookId"), "ADMIN");
const result = await removeMember(book.id, book.role, str(formData, "userId"));
revalidatePath(`/books/${book.id}/settings`);
back(book.id, result);
}
/** Den inloggade lämnar en bok som någon annan delat med hen. */
export async function leaveSharedBook(formData: FormData) {
const user = await requireUser();
await leaveBook(str(formData, "bookId"), user.id);
revalidatePath("/");
redirect("/");
}
+2 -2
View File
@@ -9,7 +9,7 @@ import { requireBook } from "@/lib/session";
const TIME = /^([01]\d|2[0-3]):[0-5]\d$/;
export async function addShifts(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "EDITOR");
const personId = str(formData, "personId");
const workplaceId = str(formData, "workplaceId") || null;
const startTime = str(formData, "startTime");
@@ -51,7 +51,7 @@ export async function addShifts(formData: FormData) {
}
export async function deleteShift(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "EDITOR");
await prisma.shift.deleteMany({ where: { id: str(formData, "id"), bookId: book.id } });
revalidateBook(book.id);
}
+2 -2
View File
@@ -9,7 +9,7 @@ import { requireBook } from "@/lib/session";
import { validateFields } from "@/lib/templates";
export async function saveTemplate(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "ADMIN");
const kind = parseTemplateKind(str(formData, "kind"));
if (!kind) throw new Error("Invalid kind");
const url = `/books/${book.id}/templates/${templateSlug(kind)}`;
@@ -32,7 +32,7 @@ export async function saveTemplate(formData: FormData) {
}
export async function resetTemplate(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "ADMIN");
const kind = parseTemplateKind(str(formData, "kind"));
if (!kind) throw new Error("Invalid kind");
await prisma.template.deleteMany({ where: { bookId: book.id, kind } });
+19 -7
View File
@@ -2,14 +2,20 @@
import { redirect } from "next/navigation";
import { revalidatePath } from "next/cache";
import { prisma } from "@/lib/db";
import { str } from "@/lib/form";
import { emptyBookTrash, purgeTrashItem, restoreBook, restoreEntity } from "@/lib/trash";
import { requireBook, requireUser } from "@/lib/session";
// Borttagna poster ligger i papperskorgen under bokens ägare, men återställs och rensas av bokens medlemmar:
// redaktörer återställer, administratörer rensar. Borttagna böcker tillhör bara den som äger dem.
export async function restoreTrashEntity(formData: FormData) {
const user = await requireUser();
const restored = await restoreEntity(user.id, str(formData, "id"));
if (!restored) redirect(`/books/${str(formData, "bookId")}/trash?restore=failed`);
const bookId = str(formData, "bookId");
const book = await requireBook(bookId, "EDITOR");
const item = await prisma.trashItem.findFirst({ where: { id: str(formData, "id"), bookId: book.id, kind: "entity" }, select: { id: true } });
const restored = item ? await restoreEntity(book.ownerId, item.id) : null;
if (!restored) redirect(`/books/${book.id}/trash?restore=failed`);
revalidatePath(`/books/${restored.bookId}`, "layout");
redirect(`/books/${restored.bookId}/entity/${restored.entityId}`);
}
@@ -24,14 +30,20 @@ export async function restoreTrashBook(formData: FormData) {
export async function purgeTrash(formData: FormData) {
const user = await requireUser();
await purgeTrashItem(user.id, str(formData, "id"));
const item = await prisma.trashItem.findUnique({ where: { id: str(formData, "id") } });
if (!item) return;
if (item.kind === "entity" && item.bookId) {
await requireBook(item.bookId, "ADMIN");
} else if (item.ownerId !== user.id) {
return;
}
await purgeTrashItem(item.ownerId, item.id);
revalidatePath("/");
const bookId = str(formData, "bookId");
if (bookId) revalidatePath(`/books/${bookId}/trash`);
if (item.bookId) revalidatePath(`/books/${item.bookId}/trash`);
}
export async function emptyTrash(formData: FormData) {
const book = await requireBook(str(formData, "bookId"));
const book = await requireBook(str(formData, "bookId"), "ADMIN");
await emptyBookTrash(book.ownerId, book.id);
revalidatePath(`/books/${book.id}/trash`);
}
+38
View File
@@ -0,0 +1,38 @@
"use server";
import { revalidateBook, str } from "@/lib/form";
import { requireBook } from "@/lib/session";
import { MAX_DOCX_BYTES } from "@/lib/word-docx";
import { IMPORT_KINDS, type ImportKind } from "@/lib/word-import";
import { MAX_WORD_FILES, MAX_WORD_ITEMS, commitWordImport, previewWordFiles, type CommitItem, type CommitResult, type PreviewDocument } from "@/lib/word-import-db";
export type PreviewResponse = { docs: PreviewDocument[] } | { error: "no-files" | "limit" };
/** Läser uppladdade Word-filer och visar vad som hittades. Ingenting sparas. */
export async function previewWordImport(formData: FormData): Promise<PreviewResponse> {
const book = await requireBook(str(formData, "bookId"), "EDITOR");
const uploads = formData.getAll("files").filter((f): f is File => typeof f !== "string" && f.size > 0);
if (uploads.length === 0) return { error: "no-files" };
if (uploads.length > MAX_WORD_FILES) return { error: "limit" };
const kinds = formData.getAll("kinds").map((k) => (IMPORT_KINDS as string[]).includes(String(k)) ? (String(k) as ImportKind) : null);
const files = await Promise.all(
uploads.map(async (file) => ({
name: file.name.slice(0, 200),
// Stora filer läses inte alls, de rapporteras som för stora
bytes: file.size > MAX_DOCX_BYTES ? new Uint8Array(4) : new Uint8Array(await file.arrayBuffer()),
tooLarge: file.size > MAX_DOCX_BYTES,
})),
);
const docs = await previewWordFiles(book.id, files.map(({ name, bytes }) => ({ name, bytes })), kinds);
return { docs: docs.map((doc, i) => (files[i].tooLarge ? { ...doc, error: "too-large" as const } : doc)) };
}
/** Sparar det användaren valt i förhandsgranskningen. Allt kontrolleras igen mot boken innan det sparas. */
export async function saveWordImport(input: { bookId: string; items: CommitItem[]; appendUnmatched: boolean }): Promise<CommitResult> {
const book = await requireBook(String(input.bookId), "EDITOR");
const items = Array.isArray(input.items) ? input.items.slice(0, MAX_WORD_ITEMS) : [];
const result = await commitWordImport(book.id, book.userId, items, { appendUnmatched: input.appendUnmatched === true });
revalidateBook(book.id);
return result;
}
+11 -2
View File
@@ -22,9 +22,13 @@ export default async function BooksPage({
const user = await requireUser();
const { t } = await getT();
const books = await prisma.book.findMany({
where: { ownerId: user.id },
where: { OR: [{ ownerId: user.id }, { members: { some: { userId: user.id } } }] },
orderBy: { updatedAt: "desc" },
include: { _count: { select: { entities: true } } },
include: {
_count: { select: { entities: true } },
owner: { select: { name: true, email: true } },
members: { where: { userId: user.id }, select: { role: true } },
},
});
const trashedBooks = await prisma.trashItem.findMany({ where: { ownerId: user.id, kind: "book" }, orderBy: { deletedAt: "desc" } });
@@ -64,6 +68,11 @@ export default async function BooksPage({
<div className="d-flex gap-2">
{book.genre ? <span className="badge bg-azure-lt">{book.genre}</span> : null}
<span className="badge">{t("books.items", { n: book._count.entities })}</span>
{book.ownerId === user.id ? null : (
<span className="badge bg-purple-lt" title={t("share.sharedBy", { name: book.owner.name ?? book.owner.email ?? "?" })}>
{t("share.sharedBy", { name: book.owner.name ?? book.owner.email ?? "?" })} · {t("share.role." + (book.members[0]?.role ?? "VIEWER"))}
</span>
)}
</div>
</div>
</Link>
+3 -2
View File
@@ -1,6 +1,6 @@
import { strToU8, zipSync, type Zippable } from "fflate";
import { buildExport } from "@/lib/book-transfer";
import { prisma } from "@/lib/db";
import { bookAccess } from "@/lib/book-access";
import { limitRequest } from "@/lib/rate-limit";
import { getCurrentUser } from "@/lib/session";
@@ -15,7 +15,8 @@ export async function GET(req: Request, { params }: { params: Promise<{ bookId:
if (limited) return limited;
const { bookId } = await params;
const book = await prisma.book.findFirst({ where: { id: bookId, ownerId: user.id }, select: { title: true } });
// Alla med tillgång till boken får exportera den, även läsare
const book = await bookAccess(bookId, user.id);
if (!book) return new Response("Not found", { status: 404 });
const asJson = new URL(req.url).searchParams.get("format") === "json";
+2 -1
View File
@@ -1,3 +1,4 @@
import { bookAccess } from "@/lib/book-access";
import { prisma } from "@/lib/db";
import { limitRequest } from "@/lib/rate-limit";
import { getCurrentUser } from "@/lib/session";
@@ -14,7 +15,7 @@ export async function GET(req: Request, { params }: { params: Promise<{ bookId:
if (limited) return limited;
const { bookId } = await params;
const book = await prisma.book.findFirst({ where: { id: bookId, ownerId: user.id }, select: { id: true } });
const book = await bookAccess(bookId, user.id);
if (!book) return new Response("Not found", { status: 404 });
const q = (new URL(req.url).searchParams.get("q") ?? "").trim().slice(0, 100);
+1 -1
View File
@@ -17,7 +17,7 @@ export default async function NewEntityPage({
}) {
const { bookId, kind: slug } = await params;
const { name, error } = await searchParams;
await requireBook(bookId);
await requireBook(bookId, "EDITOR");
const info = KIND_BY_SLUG.get(slug);
if (!info) notFound();
const { t, locale } = await getT();
+4 -3
View File
@@ -7,6 +7,7 @@ import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { fileUrl } from "@/lib/files";
import { KIND_BY_SLUG } from "@/lib/kinds";
import { hasRole } from "@/lib/access";
import { requireBook } from "@/lib/session";
export default async function EntityListPage({
@@ -18,7 +19,7 @@ export default async function EntityListPage({
}) {
const { bookId, kind: slug } = await params;
const { q, tag } = await searchParams;
await requireBook(bookId);
const book = await requireBook(bookId);
const info = KIND_BY_SLUG.get(slug);
if (!info) notFound();
const { t } = await getT();
@@ -49,7 +50,7 @@ export default async function EntityListPage({
<PageHeader
title={t(`kind.${info.kind}.other`)}
actions={
<Link href={`${base}/new`} className="btn btn-primary">
<Link href={`${base}/new`} className="btn btn-primary" hidden={!hasRole(book.role, "EDITOR")}>
<IconPlus size={18} className="me-1" />
{t(`kind.${info.kind}.new`)}
</Link>
@@ -124,7 +125,7 @@ export default async function EntityListPage({
))}
</td>
<td className="text-end w-1">
<Link href={`/books/${bookId}/entity/${entity.id}/edit`} className="btn btn-sm">
<Link href={`/books/${bookId}/entity/${entity.id}/edit`} className="btn btn-sm" hidden={!hasRole(book.role, "EDITOR")}>
{t("common.edit")}
</Link>
</td>
@@ -15,7 +15,7 @@ export default async function EditEntityPage({
}) {
const { bookId, entityId } = await params;
const { error } = await searchParams;
const entity = await requireEntity(bookId, entityId);
const entity = await requireEntity(bookId, entityId, "EDITOR");
const { t, locale } = await getT();
const { fields } = await getTemplate(bookId, entity.kind, locale);
const refEntities = await prisma.entity.findMany({
@@ -6,7 +6,8 @@ import { EmptyState, PageBody, PageHeader } from "@/components/page";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { diffSnapshots, MAX_VERSIONS, snapshotOf, type Snapshot } from "@/lib/history";
import { requireEntity } from "@/lib/session";
import { hasRole } from "@/lib/access";
import { requireBook, requireEntity } from "@/lib/session";
import { getTemplate } from "@/lib/templates";
export const metadata = { title: "Historik" };
@@ -14,6 +15,7 @@ export const metadata = { title: "Historik" };
export default async function HistoryPage({ params }: { params: Promise<{ bookId: string; entityId: string }> }) {
const { bookId, entityId } = await params;
const entity = await requireEntity(bookId, entityId);
const canEdit = hasRole((await requireBook(bookId)).role, "EDITOR");
const { t, locale } = await getT();
const { fields } = await getTemplate(bookId, entity.kind, locale);
@@ -63,15 +65,17 @@ export default async function HistoryPage({ params }: { params: Promise<{ bookId
) : null}
</h3>
<div className="card-actions">
<form action={restoreVersion}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="entityId" value={entityId} />
<input type="hidden" name="versionId" value={version.id} />
<ConfirmSubmit className="btn btn-sm" message={t("history.restoreConfirm")}>
<IconArrowBackUp size={16} className="me-1" />
{t("history.restore")}
</ConfirmSubmit>
</form>
{canEdit ? (
<form action={restoreVersion}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="entityId" value={entityId} />
<input type="hidden" name="versionId" value={version.id} />
<ConfirmSubmit className="btn btn-sm" message={t("history.restoreConfirm")}>
<IconArrowBackUp size={16} className="me-1" />
{t("history.restore")}
</ConfirmSubmit>
</form>
) : null}
</div>
</div>
<div className="list-group list-group-flush">
@@ -10,7 +10,8 @@ import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { fileUrl } from "@/lib/files";
import { KIND_INFO, WORKPLACE_KINDS } from "@/lib/kinds";
import { requireEntity } from "@/lib/session";
import { hasRole } from "@/lib/access";
import { requireBook, requireEntity } from "@/lib/session";
import { formatFieldValue, getTemplate, type FieldDef } from "@/lib/templates";
type RefTarget = { id: string; name: string; code: string | null };
@@ -39,6 +40,7 @@ function groupFields(fields: FieldDef[], data: Record<string, unknown>, byId: Ma
export default async function EntityPage({ params }: { params: Promise<{ bookId: string; entityId: string }> }) {
const { bookId, entityId } = await params;
const base = await requireEntity(bookId, entityId);
const canEdit = hasRole((await requireBook(bookId)).role, "EDITOR");
const { t, locale } = await getT();
const [entity, template, bookEntities, maps] = await Promise.all([
@@ -152,24 +154,28 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
}
actions={
<>
<Link href={`${entityHref(entity.id)}/edit`} className="btn">
<IconPencil size={18} className="me-1" />
{t("common.edit")}
</Link>
{canEdit ? (
<Link href={`${entityHref(entity.id)}/edit`} className="btn">
<IconPencil size={18} className="me-1" />
{t("common.edit")}
</Link>
) : null}
{versionCount > 0 ? (
<Link href={`${entityHref(entity.id)}/history`} className="btn">
<IconHistory size={18} className="me-1" />
{t("history.button", { n: versionCount })}
</Link>
) : null}
<form action={deleteEntity}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={entity.id} />
<ConfirmSubmit className="btn btn-outline-danger" message={t("trash.moveConfirm")}>
<IconTrash size={18} className="me-1" />
{t("common.delete")}
</ConfirmSubmit>
</form>
{canEdit ? (
<form action={deleteEntity}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={entity.id} />
<ConfirmSubmit className="btn btn-outline-danger" message={t("trash.moveConfirm")}>
<IconTrash size={18} className="me-1" />
{t("common.delete")}
</ConfirmSubmit>
</form>
) : null}
</>
}
/>
@@ -297,13 +303,15 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
)}
{item.description ? <div className="text-secondary small">{item.description}</div> : null}
</div>
<RemoveRelation bookId={bookId} id={item.id} label={t("common.delete")} />
{canEdit ? <RemoveRelation bookId={bookId} id={item.id} label={t("common.delete")} /> : null}
</div>
))}
</div>
<div className="card-body border-top">
<RelationForm bookId={bookId} entities={allEntities} fixedFromId={entity.id} t={t} />
</div>
{canEdit ? (
<div className="card-body border-top">
<RelationForm bookId={bookId} entities={allEntities} fixedFromId={entity.id} t={t} />
</div>
) : null}
</div>
{entity.kind === "CHARACTER" ? (
@@ -0,0 +1,21 @@
import { PageBody, PageHeader } from "@/components/page";
import { WordImport } from "@/components/word-import";
import { getT } from "@/i18n/server";
import { requireBook } from "@/lib/session";
export const metadata = { title: "Importera från Word" };
export default async function ImportWordPage({ params }: { params: Promise<{ bookId: string }> }) {
const { bookId } = await params;
await requireBook(bookId, "EDITOR");
const { t } = await getT();
return (
<>
<PageHeader title={t("wordimport.title")} />
<PageBody>
<WordImport bookId={bookId} />
</PageBody>
</>
);
}
+10 -1
View File
@@ -1,4 +1,5 @@
import { Shell } from "@/components/shell";
import { getT } from "@/i18n/server";
import { requireBook, requireUser } from "@/lib/session";
export default async function BookLayout({
@@ -11,8 +12,16 @@ export default async function BookLayout({
const { bookId } = await params;
const user = await requireUser();
const book = await requireBook(bookId);
const { t } = await getT();
return (
<Shell user={user} book={{ id: book.id, title: book.title }}>
<Shell user={user} book={{ id: book.id, title: book.title, role: book.role }}>
{book.role === "VIEWER" ? (
<div className="page-body pb-0 mt-3 d-print-none">
<div className="container-xl">
<div className="alert alert-info mb-0">{t("share.viewerNotice")}</div>
</div>
</div>
) : null}
{children}
</Shell>
);
+4 -2
View File
@@ -6,6 +6,7 @@ import { PageBody, PageHeader } from "@/components/page";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { fileUrl } from "@/lib/files";
import { hasRole } from "@/lib/access";
import { requireBook } from "@/lib/session";
// Standard är OpenStreetMaps publika tjänster. Byt via miljövariabler vid tyngre användning.
@@ -22,7 +23,7 @@ export default async function MapPage({
}) {
const { bookId, mapId } = await params;
const { place, marker } = await searchParams;
await requireBook(bookId);
const canEdit = hasRole((await requireBook(bookId)).role, "EDITOR");
const { t } = await getT();
const [map, entities] = await Promise.all([
@@ -47,6 +48,7 @@ export default async function MapPage({
/>
<PageBody>
<MapLoader
readOnly={!canEdit}
bookId={bookId}
mapId={map.id}
kind={map.kind}
@@ -71,7 +73,7 @@ export default async function MapPage({
initialMarkerId={marker ?? null}
/>
<div className="card mt-4">
<div className="card mt-4" hidden={!canEdit}>
<div className="card-header">
<h3 className="card-title">{t("map.settings")}</h3>
</div>
+3 -2
View File
@@ -4,6 +4,7 @@ import { createMap } from "@/actions/maps";
import { EmptyState, PageBody, PageHeader } from "@/components/page";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { hasRole } from "@/lib/access";
import { requireBook } from "@/lib/session";
export const metadata = { title: "Kartor" };
@@ -17,7 +18,7 @@ export default async function MapsPage({
}) {
const { bookId } = await params;
const { error } = await searchParams;
await requireBook(bookId);
const canEdit = hasRole((await requireBook(bookId)).role, "EDITOR");
const { t } = await getT();
const maps = await prisma.bookMap.findMany({
where: { bookId },
@@ -60,7 +61,7 @@ export default async function MapsPage({
)}
</div>
<div className="col-lg-4">
<div className="col-lg-4" hidden={!canEdit}>
<form action={createMap} className="card">
<input type="hidden" name="bookId" value={bookId} />
<div className="card-header">
+3 -2
View File
@@ -5,6 +5,7 @@ import { EmptyState, PageBody, PageHeader } from "@/components/page";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { KIND_INFO, KINDS } from "@/lib/kinds";
import { hasRole } from "@/lib/access";
import { requireBook } from "@/lib/session";
export default async function BookDashboard({
@@ -59,7 +60,7 @@ export default async function BookDashboard({
</Link>
<div className="text-secondary">{countOf[kind] ?? 0}</div>
</div>
<div className="col-auto position-relative" style={{ zIndex: 2 }}>
<div className="col-auto position-relative" style={{ zIndex: 2 }} hidden={!hasRole(book.role, "EDITOR")}>
<Link
href={`/books/${bookId}/e/${slug}/new`}
className="btn btn-icon btn-sm btn-ghost-secondary"
@@ -97,7 +98,7 @@ export default async function BookDashboard({
</Link>
<div className="text-secondary">{countOf[kind] ?? 0}</div>
</div>
<div className="col-auto position-relative" style={{ zIndex: 2 }}>
<div className="col-auto position-relative" style={{ zIndex: 2 }} hidden={!hasRole(book.role, "EDITOR")}>
<Link
href={`/books/${bookId}/e/${slug}/new`}
className="btn btn-icon btn-sm btn-ghost-secondary"
@@ -4,11 +4,13 @@ import { Fragment } from "react";
import { IconTrash } from "@tabler/icons-react";
import { deleteRelation, saveRelation } from "@/actions/relations";
import { ConfirmSubmit } from "@/components/confirm-submit";
import { ConflictForm } from "@/components/conflict-form";
import { EntitySelect } from "@/components/entity-select";
import { FieldInput } from "@/components/entity-form";
import { RelationBondFields } from "@/components/relation-bond-fields";
import { PageBody, PageHeader } from "@/components/page";
import { getT } from "@/i18n/server";
import { versionOf } from "@/lib/conflict";
import { prisma } from "@/lib/db";
import { requireBook } from "@/lib/session";
import { getTemplate } from "@/lib/templates";
@@ -22,7 +24,7 @@ export default async function RelationPage({
}) {
const { bookId, relationId } = await params;
const { saved } = await searchParams;
await requireBook(bookId);
await requireBook(bookId, "EDITOR");
const { t, locale } = await getT();
const relation = await prisma.relation.findFirst({
@@ -95,7 +97,7 @@ export default async function RelationPage({
/>
<PageBody>
{saved ? <div className="alert alert-success">{t("common.saved")}</div> : null}
<form action={saveRelation}>
<ConflictForm action={saveRelation} version={versionOf(relation.updatedAt)}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={relation.id} />
<div className="card mb-3">
@@ -163,7 +165,7 @@ export default async function RelationPage({
{t("common.save")}
</button>
</div>
</form>
</ConflictForm>
</PageBody>
</>
);
+4 -3
View File
@@ -7,6 +7,7 @@ import { RelationForm } from "@/components/relation-form";
import { RelationGraph } from "@/components/relation-graph";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { hasRole } from "@/lib/access";
import { requireBook } from "@/lib/session";
export const metadata = { title: "Relationer" };
@@ -20,7 +21,7 @@ export default async function RelationsPage({
}) {
const { bookId } = await params;
const { entity: entityFilter } = await searchParams;
await requireBook(bookId);
const canEdit = hasRole((await requireBook(bookId)).role, "EDITOR");
const { t } = await getT();
const [entities, relations] = await Promise.all([
@@ -124,7 +125,7 @@ export default async function RelationsPage({
))}
</td>
<td className="text-secondary">{r.description}</td>
<td className="w-1">
<td className="w-1" hidden={!canEdit}>
<form action={deleteRelation}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={r.id} />
@@ -142,7 +143,7 @@ export default async function RelationsPage({
</div>
</div>
<div className="col-lg-4">
<div className="col-lg-4" hidden={!canEdit}>
<div className="card">
<div className="card-header">
<h3 className="card-title">{t("relation.add")}</h3>
+16 -11
View File
@@ -7,6 +7,7 @@ import type { TFunction } from "@/i18n/core";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { WORKPLACE_KINDS } from "@/lib/kinds";
import { hasRole } from "@/lib/access";
import { requireBook } from "@/lib/session";
export const metadata = { title: "Scheman" };
@@ -28,11 +29,13 @@ function ShiftChip({
shift,
bookId,
t,
canEdit,
showPerson,
}: {
shift: ShiftRow;
bookId: string;
t: TFunction;
canEdit: boolean;
showPerson?: boolean;
}) {
return (
@@ -65,13 +68,15 @@ function ShiftChip({
))}
</div>
</div>
<form action={deleteShift}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={shift.id} />
<button type="submit" className="btn btn-icon btn-sm btn-ghost-secondary" title={t("common.delete")} aria-label={t("common.delete")}>
<IconX size={14} />
</button>
</form>
{canEdit ? (
<form action={deleteShift}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={shift.id} />
<button type="submit" className="btn btn-icon btn-sm btn-ghost-secondary" title={t("common.delete")} aria-label={t("common.delete")}>
<IconX size={14} />
</button>
</form>
) : null}
</div>
);
}
@@ -86,7 +91,7 @@ export default async function SchedulesPage({
const { bookId } = await params;
const { view = "person", range: rangeParam, person, workplace } = await searchParams;
const range = rangeParam === "night" ? "night" : "day";
await requireBook(bookId);
const canEdit = hasRole((await requireBook(bookId)).role, "EDITOR");
const { t } = await getT();
const [people, workplaces, shifts] = await Promise.all([
@@ -275,7 +280,7 @@ export default async function SchedulesPage({
{shifts
.filter((s) => s.weekday === d)
.map((s) => (
<ShiftChip key={s.id} shift={s} bookId={bookId} t={t} showPerson />
<ShiftChip key={s.id} shift={s} bookId={bookId} t={t} canEdit={canEdit} showPerson />
))}
</td>
))}
@@ -314,7 +319,7 @@ export default async function SchedulesPage({
{rowShifts
.filter((s) => s.weekday === d)
.map((s) => (
<ShiftChip key={s.id} shift={s} bookId={bookId} t={t} />
<ShiftChip key={s.id} shift={s} bookId={bookId} t={t} canEdit={canEdit} />
))}
</td>
))}
@@ -332,7 +337,7 @@ export default async function SchedulesPage({
<div className="card-header">
<h3 className="card-title">{t("schedule.add")}</h3>
</div>
{people.length === 0 ? (
{!canEdit ? null : people.length === 0 ? (
<div className="card-body text-secondary">{t("schedule.noPeople")}</div>
) : (
<form action={addShifts}>
+173 -34
View File
@@ -1,16 +1,32 @@
import { IconDownload } from "@tabler/icons-react";
import { deleteBook, updateBook } from "@/actions/books";
import { changeMemberRole, leaveSharedBook, removeBookMember, shareBook } from "@/actions/sharing";
import { ConfirmSubmit } from "@/components/confirm-submit";
import { PageBody, PageHeader } from "@/components/page";
import { getT } from "@/i18n/server";
import { MEMBER_ROLES, canChangeMember, hasRole, manageableRoles } from "@/lib/access";
import { requireBook } from "@/lib/session";
import { SHARE_RESULTS, listMembers, type ShareResult } from "@/lib/sharing";
export const metadata = { title: "Bokinställningar" };
export default async function SettingsPage({ params }: { params: Promise<{ bookId: string }> }) {
export default async function SettingsPage({
params,
searchParams,
}: {
params: Promise<{ bookId: string }>;
searchParams: Promise<{ share?: string }>;
}) {
const { bookId } = await params;
const { share } = await searchParams;
const book = await requireBook(bookId);
const { t } = await getT();
const isAdmin = hasRole(book.role, "ADMIN");
const isOwner = book.role === "OWNER";
const { owner, members } = await listMembers(book.id);
const result = SHARE_RESULTS.includes(share as ShareResult) ? (share as ShareResult) : null;
const grantable = manageableRoles(book.role);
const person = (u: { name: string | null; email: string | null }) => u.name ?? u.email ?? "?";
return (
<>
@@ -18,34 +34,145 @@ export default async function SettingsPage({ params }: { params: Promise<{ bookI
<PageBody>
<div className="row row-cards">
<div className="col-lg-8">
<form action={updateBook} className="card">
<form action={updateBook} className="card mb-3">
<input type="hidden" name="bookId" value={book.id} />
<div className="card-body">
<div className="row g-3">
<div className="col-md-6">
<label className="form-label required">{t("common.title")}</label>
<input name="title" className="form-control" required maxLength={200} defaultValue={book.title} />
</div>
<div className="col-md-6">
<label className="form-label">{t("books.subtitle")}</label>
<input name="subtitle" className="form-control" maxLength={200} defaultValue={book.subtitle ?? ""} />
</div>
<div className="col-md-6">
<label className="form-label">{t("books.genre")}</label>
<input name="genre" className="form-control" maxLength={100} defaultValue={book.genre ?? ""} />
</div>
<div className="col-12">
<label className="form-label">{t("common.description")}</label>
<textarea name="description" className="form-control" rows={4} defaultValue={book.description ?? ""} />
<fieldset disabled={!isAdmin}>
<div className="card-body">
{isAdmin ? null : <p className="text-secondary">{t("settings.readOnly")}</p>}
<div className="row g-3">
<div className="col-md-6">
<label className="form-label required">{t("common.title")}</label>
<input name="title" className="form-control" required maxLength={200} defaultValue={book.title} />
</div>
<div className="col-md-6">
<label className="form-label">{t("books.subtitle")}</label>
<input name="subtitle" className="form-control" maxLength={200} defaultValue={book.subtitle ?? ""} />
</div>
<div className="col-md-6">
<label className="form-label">{t("books.genre")}</label>
<input name="genre" className="form-control" maxLength={100} defaultValue={book.genre ?? ""} />
</div>
<div className="col-12">
<label className="form-label">{t("common.description")}</label>
<textarea name="description" className="form-control" rows={4} defaultValue={book.description ?? ""} />
</div>
</div>
</div>
</div>
<div className="card-footer text-end">
<button type="submit" className="btn btn-primary">
{t("common.save")}
</button>
</div>
{isAdmin ? (
<div className="card-footer text-end">
<button type="submit" className="btn btn-primary">
{t("common.save")}
</button>
</div>
) : null}
</fieldset>
</form>
<div className="card">
<div className="card-header">
<h3 className="card-title">{t("share.title")}</h3>
</div>
<div className="card-body">
<p className="text-secondary">{t("share.help")}</p>
<p className="text-secondary small">{t("share.roles")}</p>
{result ? <div className={`alert alert-${result === "ok" ? "success" : "warning"}`}>{t(`share.result.${result}`)}</div> : null}
</div>
<div className="table-responsive">
<table className="table table-vcenter card-table">
<tbody>
<tr>
<td>
<div className="fw-bold">{person(owner)}</div>
{owner.email && owner.name ? <div className="text-secondary small">{owner.email}</div> : null}
</td>
<td>
<span className="badge bg-primary-lt">{t("share.role.OWNER")}</span>
</td>
<td className="w-1" />
</tr>
{members.map((m) => {
const manageable = isAdmin && canChangeMember(book.role, m.role, null);
return (
<tr key={m.id}>
<td>
<div className="fw-bold">
{person(m.user)}
{m.userId === book.userId ? <span className="text-secondary fw-normal"> ({t("share.you")})</span> : null}
</div>
{m.user.email && m.user.name ? <div className="text-secondary small">{m.user.email}</div> : null}
</td>
<td>
{manageable ? (
<form action={changeMemberRole} className="d-flex gap-2">
<input type="hidden" name="bookId" value={book.id} />
<input type="hidden" name="userId" value={m.userId} />
<select name="role" className="form-select form-select-sm" defaultValue={m.role}>
{MEMBER_ROLES.filter((r) => grantable.includes(r)).map((r) => (
<option key={r} value={r}>
{t(`share.role.${r}`)}
</option>
))}
</select>
<button type="submit" className="btn btn-sm">
{t("common.save")}
</button>
</form>
) : (
<span className="badge">{t(`share.role.${m.role}`)}</span>
)}
</td>
<td className="w-1">
{manageable ? (
<form action={removeBookMember}>
<input type="hidden" name="bookId" value={book.id} />
<input type="hidden" name="userId" value={m.userId} />
<ConfirmSubmit className="btn btn-sm btn-outline-danger" message={t("share.removeConfirm")}>
{t("share.remove")}
</ConfirmSubmit>
</form>
) : null}
</td>
</tr>
);
})}
{members.length === 0 ? (
<tr>
<td colSpan={3} className="text-secondary">
{t("share.nobody")}
</td>
</tr>
) : null}
</tbody>
</table>
</div>
{isAdmin ? (
<form action={shareBook} className="card-body border-top">
<input type="hidden" name="bookId" value={book.id} />
<div className="row g-2 align-items-end">
<div className="col-md-6">
<label className="form-label">{t("share.email")}</label>
<input type="email" name="email" className="form-control" required maxLength={200} />
<div className="form-hint">{t("share.emailHelp")}</div>
</div>
<div className="col-md-4">
<label className="form-label">{t("share.role")}</label>
<select name="role" className="form-select" defaultValue="EDITOR">
{MEMBER_ROLES.filter((r) => grantable.includes(r)).map((r) => (
<option key={r} value={r}>
{t(`share.role.${r}`)}
</option>
))}
</select>
</div>
<div className="col-md-2 text-end">
<button type="submit" className="btn btn-primary w-100">
{t("share.add")}
</button>
</div>
</div>
</form>
) : null}
</div>
</div>
<div className="col-lg-4">
@@ -64,16 +191,28 @@ export default async function SettingsPage({ params }: { params: Promise<{ bookI
</div>
</div>
</div>
<div className="card border-danger">
<div className="card-header">
<h3 className="card-title text-danger">{t("settings.danger")}</h3>
{isOwner ? (
<div className="card border-danger">
<div className="card-header">
<h3 className="card-title text-danger">{t("settings.danger")}</h3>
</div>
<form action={deleteBook} className="card-body">
<input type="hidden" name="bookId" value={book.id} />
<p className="text-secondary">{t("settings.deleteBookHelp")}</p>
<ConfirmSubmit>{t("settings.deleteBook")}</ConfirmSubmit>
</form>
</div>
<form action={deleteBook} className="card-body">
<input type="hidden" name="bookId" value={book.id} />
<p className="text-secondary">{t("settings.deleteBookHelp")}</p>
<ConfirmSubmit>{t("settings.deleteBook")}</ConfirmSubmit>
</form>
</div>
) : (
<div className="card">
<form action={leaveSharedBook} className="card-body">
<input type="hidden" name="bookId" value={book.id} />
<p className="text-secondary">{t("share.leaveHelp", { owner: person(owner) })}</p>
<ConfirmSubmit className="btn btn-outline-danger" message={t("share.leaveConfirm")}>
{t("share.leave")}
</ConfirmSubmit>
</form>
</div>
)}
</div>
</div>
</PageBody>
@@ -15,7 +15,7 @@ export default async function TemplateEditPage({
}) {
const { bookId, kind: slug } = await params;
const { error, saved } = await searchParams;
await requireBook(bookId);
await requireBook(bookId, "ADMIN");
const kind = templateKindFromSlug(slug);
if (!kind) notFound();
const { t, locale } = await getT();
+1 -1
View File
@@ -11,7 +11,7 @@ export const metadata = { title: "Mallar" };
export default async function TemplatesPage({ params }: { params: Promise<{ bookId: string }> }) {
const { bookId } = await params;
await requireBook(bookId);
await requireBook(bookId, "ADMIN");
const { t, locale } = await getT();
const kinds: { kind: TemplateKind; color: string }[] = [
@@ -3,10 +3,12 @@ import { notFound } from "next/navigation";
import { IconTrash } from "@tabler/icons-react";
import { deleteEvent, saveEvent } from "@/actions/events";
import { ConfirmSubmit } from "@/components/confirm-submit";
import { ConflictForm } from "@/components/conflict-form";
import { EntitySelect } from "@/components/entity-select";
import { PageBody, PageHeader } from "@/components/page";
import { StoryDateInput } from "@/components/story-date-input";
import { getT } from "@/i18n/server";
import { versionOf } from "@/lib/conflict";
import { prisma } from "@/lib/db";
import { requireBook } from "@/lib/session";
@@ -19,7 +21,7 @@ export default async function EventPage({
}) {
const { bookId, eventId } = await params;
const { saved, error } = await searchParams;
await requireBook(bookId);
await requireBook(bookId, "EDITOR");
const { t } = await getT();
const event = await prisma.storyEvent.findFirst({ where: { id: eventId, bookId }, include: { participants: true } });
@@ -49,7 +51,7 @@ export default async function EventPage({
<PageBody>
{saved ? <div className="alert alert-success">{t("common.saved")}</div> : null}
{error === "date" ? <div className="alert alert-danger">{t("timeline.invalidDate")}</div> : null}
<form action={saveEvent}>
<ConflictForm action={saveEvent} version={versionOf(event.updatedAt)}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={event.id} />
<div className="card mb-3">
@@ -88,7 +90,7 @@ export default async function EventPage({
{t("common.save")}
</button>
</div>
</form>
</ConflictForm>
</PageBody>
</>
);
+3 -2
View File
@@ -5,6 +5,7 @@ import { EmptyState, PageBody, PageHeader } from "@/components/page";
import { StoryDateInput } from "@/components/story-date-input";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { hasRole } from "@/lib/access";
import { requireBook } from "@/lib/session";
import { storyYear } from "@/lib/story-date";
import { loadTimeline, TIMELINE_KINDS, type TimelineItem, type TimelineKind } from "@/lib/timeline";
@@ -28,7 +29,7 @@ export default async function TimelinePage({
}) {
const { bookId } = await params;
const { person, kind, error } = await searchParams;
await requireBook(bookId);
const canEdit = hasRole((await requireBook(bookId)).role, "EDITOR");
const { t } = await getT();
const wanted = (Array.isArray(kind) ? kind : kind ? [kind] : []).filter((k): k is TimelineKind => (TIMELINE_KINDS as string[]).includes(k));
@@ -184,7 +185,7 @@ export default async function TimelinePage({
) : null}
</div>
<div className="col-lg-4">
<div className="col-lg-4" hidden={!canEdit}>
<div className="card">
<div className="card-header">
<h3 className="card-title">{t("timeline.addEvent")}</h3>
+6 -3
View File
@@ -7,6 +7,7 @@ import { EmptyState, PageBody, PageHeader } from "@/components/page";
import { getT } from "@/i18n/server";
import { prisma } from "@/lib/db";
import { KIND_INFO, parseKind } from "@/lib/kinds";
import { hasRole } from "@/lib/access";
import { requireBook } from "@/lib/session";
import { TRASH_DAYS } from "@/lib/trash";
@@ -22,6 +23,8 @@ export default async function TrashPage({
const { bookId } = await params;
const { restore } = await searchParams;
const book = await requireBook(bookId);
const canRestore = hasRole(book.role, "EDITOR");
const canPurge = hasRole(book.role, "ADMIN");
const { t } = await getT();
const items = await prisma.trashItem.findMany({
where: { ownerId: book.ownerId, bookId, kind: "entity" },
@@ -33,7 +36,7 @@ export default async function TrashPage({
<PageHeader
title={t("trash.title")}
actions={
items.length > 0 ? (
items.length > 0 && canPurge ? (
<form action={emptyTrash}>
<input type="hidden" name="bookId" value={bookId} />
<ConfirmSubmit className="btn btn-outline-danger" message={t("trash.emptyConfirm")}>
@@ -72,7 +75,7 @@ export default async function TrashPage({
{t("trash.daysLeft", { n: daysLeft })}
</div>
</div>
<form action={restoreTrashEntity}>
<form action={restoreTrashEntity} hidden={!canRestore}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={item.id} />
<button type="submit" className="btn btn-sm">
@@ -80,7 +83,7 @@ export default async function TrashPage({
{t("trash.restore")}
</button>
</form>
<form action={purgeTrash}>
<form action={purgeTrash} hidden={!canPurge}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="id" value={item.id} />
<ConfirmSubmit className="btn btn-sm btn-outline-danger" message={t("trash.purgeConfirm")}>
+98
View File
@@ -0,0 +1,98 @@
"use client";
import { useRef, useState, useTransition, type ReactNode } from "react";
import { useT } from "@/i18n/client";
import type { ConflictInfo, SaveResult } from "@/lib/conflict";
/**
* Formulär som skickas med en sparåtgärd och klarar att någon annan hunnit ändra samma sak.
* Formuläret skickas med versionen det öppnades med. Om åtgärden svarar med en krock visas en ruta ovanför
* formuläret, och det användaren skrivit finns kvar tills hen väljer att spara ändå eller ladda om.
*/
export function ConflictForm({
action,
version,
children,
className,
}: {
action: (formData: FormData) => Promise<SaveResult | void>;
/** Versionen av det som redigeras, tom för nya poster */
version: string;
children: ReactNode;
className?: string;
}) {
const t = useT();
const formRef = useRef<HTMLFormElement>(null);
const [conflict, setConflict] = useState<ConflictInfo | null>(null);
const [pending, startTransition] = useTransition();
// Skickas för hand i stället för via form action, eftersom React annars tömmer formuläret efter åtgärden
function submit(overrideVersion?: string) {
const form = formRef.current;
if (!form) return;
const data = new FormData(form);
if (overrideVersion) data.set("version", overrideVersion);
startTransition(async () => {
const result = await action(data);
setConflict(result && "conflict" in result ? result.conflict : null);
});
}
const time = conflict ? new Date(conflict.at).toLocaleString() : "";
return (
<form
ref={formRef}
className={className}
onSubmit={(event) => {
event.preventDefault();
if (!pending) submit();
}}
>
<input type="hidden" name="version" defaultValue={version} />
{conflict ? (
<div className="alert alert-warning" role="alert">
<h4 className="alert-title">{t("conflict.title")}</h4>
<div className="mb-2">{conflict.by ? t("conflict.by", { name: conflict.by, time }) : t("conflict.byUnknown", { time })}</div>
{conflict.changes.length > 0 ? (
<>
<div className="mb-1">{t("conflict.diff")}</div>
<div className="table-responsive bg-body rounded mb-2">
<table className="table table-sm mb-0">
<thead>
<tr>
<th />
<th>{t("conflict.saved")}</th>
<th>{t("conflict.yours")}</th>
</tr>
</thead>
<tbody>
{conflict.changes.slice(0, 12).map((c) => (
<tr key={c.label}>
<td className="fw-bold">{c.label}</td>
<td className="text-break">{c.before || <span className="text-secondary">{t("conflict.empty")}</span>}</td>
<td className="text-break">{c.after || <span className="text-secondary">{t("conflict.empty")}</span>}</td>
</tr>
))}
</tbody>
</table>
</div>
</>
) : null}
<div className="d-flex flex-wrap gap-2 align-items-center">
<button type="button" className="btn btn-warning" disabled={pending} onClick={() => submit(conflict.version)}>
{t("conflict.overwrite")}
</button>
<button type="button" className="btn" onClick={() => window.location.reload()}>
{t("conflict.reload")}
</button>
</div>
<div className="text-secondary small mt-2">
{t("conflict.overwriteHelp")} {t("conflict.reloadHelp")}
</div>
</div>
) : null}
{children}
</form>
);
}
+5 -3
View File
@@ -2,6 +2,8 @@ import { Fragment } from "react";
import Link from "next/link";
import type { Entity, EntityKind } from "@prisma/client";
import type { TFunction } from "@/i18n/core";
import { versionOf, type SaveResult } from "@/lib/conflict";
import { ConflictForm } from "./conflict-form";
import { NameFill } from "./name-fill";
import { StoryDateInput } from "./story-date-input";
import { fileUrl } from "@/lib/files";
@@ -99,7 +101,7 @@ export function EntityForm({
refEntities,
t,
}: {
action: (formData: FormData) => Promise<void>;
action: (formData: FormData) => Promise<SaveResult | void>;
bookId: string;
kind: EntityKind;
entity?: Entity;
@@ -113,7 +115,7 @@ export function EntityForm({
const image = fileUrl(entity?.imageFile, "thumb");
return (
<form action={action}>
<ConflictForm action={action} version={entity ? versionOf(entity.updatedAt) : ""}>
<input type="hidden" name="bookId" value={bookId} />
<input type="hidden" name="kind" value={kind} />
{entity ? <input type="hidden" name="id" value={entity.id} /> : null}
@@ -205,6 +207,6 @@ export function EntityForm({
{t("common.save")}
</button>
</div>
</form>
</ConflictForm>
);
}
+29 -20
View File
@@ -37,6 +37,8 @@ export type MapViewProps = {
geocoderUrl: string;
preselectEntityId: string | null;
initialMarkerId: string | null;
/** Läsare ser kartan och markeringarna men kan inte ändra något */
readOnly?: boolean;
};
type Draft = {
@@ -65,6 +67,7 @@ function pinIcon(color: string, highlight = false) {
export default function MapView(props: MapViewProps) {
const { bookId, mapId, kind, imageUrl, markers, entities } = props;
const readOnly = props.readOnly ?? false;
const t = useT();
const router = useRouter();
const [pending, startTransition] = useTransition();
@@ -93,7 +96,7 @@ export default function MapView(props: MapViewProps) {
const entityName = (id: string) => entities.find((e) => e.id === id)?.name ?? "";
handlers.current.mapClick = (lat, lng) => {
if (!adding) return;
if (readOnly || !adding) return;
const pre = initial.current.place ?? "";
setDraft({ id: null, label: pre ? entityName(pre) : "", note: "", color: "blue", entityId: pre, lat, lng });
setAdding(false);
@@ -171,7 +174,7 @@ export default function MapView(props: MapViewProps) {
const icon = pinIcon(m.color, m.id === draftId);
let lm = layers.get(m.id);
if (!lm) {
const created = L.marker([m.lat, m.lng], { icon, draggable: true, autoPan: true }).addTo(map);
const created = L.marker([m.lat, m.lng], { icon, draggable: !readOnly, autoPan: true }).addTo(map);
created.on("click", () => handlers.current.openMarker(m.id));
created.on("dragend", () => {
const p = created.getLatLng();
@@ -319,24 +322,26 @@ export default function MapView(props: MapViewProps) {
<div className="col-lg-4">
<div className="card mb-3">
<div className="card-body d-flex flex-wrap gap-2 align-items-center">
<button
type="button"
className={`btn ${adding ? "btn-warning" : "btn-primary"}`}
onClick={() => {
setDraft(null);
setAdding((v) => !v);
}}
>
{adding ? <IconX size={18} className="me-1" /> : <IconPlus size={18} className="me-1" />}
{adding ? t("map.cancelAdd") : t("map.addMarker")}
</button>
{kind === "GEO" ? (
{readOnly ? null : (
<button
type="button"
className={`btn ${adding ? "btn-warning" : "btn-primary"}`}
onClick={() => {
setDraft(null);
setAdding((v) => !v);
}}
>
{adding ? <IconX size={18} className="me-1" /> : <IconPlus size={18} className="me-1" />}
{adding ? t("map.cancelAdd") : t("map.addMarker")}
</button>
)}
{kind === "GEO" && !readOnly ? (
<button type="button" className="btn" onClick={persistView} disabled={pending}>
<IconCurrentLocation size={18} className="me-1" />
{viewSaved ? t("map.viewSaved") : t("map.saveView")}
</button>
) : null}
<div className="w-100 text-secondary small">{adding ? t("map.addHint") : t("map.dragHint")}</div>
{readOnly ? null : <div className="w-100 text-secondary small">{adding ? t("map.addHint") : t("map.dragHint")}</div>}
</div>
</div>
@@ -379,6 +384,7 @@ export default function MapView(props: MapViewProps) {
</div>
) : null}
</div>
<fieldset disabled={readOnly}>
<div className="card-body">
<div className="mb-3">
<label className="form-label required">{t("map.markerLabel")}</label>
@@ -448,18 +454,21 @@ export default function MapView(props: MapViewProps) {
</div>
) : null}
</div>
</fieldset>
<div className="card-footer d-flex gap-2">
{draft.id ? (
{draft.id && !readOnly ? (
<button type="button" className="btn btn-outline-danger" onClick={removeDraft} disabled={pending}>
{t("common.delete")}
</button>
) : null}
<button type="button" className="btn ms-auto" onClick={() => setDraft(null)}>
{t("common.cancel")}
</button>
<button type="submit" className="btn btn-primary" disabled={pending}>
{t("common.save")}
{readOnly ? t("common.back") : t("common.cancel")}
</button>
{readOnly ? null : (
<button type="submit" className="btn btn-primary" disabled={pending}>
{t("common.save")}
</button>
)}
</div>
</form>
) : null}
+18 -6
View File
@@ -4,6 +4,7 @@ import {
IconBook2,
IconCalendarWeek,
IconDice5,
IconFileImport,
IconChartDots3,
IconLayoutDashboard,
IconListDetails,
@@ -21,6 +22,7 @@ import type { ReactNode } from "react";
import { signOut } from "@/auth";
import { setLocale } from "@/actions/settings";
import { getT } from "@/i18n/server";
import { hasRole, type BookRole } from "@/lib/access";
import { isAdminUser } from "@/lib/admin";
import { APP_VERSION_LABEL } from "@/lib/version";
import { LOCALES } from "@/i18n/core";
@@ -32,7 +34,7 @@ import { ThemeToggle } from "./theme-toggle";
type ShellProps = {
user: { id: string; name?: string | null; email?: string | null };
book?: { id: string; title: string };
book?: { id: string; title: string; role?: BookRole };
children: ReactNode;
};
@@ -40,6 +42,8 @@ export async function Shell({ user, book, children }: ShellProps) {
const { t, locale } = await getT();
const base = book ? `/books/${book.id}` : "";
const admin = await isAdminUser(user.id, user.email ?? null);
const canEdit = !book || hasRole(book.role ?? "VIEWER", "EDITOR");
const bookAdmin = !book || hasRole(book.role ?? "VIEWER", "ADMIN");
// Sidor och "skapa ny" för kommandopaletten (Ctrl+K)
const pages = [
@@ -54,15 +58,16 @@ export async function Shell({ user, book, children }: ShellProps) {
{ label: t("nav.schedules"), href: `${base}/schedules` },
{ label: t("nav.maps"), href: `${base}/maps` },
{ label: t("nav.names"), href: `${base}/names` },
...(canEdit ? [{ label: t("nav.importWord"), href: `${base}/import-word` }] : []),
{ label: t("nav.idRegister"), href: `${base}/register` },
{ label: t("nav.templates"), href: `${base}/templates` },
...(bookAdmin ? [{ label: t("nav.templates"), href: `${base}/templates` }] : []),
{ label: t("nav.trash"), href: `${base}/trash` },
{ label: t("nav.settings"), href: `${base}/settings` },
]
: [{ label: t("nav.books"), href: "/" }]),
...(admin ? [{ label: t("nav.admin"), href: "/admin" }] : []),
];
const creates = book ? KINDS.map((k) => ({ label: t(`kind.${k.kind}.new`), href: `${base}/e/${k.slug}/new` })) : [];
const creates = book && canEdit ? KINDS.map((k) => ({ label: t(`kind.${k.kind}.new`), href: `${base}/e/${k.slug}/new` })) : [];
return (
<div className="page">
@@ -161,9 +166,16 @@ export async function Shell({ user, book, children }: ShellProps) {
<NavLink href={`${base}/names`} icon={<IconDice5 size={20} />}>
{t("nav.names")}
</NavLink>
<NavLink href={`${base}/templates`} icon={<IconTemplate size={20} />}>
{t("nav.templates")}
</NavLink>
{canEdit ? (
<NavLink href={`${base}/import-word`} icon={<IconFileImport size={20} />}>
{t("nav.importWord")}
</NavLink>
) : null}
{bookAdmin ? (
<NavLink href={`${base}/templates`} icon={<IconTemplate size={20} />}>
{t("nav.templates")}
</NavLink>
) : null}
<NavLink href={`${base}/trash`} icon={<IconTrash size={20} />}>
{t("nav.trash")}
</NavLink>
+263
View File
@@ -0,0 +1,263 @@
"use client";
import Link from "next/link";
import { useState, useTransition } from "react";
import { previewWordImport, saveWordImport } from "@/actions/word-import";
import { useT } from "@/i18n/client";
import type { ImportKind } from "@/lib/word-import";
import type { CommitResult, PreviewDocument } from "@/lib/word-import-db";
const KINDS: ImportKind[] = ["CHARACTER", "PET", "HOME", "COMPANY", "PREMISES", "EDUCATION", "SCENARIO", "RELATION", "VEHICLE", "REFERENCE", "RESEARCH", "APP", "WEBSITE"];
const SHOWN_ITEMS = 40;
type Decision = { include: boolean; name: string };
/** Importerar ifyllda Word-mallar: ladda upp, granska vad som hittades, bekräfta. Inget sparas före bekräftelsen. */
export function WordImport({ bookId }: { bookId: string }) {
const t = useT();
const [files, setFiles] = useState<File[]>([]);
const [kinds, setKinds] = useState<string[]>([]);
const [docs, setDocs] = useState<PreviewDocument[] | null>(null);
const [decisions, setDecisions] = useState<Decision[][]>([]);
const [append, setAppend] = useState(true);
const [error, setError] = useState<string | null>(null);
const [result, setResult] = useState<CommitResult | null>(null);
const [pending, startTransition] = useTransition();
function review(selected: File[], chosenKinds: string[]) {
setError(null);
setResult(null);
const data = new FormData();
data.set("bookId", bookId);
selected.forEach((file, i) => {
data.append("files", file);
data.append("kinds", chosenKinds[i] ?? "");
});
startTransition(async () => {
const response = await previewWordImport(data);
if ("error" in response) {
setError(t(`wordimport.error.${response.error}`));
setDocs(null);
return;
}
setDocs(response.docs);
// Poster som redan finns är avmarkerade, och relationer utan två kända deltagare går inte att importera
setDecisions(
response.docs.map((doc) =>
doc.items.map((item) => ({
include: !doc.error && item.name !== "" && item.duplicates.length === 0 && (item.entityKind !== "RELATION" || (doc.relation?.participants.filter((p) => p.entityId).length ?? 0) >= 2),
name: item.name,
})),
),
);
});
}
function update(doc: number, item: number, change: Partial<Decision>) {
setDecisions((all) => all.map((list, d) => (d === doc ? list.map((x, i) => (i === item ? { ...x, ...change } : x)) : list)));
}
const selectedCount = decisions.reduce((sum, list) => sum + list.filter((d) => d.include).length, 0);
function commit() {
if (!docs) return;
const items = docs.flatMap((doc, d) =>
doc.items.map((item, i) => ({
include: decisions[d]?.[i]?.include ?? false,
entityKind: item.entityKind,
name: decisions[d]?.[i]?.name ?? item.name,
code: item.code,
data: item.data,
links: item.links,
unmatched: item.unmatched,
participants: item.entityKind === "RELATION" ? (doc.relation?.participants.map((p) => p.entityId).filter((id): id is string => !!id) ?? []) : undefined,
})),
);
startTransition(async () => {
setResult(await saveWordImport({ bookId, items, appendUnmatched: append }));
setDocs(null);
setFiles([]);
setKinds([]);
});
}
return (
<div>
<div className="card mb-3">
<div className="card-body">
<p className="text-secondary">{t("wordimport.help")}</p>
<p className="text-secondary small">{t("wordimport.helpFormat")}</p>
<div className="row g-2 align-items-end">
<div className="col-md-8">
<label className="form-label">{t("wordimport.choose")}</label>
<input
type="file"
className="form-control"
multiple
accept=".docx,application/vnd.openxmlformats-officedocument.wordprocessingml.document"
onChange={(e) => {
setFiles(Array.from(e.target.files ?? []));
setKinds([]);
setDocs(null);
setResult(null);
}}
/>
</div>
<div className="col-md-4">
<button type="button" className="btn btn-primary w-100" disabled={pending || files.length === 0} onClick={() => review(files, kinds)}>
{pending && !docs ? t("wordimport.reading") : t("wordimport.review")}
</button>
</div>
</div>
{error ? <div className="alert alert-danger mt-3 mb-0">{error}</div> : null}
</div>
</div>
{result ? (
<div className="alert alert-success">
{t("wordimport.done", { created: result.created, relations: result.relations, skipped: result.skipped })}{" "}
<Link href={`/books/${bookId}`}>{t("common.back")}</Link>
</div>
) : null}
{docs?.map((doc, d) => (
<div className="card mb-3" key={`${doc.file}-${d}`}>
<div className="card-header">
<h3 className="card-title text-truncate">{doc.file}</h3>
{doc.error ? null : (
<div className="card-actions d-flex align-items-center gap-2">
<label className="form-label mb-0 text-secondary small">{t("wordimport.docType")}</label>
<select
className="form-select form-select-sm w-auto"
value={doc.kind ?? ""}
disabled={pending}
onChange={(e) => {
const next = [...kinds];
next[d] = e.target.value;
setKinds(next);
review(files, next);
}}
>
{doc.kind ? null : <option value="">{t("wordimport.unknownType")}</option>}
{KINDS.map((k) => (
<option key={k} value={k}>
{k === "RELATION" ? t("relation.one") : t(`kind.${k}.one`)}
</option>
))}
</select>
</div>
)}
</div>
<div className="card-body">
{doc.error ? <div className="text-danger">{t(`wordimport.error.${doc.error}`)}</div> : null}
{doc.warnings.map((w) => (
<div key={w} className="alert alert-warning py-2">
{t(`wordimport.warning.${w}`)}
</div>
))}
{doc.items.length > 0 ? <div className="text-secondary mb-2">{t("wordimport.items", { n: doc.items.length })}</div> : null}
{doc.relation ? (
<div className="mb-3">
<div className="fw-bold">{t("wordimport.participants")}</div>
<ul className="mb-1">
{doc.relation.participants.map((p, i) => (
<li key={i} className={p.entityId ? "" : "text-warning"}>
{p.entityId ? p.text : t("wordimport.notFound", { name: p.text })}
</li>
))}
</ul>
{doc.relation.participants.filter((p) => p.entityId).length < 2 ? <div className="text-warning">{t("wordimport.tooFew")}</div> : null}
</div>
) : null}
{doc.items.slice(0, SHOWN_ITEMS).map((item, i) => {
const decision = decisions[d]?.[i];
if (!decision) return null;
const fieldCount = Object.keys(item.data).length;
const relation = item.entityKind === "RELATION";
const blocked = relation && (doc.relation?.participants.filter((p) => p.entityId).length ?? 0) < 2;
return (
<div key={i} className="border rounded p-2 mb-2">
<div className="d-flex align-items-center gap-2 flex-wrap">
<input type="checkbox" className="form-check-input m-0" checked={decision.include} disabled={blocked} onChange={(e) => update(d, i, { include: e.target.checked })} />
{relation ? (
<span className="fw-bold">{item.name}</span>
) : (
<input
className="form-control form-control-sm w-auto flex-fill"
style={{ minWidth: "12rem" }}
aria-label={t("wordimport.name")}
value={decision.name}
maxLength={200}
onChange={(e) => update(d, i, { name: e.target.value })}
/>
)}
{item.code ? <span className="badge">{item.code}</span> : null}
<span className="badge bg-blue-lt">{t("wordimport.fields", { n: fieldCount })}</span>
{item.links.length > 0 ? <span className="badge bg-azure-lt">{t("wordimport.links", { n: item.links.length })}</span> : null}
{item.duplicates.length > 0 ? (
<span className="badge bg-yellow-lt" title={t("wordimport.existsHelp")}>
{t("wordimport.exists", { name: item.duplicates[0].code ?? item.duplicates[0].name })}
</span>
) : null}
</div>
<details className="mt-1">
<summary className="text-secondary small">{t("wordimport.details")}</summary>
<div className="row mt-2">
<div className="col-md-6">
<div className="fw-bold small">{t("wordimport.matched")}</div>
<ul className="small mb-2">
{Object.entries(item.data).map(([key, value]) => (
<li key={key}>
<span className="text-secondary">{key}:</span> {item.display[key] ?? String(value).slice(0, 120)}
</li>
))}
{item.links.map((link, k) => (
<li key={`l${k}`} className={link.entityId ? "" : "text-warning"}>
{link.entityId ? t("wordimport.linkTo", { type: link.type, name: link.text }) : t("wordimport.notFound", { name: link.text })}
</li>
))}
</ul>
</div>
<div className="col-md-6">
{item.unmatched.length > 0 ? (
<>
<div className="fw-bold small">{t("wordimport.unmatched")}</div>
<ul className="small mb-0">
{item.unmatched.map((p, k) => (
<li key={k}>
<span className="text-secondary">{p.label}:</span> {p.value.slice(0, 160)}
</li>
))}
</ul>
</>
) : null}
</div>
</div>
</details>
</div>
);
})}
{doc.items.length > SHOWN_ITEMS ? <div className="text-secondary">{t("wordimport.more", { n: doc.items.length - SHOWN_ITEMS })}</div> : null}
</div>
</div>
))}
{docs ? (
<div className="card">
<div className="card-body d-flex flex-wrap gap-3 align-items-center">
<label className="form-check mb-0">
<input type="checkbox" className="form-check-input" checked={append} onChange={(e) => setAppend(e.target.checked)} />
<span className="form-check-label">{t("wordimport.append")}</span>
</label>
<button type="button" className="btn btn-primary ms-auto" disabled={pending || selectedCount === 0} onClick={commit}>
{pending ? t("wordimport.importing") : t("wordimport.import", { n: selectedCount })}
</button>
{selectedCount === 0 ? <span className="text-secondary">{t("wordimport.noneSelected")}</span> : null}
</div>
</div>
) : null}
</div>
);
}
+82
View File
@@ -453,4 +453,86 @@ export const en: Record<keyof typeof sv, string> = {
"import.done": "The book was imported: {entities} items, {relations} relationships and {maps} maps.",
"import.skipped": "{n} images or links were missing from the file and were skipped.",
"settings.exportHelp": "Downloads the whole book: items, relationships, schedules, maps, templates and images. The zip file can be imported as a new book here or in another installation. The JSON variant contains data only, without images.",
"share.title": "Sharing",
"share.help": "Share the book with others who have logged in to the app. They see it under My books.",
"share.roles": "Viewers see everything and can export. Editors change the content. Administrators share the book and change settings and templates. Only the owner deletes the book and manages administrators.",
"share.email": "Email address",
"share.emailHelp": "The address the person logs in with.",
"share.role": "Role",
"share.add": "Share",
"share.owner": "Owner",
"share.you": "you",
"share.remove": "Remove",
"share.removeConfirm": "Remove this person's access to the book?",
"share.nobody": "The book is not shared with anyone.",
"share.leave": "Leave the book",
"share.leaveHelp": "The book is shared by {owner}. You can leave it, and the owner can share it with you again.",
"share.leaveConfirm": "Leave the book? You lose access until the owner shares it again.",
"share.sharedBy": "Shared by {name}",
"share.viewerNotice": "You have read-only access to this book and cannot change anything.",
"share.role.ADMIN": "Administrator",
"share.role.EDITOR": "Editor",
"share.role.VIEWER": "Viewer",
"share.role.OWNER": "Owner",
"share.result.ok": "Done.",
"share.result.not-found": "No user with that email address has logged in to the app yet. Ask the person to log in once first.",
"share.result.owner": "That person already owns the book.",
"share.result.already": "The book is already shared with that person.",
"share.result.forbidden": "You are not allowed to make that change.",
"share.result.invalid": "Invalid email address or role.",
"settings.readOnly": "Only administrators can change the book's details.",
"conflict.title": "Someone else has saved changes since you opened the page",
"conflict.by": "Last saved by {name} {time}.",
"conflict.byUnknown": "Last saved {time}.",
"conflict.diff": "This is how your form differs from the saved version:",
"conflict.saved": "Saved",
"conflict.yours": "Yours",
"conflict.empty": "(empty)",
"conflict.overwrite": "Save my changes anyway",
"conflict.overwriteHelp": "The saved version is overwritten. For items it stays in the history.",
"conflict.reload": "Reload the page",
"conflict.reloadHelp": "You then see the saved version, and your unsaved changes are lost.",
"nav.importWord": "Import from Word",
"wordimport.title": "Import from Word",
"wordimport.help": "Upload filled-in Word templates (.docx) from Mall/ and Register/. The app interprets them and shows what it found. Nothing is saved until you confirm, and you can change names, deselect items and change the document type.",
"wordimport.helpFormat": "Write the value after the label in the same cell or the cell next to it, and mark choices with an X (for example Yes: X No:). Schedules and the map register are not imported.",
"wordimport.choose": "Word files",
"wordimport.review": "Review",
"wordimport.reading": "Reading…",
"wordimport.docType": "Document type",
"wordimport.unknownType": "Unknown type, choose",
"wordimport.error.not-docx": "Not a Word document (.docx).",
"wordimport.error.too-large": "The file is too large (8 MB at most).",
"wordimport.error.invalid": "The file could not be read.",
"wordimport.error.no-files": "Choose at least one file.",
"wordimport.error.limit": "Too many files (20 at most).",
"wordimport.items": "{n} items found",
"wordimport.name": "Name",
"wordimport.code": "ID",
"wordimport.fields": "{n} fields",
"wordimport.links": "{n} links",
"wordimport.exists": "Already exists: {name}",
"wordimport.existsHelp": "An item with the same name already exists, so it is unchecked. Check it to create another one anyway.",
"wordimport.details": "Details",
"wordimport.matched": "Interpreted",
"wordimport.unmatched": "Not interpreted",
"wordimport.linkTo": "{type}: {name}",
"wordimport.notFound": "{name} (not in the book, skipped)",
"wordimport.participants": "Participants",
"wordimport.tooFew": "The relationship needs at least two participants that exist in the book.",
"wordimport.append": "Put what could not be interpreted in the Other or Description field",
"wordimport.import": "Import {n}",
"wordimport.importing": "Saving…",
"wordimport.done": "{created} items and {relations} links were created. {skipped} were skipped.",
"wordimport.noneSelected": "Nothing selected to import.",
"wordimport.warning.unknown-kind": "The document type could not be determined. Choose the type above.",
"wordimport.warning.empty": "Nothing filled in was found in the document.",
"wordimport.warning.few-participants": "Fewer than two participants were found.",
"wordimport.more": "…and {n} more",
"wordimport.another": "Import more",
"wordimport.warning.unsupported": "Schedules and the map register are not imported here. Add schedules under Schedules and maps under Maps.",
};
+82
View File
@@ -451,4 +451,86 @@ export const sv = {
"import.done": "Boken importerades: {entities} poster, {relations} relationer och {maps} kartor.",
"import.skipped": "{n} bilder eller kopplingar saknades i filen och hoppades över.",
"settings.exportHelp": "Laddar ner hela boken: poster, relationer, scheman, kartor, mallar och bilder. Zip-filen kan importeras som en ny bok här eller i en annan installation. JSON-varianten innehåller bara data, utan bilder.",
"share.title": "Delning",
"share.help": "Dela boken med andra som har loggat in i appen. De ser boken under Mina böcker.",
"share.roles": "Läsare ser allt och kan exportera. Redaktörer ändrar innehållet. Administratörer delar boken och ändrar inställningar och mallar. Bara ägaren tar bort boken och hanterar administratörer.",
"share.email": "E-postadress",
"share.emailHelp": "Samma adress som personen loggar in med.",
"share.role": "Roll",
"share.add": "Dela",
"share.owner": "Ägare",
"share.you": "du",
"share.remove": "Ta bort",
"share.removeConfirm": "Ta bort personens tillgång till boken?",
"share.nobody": "Boken är inte delad med någon.",
"share.leave": "Lämna boken",
"share.leaveHelp": "Boken delas av {owner}. Du kan lämna den, och ägaren kan dela den med dig igen.",
"share.leaveConfirm": "Lämna boken? Du förlorar tillgången tills ägaren delar den igen.",
"share.sharedBy": "Delad av {name}",
"share.viewerNotice": "Du har läsrättigheter i den här boken och kan inte ändra något.",
"share.role.ADMIN": "Administratör",
"share.role.EDITOR": "Redaktör",
"share.role.VIEWER": "Läsare",
"share.role.OWNER": "Ägare",
"share.result.ok": "Klart.",
"share.result.not-found": "Ingen användare med den e-postadressen har loggat in i appen än. Be personen logga in en gång först.",
"share.result.owner": "Den personen äger redan boken.",
"share.result.already": "Boken är redan delad med den personen.",
"share.result.forbidden": "Du får inte göra den ändringen.",
"share.result.invalid": "Ogiltig e-postadress eller roll.",
"settings.readOnly": "Bara administratörer kan ändra bokens uppgifter.",
"conflict.title": "Någon annan har sparat ändringar sedan du öppnade sidan",
"conflict.by": "Senast sparad av {name} {time}.",
"conflict.byUnknown": "Senast sparad {time}.",
"conflict.diff": "Så här skiljer sig ditt formulär från den sparade versionen:",
"conflict.saved": "Sparad",
"conflict.yours": "Ditt",
"conflict.empty": "(tomt)",
"conflict.overwrite": "Spara mina ändringar ändå",
"conflict.overwriteHelp": "Den sparade versionen skrivs över. För poster finns den kvar i historiken.",
"conflict.reload": "Ladda om sidan",
"conflict.reloadHelp": "Du ser då den sparade versionen, och dina osparade ändringar förloras.",
"nav.importWord": "Importera från Word",
"wordimport.title": "Importera från Word",
"wordimport.help": "Ladda upp ifyllda Word-mallar (.docx) från Mall/ och Register/. Appen tolkar dem och visar vad den hittade. Först när du bekräftar sparas något, och du kan ändra namn, välja bort poster och byta dokumenttyp.",
"wordimport.helpFormat": "Skriv värdet efter etiketten i samma cell eller i cellen bredvid, och markera val med ett X (till exempel Ja: X Nej:). Scheman och kartregistret importeras inte.",
"wordimport.choose": "Word-filer",
"wordimport.review": "Granska",
"wordimport.reading": "Läser…",
"wordimport.docType": "Dokumenttyp",
"wordimport.unknownType": "Okänd typ, välj",
"wordimport.error.not-docx": "Inte ett Word-dokument (.docx).",
"wordimport.error.too-large": "Filen är för stor (högst 8 MB).",
"wordimport.error.invalid": "Filen kunde inte läsas.",
"wordimport.error.no-files": "Välj minst en fil.",
"wordimport.error.limit": "För många filer (högst 20).",
"wordimport.items": "{n} poster hittades",
"wordimport.name": "Namn",
"wordimport.code": "ID",
"wordimport.fields": "{n} fält",
"wordimport.links": "{n} kopplingar",
"wordimport.exists": "Finns redan: {name}",
"wordimport.existsHelp": "En post med samma namn finns redan, så den är avmarkerad. Markera den för att skapa en till ändå.",
"wordimport.details": "Detaljer",
"wordimport.matched": "Tolkat",
"wordimport.unmatched": "Ej tolkat",
"wordimport.linkTo": "{type}: {name}",
"wordimport.notFound": "{name} (finns inte i boken, hoppas över)",
"wordimport.participants": "Deltagare",
"wordimport.tooFew": "Relationen behöver minst två deltagare som finns i boken.",
"wordimport.append": "Lägg det som inte gick att tolka i fältet Övrigt eller Beskrivning",
"wordimport.import": "Importera {n}",
"wordimport.importing": "Sparar…",
"wordimport.done": "{created} poster och {relations} kopplingar skapades. {skipped} hoppades över.",
"wordimport.noneSelected": "Inget valt att importera.",
"wordimport.warning.unknown-kind": "Dokumentets typ kunde inte avgöras. Välj typ här ovanför.",
"wordimport.warning.empty": "Inget ifyllt hittades i dokumentet.",
"wordimport.warning.few-participants": "Färre än två deltagare hittades.",
"wordimport.more": "…och {n} till",
"wordimport.another": "Importera fler",
"wordimport.warning.unsupported": "Scheman och kartregister importeras inte här. Lägg in scheman under Scheman och kartor under Kartor.",
} as const;
+31
View File
@@ -0,0 +1,31 @@
// Roller i en bok. Ägaren är den som skapade boken (Book.ownerId), övriga får en roll genom delning.
// VIEWER läser allt och kan exportera
// EDITOR skriver som ägaren: poster, relationer, scheman, kartor, händelser, återställer ur papperskorgen
// ADMIN dessutom delning, bokinställningar, mallar och att tömma papperskorgen
// OWNER dessutom att ta bort boken och att ge och ta bort administratörer
export type BookRole = "OWNER" | "ADMIN" | "EDITOR" | "VIEWER";
export type MemberRole = Exclude<BookRole, "OWNER">;
export const MEMBER_ROLES: MemberRole[] = ["ADMIN", "EDITOR", "VIEWER"];
const RANK: Record<BookRole, number> = { VIEWER: 1, EDITOR: 2, ADMIN: 3, OWNER: 4 };
export const hasRole = (role: BookRole, min: BookRole) => RANK[role] >= RANK[min];
export function parseMemberRole(value: unknown): MemberRole | null {
return typeof value === "string" && (MEMBER_ROLES as string[]).includes(value) ? (value as MemberRole) : null;
}
/** Vilka roller en person med rollen `actor` får ge, ändra och ta bort. Bara ägaren hanterar administratörer. */
export function manageableRoles(actor: BookRole): MemberRole[] {
if (actor === "OWNER") return ["ADMIN", "EDITOR", "VIEWER"];
if (actor === "ADMIN") return ["EDITOR", "VIEWER"];
return [];
}
/** Får `actor` ändra en medlem som har rollen `current` till rollen `next`, eller ta bort medlemmen (next = null)? */
export function canChangeMember(actor: BookRole, current: MemberRole, next: MemberRole | null): boolean {
const allowed = manageableRoles(actor);
return allowed.includes(current) && (next === null || allowed.includes(next));
}
+14
View File
@@ -0,0 +1,14 @@
import type { BookRole } from "./access";
import { prisma } from "./db";
/** En användares roll i en bok (ägare eller delad), eller null om boken inte finns eller inte är delad med användaren. */
export async function bookAccess(bookId: string, userId: string) {
const book = await prisma.book.findFirst({
where: { id: bookId, OR: [{ ownerId: userId }, { members: { some: { userId } } }] },
include: { members: { where: { userId }, select: { role: true } } },
});
if (!book) return null;
const { members, ...rest } = book;
const role: BookRole = book.ownerId === userId ? "OWNER" : (members[0]?.role ?? "VIEWER");
return { ...rest, role, userId };
}
+34
View File
@@ -0,0 +1,34 @@
import { prisma } from "./db";
// Skydd mot att två ändringar krockar. Formuläret skickar med versionen (tidpunkten för senaste ändringen) som det
// öppnades med. Har posten ändrats sedan dess sparas ingenting, och användaren får välja att spara ändå
// (då hamnar den andras version i historiken) eller ladda om.
export type ConflictChange = { label: string; /** Sparad version */ before: string; /** Det som skickades in */ after: string };
export type ConflictInfo = {
/** Aktuell version, som skickas med igen när användaren väljer att spara ändå */
version: string;
/** Vem som senast sparade, om det är känt */
by: string | null;
/** När, som ISO-tid */
at: string;
changes: ConflictChange[];
};
/** Svar från en sparåtgärd som inte kunde spara. Lyckad sparning omdirigerar i stället. */
export type SaveResult = { conflict: ConflictInfo } | undefined;
export const versionOf = (updatedAt: Date) => String(updatedAt.getTime());
/** Sant om formuläret öppnades med en äldre version än den sparade. Saknas version kontrolleras inget. */
export function isStale(expected: string, current: Date): boolean {
return expected !== "" && expected !== versionOf(current);
}
export async function conflictInfo(current: { updatedAt: Date; updatedById: string | null }, changes: ConflictChange[] = []): Promise<ConflictInfo> {
const user = current.updatedById
? await prisma.user.findUnique({ where: { id: current.updatedById }, select: { name: true, email: true } })
: null;
return { version: versionOf(current.updatedAt), by: user?.name ?? user?.email ?? null, at: current.updatedAt.toISOString(), changes };
}
+6
View File
@@ -42,6 +42,12 @@ async function nextNumber(db: Db, bookId: string, key: string): Promise<number>
return row.next;
}
/** Ser till att räknaren minst har nått n, så att nya ID inte krockar med ett ID som tagits in utifrån (import). */
export async function reserveNumber(bookId: string, key: string, n: number, db: Db = prisma): Promise<void> {
await db.idCounter.upsert({ where: { bookId_key: { bookId, key } }, create: { bookId, key, next: n }, update: {} });
await db.idCounter.updateMany({ where: { bookId, key, next: { lt: n } }, data: { next: n } });
}
/** T.ex. KI-0001. Ger null för typer utan ID. */
export async function nextEntityCode(bookId: string, kind: EntityKind, db: Db = prisma): Promise<string | null> {
const prefix = ENTITY_PREFIX[kind];
+12 -7
View File
@@ -1,7 +1,9 @@
import { cache } from "react";
import { notFound, redirect } from "next/navigation";
import { auth } from "@/auth";
import { hasRole, type BookRole } from "./access";
import { isAdminUser } from "./admin";
import { bookAccess } from "./book-access";
import { prisma } from "./db";
/**
@@ -39,17 +41,20 @@ export async function requireAdmin() {
return user;
}
/** Hämtar boken om den tillhör inloggad användare, annars 404. */
export async function requireBook(bookId: string) {
/**
* Hämtar boken om inloggad användare äger den eller har fått den delad, med minst rollen `min`.
* Annars 404, så att man inte kan se vilka böcker som finns.
*/
export async function requireBook(bookId: string, min: BookRole = "VIEWER") {
const user = await requireUser();
const book = await prisma.book.findFirst({ where: { id: bookId, ownerId: user.id } });
if (!book) notFound();
return book;
const access = await bookAccess(bookId, user.id);
if (!access || !hasRole(access.role, min)) notFound();
return access;
}
/** Hämtar en post i boken, annars 404. */
export async function requireEntity(bookId: string, entityId: string) {
await requireBook(bookId);
export async function requireEntity(bookId: string, entityId: string, min: BookRole = "VIEWER") {
await requireBook(bookId, min);
const entity = await prisma.entity.findFirst({ where: { id: entityId, bookId } });
if (!entity) notFound();
return entity;
+58
View File
@@ -0,0 +1,58 @@
import { canChangeMember, manageableRoles, type BookRole, type MemberRole } from "./access";
import { prisma } from "./db";
import { log } from "./log";
// Delning av böcker. Ägaren står i Book.ownerId, övriga i BookMember. Reglerna för vem som får ändra vem finns i access.ts.
export type ShareResult = "ok" | "not-found" | "owner" | "already" | "forbidden" | "invalid";
export const SHARE_RESULTS: ShareResult[] = ["ok", "not-found", "owner", "already", "forbidden", "invalid"];
const EMAIL = /^[^\s@]+@[^\s@]+$/;
export async function listMembers(bookId: string) {
const [book, members] = await Promise.all([
prisma.book.findUniqueOrThrow({ where: { id: bookId }, select: { owner: { select: { id: true, name: true, email: true } } } }),
prisma.bookMember.findMany({ where: { bookId }, include: { user: { select: { id: true, name: true, email: true } } }, orderBy: { createdAt: "asc" } }),
]);
return { owner: book.owner, members };
}
/** Delar boken med den användare som har loggat in med e-postadressen. Personen måste alltså finnas i appen. */
export async function addMember(bookId: string, actor: BookRole, emailRaw: string, role: MemberRole): Promise<ShareResult> {
const email = emailRaw.trim().toLowerCase();
if (!EMAIL.test(email) || email.length > 200) return "invalid";
if (!manageableRoles(actor).includes(role)) return "forbidden";
const user = await prisma.user.findFirst({ where: { email: { equals: email, mode: "insensitive" } }, orderBy: { createdAt: "asc" } });
if (!user) return "not-found";
const book = await prisma.book.findUniqueOrThrow({ where: { id: bookId }, select: { ownerId: true } });
if (book.ownerId === user.id) return "owner";
if (await prisma.bookMember.findUnique({ where: { bookId_userId: { bookId, userId: user.id } }, select: { id: true } })) return "already";
await prisma.bookMember.create({ data: { bookId, userId: user.id, role } });
log.info("Bok delad", { bookId, userId: user.id, role });
return "ok";
}
export async function setMemberRole(bookId: string, actor: BookRole, userId: string, role: MemberRole): Promise<ShareResult> {
const member = await prisma.bookMember.findUnique({ where: { bookId_userId: { bookId, userId } } });
if (!member) return "not-found";
if (!canChangeMember(actor, member.role, role)) return "forbidden";
await prisma.bookMember.update({ where: { id: member.id }, data: { role } });
return "ok";
}
export async function removeMember(bookId: string, actor: BookRole, userId: string): Promise<ShareResult> {
const member = await prisma.bookMember.findUnique({ where: { bookId_userId: { bookId, userId } } });
if (!member) return "not-found";
if (!canChangeMember(actor, member.role, null)) return "forbidden";
await prisma.bookMember.delete({ where: { id: member.id } });
log.info("Delning borttagen", { bookId, userId });
return "ok";
}
/** En medlem lämnar boken. Ägaren kan inte lämna sin egen bok. */
export async function leaveBook(bookId: string, userId: string): Promise<boolean> {
const { count } = await prisma.bookMember.deleteMany({ where: { bookId, userId } });
return count > 0;
}
+136
View File
@@ -0,0 +1,136 @@
import { strFromU8, unzipSync } from "fflate";
// Läser texten ur ett Word-dokument (.docx) som en lista med stycken och tabeller. Allt som inte är text, till exempel
// bilder och formatering, hoppas över. Ett .docx är en zip-fil där texten ligger i word/document.xml.
export const MAX_DOCX_BYTES = 8 * 1024 * 1024;
const MAX_XML_BYTES = 30 * 1024 * 1024;
export type DocBlock = { type: "paragraph"; text: string } | { type: "table"; rows: string[][] };
export type DocxErrorCode = "not-docx" | "too-large" | "invalid";
export class DocxError extends Error {
constructor(public code: DocxErrorCode) {
super(code);
}
}
const ENTITIES: Record<string, string> = { amp: "&", lt: "<", gt: ">", quot: '"', apos: "'" };
export function decodeXml(text: string): string {
return text.replace(/&(#x[0-9a-f]+|#\d+|[a-z]+);/gi, (whole, name: string) => {
if (name[0] === "#") {
const code = name[1].toLowerCase() === "x" ? parseInt(name.slice(2), 16) : parseInt(name.slice(1), 10);
return Number.isFinite(code) && code > 0 && code < 0x110000 ? String.fromCodePoint(code) : "";
}
return ENTITIES[name.toLowerCase()] ?? whole;
});
}
/** Plockar ut innehållet i word/document.xml ur en docx-fil. */
export function readDocumentXml(bytes: Uint8Array): string {
if (bytes.length > MAX_DOCX_BYTES) throw new DocxError("too-large");
if (bytes.length < 4 || bytes[0] !== 0x50 || bytes[1] !== 0x4b) throw new DocxError("not-docx");
let entries: Record<string, Uint8Array>;
try {
// Bara huvuddokumentet packas upp, med gräns mot zip-bomber
entries = unzipSync(bytes, { filter: (file) => file.name === "word/document.xml" && file.originalSize <= MAX_XML_BYTES });
} catch {
throw new DocxError("invalid");
}
const xml = entries["word/document.xml"];
if (!xml) throw new DocxError("not-docx");
return strFromU8(xml);
}
const TAG = /<(\/?)w:(tbl|tr|tc|p|t|tab|br|cr|sym)\b([^>]*?)(\/?)>/g;
/**
* Delar upp dokumentets XML i stycken och tabeller. Tabeller i tabeller platt ut: deras text hamnar i den yttre cellen.
* Stycken i en cell slås ihop med radbrytning.
*/
export function parseDocumentXml(xml: string): DocBlock[] {
const blocks: DocBlock[] = [];
let tableDepth = 0;
let rows: string[][] | null = null;
let row: string[] | null = null;
let cell: string[] | null = null;
let paragraph: string | null = null;
TAG.lastIndex = 0;
let match: RegExpExecArray | null;
while ((match = TAG.exec(xml))) {
const [, closing, name, attrs, selfClosing] = match;
const open = !closing && !selfClosing;
switch (name) {
case "tbl":
if (open) {
tableDepth++;
if (tableDepth === 1) rows = [];
} else if (closing) {
tableDepth--;
if (tableDepth === 0 && rows) {
blocks.push({ type: "table", rows });
rows = null;
}
if (tableDepth < 0) tableDepth = 0;
}
break;
case "tr":
if (tableDepth === 1) {
if (open) row = [];
else if (closing && row && rows) {
rows.push(row);
row = null;
}
}
break;
case "tc":
if (tableDepth === 1) {
if (open) cell = [];
else if (closing && cell && row) {
row.push(cell.join("\n"));
cell = null;
}
}
break;
case "p":
if (open) {
paragraph = "";
} else if (closing && paragraph !== null) {
const text = paragraph.replace(/ +/g, " ").replace(/[ \t]*\n[ \t]*/g, "\n").trim();
if (tableDepth > 0) cell?.push(text);
else if (text) blocks.push({ type: "paragraph", text });
paragraph = null;
}
break;
case "t":
if (open && paragraph !== null) {
const end = xml.indexOf("</w:t>", TAG.lastIndex);
if (end >= 0) {
paragraph += decodeXml(xml.slice(TAG.lastIndex, end));
TAG.lastIndex = end + "</w:t>".length;
}
}
break;
case "tab":
if (paragraph !== null) paragraph += "\t";
break;
case "br":
case "cr":
if (paragraph !== null) paragraph += "\n";
break;
case "sym":
// En symbol (till exempel en ruta med bock) räknas som ett kryss
if (paragraph !== null && /w:char="F0(FE|FD|52|53)"/i.test(attrs)) paragraph += "✓";
break;
}
}
return blocks;
}
export function readDocx(bytes: Uint8Array): DocBlock[] {
return parseDocumentXml(readDocumentXml(bytes));
}
+235
View File
@@ -0,0 +1,235 @@
import type { EntityKind, Prisma } from "@prisma/client";
import { prisma } from "./db";
import { ENTITY_PREFIX, nextEntityCode, nextRelationCode, reserveNumber } from "./ids";
import { parseKind } from "./kinds";
import { normalizeStoryDate } from "./story-date";
import { getTemplate, type FieldDef } from "./templates";
import { DocxError, readDocx } from "./word-docx";
import {
IMPORT_KINDS,
analyzeDocument,
describeUnmatched,
overflowField,
usableCode,
type ImportKind,
type ItemLink,
type KnownEntity,
type Pair,
type ParsedDocument,
type ParsedItem,
} from "./word-import";
// Förhandsgranskning och sparande av importen från Word. Tolkningen själv ligger i word-import.ts.
export const MAX_WORD_FILES = 20;
export const MAX_WORD_ITEMS = 500;
export type PreviewItem = ParsedItem & { duplicates: { id: string; name: string; code: string | null }[] };
export type PreviewDocument = Omit<ParsedDocument, "items"> & {
items: PreviewItem[];
/** Satt om filen inte gick att läsa */
error: "not-docx" | "too-large" | "invalid" | null;
};
async function loadContext(bookId: string) {
const entities = await prisma.entity.findMany({ where: { bookId }, select: { id: true, name: true, code: true, kind: true } });
const known: KnownEntity[] = entities;
const templates: Partial<Record<ImportKind, FieldDef[]>> = {};
for (const kind of IMPORT_KINDS) templates[kind] = (await getTemplate(bookId, kind, "sv")).fields;
return { known, templates };
}
/** Läser Word-filerna och tolkar dem, utan att spara något. `kinds` låter användaren byta dokumenttyp per fil. */
export async function previewWordFiles(
bookId: string,
files: { name: string; bytes: Uint8Array }[],
kinds: (ImportKind | null)[] = [],
): Promise<PreviewDocument[]> {
const { known, templates } = await loadContext(bookId);
const byName = new Map<string, KnownEntity[]>();
for (const e of known) byName.set(`${e.kind}|${e.name.toLowerCase()}`, [...(byName.get(`${e.kind}|${e.name.toLowerCase()}`) ?? []), e]);
return files.slice(0, MAX_WORD_FILES).map((file, index): PreviewDocument => {
try {
const blocks = readDocx(file.bytes);
const parsed = analyzeDocument(blocks, file.name, known, { kind: kinds[index] ?? null, templates });
return {
...parsed,
error: null,
items: parsed.items.map((item) => ({
...item,
duplicates:
item.entityKind === "RELATION" ? [] : (byName.get(`${item.entityKind}|${item.name.toLowerCase()}`) ?? []).map((e) => ({ id: e.id, name: e.name, code: e.code })),
})),
};
} catch (error) {
if (error instanceof DocxError) return { file: file.name, kind: null, items: [], relation: null, warnings: [], error: error.code };
throw error;
}
});
}
// ─── Spara ──────────────────────────────────────────────────────────────────
/** Det som webbläsaren skickar tillbaka efter förhandsgranskningen. Allt kontrolleras igen innan något sparas. */
export type CommitItem = {
include: boolean;
entityKind: string;
name: string;
code: string | null;
data: Record<string, unknown>;
links: ItemLink[];
unmatched: Pair[];
/** Deltagare i en relation (post-id) */
participants?: string[];
};
export type CommitResult = { created: number; relations: number; skipped: number };
const text = (value: unknown, max: number): string => (typeof value === "string" ? value.trim().slice(0, max) : "");
/** Behåller bara de fält som finns i mallen och har ett giltigt värde av rätt sort. */
export function cleanData(fields: FieldDef[], data: Record<string, unknown>, entities: Map<string, EntityKind>): Record<string, unknown> {
const clean: Record<string, unknown> = {};
for (const field of fields) {
const value = data[field.key];
if (value === undefined || value === null || value === "") continue;
switch (field.type) {
case "number":
if (typeof value === "number" && Number.isFinite(value)) clean[field.key] = value;
break;
case "checkbox":
if (typeof value === "boolean") clean[field.key] = value;
break;
case "date": {
const date = normalizeStoryDate(value);
if (date) clean[field.key] = date;
break;
}
case "select":
if (typeof value === "string" && (field.options ?? []).includes(value)) clean[field.key] = value;
break;
case "url":
if (typeof value === "string" && /^https?:\/\/\S+$/i.test(value) && value.length <= 2000) clean[field.key] = value;
break;
case "reference": {
const kind = typeof value === "string" ? entities.get(value) : undefined;
if (typeof value === "string" && kind && (!field.refKind || field.refKind === kind)) clean[field.key] = value;
break;
}
default:
if (typeof value === "string") clean[field.key] = value.trim().slice(0, 20000);
}
}
return clean;
}
const RELATION_BY_CATEGORY: Record<string, { type: string; bond: "PARTNER" | null }> = {
Vännergrupp: { type: "Vänner", bond: null },
Partner: { type: "Partner till", bond: "PARTNER" },
Familj: { type: "Familj", bond: null },
Kollegor: { type: "Kollega till", bond: null },
};
export async function commitWordImport(
bookId: string,
userId: string,
items: CommitItem[],
options: { appendUnmatched: boolean },
): Promise<CommitResult> {
const chosen = items.slice(0, MAX_WORD_ITEMS).filter((i) => i && i.include);
const result: CommitResult = { created: 0, relations: 0, skipped: items.length - chosen.length, };
if (chosen.length === 0) return result;
const existing = await prisma.entity.findMany({ where: { bookId }, select: { id: true, kind: true, code: true } });
const kindOf = new Map(existing.map((e) => [e.id, e.kind]));
const takenCodes = new Set(existing.map((e) => e.code).filter((c): c is string => !!c));
const templates = new Map<ImportKind, FieldDef[]>();
for (const kind of IMPORT_KINDS) templates.set(kind, (await getTemplate(bookId, kind, "sv")).fields);
await prisma.$transaction(
async (tx) => {
for (const item of chosen) {
const kind = item.entityKind === "RELATION" ? "RELATION" : parseKind(item.entityKind);
if (!kind) {
result.skipped++;
continue;
}
const fields = templates.get(kind)!;
const data = cleanData(fields, item.data ?? {}, kindOf);
const unmatched = (Array.isArray(item.unmatched) ? item.unmatched : []).filter((p) => text(p?.label, 200) && text(p?.value, 20000)).slice(0, 100);
const overflow = overflowField(fields);
if (options.appendUnmatched && unmatched.length > 0 && overflow) {
const extra = describeUnmatched(unmatched.map((p) => ({ label: text(p.label, 200), value: text(p.value, 5000) })));
const current = typeof data[overflow] === "string" ? `${data[overflow]}\n\n` : "";
data[overflow] = `${current}${extra}`.slice(0, 20000);
}
if (kind === "RELATION") {
const ids = [...new Set((item.participants ?? []).filter((id) => typeof id === "string" && kindOf.has(id)))];
if (ids.length < 2) {
result.skipped++;
continue;
}
const mapped = RELATION_BY_CATEGORY[String(data.category ?? "")];
await tx.relation.create({
data: {
bookId,
code: await nextRelationCode(bookId, tx),
fromId: ids[0],
toId: ids[1],
type: mapped?.type ?? (text(item.name, 100) || "Relation"),
bond: mapped?.bond ?? null,
data: data as Prisma.InputJsonObject,
updatedById: userId,
members: { create: ids.slice(2).map((entityId) => ({ entityId })) },
},
});
result.relations++;
continue;
}
const name = text(item.name, 200);
if (!name) {
result.skipped++;
continue;
}
const wanted = usableCode(kind, text(item.code, 50) || null);
let code: string | null;
if (wanted && !takenCodes.has(wanted)) {
code = wanted;
await reserveNumber(bookId, ENTITY_PREFIX[kind]!, Number(wanted.split("-")[1]), tx);
} else {
code = await nextEntityCode(bookId, kind, tx);
}
if (code) takenCodes.add(code);
const entity = await tx.entity.create({
data: { bookId, kind, name, code, tags: [], data: data as Prisma.InputJsonObject, updatedById: userId },
});
kindOf.set(entity.id, kind);
result.created++;
for (const link of Array.isArray(item.links) ? item.links.slice(0, 200) : []) {
const other = typeof link?.entityId === "string" && kindOf.has(link.entityId) ? link.entityId : null;
const type = text(link?.type, 100);
if (!other || !type || other === entity.id) continue;
await tx.relation.create({
data: {
bookId,
code: await nextRelationCode(bookId, tx),
fromId: link.toDocument ? other : entity.id,
toId: link.toDocument ? entity.id : other,
type,
description: text(link.note, 2000) || null,
updatedById: userId,
},
});
result.relations++;
}
}
},
{ timeout: 60_000, maxWait: 10_000 },
);
return result;
}
+767
View File
@@ -0,0 +1,767 @@
import type { EntityKind } from "@prisma/client";
import { ENTITY_PREFIX } from "./ids";
import { normalizeStoryDate } from "./story-date";
import { getDefaultTemplate, type FieldDef } from "./templates";
import type { DocBlock } from "./word-docx";
import { isOptionList, labelsMatch, looseMatch, markedOption, normLabel, parseOptions, parseYesNo, pickOption } from "./word-labels";
// Tolkar ifyllda Word-mallar (Mall/ och Register/) till poster. Dokumenten är tabeller med etikett och värde,
// listor över deltagare, stycken under rubriker och register med många rader. Det som inte går att tolka
// rapporteras i stället för att försvinna. Allt här är ren beräkning; databasen används först i word-import-db.ts.
export type ImportKind = EntityKind | "RELATION";
export const IMPORT_KINDS: ImportKind[] = [
"CHARACTER",
"PET",
"HOME",
"COMPANY",
"PREMISES",
"EDUCATION",
"SCENARIO",
"RELATION",
"VEHICLE",
"REFERENCE",
"RESEARCH",
"APP",
"WEBSITE",
];
/** Poster i boken som referenser och deltagarlistor kan peka på. */
export type KnownEntity = { id: string; name: string; code: string | null; kind: EntityKind };
export type Pair = { label: string; value: string };
export type ListEntry = { name: string; code: string; role: string; subject: string };
export type ListBlock = { heading: string; entries: ListEntry[] };
export type RegisterTable = { header: string[]; rows: string[][] };
export type Extracted = {
pairs: Pair[];
/** Alla etiketter som fanns i dokumentet, även de som saknar värde. De avgör vilken sorts dokument det är. */
labels: string[];
lists: ListBlock[];
registers: RegisterTable[];
/** Rubriker och löpande text, för att känna igen vilken sorts dokument det är */
texts: string[];
};
// ─── Hjälpare ───────────────────────────────────────────────────────────────
const PAREN = /\([^)]*\)/g;
const MAX_LABEL = 90;
/** Delar en cell eller ett stycke i etikett och resten, t.ex. "Anställd hos:(inkludera ID)". Null om det inte är en etikett. */
export function splitLabel(text: string): { label: string; rest: string } | null {
const firstLine = text.split("\n")[0];
const colon = firstLine.indexOf(":");
if (colon < 2 || colon > MAX_LABEL) return null;
const label = firstLine.slice(0, colon).trim();
if (!label || /^https?$/i.test(label) || !/[A-Za-zÅÄÖåäö]/.test(label)) return null;
const rest = text.slice(colon + 1);
return { label, rest };
}
/** Ifyllt värde i resten av en etikettcell: mallens hjälptext i parentes och avslutande kolon räknas bort. */
function filledValue(rest: string): string {
return rest.replace(PAREN, " ").replace(/^[\s:]+|[\s:]+$/g, "").replace(/\s*\n\s*/g, "\n").trim();
}
const isLabelCell = (text: string) => {
const parts = splitLabel(text);
return parts !== null && !isOptionList(text);
};
const isEmptyRow = (cells: string[]) => cells.every((c) => !c.trim());
/** Har texten någon rad som är en etikett utan värde ("Om lägenheten:")? Då är den en mall-text, inte ett ifyllt värde. */
const hasLabelLine = (text: string) =>
text.split("\n").some((line) => {
const parts = isOptionList(line) ? null : splitLabel(line.trim());
return parts !== null && !filledValue(parts.rest);
});
type LabelLine = { label: string; inline: string; lines: number[] };
/**
* En cell kan ha många etiketter, en per rad ("Förnamn:", "Efternamn:" ...), med värdena på motsvarande rader i cellen
* bredvid. En etikett som Word brutit över två rader ("Ålder" och "födelsedatum:") slås ihop.
*/
export function multiLabels(cell: string): LabelLine[] {
const entries: LabelLine[] = [];
let buffer: { text: string; index: number }[] = [];
cell.split("\n").forEach((raw, index) => {
const line = raw.trim();
if (!line) {
buffer = [];
return;
}
const parts = isOptionList(line) ? null : splitLabel(line);
if (!parts) {
buffer.push({ text: line, index });
return;
}
entries.push({
label: [...buffer.map((b) => b.text), parts.label].join(" ").trim(),
inline: filledValue(parts.rest),
lines: [...buffer.map((b) => b.index), index],
});
buffer = [];
});
return entries;
}
const LIST_LABELS = new Set(["namn", "karaktärs", "karaktärsnummer", "karaktärskod", "roll", "ämne"]);
/**
* En lista i en enda cell: kolumnrubrikerna ("Namn:", "Roll:", "Karaktärs ID:") står på egna rader och de som ingår
* skrivs på raderna under, en per rad. Kolumner på en rad skiljs åt med tabb. Null om cellen inte är en sådan lista.
*/
export function parseCellList(text: string): ListEntry[] | null {
const lines = text.split("\n").map((l) => l.trim());
const isHeaderLine = (line: string) => {
const parts = splitLabel(line);
return parts !== null && !filledValue(parts.rest) && LIST_LABELS.has(normLabel(parts.label));
};
const headers: string[] = [];
for (const line of lines) if (isHeaderLine(line)) headers.push(normLabel(splitLabel(line)!.label));
const columns = [...new Set(headers)];
if (!columns.includes("namn") || !columns.some((c) => c.startsWith("karaktärs"))) return null;
const others = columns.filter((c) => c !== "namn" && !c.startsWith("karaktärs"));
const entries: ListEntry[] = [];
for (const line of lines) {
if (!line || isHeaderLine(line) || /^\(.*\)$/.test(line)) continue;
const code = CODE_IN_TEXT.exec(line)?.[0] ?? "";
const cols = line.replace(code, "").split("\t").map((c) => c.trim()).filter(Boolean);
const entry: ListEntry = { name: cols[0] ?? "", code, role: "", subject: "" };
others.forEach((column, i) => {
if (column === "roll") entry.role = cols[i + 1] ?? "";
if (column === "ämne") entry.subject = cols[i + 1] ?? "";
});
if (entry.name || entry.code) entries.push(entry);
}
return entries;
}
/**
* En cell med etiketter och värden om vartannat, en sak per rad ("Hyra:", "5000", "Balkong:", "Ja: X Nej:").
* Mallens hjälptexter i parentes hoppas över.
*/
export function parseInlineBlock(text: string, isKnown: (label: string) => boolean): { pairs: Pair[]; labels: string[]; texts: string[] } {
const result = { pairs: [] as Pair[], labels: [] as string[], texts: [] as string[] };
let current: { label: string; lines: string[] } | null = null;
const close = () => {
const value = current?.lines.join("\n").trim();
if (current && value) result.pairs.push({ label: current.label, value });
current = null;
};
for (const raw of text.split("\n")) {
const line = raw.trim();
if (!line || /^\([^)]*\)$/.test(line)) continue;
let parts = isOptionList(line) ? null : splitLabel(line);
// En fråga eller rubrik utan kolon som är en känd etikett
if (!parts && current !== null && isKnown(line)) parts = { label: line, rest: "" };
// Sista alternativet i en lista som bryts över flera rader ("Ja: delvis:" följt av "Nej:")
const restValue = parts ? filledValue(parts.rest) : "";
const continuesOptions =
parts !== null &&
(restValue === "" || /^(?:x|✓|✔|☒|☑|■)$/i.test(restValue)) &&
current !== null &&
isOptionList((current as { lines: string[] }).lines.join("\n")) &&
!/\s/.test(parts.label) &&
parts.label.length <= 15 &&
!isKnown(parts.label);
if (parts && !continuesOptions) {
// "Ålder" följd av "födelsedatum:" är en etikett som Word delat över två rader
const previous: string | undefined = current ? (current as { lines: string[] }).lines.at(-1) : undefined;
if (previous && isKnown(`${previous} ${parts.label}`)) {
(current as { lines: string[] }).lines.pop();
parts = { label: `${previous} ${parts.label}`, rest: parts.rest };
}
close();
result.labels.push(parts.label);
current = { label: parts.label, lines: [] };
const inline = filledValue(parts.rest);
if (inline) current.lines.push(inline);
} else if (current) {
(current as { lines: string[] }).lines.push(line);
} else {
result.texts.push(line);
}
}
close();
return result;
}
/** Värdet på någon av etikettens rader i värdecellen, den första som är ifylld. */
function valueAt(valueCell: string, lines: number[]): string {
const rows = valueCell.split("\n");
for (const i of lines) if (rows[i]?.trim()) return rows[i].trim();
return "";
}
/** Kolumnnamn i en deltagarlista, t.ex. "Namn | Karaktärs ID" eller "Namn | Roll | Karaktärsnummer". */
function listHeader(cells: string[]): { name: number; code: number; role: number; subject: number } | null {
const norm = cells.map((c) => normLabel(c.replace(/:/g, " ")));
const find = (re: RegExp) => norm.findIndex((n) => re.test(n));
const name = find(/^namn$/);
const code = find(/^karaktärs\s?(nummer|kod|id)?$|^karaktärsnummer$|^karaktärer$/);
if (name < 0 || code < 0 || cells.length < 2) return null;
return { name, code, role: find(/^roll$/), subject: find(/^ämne$/) };
}
// ─── Läsa ut etiketter och värden ───────────────────────────────────────────
/**
* Går igenom dokumentets block och plockar ut etikett/värde-par, deltagarlistor och register.
* `isKnown` avgör om en rad som "Etikett: text" i ett stycke ska läsas som en etikett med värde (annars är det löpande text).
*/
export function extract(blocks: DocBlock[], isKnown: (label: string) => boolean): Extracted {
const out: Extracted = { pairs: [], labels: [], lists: [], registers: [], texts: [] };
// Ett val där inget är markerat ("Ja: Nej:") är ett tomt värde
const addPair = (label: string, value: string) => {
const options = parseOptions(value);
if (value.trim() && !(options && !options.some((o) => o.marked))) out.pairs.push({ label, value });
};
let heading = "";
let section: { label: string; lines: string[] } | null = null;
const closeSection = () => {
if (section) {
const value = section.lines.join("\n").trim();
if (value) addPair(section.label, value);
}
section = null;
};
const readTable = (rows: string[][]) => {
// Register: en rubrikrad med minst två etiketter följt av rader med samma antal celler
const first = rows[0] ?? [];
const labelled = first.filter((c) => c.trim() && isLabelCell(c));
const isRegister = rows.length >= 3 && first.length >= 2 && first.every((c) => c.trim()) && labelled.length === first.length && !listHeader(first);
if (isRegister) {
out.registers.push({
header: first.map((c) => (splitLabel(c)?.label ?? c).trim()),
rows: rows.slice(1).filter((r) => r.length === first.length && !isEmptyRow(r)),
});
return;
}
let list: { head: ReturnType<typeof listHeader>; entries: ListEntry[]; heading: string } | null = null;
const flushList = () => {
if (list && list.entries.length > 0) out.lists.push({ heading: list.heading, entries: list.entries });
list = null;
};
let carry: string | null = null; // etikett på en rad som saknar värde, värdet kan stå på nästa rad
for (const cells of rows) {
const carried: string | null = carry;
carry = null;
if (list && list.head) {
// En rad med etiketter avslutar listan
if (cells.length === 0 || cells.some((c) => c.trim() && isLabelCell(c))) {
flushList();
} else {
if (isEmptyRow(cells)) continue;
const at = (i: number) => (i >= 0 ? (cells[i] ?? "").trim() : "");
list.entries.push({ name: at(list.head.name), code: at(list.head.code), role: at(list.head.role), subject: at(list.head.subject) });
continue;
}
}
const head = listHeader(cells);
if (head) {
list = { head, entries: [], heading };
continue;
}
if (isEmptyRow(cells)) {
carry = carried;
continue;
}
if (carried !== null) {
const only = cells.filter((c) => c.trim());
if (only.length === 1 && (isOptionList(only[0]) || (!isLabelCell(only[0]) && !hasLabelLine(only[0]) && !isKnown(only[0])))) {
addPair(carried, only[0].trim());
continue;
}
}
const filled = cells.filter((c) => c.trim());
if (filled.length === 1 && filled[0].includes("\n") && !isOptionList(filled[0])) {
const entries = parseCellList(filled[0]);
if (entries) {
if (entries.length > 0) out.lists.push({ heading, entries });
continue;
}
const block = parseInlineBlock(filled[0], isKnown);
out.labels.push(...block.labels);
for (const pair of block.pairs) addPair(pair.label, pair.value);
out.texts.push(...block.texts);
continue;
}
// Etikett/värde-par i raden. Värdet är nästa cell, om den inte själv är en etikett.
let pending: string | null = null;
const consumed = new Set<number>();
for (const [index, cell] of cells.entries()) {
if (consumed.has(index)) continue;
const text = cell.trim();
if (pending === null && text.includes("\n")) {
const entries = isOptionList(text) ? [] : multiLabels(text);
if (entries.length >= 2) {
const valueCell = cells[index + 1] ?? "";
consumed.add(index + 1);
for (const entry of entries) {
out.labels.push(entry.label);
const value = entry.inline || valueAt(valueCell, entry.lines);
if (value) addPair(entry.label, value);
}
continue;
}
}
let parts = text && !isOptionList(text) ? splitLabel(text) : null;
// En etikett utan kolon som följs av en alternativlista, t.ex. "Finns skisser | Ja: Nej:"
if (!parts && pending === null && text && !isOptionList(text) && isOptionList((cells[index + 1] ?? "").trim())) parts = { label: text, rest: "" };
// En fråga eller rubrik utan kolon som är en känd etikett, t.ex. "Hur påverkas karaktärerna under scenariot?"
if (!parts && pending === null && text && !text.includes("\n") && isKnown(text)) parts = { label: text, rest: "" };
if (pending !== null) {
if (!parts) {
if (text) addPair(pending, text);
pending = null;
continue;
}
pending = null;
}
if (!text) continue;
if (parts) {
out.labels.push(parts.label);
const value = filledValue(parts.rest);
if (value) addPair(parts.label, value);
else pending = parts.label;
} else {
out.texts.push(text);
}
}
// En rad med bara en etikett är en rubrik för en lista som följer
if (pending !== null && cells.filter((c) => c.trim()).length === 1) {
heading = pending;
carry = pending;
}
}
flushList();
};
for (const block of blocks) {
if (block.type === "table") {
closeSection();
readTable(block.rows);
continue;
}
const text = block.text;
const parts = isOptionList(text) ? null : splitLabel(text);
if (parts) {
out.labels.push(parts.label);
const value = filledValue(parts.rest);
if (!value) {
// En rubrik: det som följer är värdet
closeSection();
heading = parts.label;
section = { label: parts.label, lines: [] };
continue;
}
if (isKnown(parts.label)) {
closeSection();
addPair(parts.label, value);
continue;
}
}
if (!parts && !text.includes("\n") && isKnown(text)) {
out.labels.push(text);
closeSection();
heading = text;
section = { label: text, lines: [] };
continue;
}
if (section) section.lines.push(text);
else out.texts.push(text);
}
closeSection();
return out;
}
// ─── Dokumenttyper ──────────────────────────────────────────────────────────
/** Etiketten på dokumentets eget ID-fält, per dokumenttyp. */
const CODE_LABEL: Partial<Record<ImportKind, string>> = {
CHARACTER: "karaktärs",
PET: "djur",
HOME: "bostads",
COMPANY: "företags",
PREMISES: "lokal",
EDUCATION: "utbildnings",
SCENARIO: "scenario",
VEHICLE: "fordons",
REFERENCE: "referens",
RESEARCH: "research",
RELATION: "relations",
};
/** Etiketter som pekar ut vilken sorts dokument det är (normaliserade, utan "ID"). */
const KIND_BY_LABEL: Record<string, ImportKind> = Object.fromEntries(Object.entries(CODE_LABEL).map(([kind, label]) => [label!, kind as ImportKind]));
/** Etiketter som ger postens namn. Flera delar sätts ihop i ordning (förnamn och efternamn). */
const NAME_LABELS: Partial<Record<ImportKind, string[]>> = {
CHARACTER: ["förnamn", "efternamn"],
PET: ["namn"],
COMPANY: ["företagets namn", "företags namn", "företagsnamn"],
EDUCATION: ["skolans namn", "utbildningens namn"],
APP: ["namn"],
WEBSITE: ["namn"],
VEHICLE: ["märke och modell"],
};
const GENERIC_NAME = ["namn"];
type LinkRule = { type: string; /** Posten i dokumentet är det man länkar till */ toDocument: boolean };
/** Vad en deltagarlista eller ett fält betyder, per dokumenttyp och rubrik (normaliserad). */
const LINK_RULES: Partial<Record<ImportKind, Record<string, LinkRule>>> = {
HOME: { boende: { type: "Bor på", toDocument: true } },
COMPANY: { anställda: { type: "Jobbar på", toDocument: true } },
EDUCATION: {
"lärare till klassen": { type: "Lärare på", toDocument: true },
"elever i klassen": { type: "Elev på", toDocument: true },
},
SCENARIO: {
"involverade karaktärer": { type: "Involverad i", toDocument: true },
"berörda karaktärer": { type: "Berörd av", toDocument: true },
},
CHARACTER: { "anställd hos": { type: "Jobbar på", toDocument: false } },
PET: { ägare: { type: "Husdjur till", toDocument: false } },
};
/** Etiketter i dokumenten som avser ett fält med annat namn i mallen. */
const ALIASES: Partial<Record<ImportKind, Record<string, string>>> = { SCENARIO: { kopplat: "linkedEntity" } };
export function fieldsFor(kind: ImportKind, templates?: Partial<Record<ImportKind, FieldDef[]>>): FieldDef[] {
return templates?.[kind] ?? getDefaultTemplate(kind, "sv");
}
/** Scheman och kartregistret går inte att importera här, de har egna sidor. */
function unsupportedDocument(extracted: Extracted): boolean {
const first = extracted.registers.map((r) => normLabel(r.header[0] ?? ""));
return first.some((h) => h === "schema" || h === "kart" || h === "tid") || extracted.texts.some((t) => /^schema\b/i.test(t));
}
/** Gissar vilken sorts dokument det är: först efter dokumentets eget ID-fält, annars efter hur många etiketter som passar. */
export function detectKind(extracted: Extracted, filename: string, templates?: Partial<Record<ImportKind, FieldDef[]>>): ImportKind | null {
if (unsupportedDocument(extracted)) return null;
const allLabels = [...extracted.labels, ...extracted.registers.flatMap((r) => r.header)];
for (const label of allLabels) {
const kind = KIND_BY_LABEL[normLabel(label)];
// "Lokal ID" är ett eget ID i en lokalmall men en koppling i en företagsmall, så de mer unika etiketterna prövas först
if (kind && kind !== "PREMISES") return kind;
}
const text = [filename, ...extracted.texts, ...extracted.labels].join(" ").toLowerCase();
if (/hemsid/.test(text)) return "WEBSITE";
if (/\bapp(ar|likation\w*)?\b|appregister/.test(text)) return "APP";
if (allLabels.some((l) => normLabel(l) === "lokal")) return "PREMISES";
let best: { kind: ImportKind; score: number } | null = null;
for (const kind of IMPORT_KINDS) {
const fields = fieldsFor(kind, templates);
const score = allLabels.filter((l) => fields.some((f) => labelsMatch(l, f.label))).length;
if (score > (best?.score ?? 0)) best = { kind, score };
}
return best?.kind ?? null;
}
// ─── Värden ─────────────────────────────────────────────────────────────────
const CODE_IN_TEXT = /\b[A-ZÅÄÖ]{1,4}-\d{2,6}\b/;
/** Hittar en post i boken utifrån text som "KI-0003", "Anna Lind" eller "Anna Lind KI-0003". */
export function findEntity(text: string, known: KnownEntity[], kind?: EntityKind): KnownEntity | null {
const pool = kind ? known.filter((e) => e.kind === kind) : known;
const code = CODE_IN_TEXT.exec(text)?.[0];
if (code) {
const byCode = pool.find((e) => e.code === code);
if (byCode) return byCode;
}
const name = text.replace(CODE_IN_TEXT, "").replace(/[()[\],;:]+/g, " ").replace(/\s+/g, " ").trim().toLowerCase();
if (!name) return null;
const matches = pool.filter((e) => e.name.toLowerCase() === name);
return matches.length === 1 ? matches[0] : null;
}
export type ItemLink = {
/** Vilken typ av relation som skapas */
type: string;
toDocument: boolean;
/** Posten i boken, eller null om den inte hittades */
entityId: string | null;
/** Det som stod i dokumentet */
text: string;
note: string;
};
export type ParsedItem = {
entityKind: ImportKind;
name: string;
code: string | null;
data: Record<string, unknown>;
/** Läsbar text för kopplingsfält, per fältnyckel */
display: Record<string, string>;
links: ItemLink[];
/** Det som stod i dokumentet men inte gick att placera i ett fält */
unmatched: Pair[];
};
type Context = { known: KnownEntity[]; fields: FieldDef[] };
/** Gör om ett värde ur dokumentet till rätt sort för fältet, eller null om det inte går. */
function convert(field: FieldDef, raw: string, ctx: Context): { value: unknown; display?: string } | null {
const text = raw.trim();
if (!text) return null;
switch (field.type) {
case "number": {
const n = Number(/-?\d+(?:[.,]\d+)?/.exec(text.replace(/\s/g, ""))?.[0]?.replace(",", "."));
return Number.isFinite(n) ? { value: n } : null;
}
case "date": {
const date = normalizeStoryDate(text) ?? normalizeStoryDate(/\d{4}(?:-\d{1,2}(?:-\d{1,2})?)?/.exec(text)?.[0]);
return date ? { value: date } : null;
}
case "checkbox": {
const yes = parseYesNo(text);
return yes === null ? null : { value: yes };
}
case "select": {
const option = pickOption(text, field.options ?? []);
return option ? { value: option } : null;
}
case "url":
return /^https?:\/\/\S+$/i.test(text) ? { value: text } : null;
case "reference": {
const entity = findEntity(text, ctx.known, field.refKind);
return entity ? { value: entity.id, display: entity.code ? `${entity.code} · ${entity.name}` : entity.name } : null;
}
default:
return { value: text };
}
}
/** Delar ett värde som "KI-0001, Anna" eller en lista med en post per rad i flera poster. */
function splitEntries(value: string): string[] {
return value
.split(/\n|;|,(?=\s*[A-ZÅÄÖ])/)
.map((s) => s.trim())
.filter(Boolean);
}
/** Tolkar etikett/värde-par till en post. */
export function buildItem(kind: ImportKind, pairs: Pair[], lists: ListBlock[], ctx: Context): ParsedItem {
const item: ParsedItem = { entityKind: kind, name: "", code: null, data: {}, display: {}, links: [], unmatched: [] };
const nameParts: { order: number; value: string }[] = [];
const nameLabels = NAME_LABELS[kind] ?? [];
const links = LINK_RULES[kind] ?? {};
const used = new Set<string>();
for (const pair of pairs) {
const norm = normLabel(pair.label);
const value = pair.value.trim();
if (!value) continue;
if (norm === CODE_LABEL[kind]) {
item.code = CODE_IN_TEXT.exec(value)?.[0] ?? null;
continue;
}
const nameIndex = nameLabels.findIndex((n) => normLabel(n) === norm);
if (nameIndex >= 0 || (GENERIC_NAME.includes(norm) && nameLabels.length === 0)) {
nameParts.push({ order: Math.max(nameIndex, 0), value });
// Märke och modell är dessutom ett vanligt fält i mallen
if (kind !== "VEHICLE") continue;
}
if (GENERIC_NAME.includes(norm) && nameLabels.length > 0 && nameIndex < 0 && kind !== "VEHICLE") {
nameParts.push({ order: 9, value });
continue;
}
const linkKey = Object.keys(links).find((k) => labelsMatch(k, pair.label));
if (linkKey && !links[linkKey].toDocument) {
for (const entry of splitEntries(value)) {
const entity = findEntity(entry, ctx.known);
item.links.push({ type: links[linkKey].type, toDocument: false, entityId: entity?.id ?? null, text: entry, note: "" });
}
continue;
}
// Ålder och födelsedatum står ihop i en etikett i karaktärsmallen
if (kind === "CHARACTER" && labelsMatch(pair.label, "ålderfödelsedatum")) {
const date = normalizeStoryDate(/\d{4}(?:-\d{1,2}(?:-\d{1,2})?)?/.exec(value)?.[0]);
const age = /^\d{1,3}$/.exec(value.trim())?.[0];
if (date && !used.has("birthDate")) {
item.data.birthDate = date;
used.add("birthDate");
continue;
}
if (age && !used.has("age")) {
item.data.age = Number(age);
used.add("age");
continue;
}
}
const alias = ALIASES[kind]?.[norm];
const free = ctx.fields.filter((f) => !used.has(f.key));
const loose = free.filter((f) => looseMatch(pair.label, f.label));
const field = free.find((f) => f.key === alias || labelsMatch(pair.label, f.label)) ?? (loose.length === 1 ? loose[0] : undefined);
const converted = field ? convert(field, value, ctx) : null;
if (field && converted) {
item.data[field.key] = converted.value;
if (converted.display) item.display[field.key] = converted.display;
used.add(field.key);
} else {
item.unmatched.push({ label: pair.label.trim(), value });
}
}
item.name = nameParts.sort((a, b) => a.order - b.order).map((p) => p.value).join(" ").trim();
for (const list of lists) {
const key = Object.keys(links).find((k) => labelsMatch(k, list.heading));
if (!key) {
for (const e of list.entries) item.unmatched.push({ label: list.heading || "Lista", value: [e.name, e.code].filter(Boolean).join(" ") });
continue;
}
for (const entry of list.entries) {
const text = [entry.name, entry.code].filter(Boolean).join(" ");
if (!text) continue;
const entity = findEntity(entry.code || "", ctx.known) ?? findEntity(text, ctx.known);
item.links.push({
type: links[key].type,
toDocument: links[key].toDocument,
entityId: entity?.id ?? null,
text,
note: [entry.role, entry.subject].filter(Boolean).join(", "),
});
}
}
return item;
}
export function usableCode(kind: EntityKind, code: string | null): string | null {
const prefix = ENTITY_PREFIX[kind];
return code && prefix && new RegExp(`^${prefix}-\\d+$`).test(code) ? code : null;
}
// ─── Hela dokument ──────────────────────────────────────────────────────────
export type ParsedDocument = {
file: string;
kind: ImportKind | null;
items: ParsedItem[];
/** För en relation: deltagarna, med postens id eller null om den inte hittades */
relation: null | { type: string; participants: { entityId: string | null; text: string }[] };
warnings: string[];
};
const baseName = (file: string) => file.replace(/\.[^.]+$/, "").trim();
/** Fördelar paren i ett appregister (upprepade Namn/Beskrivning) på en post per app. */
function groupByName(pairs: Pair[]): Pair[][] {
const groups: Pair[][] = [];
for (const pair of pairs) {
if (normLabel(pair.label) === "namn" || groups.length === 0) groups.push([]);
groups[groups.length - 1].push(pair);
}
return groups.filter((g) => g.some((p) => normLabel(p.label) === "namn"));
}
function fallbackName(kind: ImportKind, item: ParsedItem, file: string): string {
if (item.name) return item.name;
const address = typeof item.data.address === "string" ? item.data.address : "";
const description = typeof item.data.description === "string" ? item.data.description : "";
const type = ["homeType", "scenarioType"].map((k) => item.data[k]).find((v) => typeof v === "string") as string | undefined;
const typed = [type, item.code].filter(Boolean).join(" ");
// Ett scenario heter efter typ och ID, referenser och research efter sin beskrivning
const candidates = kind === "SCENARIO" ? [typed, address, description.slice(0, 60)] : [address, description.slice(0, 60), typed];
return (candidates.find(Boolean) || item.code || baseName(file) || kind).slice(0, 200);
}
export function analyzeDocument(
blocks: DocBlock[],
file: string,
known: KnownEntity[],
options: { kind?: ImportKind | null; templates?: Partial<Record<ImportKind, FieldDef[]>> } = {},
): ParsedDocument {
const templates = options.templates;
const knownLabel = (label: string) =>
IMPORT_KINDS.some((k) => fieldsFor(k, templates).some((f) => labelsMatch(label, f.label))) ||
Object.values(CODE_LABEL).some((c) => normLabel(label) === c) ||
labelsMatch(label, "ålderfödelsedatum");
const extracted = extract(blocks, knownLabel);
const kind = options.kind ?? detectKind(extracted, file, templates);
const result: ParsedDocument = { file, kind, items: [], relation: null, warnings: [] };
if (!kind) {
result.warnings.push(unsupportedDocument(extracted) ? "unsupported" : "unknown-kind");
return result;
}
const ctx: Context = { known, fields: fieldsFor(kind, templates) };
if (kind === "RELATION") {
const item = buildItem(kind, extracted.pairs, [], ctx);
const list = extracted.lists.find((l) => /ingår/.test(normLabel(l.heading))) ?? extracted.lists[0];
const participants = (list?.entries ?? [])
.filter((e) => e.name || e.code)
.map((e) => ({ text: [e.name, e.code].filter(Boolean).join(" "), entityId: (findEntity(e.code, known) ?? findEntity(e.name, known, "CHARACTER"))?.id ?? null }));
const category = typeof item.data.category === "string" ? item.data.category : "";
result.relation = { type: category || "Relation", participants };
item.name = result.relation.type;
result.items.push(item);
if (participants.length < 2) result.warnings.push("few-participants");
return result;
}
if (extracted.registers.length > 0) {
for (const table of extracted.registers) {
for (const row of table.rows) {
const pairs = table.header.map((label, i) => ({ label, value: row[i] ?? "" })).filter((p) => p.value.trim());
// Kolumnen med registrets eget ID heter t.ex. "Fordons ID"
const item = buildItem(kind, pairs, [], ctx);
item.name = fallbackName(kind, item, file);
result.items.push(item);
}
}
if (result.items.length === 0) result.warnings.push("empty");
return result;
}
if (kind === "APP" || kind === "WEBSITE") {
for (const group of groupByName(extracted.pairs)) {
const item = buildItem(kind, group, [], ctx);
item.name = fallbackName(kind, item, file);
result.items.push(item);
}
if (result.items.length === 0) result.warnings.push("empty");
return result;
}
const item = buildItem(kind, extracted.pairs, extracted.lists, ctx);
item.name = fallbackName(kind, item, file);
if (Object.keys(item.data).length === 0 && !item.name && item.links.length === 0) result.warnings.push("empty");
result.items.push(item);
return result;
}
/** Fält som tar emot det som inte gick att placera: Övrigt eller Beskrivning, annars ingenting. */
export function overflowField(fields: FieldDef[]): string | null {
return (fields.find((f) => f.key === "notes") ?? fields.find((f) => f.key === "description"))?.key ?? null;
}
export function describeUnmatched(unmatched: Pair[]): string {
return unmatched.map((p) => `${p.label}: ${p.value}`).join("\n");
}
export { markedOption, parseOptions };
+138
View File
@@ -0,0 +1,138 @@
// Etiketter i Word-mallarna: jämförelse mellan etiketter, och val i rutor som "Ja: X Nej:".
/** Gör en etikett jämförbar: små bokstäver, utan parenteser (mallens hjälptexter), skiljetecken och ID-ord. */
export function normLabel(text: string): string {
return text
.toLowerCase()
.replace(/\([^)]*\)/g, " ")
.replace(/[-–—_/.,:;?!"']/g, " ")
.split(/\s+/)
.filter((w) => w && w !== "id" && w !== "nr")
.join(" ")
.trim();
}
const compact = (s: string) => s.replace(/\s+/g, "");
/**
* Är två etiketter samma sak? Orden får stå i annan ordning, mellanslag och bindestreck spelar ingen roll
* ("Djur kategori" och "Djurkategori"), och en skrivfel-ändelse på upp till två tecken godtas ("Längde" och "Längd").
*/
export function labelsMatch(a: string, b: string): boolean {
const x = normLabel(a);
const y = normLabel(b);
if (!x || !y) return false;
if (x === y || compact(x) === compact(y)) return true;
if ([...x.split(" ")].sort().join(" ") === [...y.split(" ")].sort().join(" ")) return true;
const [short, long] = compact(x).length <= compact(y).length ? [compact(x), compact(y)] : [compact(y), compact(x)];
return short.length >= 4 && long.startsWith(short) && long.length - short.length <= 2;
}
const STOP = new Set(["i", "och", "eller", "om", "av", "på", "till", "för", "att", "med", "mer", "är", "den", "det", "hur", "en", "ett", "som", "att", "beskriv"]);
/**
* Lösare jämförelse för etiketter som skrivits längre eller på annat sätt än i mallen, t.ex. "Djurets personlighet" mot
* "Personlighet". Alla betydelsebärande ord i fältets etikett ska finnas i dokumentets, och minst ett ord ska vara långt.
*/
export function looseMatch(docLabel: string, fieldLabel: string): boolean {
const words = (s: string) => normLabel(s).split(" ").filter((w) => w && !STOP.has(w));
const wanted = words(fieldLabel);
const have = words(docLabel);
if (wanted.length === 0 || have.length === 0 || !wanted.some((w) => w.length >= 5)) return false;
const joined = have.join("");
return wanted.every((w) => have.some((h) => h.startsWith(w) || w.startsWith(h)) || (w.length >= 4 && joined.includes(w)));
}
// ─── Val i rutor ("Ja: X Nej:") ─────────────────────────────────────────────
export type MarkedOption = { label: string; marked: boolean };
const AFTER_MARK = /^(?:x|✓|✔|☒|☑|■)(?=\s|$)\s*/i;
const BEFORE_MARK = /^(?:✓|✔|☒|☑|■)\s*/;
const UNCHECKED = /^☐\s*/;
/** Är texten en lista med alternativ, till exempel "Ja: Nej:"? Parenteser (hjälptexter) räknas inte. */
export function isOptionList(text: string): boolean {
const stripped = text.replace(/\([^)]*\)/g, " ");
if (stripped.length > 300) return false;
const lines = stripped.split("\n").map((l) => l.trim()).filter(Boolean);
if (lines.length === 0 || !singleLineOptions(lines[0])) return false;
// Alternativen kan fortsätta på nästa rad: en ny rad med alternativ, eller ett enstaka kort alternativ ("Blivande:")
return lines.slice(1).every((line) => singleLineOptions(line) || /^[^\s:]{1,15}:\s*(?:x|✓|✔|☒|☑|■)?$/i.test(line));
}
/** Minst två alternativ med text på en rad, och varje del mellan kolon ska vara kort: alternativ, inte meningar. */
function singleLineOptions(line: string): boolean {
const parts = line.split(":");
if (parts.slice(0, -1).filter((part) => part.trim()).length < 2) return false;
return parts.every((part) => part.trim().length <= 40);
}
/**
* Läser en rad med alternativ och vilka som är markerade. Ett alternativ är markerat om det har ett kryss efter sig
* ("Ja: X Nej:") eller en ruta med kryss före sig ("☒ Ja: ☐ Nej:"). Returnerar null om texten inte är en alternativlista.
*/
export function parseOptions(text: string): MarkedOption[] | null {
if (!isOptionList(text)) return null;
const parts = text.replace(/\([^)]*\)/g, " ").replace(/\s*\n\s*/g, " ").split(":");
const options: MarkedOption[] = [];
parts.forEach((part, index) => {
let rest = part.trim();
// Kryss efter föregående alternativ
if (index > 0 && options.length > 0) {
const after = AFTER_MARK.exec(rest);
if (after) {
options[options.length - 1].marked = true;
rest = rest.slice(after[0].length).trim();
}
}
if (index === parts.length - 1) return; // texten efter sista kolonet är bara ett eventuellt kryss
let marked = false;
const before = BEFORE_MARK.exec(rest) ?? (index === 0 ? AFTER_MARK.exec(rest) : null);
if (before) {
marked = true;
rest = rest.slice(before[0].length).trim();
} else {
const unchecked = UNCHECKED.exec(rest);
if (unchecked) rest = rest.slice(unchecked[0].length).trim();
}
if (rest) options.push({ label: rest, marked });
});
return options.length >= 2 ? options : null;
}
/** Det markerade alternativet, eller null om inget (eller flera) är markerat. */
export function markedOption(options: MarkedOption[]): string | null {
const marked = options.filter((o) => o.marked);
return marked.length === 1 ? marked[0].label : null;
}
const YES = new Set(["ja", "yes", "x", "✓", "✔", "☒", "☑", "sant", "true"]);
const NO = new Set(["nej", "no", "falskt", "false"]);
/** Tolkar ett ja/nej-värde, eller null om det inte går att avgöra. */
export function parseYesNo(raw: string): boolean | null {
const options = parseOptions(raw);
const text = (options ? markedOption(options) : raw.trim())?.toLowerCase().replace(/[.!]+$/, "") ?? "";
if (YES.has(text)) return true;
if (NO.has(text)) return false;
return null;
}
/** Hittar det alternativ i `options` som texten avser (samma ord, eller samma början), eller null. */
export function pickOption(raw: string, options: string[]): string | null {
const parsed = parseOptions(raw);
const text = (parsed ? markedOption(parsed) : raw.trim()) ?? "";
if (!text) return null;
const wanted = normLabel(text);
if (!wanted) return null;
const exact = options.find((o) => normLabel(o) === wanted);
if (exact) return exact;
const prefix = options.find((o) => {
const n = normLabel(o);
const [short, long] = n.length <= wanted.length ? [n, wanted] : [wanted, n];
return short.length >= 3 && long.startsWith(short);
});
return prefix ?? null;
}