import { mkdir, readFile, rm, writeFile } from "node:fs/promises"; import path from "node:path"; import { strToU8, zipSync, type Zippable } from "fflate"; import type { EntityKind, Prisma, WeekPattern } from "@prisma/client"; import { buildExport, importBook, readImportFile } from "./book-transfer"; import { prisma } from "./db"; import { deleteImage } from "./files"; import { nextEntityCode, nextRelationCode } from "./ids"; import { log } from "./log"; // Papperskorg. Borttagna poster sparas som en ögonblicksbild i databasen (med relationer, scheman och markeringar), // borttagna böcker som en zip-fil på disk (samma format som exporten). Rensas automatiskt efter TRASH_DAYS. export const TRASH_DAYS = Number(process.env.TRASH_DAYS) || 30; export const TRASH_DIR = path.resolve(process.env.TRASH_DIR ?? "./data/trash"); type Snapshot = { entity: { id: string; bookId: string; kind: EntityKind; name: string; code: string | null; summary: string | null; imageFile: string | null; tags: string[]; data: Prisma.JsonValue; }; relations: { id: string; code: string | null; fromId: string; toId: string; type: string; description: string | null; data: Prisma.JsonValue; members: string[]; }[]; memberOf: string[]; // relationer som posten deltog i som extra deltagare shifts: { workplaceId: string | null; weekday: number; startTime: string; endTime: string; weeks: WeekPattern; label: string | null; scheduleCode: string | null; }[]; hostedShiftIds: string[]; // pass som hade posten som arbetsplats markerIds: string[]; }; // ─── Poster ───────────────────────────────────────────────────────────────── /** Flyttar en post till papperskorgen. Bilden behålls tills posten återställs eller rensas. */ export async function trashEntity(ownerId: string, bookId: string, entityId: string) { const entity = await prisma.entity.findFirstOrThrow({ where: { id: entityId, bookId }, include: { outgoing: { include: { members: true } }, incoming: { include: { members: true } }, memberOf: true, shifts: true, hostedShifts: { select: { id: true } }, markers: { select: { id: true } }, }, }); const snapshot: Snapshot = { entity: { id: entity.id, bookId: entity.bookId, kind: entity.kind, name: entity.name, code: entity.code, summary: entity.summary, imageFile: entity.imageFile, tags: entity.tags, data: entity.data, }, relations: [...entity.outgoing, ...entity.incoming].map((r) => ({ id: r.id, code: r.code, fromId: r.fromId, toId: r.toId, type: r.type, description: r.description, data: r.data, members: r.members.map((m) => m.entityId), })), memberOf: entity.memberOf.map((m) => m.relationId), shifts: entity.shifts.map((s) => ({ workplaceId: s.workplaceId, weekday: s.weekday, startTime: s.startTime, endTime: s.endTime, weeks: s.weeks, label: s.label, scheduleCode: s.scheduleCode, })), hostedShiftIds: entity.hostedShifts.map((s) => s.id), markerIds: entity.markers.map((m) => m.id), }; await prisma.$transaction([ prisma.trashItem.create({ data: { ownerId, bookId, kind: "entity", label: entity.name, detail: entity.kind, payload: snapshot as unknown as Prisma.InputJsonObject, }, }), prisma.entity.delete({ where: { id: entity.id } }), ]); log.info("Post flyttad till papperskorgen", { entityId, bookId, kind: entity.kind }); } /** Återställer en post. Returnerar bokens och postens id, eller null om boken inte längre finns. */ export async function restoreEntity(ownerId: string, trashId: string): Promise<{ bookId: string; entityId: string } | null> { const item = await prisma.trashItem.findFirst({ where: { id: trashId, ownerId, kind: "entity" } }); const snap = item?.payload as unknown as Snapshot | null; if (!item || !snap) return null; const bookId = snap.entity.bookId; const book = await prisma.book.findFirst({ where: { id: bookId, ownerId }, select: { id: true } }); if (!book) return null; if (await prisma.entity.findUnique({ where: { id: snap.entity.id }, select: { id: true } })) return null; await prisma.$transaction(async (tx) => { // Koden behålls om den är ledig, annars får posten en ny const codeTaken = snap.entity.code ? await tx.entity.findFirst({ where: { bookId, code: snap.entity.code }, select: { id: true } }) : null; const code = snap.entity.code && !codeTaken ? snap.entity.code : await nextEntityCode(bookId, snap.entity.kind, tx); await tx.entity.create({ data: { id: snap.entity.id, bookId, kind: snap.entity.kind, name: snap.entity.name, code, summary: snap.entity.summary, imageFile: snap.entity.imageFile, tags: snap.entity.tags, data: (snap.entity.data ?? {}) as Prisma.InputJsonObject, }, }); const others = new Set( (await tx.entity.findMany({ where: { bookId }, select: { id: true } })).map((e) => e.id), ); for (const r of snap.relations) { if (!others.has(r.fromId) || !others.has(r.toId)) continue; // den andra parten är borta if (await tx.relation.findUnique({ where: { id: r.id }, select: { id: true } })) continue; const taken = r.code ? await tx.relation.findFirst({ where: { bookId, code: r.code }, select: { id: true } }) : null; await tx.relation.create({ data: { id: r.id, bookId, code: r.code && !taken ? r.code : await nextRelationCode(bookId, tx), fromId: r.fromId, toId: r.toId, type: r.type, description: r.description, data: (r.data ?? {}) as Prisma.InputJsonObject, members: { create: r.members.filter((m) => others.has(m) && m !== r.fromId && m !== r.toId).map((entityId) => ({ entityId })) }, }, }); } for (const relationId of snap.memberOf) { const relation = await tx.relation.findUnique({ where: { id: relationId }, select: { fromId: true, toId: true } }); if (relation && relation.fromId !== snap.entity.id && relation.toId !== snap.entity.id) { await tx.relationMember.createMany({ data: [{ relationId, entityId: snap.entity.id }], skipDuplicates: true }); } } for (const s of snap.shifts) { await tx.shift.create({ data: { bookId, personId: snap.entity.id, workplaceId: s.workplaceId && others.has(s.workplaceId) ? s.workplaceId : null, weekday: s.weekday, startTime: s.startTime, endTime: s.endTime, weeks: s.weeks, label: s.label, scheduleCode: s.scheduleCode, }, }); } if (snap.hostedShiftIds.length) await tx.shift.updateMany({ where: { id: { in: snap.hostedShiftIds }, bookId }, data: { workplaceId: snap.entity.id } }); if (snap.markerIds.length) await tx.marker.updateMany({ where: { id: { in: snap.markerIds }, map: { bookId } }, data: { entityId: snap.entity.id } }); await tx.trashItem.delete({ where: { id: item.id } }); }); log.info("Post återställd från papperskorgen", { entityId: snap.entity.id, bookId }); return { bookId, entityId: snap.entity.id }; } // ─── Böcker ───────────────────────────────────────────────────────────────── /** Sparar boken som en zip i papperskorgen och tar sedan bort den. Zip-filen skrivs först, så ett fel förlorar ingenting. */ export async function trashBook(ownerId: string, bookId: string) { const { data, files } = await buildExport(bookId, true); const entries: Zippable = { "book.json": strToU8(JSON.stringify(data)) }; for (const [name, bytes] of files) entries[`files/${name}`] = [bytes, { level: 0 }]; const item = await prisma.trashItem.create({ data: { ownerId, kind: "book", label: data.book.title, detail: String(data.entities.length) }, }); const file = `${item.id}.zip`; try { await mkdir(TRASH_DIR, { recursive: true }); await writeFile(path.join(TRASH_DIR, file), zipSync(entries)); await prisma.trashItem.update({ where: { id: item.id }, data: { file } }); } catch (error) { await prisma.trashItem.delete({ where: { id: item.id } }).catch(() => undefined); throw error; } const images = [...data.entities.map((e) => e.image), ...data.maps.map((m) => m.image)]; // Bilderna finns nu i zip-filen och kan tas bort från uppladdningsmappen const [entityImages, mapImages] = await Promise.all([ prisma.entity.findMany({ where: { bookId, imageFile: { not: null } }, select: { imageFile: true } }), prisma.bookMap.findMany({ where: { bookId, imageFile: { not: null } }, select: { imageFile: true } }), ]); await prisma.book.delete({ where: { id: bookId } }); await Promise.all([...entityImages, ...mapImages].map((row) => deleteImage(row.imageFile))); log.info("Bok flyttad till papperskorgen", { bookId, trashId: item.id, images: images.filter(Boolean).length }); } /** Återställer en bok som en ny bok. Returnerar den nya bokens id. */ export async function restoreBook(ownerId: string, trashId: string): Promise { const item = await prisma.trashItem.findFirst({ where: { id: trashId, ownerId, kind: "book" } }); if (!item?.file) return null; const bytes = await readFile(path.join(TRASH_DIR, item.file)); const { data, files } = readImportFile(new Uint8Array(bytes)); const result = await importBook(ownerId, data, files); await purge(item); log.info("Bok återställd från papperskorgen", { trashId, bookId: result.bookId }); return result.bookId; } // ─── Rensning ─────────────────────────────────────────────────────────────── async function purge(item: { id: string; kind: string; file: string | null; payload: Prisma.JsonValue }) { if (item.kind === "book" && item.file) { await rm(path.join(TRASH_DIR, item.file), { force: true }); } else if (item.kind === "entity") { const snap = item.payload as unknown as Snapshot | null; if (snap) { await deleteImage(snap.entity.imageFile); await prisma.entityVersion.deleteMany({ where: { entityId: snap.entity.id } }); } } await prisma.trashItem.delete({ where: { id: item.id } }); } export async function purgeTrashItem(ownerId: string, trashId: string) { const item = await prisma.trashItem.findFirst({ where: { id: trashId, ownerId } }); if (item) await purge(item); } export async function emptyBookTrash(ownerId: string, bookId: string) { const items = await prisma.trashItem.findMany({ where: { ownerId, bookId, kind: "entity" } }); for (const item of items) await purge(item); } /** Tar bort allt som legat i papperskorgen längre än TRASH_DAYS. Returnerar antal rensade poster. */ export async function purgeExpiredTrash(): Promise { const limit = new Date(Date.now() - TRASH_DAYS * 24 * 60 * 60 * 1000); const items = await prisma.trashItem.findMany({ where: { deletedAt: { lt: limit } } }); for (const item of items) { try { await purge(item); } catch (error) { log.error("Kunde inte rensa papperskorgen", { trashId: item.id, error }); } } return items.length; }