diff --git a/src/app/books/[bookId]/settings/page.tsx b/src/app/books/[bookId]/settings/page.tsx
index 6419443..4d779b8 100644
--- a/src/app/books/[bookId]/settings/page.tsx
+++ b/src/app/books/[bookId]/settings/page.tsx
@@ -52,10 +52,16 @@ export default async function SettingsPage({ params }: { params: Promise<{ bookI
diff --git a/src/i18n/en.ts b/src/i18n/en.ts
index 73ef045..8eddeda 100644
--- a/src/i18n/en.ts
+++ b/src/i18n/en.ts
@@ -314,6 +314,18 @@ export const en: Record = {
"settings.danger": "Danger zone",
"settings.deleteBook": "Delete book",
"settings.deleteBookHelp": "Permanently deletes the book and all its content. Export first if you want a copy.",
- "settings.export": "Export as JSON",
- "settings.exportHelp": "Downloads all items, relationships, schedules, maps and templates in the book.",
+ "settings.export": "Export with images (.zip)",
+ "settings.exportJson": "Export data only (.json)",
+ "import.title": "Import book",
+ "import.help": "Choose an export file (.zip or .json). The book is imported as a new book with new internal IDs, nothing is overwritten.",
+ "import.button": "Import",
+ "import.failed": "The import failed: {reason}",
+ "import.error.not-export": "the file is not an export from Story Planner",
+ "import.error.version": "the export file version is not supported",
+ "import.error.too-large": "the file is too large",
+ "import.error.empty": "no file was chosen or the file is empty",
+ "import.error.invalid": "the file is damaged or has the wrong format",
+ "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.",
};
diff --git a/src/i18n/sv.ts b/src/i18n/sv.ts
index bc370dd..fc39c05 100644
--- a/src/i18n/sv.ts
+++ b/src/i18n/sv.ts
@@ -312,6 +312,18 @@ export const sv = {
"settings.danger": "Farlig zon",
"settings.deleteBook": "Ta bort boken",
"settings.deleteBookHelp": "Raderar boken och allt innehåll permanent. Exportera först om du vill spara en kopia.",
- "settings.export": "Exportera som JSON",
- "settings.exportHelp": "Laddar ner alla poster, relationer, scheman, kartor och mallar i boken.",
+ "settings.export": "Exportera med bilder (.zip)",
+ "settings.exportJson": "Exportera bara data (.json)",
+ "import.title": "Importera bok",
+ "import.help": "Välj en exportfil (.zip eller .json). Boken importeras som en ny bok med nya ID-nummer i systemet, ingenting skrivs över.",
+ "import.button": "Importera",
+ "import.failed": "Importen misslyckades: {reason}",
+ "import.error.not-export": "filen är inte en exportfil från Bokplanerare",
+ "import.error.version": "exportfilens version stöds inte",
+ "import.error.too-large": "filen är för stor",
+ "import.error.empty": "ingen fil valdes eller filen är tom",
+ "import.error.invalid": "filen är skadad eller har fel format",
+ "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.",
} as const;
diff --git a/src/lib/book-transfer.ts b/src/lib/book-transfer.ts
new file mode 100644
index 0000000..9c1eba7
--- /dev/null
+++ b/src/lib/book-transfer.ts
@@ -0,0 +1,614 @@
+import { randomUUID } from "node:crypto";
+import { strFromU8, unzipSync } from "fflate";
+import type { EntityKind, Prisma, WeekPattern } from "@prisma/client";
+import { prisma } from "./db";
+import { deleteImage, readImageBytes, saveImageBytes } from "./files";
+import { ENTITY_PREFIX, MAP_PREFIX, MARKER_PREFIX, RELATION_PREFIX, SCHEDULE_PREFIX, mapLetter, pad } from "./ids";
+import { MARKER_COLORS, parseKind, parseTemplateKind } from "./kinds";
+import { validateFields, type FieldDef } from "./templates";
+
+// Export och import av en hel bok. Filen är en zip med book.json och bilderna i files/,
+// eller bara JSON utan bilder. Import skapar alltid en ny bok med nya id och skriver aldrig över något.
+
+export const EXPORT_FORMAT = "bookmanager-export";
+export const EXPORT_VERSION = 1;
+export const MAX_IMPORT_BYTES = 300 * 1024 * 1024;
+const MAX_FILE_BYTES = 16 * 1024 * 1024;
+const MAX_ITEMS = 20000;
+
+export type ImportErrorCode = "not-export" | "version" | "too-large" | "empty" | "invalid";
+export const IMPORT_ERROR_CODES: ImportErrorCode[] = ["not-export", "version", "too-large", "empty", "invalid"];
+
+export class ImportError extends Error {
+ constructor(
+ public code: ImportErrorCode,
+ public detail = "",
+ ) {
+ super(`${code}${detail ? `: ${detail}` : ""}`);
+ }
+}
+
+type Json = Prisma.InputJsonValue;
+
+export type ExportData = {
+ format: typeof EXPORT_FORMAT;
+ version: number;
+ exportedAt: string;
+ includesImages: boolean;
+ book: { title: string; subtitle: string | null; genre: string | null; description: string | null };
+ entities: {
+ id: string;
+ kind: EntityKind;
+ name: string;
+ code: string | null;
+ summary: string | null;
+ tags: string[];
+ data: Record;
+ image: string | null;
+ }[];
+ relations: {
+ id: string;
+ code: string | null;
+ fromId: string;
+ toId: string;
+ type: string;
+ description: string | null;
+ data: Record;
+ members: string[];
+ }[];
+ shifts: {
+ personId: string;
+ workplaceId: string | null;
+ weekday: number;
+ startTime: string;
+ endTime: string;
+ weeks: WeekPattern;
+ label: string | null;
+ scheduleCode: string | null;
+ }[];
+ maps: {
+ id: string;
+ code: string | null;
+ name: string;
+ kind: "GEO" | "IMAGE";
+ image: string | null;
+ centerLat: number | null;
+ centerLng: number | null;
+ zoom: number | null;
+ markers: {
+ code: string | null;
+ entityId: string | null;
+ label: string;
+ note: string | null;
+ color: string;
+ lat: number;
+ lng: number;
+ }[];
+ }[];
+ templates: { kind: string; fields: FieldDef[] }[];
+};
+
+// ─── Export ─────────────────────────────────────────────────────────────────
+
+export async function buildExport(bookId: string, withImages: boolean) {
+ const book = await prisma.book.findUniqueOrThrow({
+ where: { id: bookId },
+ include: {
+ entities: { orderBy: { createdAt: "asc" } },
+ relations: { orderBy: { createdAt: "asc" }, include: { members: true } },
+ shifts: { orderBy: { createdAt: "asc" } },
+ maps: { orderBy: { createdAt: "asc" }, include: { markers: { orderBy: { createdAt: "asc" } } } },
+ templates: true,
+ },
+ });
+
+ const files = new Map();
+ const image = async (name: string | null): Promise => {
+ if (!withImages || !name) return null;
+ const bytes = await readImageBytes(name);
+ if (!bytes) return null;
+ files.set(name, bytes);
+ return name;
+ };
+
+ const entities: ExportData["entities"] = [];
+ for (const e of book.entities) {
+ entities.push({
+ id: e.id,
+ kind: e.kind,
+ name: e.name,
+ code: e.code,
+ summary: e.summary,
+ tags: e.tags,
+ data: (e.data ?? {}) as Record,
+ image: await image(e.imageFile),
+ });
+ }
+
+ const maps: ExportData["maps"] = [];
+ for (const m of book.maps) {
+ maps.push({
+ id: m.id,
+ code: m.code,
+ name: m.name,
+ kind: m.kind,
+ image: await image(m.imageFile),
+ centerLat: m.centerLat,
+ centerLng: m.centerLng,
+ zoom: m.zoom,
+ markers: m.markers.map((k) => ({
+ code: k.code,
+ entityId: k.entityId,
+ label: k.label,
+ note: k.note,
+ color: k.color,
+ lat: k.lat,
+ lng: k.lng,
+ })),
+ });
+ }
+
+ const data: ExportData = {
+ format: EXPORT_FORMAT,
+ version: EXPORT_VERSION,
+ exportedAt: new Date().toISOString(),
+ includesImages: withImages,
+ book: { title: book.title, subtitle: book.subtitle, genre: book.genre, description: book.description },
+ entities,
+ relations: book.relations.map((r) => ({
+ id: r.id,
+ code: r.code,
+ fromId: r.fromId,
+ toId: r.toId,
+ type: r.type,
+ description: r.description,
+ data: (r.data ?? {}) as Record,
+ members: r.members.map((m) => m.entityId),
+ })),
+ shifts: book.shifts.map((s) => ({
+ personId: s.personId,
+ workplaceId: s.workplaceId,
+ weekday: s.weekday,
+ startTime: s.startTime,
+ endTime: s.endTime,
+ weeks: s.weeks,
+ label: s.label,
+ scheduleCode: s.scheduleCode,
+ })),
+ maps,
+ templates: book.templates.map((t) => ({ kind: t.kind, fields: t.fields as unknown as FieldDef[] })),
+ };
+ return { data, files };
+}
+
+// ─── Läsa och kontrollera en importfil ──────────────────────────────────────
+
+const isObj = (v: unknown): v is Record => typeof v === "object" && v !== null && !Array.isArray(v);
+
+function text(v: unknown, max: number): string | null {
+ if (typeof v !== "string") return null;
+ const t = v.trim().slice(0, max);
+ return t || null;
+}
+
+function required(v: unknown, max: number, what: string): string {
+ const t = text(v, max);
+ if (!t) throw new ImportError("invalid", what);
+ return t;
+}
+
+function finite(v: unknown): number | null {
+ return typeof v === "number" && Number.isFinite(v) ? v : null;
+}
+
+function list(v: unknown, what: string): unknown[] {
+ if (v === undefined || v === null) return [];
+ if (!Array.isArray(v)) throw new ImportError("invalid", what);
+ if (v.length > MAX_ITEMS) throw new ImportError("too-large", what);
+ return v;
+}
+
+function object(v: unknown): Record {
+ return isObj(v) ? (v as Record) : {};
+}
+
+export function parseExport(raw: unknown): ExportData {
+ if (!isObj(raw) || raw.format !== EXPORT_FORMAT) throw new ImportError("not-export");
+ if (raw.version !== EXPORT_VERSION) throw new ImportError("version", String(raw.version));
+ const book = isObj(raw.book) ? raw.book : {};
+
+ const entities = list(raw.entities, "entities").map((item, i): ExportData["entities"][number] => {
+ if (!isObj(item)) throw new ImportError("invalid", `entities[${i}]`);
+ const kind = parseKind(item.kind);
+ if (!kind) throw new ImportError("invalid", `entities[${i}].kind`);
+ return {
+ id: required(item.id, 100, `entities[${i}].id`),
+ kind,
+ name: required(item.name, 200, `entities[${i}].name`),
+ code: text(item.code, 50),
+ summary: text(item.summary, 20000),
+ tags: Array.isArray(item.tags) ? item.tags.map((t) => text(t, 40)).filter((t): t is string => !!t).slice(0, 30) : [],
+ data: object(item.data),
+ image: text(item.image, 120),
+ };
+ });
+
+ const relations = list(raw.relations, "relations").map((item, i): ExportData["relations"][number] => {
+ if (!isObj(item)) throw new ImportError("invalid", `relations[${i}]`);
+ return {
+ id: text(item.id, 100) ?? randomUUID(),
+ code: text(item.code, 50),
+ fromId: required(item.fromId, 100, `relations[${i}].fromId`),
+ toId: required(item.toId, 100, `relations[${i}].toId`),
+ type: required(item.type, 100, `relations[${i}].type`),
+ description: text(item.description, 2000),
+ data: object(item.data),
+ members: Array.isArray(item.members) ? item.members.map((m) => text(m, 100)).filter((m): m is string => !!m) : [],
+ };
+ });
+
+ const shifts = list(raw.shifts, "shifts").map((item, i): ExportData["shifts"][number] => {
+ if (!isObj(item)) throw new ImportError("invalid", `shifts[${i}]`);
+ const weekday = finite(item.weekday);
+ const time = /^([01]\d|2[0-3]):[0-5]\d$/;
+ const start = text(item.startTime, 5);
+ const end = text(item.endTime, 5);
+ if (weekday === null || !Number.isInteger(weekday) || weekday < 0 || weekday > 6 || !start || !end || !time.test(start) || !time.test(end)) {
+ throw new ImportError("invalid", `shifts[${i}]`);
+ }
+ return {
+ personId: required(item.personId, 100, `shifts[${i}].personId`),
+ workplaceId: text(item.workplaceId, 100),
+ weekday,
+ startTime: start,
+ endTime: end,
+ weeks: item.weeks === "ODD" || item.weeks === "EVEN" ? item.weeks : "ALL",
+ label: text(item.label, 100),
+ scheduleCode: text(item.scheduleCode, 50),
+ };
+ });
+
+ const maps = list(raw.maps, "maps").map((item, i): ExportData["maps"][number] => {
+ if (!isObj(item)) throw new ImportError("invalid", `maps[${i}]`);
+ const markers = list(item.markers, `maps[${i}].markers`).map((m, j) => {
+ if (!isObj(m)) throw new ImportError("invalid", `maps[${i}].markers[${j}]`);
+ const lat = finite(m.lat);
+ const lng = finite(m.lng);
+ if (lat === null || lng === null) throw new ImportError("invalid", `maps[${i}].markers[${j}] position`);
+ return {
+ code: text(m.code, 50),
+ entityId: text(m.entityId, 100),
+ label: required(m.label, 200, `maps[${i}].markers[${j}].label`),
+ note: text(m.note, 5000),
+ color: typeof m.color === "string" && m.color in MARKER_COLORS ? m.color : "blue",
+ lat,
+ lng,
+ };
+ });
+ return {
+ id: text(item.id, 100) ?? randomUUID(),
+ code: text(item.code, 50),
+ name: required(item.name, 200, `maps[${i}].name`),
+ kind: item.kind === "IMAGE" ? "IMAGE" : "GEO",
+ image: text(item.image, 120),
+ centerLat: finite(item.centerLat),
+ centerLng: finite(item.centerLng),
+ zoom: finite(item.zoom) === null ? null : Math.round(item.zoom as number),
+ markers,
+ };
+ });
+
+ const templates = list(raw.templates, "templates").flatMap((item): ExportData["templates"] => {
+ if (!isObj(item)) return [];
+ const kind = parseTemplateKind(item.kind);
+ if (!kind) return [];
+ try {
+ return [{ kind, fields: validateFields(item.fields) }];
+ } catch {
+ return []; // trasig mall: boken får standardmallen
+ }
+ });
+
+ return {
+ format: EXPORT_FORMAT,
+ version: EXPORT_VERSION,
+ exportedAt: text(raw.exportedAt, 40) ?? "",
+ includesImages: raw.includesImages === true,
+ book: {
+ title: required(book.title, 200, "book.title"),
+ subtitle: text(book.subtitle, 200),
+ genre: text(book.genre, 100),
+ description: text(book.description, 20000),
+ },
+ entities,
+ relations,
+ shifts,
+ maps,
+ templates,
+ };
+}
+
+/** Läser en uppladdad fil: zip (book.json + files/) eller ren JSON. */
+export function readImportFile(bytes: Uint8Array): { data: ExportData; files: Map } {
+ if (bytes.length === 0) throw new ImportError("empty");
+ if (bytes.length > MAX_IMPORT_BYTES) throw new ImportError("too-large");
+
+ const isZip = bytes[0] === 0x50 && bytes[1] === 0x4b;
+ const files = new Map();
+ let json: string;
+
+ if (isZip) {
+ let total = 0;
+ let count = 0;
+ let entries: Record;
+ try {
+ entries = unzipSync(bytes, {
+ // Bara book.json och bilder under files/ packas upp, med gränser mot zip-bomber
+ filter: (file) => {
+ const wanted = file.name === "book.json" || (file.name.startsWith("files/") && !file.name.slice(6).includes("/"));
+ if (!wanted || file.originalSize > MAX_FILE_BYTES || ++count > MAX_ITEMS) return false;
+ total += file.originalSize;
+ return total <= MAX_IMPORT_BYTES;
+ },
+ });
+ } catch {
+ throw new ImportError("invalid", "zip");
+ }
+ const book = entries["book.json"];
+ if (!book) throw new ImportError("not-export");
+ json = strFromU8(book);
+ for (const [name, data] of Object.entries(entries)) if (name.startsWith("files/")) files.set(name.slice(6), data);
+ } else {
+ json = new TextDecoder().decode(bytes);
+ }
+
+ let raw: unknown;
+ try {
+ raw = JSON.parse(json.replace(/^/, ""));
+ } catch {
+ throw new ImportError("invalid", "json");
+ }
+ return { data: parseExport(raw), files };
+}
+
+// ─── Import ─────────────────────────────────────────────────────────────────
+
+export type ImportResult = {
+ bookId: string;
+ entities: number;
+ relations: number;
+ maps: number;
+ markers: number;
+ shifts: number;
+ skippedImages: number;
+ skippedLinks: number;
+};
+
+type Coder = { key: string; parse: (code: string) => number | null; format: (n: number) => string };
+
+const escape = (s: string) => s.replace(/[.*+?^${}()|[\]\\]/g, "\\$&");
+
+function simpleCoder(prefix: string): Coder {
+ const re = new RegExp(`^${escape(prefix)}-(\\d+)$`);
+ return { key: prefix, parse: (c) => (re.test(c) ? Number(c.match(re)![1]) : null), format: (n) => `${prefix}-${pad(n)}` };
+}
+
+function mapCoder(kind: "GEO" | "IMAGE"): Coder {
+ const key = `${MAP_PREFIX}-${mapLetter(kind)}`;
+ const re = new RegExp(`^${escape(key)}_(\\d+)$`);
+ return { key, parse: (c) => (re.test(c) ? Number(c.match(re)![1]) : null), format: (n) => `${key}_${pad(n)}` };
+}
+
+/**
+ * Behåller giltiga och unika ID från filen och ger nya löpande ID åt resten.
+ * Räknarna (counters) hamnar efter det högsta numret, så nya poster fortsätter därifrån.
+ */
+function assignCodes(items: T[], coderOf: (item: T) => Coder | null, counters: Map) {
+ const used = new Set();
+ const missing: { item: T; coder: Coder }[] = [];
+ for (const item of items) {
+ const coder = coderOf(item);
+ if (!coder) {
+ item.code = null;
+ continue;
+ }
+ const n = item.code ? coder.parse(item.code) : null;
+ if (n !== null && item.code && !used.has(item.code)) {
+ used.add(item.code);
+ counters.set(coder.key, Math.max(counters.get(coder.key) ?? 0, n));
+ } else {
+ missing.push({ item, coder });
+ }
+ }
+ for (const { item, coder } of missing) {
+ const n = (counters.get(coder.key) ?? 0) + 1;
+ counters.set(coder.key, n);
+ item.code = coder.format(n);
+ }
+}
+
+function remapIds(value: Json, ids: Map): Json {
+ if (typeof value === "string") return ids.get(value) ?? value;
+ if (Array.isArray(value)) return value.map((v) => remapIds(v as Json, ids));
+ if (isObj(value)) return Object.fromEntries(Object.entries(value).map(([k, v]) => [k, remapIds(v as Json, ids)]));
+ return value;
+}
+
+export async function importBook(ownerId: string, data: ExportData, files: Map): Promise {
+ const bookId = randomUUID();
+ const entityIds = new Map(data.entities.map((e) => [e.id, randomUUID()]));
+ let skippedImages = 0;
+ let skippedLinks = 0;
+ const savedImages: string[] = [];
+
+ const saveImage = async (name: string | null): Promise => {
+ if (!name) return null;
+ const bytes = files.get(name);
+ const saved = bytes ? await saveImageBytes(bytes) : null;
+ if (!saved) {
+ skippedImages++;
+ return null;
+ }
+ savedImages.push(saved);
+ return saved;
+ };
+
+ try {
+ // Samma namn som en befintlig bok får ett tillägg så att de går att skilja åt
+ const existingTitles = new Set((await prisma.book.findMany({ where: { ownerId }, select: { title: true } })).map((b) => b.title));
+ const title = existingTitles.has(data.book.title) ? `${data.book.title} (import)` : data.book.title;
+
+ const counters = new Map();
+
+ const entities = data.entities.map((e) => ({ ...e }));
+ assignCodes(entities, (e) => (ENTITY_PREFIX[e.kind] ? simpleCoder(ENTITY_PREFIX[e.kind]!) : null), counters);
+
+ const relationsIn = data.relations.filter((r) => {
+ const ok = entityIds.has(r.fromId) && entityIds.has(r.toId) && r.fromId !== r.toId;
+ if (!ok) skippedLinks++;
+ return ok;
+ });
+ const relations = relationsIn.map((r) => ({ ...r }));
+ assignCodes(relations, () => simpleCoder(RELATION_PREFIX), counters);
+
+ const maps = data.maps.map((m) => ({ ...m, markers: m.markers.map((k) => ({ ...k })) }));
+ assignCodes(maps, (m) => mapCoder(m.kind), counters);
+ const markers = maps.flatMap((m) => m.markers);
+ assignCodes(markers, () => simpleCoder(MARKER_PREFIX), counters);
+
+ // Ett schema-ID per person och arbetsplats
+ const shiftsIn = data.shifts.filter((s) => {
+ const ok = entityIds.has(s.personId);
+ if (!ok) skippedLinks++;
+ return ok;
+ });
+ const groups = new Map();
+ for (const s of shiftsIn) {
+ const key = `${s.personId}|${s.workplaceId && entityIds.has(s.workplaceId) ? s.workplaceId : ""}`;
+ const group = groups.get(key) ?? { code: s.scheduleCode, shifts: [] };
+ group.shifts.push(s);
+ groups.set(key, group);
+ }
+ const groupList = [...groups.values()];
+ assignCodes(groupList, () => simpleCoder(SCHEDULE_PREFIX), counters);
+
+ // Bilderna sparas före databasen, och tas bort igen om importen misslyckas
+ const entityImages = new Map();
+ for (const e of entities) entityImages.set(e.id, await saveImage(e.image));
+ const mapImages = new Map();
+ for (const m of maps) mapImages.set(m.id, await saveImage(m.image));
+
+ const sid = (id: string) => entityIds.get(id)!;
+
+ await prisma.$transaction(
+ async (tx) => {
+ await tx.book.create({
+ data: { id: bookId, ownerId, title, subtitle: data.book.subtitle, genre: data.book.genre, description: data.book.description },
+ });
+ await tx.entity.createMany({
+ data: entities.map((e) => ({
+ id: sid(e.id),
+ bookId,
+ kind: e.kind,
+ name: e.name,
+ code: e.code,
+ summary: e.summary,
+ tags: e.tags,
+ data: remapIds(e.data, entityIds) as Prisma.InputJsonObject,
+ imageFile: entityImages.get(e.id) ?? null,
+ })),
+ });
+
+ const relationRows = relations.map((r) => ({ ...r, newId: randomUUID() }));
+ await tx.relation.createMany({
+ data: relationRows.map((r) => ({
+ id: r.newId,
+ bookId,
+ code: r.code,
+ fromId: sid(r.fromId),
+ toId: sid(r.toId),
+ type: r.type,
+ description: r.description,
+ data: remapIds(r.data, entityIds) as Prisma.InputJsonObject,
+ })),
+ });
+ await tx.relationMember.createMany({
+ data: relationRows.flatMap((r) =>
+ [...new Set(r.members)]
+ .filter((m) => entityIds.has(m) && m !== r.fromId && m !== r.toId)
+ .map((m) => ({ relationId: r.newId, entityId: sid(m) })),
+ ),
+ });
+
+ await tx.shift.createMany({
+ data: groupList.flatMap((g) =>
+ g.shifts.map((s) => ({
+ bookId,
+ personId: sid(s.personId),
+ workplaceId: s.workplaceId && entityIds.has(s.workplaceId) ? sid(s.workplaceId) : null,
+ weekday: s.weekday,
+ startTime: s.startTime,
+ endTime: s.endTime,
+ weeks: s.weeks,
+ label: s.label,
+ scheduleCode: g.code,
+ })),
+ ),
+ });
+
+ const mapRows = maps.map((m) => ({ ...m, newId: randomUUID() }));
+ await tx.bookMap.createMany({
+ data: mapRows.map((m) => ({
+ id: m.newId,
+ bookId,
+ code: m.code,
+ name: m.name,
+ kind: m.kind,
+ imageFile: mapImages.get(m.id) ?? null,
+ centerLat: m.centerLat,
+ centerLng: m.centerLng,
+ zoom: m.zoom,
+ })),
+ });
+ await tx.marker.createMany({
+ data: mapRows.flatMap((m) =>
+ m.markers.map((k) => ({
+ mapId: m.newId,
+ code: k.code,
+ entityId: k.entityId && entityIds.has(k.entityId) ? sid(k.entityId) : null,
+ label: k.label,
+ note: k.note,
+ color: k.color,
+ lat: k.lat,
+ lng: k.lng,
+ })),
+ ),
+ });
+
+ const seenTemplates = new Set();
+ await tx.template.createMany({
+ data: data.templates
+ .filter((t) => !seenTemplates.has(t.kind) && seenTemplates.add(t.kind))
+ .map((t) => ({ bookId, kind: t.kind, fields: t.fields as unknown as Prisma.InputJsonArray })),
+ });
+
+ await tx.idCounter.createMany({ data: [...counters.entries()].map(([key, next]) => ({ bookId, key, next })) });
+ },
+ { timeout: 120_000, maxWait: 20_000 },
+ );
+
+ return {
+ bookId,
+ entities: entities.length,
+ relations: relations.length,
+ maps: maps.length,
+ markers: markers.length,
+ shifts: shiftsIn.length,
+ skippedImages,
+ skippedLinks,
+ };
+ } catch (error) {
+ await Promise.all(savedImages.map((name) => deleteImage(name)));
+ throw error;
+ }
+}
diff --git a/src/lib/files.ts b/src/lib/files.ts
index 7dc9f38..b991a55 100644
--- a/src/lib/files.ts
+++ b/src/lib/files.ts
@@ -1,5 +1,5 @@
import { randomUUID } from "node:crypto";
-import { mkdir, unlink, writeFile } from "node:fs/promises";
+import { mkdir, readFile, unlink, writeFile } from "node:fs/promises";
import path from "node:path";
export const UPLOAD_DIR = path.resolve(process.env.UPLOAD_DIR ?? "./data/uploads");
@@ -48,3 +48,32 @@ export async function deleteImage(name: string | null | undefined) {
export function fileUrl(name: string | null | undefined): string | null {
return name ? `/api/files/${name}` : null;
}
+
+/** Bildtyp utifrån filens första bytes (inte filnamnet), eller null om det inte är en tillåten bild. */
+export function detectImageExt(bytes: Uint8Array): "png" | "jpg" | "webp" | "gif" | null {
+ const at = (i: number) => bytes[i];
+ if (bytes.length > 8 && at(0) === 0x89 && at(1) === 0x50 && at(2) === 0x4e && at(3) === 0x47) return "png";
+ if (bytes.length > 3 && at(0) === 0xff && at(1) === 0xd8 && at(2) === 0xff) return "jpg";
+ if (bytes.length > 6 && at(0) === 0x47 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x38) return "gif";
+ if (bytes.length > 12 && at(0) === 0x52 && at(1) === 0x49 && at(2) === 0x46 && at(3) === 0x46 && at(8) === 0x57 && at(9) === 0x45 && at(10) === 0x42 && at(11) === 0x50) return "webp";
+ return null;
+}
+
+/** Sparar en bild som redan ligger i minnet (t.ex. från en importfil). Returnerar filnamnet, eller null om bilden inte duger. */
+export async function saveImageBytes(bytes: Uint8Array): Promise {
+ const ext = detectImageExt(bytes);
+ if (!ext || bytes.length > MAX_UPLOAD_BYTES) return null;
+ await mkdir(UPLOAD_DIR, { recursive: true });
+ const name = `${randomUUID()}.${ext}`;
+ await writeFile(path.join(UPLOAD_DIR, name), bytes);
+ return name;
+}
+
+export async function readImageBytes(name: string | null | undefined): Promise {
+ if (!name || !FILE_NAME_PATTERN.test(name)) return null;
+ try {
+ return await readFile(path.join(UPLOAD_DIR, name));
+ } catch {
+ return null;
+ }
+}
diff --git a/src/lib/ids.ts b/src/lib/ids.ts
index 383166a..b248178 100644
--- a/src/lib/ids.ts
+++ b/src/lib/ids.ts
@@ -30,7 +30,7 @@ export function mapLetter(kind: "GEO" | "IMAGE"): "R" | "E" {
return kind === "GEO" ? "R" : "E";
}
-const pad = (n: number) => String(n).padStart(4, "0");
+export const pad = (n: number) => String(n).padStart(4, "0");
/** Nästa löpande nummer för en räknare (atomärt). */
async function nextNumber(db: Db, bookId: string, key: string): Promise {