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

+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;
}