"use server"; import { redirect } from "next/navigation"; import { conflictInfo, isStale, versionOf, type ConflictChange, type ConflictInfo } from "@/lib/conflict"; import { prisma } from "@/lib/db"; import { deleteImage, isUpload, saveImage } from "@/lib/files"; import { revalidateBook, str } from "@/lib/form"; import { MARKER_COLORS } from "@/lib/kinds"; import { nextMapCode, nextMarkerCode } from "@/lib/ids"; import { requireBook } from "@/lib/session"; import { getT } from "@/i18n/server"; import { withinQuota } from "@/lib/storage"; async function requireMap(bookId: string, mapId: string) { 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"), "EDITOR"); const name = str(formData, "name", 200); const kind = str(formData, "kind") === "IMAGE" ? "IMAGE" : "GEO"; if (!name) return; let imageFile: string | null = null; if (kind === "IMAGE") { const upload = formData.get("image"); if (!isUpload(upload)) return; if (!(await withinQuota(book.ownerId, upload.size))) redirect(`/books/${book.id}/maps?error=quota`); imageFile = await saveImage(upload, "map"); } const code = await nextMapCode(book.id, kind); const map = await prisma.bookMap.create({ data: { bookId: book.id, code, name, kind, imageFile } }); revalidateBook(book.id); redirect(`/books/${book.id}/maps/${map.id}`); } export async function renameMap(formData: FormData) { const { book, map } = await requireMap(str(formData, "bookId"), str(formData, "mapId")); const name = str(formData, "name", 200); if (!name) return; await prisma.bookMap.update({ where: { id: map.id }, data: { name } }); revalidateBook(book.id); } export async function deleteMap(formData: FormData) { const { book, map } = await requireMap(str(formData, "bookId"), str(formData, "mapId")); await prisma.bookMap.delete({ where: { id: map.id } }); await deleteImage(map.imageFile); revalidateBook(book.id); redirect(`/books/${book.id}/maps`); } export async function saveMapView(bookId: string, mapId: string, lat: number, lng: number, zoom: number) { const { book, map } = await requireMap(bookId, mapId); if (![lat, lng, zoom].every(Number.isFinite)) return; await prisma.bookMap.update({ where: { id: map.id }, data: { centerLat: lat, centerLng: lng, zoom: Math.round(zoom) }, }); revalidateBook(book.id); } export type MarkerInput = { label: string; note: string; color: string; entityId: string | null; lat: number; lng: number; }; async function cleanMarker(bookId: string, input: MarkerInput) { const label = String(input.label ?? "").trim().slice(0, 200); if (!label) throw new Error("Label is required"); if (!Number.isFinite(input.lat) || !Number.isFinite(input.lng)) throw new Error("Invalid position"); const color = input.color in MARKER_COLORS ? input.color : "blue"; let entityId: string | null = null; if (input.entityId) { const entity = await prisma.entity.findFirst({ where: { id: input.entityId, bookId }, select: { id: true } }); entityId = entity?.id ?? null; } return { label, note: String(input.note ?? "").trim().slice(0, 5000) || null, color, entityId, lat: input.lat, lng: input.lng, }; } export async function createMarker(bookId: string, mapId: string, input: MarkerInput) { const { book, map } = await requireMap(bookId, mapId); const data = await cleanMarker(book.id, input); await prisma.marker.create({ data: { ...data, code: await nextMarkerCode(book.id), mapId: map.id, updatedById: book.userId } }); revalidateBook(book.id); } /** Svar från en ändring av en markering: ny version, en krock med någons annans ändring, eller att markeringen är borta. */ export type MarkerResult = { version: string } | { conflict: ConflictInfo } | { gone: true }; type MarkerChange = { label?: string; note?: string | null; color?: string; entityId?: string | null; lat?: number; lng?: number }; /** * Skriver en ändring om markeringen inte har ändrats sedan användaren läste den (version). Villkoret på updatedAt * gör att en samtidig ändring av någon annan inte skrivs över. */ async function changeMarker(book: { id: string; userId: string }, mapId: string, markerId: string, change: MarkerChange, version: string): Promise { const current = await prisma.marker.findFirst({ where: { id: markerId, mapId } }); if (!current) return { gone: true }; const conflict = async (marker: typeof current): Promise => { const { t } = await getT(); const changes: ConflictChange[] = []; const diff = (label: string, before: unknown, after: unknown) => { if (after !== undefined && String(before ?? "") !== String(after ?? "")) changes.push({ label, before: String(before ?? ""), after: String(after ?? "") }); }; diff(t("map.markerLabel"), marker.label, change.label); diff(t("common.note"), marker.note, change.note); diff(t("map.color"), marker.color, change.color); if (change.lat !== undefined && (change.lat !== marker.lat || change.lng !== marker.lng)) { changes.push({ label: t("map.position"), before: `${marker.lat.toFixed(5)}, ${marker.lng.toFixed(5)}`, after: `${change.lat.toFixed(5)}, ${(change.lng ?? 0).toFixed(5)}` }); } return { conflict: await conflictInfo(marker, changes) }; }; if (isStale(version, current.updatedAt)) return conflict(current); const { count } = await prisma.marker.updateMany({ where: { id: markerId, mapId, updatedAt: current.updatedAt }, data: { ...change, updatedAt: new Date(), updatedById: book.userId }, }); if (count === 0) { const now = await prisma.marker.findFirst({ where: { id: markerId, mapId } }); return now ? conflict(now) : { gone: true }; } revalidateBook(book.id); const saved = await prisma.marker.findFirstOrThrow({ where: { id: markerId, mapId } }); return { version: versionOf(saved.updatedAt) }; } export async function updateMarker(bookId: string, mapId: string, markerId: string, input: MarkerInput, version = ""): Promise { const { book, map } = await requireMap(bookId, mapId); return changeMarker(book, map.id, markerId, await cleanMarker(book.id, input), version); } export async function moveMarker(bookId: string, mapId: string, markerId: string, lat: number, lng: number, version = ""): Promise { const { book, map } = await requireMap(bookId, mapId); if (![lat, lng].every(Number.isFinite)) throw new Error("Invalid position"); return changeMarker(book, map.id, markerId, { lat, lng }, version); } export async function deleteMarker(bookId: string, mapId: string, markerId: string) { const { book, map } = await requireMap(bookId, mapId); await prisma.marker.deleteMany({ where: { id: markerId, mapId: map.id } }); revalidateBook(book.id); }