diff --git a/README.md b/README.md index b65de0a..3cc670d 100644 --- a/README.md +++ b/README.md @@ -58,7 +58,8 @@ Varje typ (karaktär, husdjur, bostad, plats, företag, lokal, utbildning, scena | Utbildningsmall | Utbildning | | Relationsmall | Relation (öppnas från relationslistan eller från en posts sida) | | Schema dag / natt | Scheman, vyn *Timrutnät* med Dag 06–18 och Natt 18–06 | -| Karaktärs-ID, Bostads-ID, Skiss-ID ... | Fältet *ID / kod* på alla poster (valfritt, sökbart) | +| Registren (Fordon, Research, Referens, Appar, Hemsidor, Kart-, Schema- och Företagsregister) | Egna poster under *Register* i menyn, och sidan *ID-register* med alla ID samlade | +| ID-översikten | ID skapas automatiskt, se nedan | Uppgifter som i Word-mallarna är ID-listor (anställda, boende, elever, involverade karaktärer, ägare) görs i appen som **relationer** mellan poster, till exempel ”Jobbar på”, ”Bor på”, ”Elev på”, ”Involverad i”. Då kan du klicka dig mellan dem och se dem i relationsdiagrammet. @@ -75,6 +76,30 @@ Under **Mallar** kan du ändra fält, ordning, rubriker och fälttyper (text, te Ändrar du en mall försvinner ingen data: värden för borttagna fält finns kvar i databasen. +## Automatiska ID + +Alla ID skapas automatiskt enligt ID-översikten, med löpande nummer per bok och typ (de börjar om i varje ny bok). ID tilldelas första gången posten sparas och ändras aldrig därefter. + +| Typ | ID | Exempel | +|---|---|---| +| Karaktär | KI | KI-0001 | +| Företag | FI | FI-0001 | +| Bostad | BI | BI-0001 | +| Husdjur | DI | DI-0001 | +| Lokal | LI | LI-0001 | +| Utbildning | UI | UI-0001 | +| Fordon | FD | FD-0001 | +| Research | RI | RI-0001 | +| Referens | RD | RD-0001 | +| Skiss | SI | SI-0001 | +| Relation | REI | REI-0001 | +| Placering (markering på karta) | PI | PI-0001 | +| Schema (en persons pass hos samma arbetsplats) | SCI | SCI-0001 | +| Karta | KD-R_ (riktig karta) eller KD-E_ (egen kartbild) | KD-R_0001 | +| Plats och Scenario (saknas i översikten, förslag) | PLI och SNI | PLI-0001, SNI-0001 | + +Appar och Hemsidor har inget ID. Prefixen ligger samlade i `src/lib/ids.ts`. Sidan **ID-register** listar alla ID i boken med sökning och filter. Befintliga poster får ID vid uppgraderingen i den ordning de skapades, och tidigare handskrivna koder ersätts. + ## Kartor - **Riktig karta**: sök adress, klicka där markeringen ska sitta, koppla den till en bostad, lokal eller plats. Dra för att flytta. *Spara vy* minns utsnittet. diff --git a/Register/Appregister.docx b/Register/Appregister.docx new file mode 100644 index 0000000..7b6e395 Binary files /dev/null and b/Register/Appregister.docx differ diff --git a/Register/Fordonsregister.docx b/Register/Fordonsregister.docx new file mode 100644 index 0000000..454f6bc Binary files /dev/null and b/Register/Fordonsregister.docx differ diff --git a/Register/Företagsregister.docx b/Register/Företagsregister.docx new file mode 100644 index 0000000..1842350 Binary files /dev/null and b/Register/Företagsregister.docx differ diff --git a/Register/Kartregister.docx b/Register/Kartregister.docx new file mode 100644 index 0000000..c85410e Binary files /dev/null and b/Register/Kartregister.docx differ diff --git a/Register/Referensregister.docx b/Register/Referensregister.docx new file mode 100644 index 0000000..9c4dce2 Binary files /dev/null and b/Register/Referensregister.docx differ diff --git a/Register/Researchregister.docx b/Register/Researchregister.docx new file mode 100644 index 0000000..f702510 Binary files /dev/null and b/Register/Researchregister.docx differ diff --git a/Register/Schemaregister.docx b/Register/Schemaregister.docx new file mode 100644 index 0000000..6491d85 Binary files /dev/null and b/Register/Schemaregister.docx differ diff --git a/Register/hemsideregister.docx b/Register/hemsideregister.docx new file mode 100644 index 0000000..49dcf22 Binary files /dev/null and b/Register/hemsideregister.docx differ diff --git a/prisma/migrations/0003_auto_ids/migration.sql b/prisma/migrations/0003_auto_ids/migration.sql new file mode 100644 index 0000000..e736c5b --- /dev/null +++ b/prisma/migrations/0003_auto_ids/migration.sql @@ -0,0 +1,106 @@ +-- Automatiska ID: nya posttyper, kodkolumner och löpande räknare per bok. +-- Befintliga poster får ID efter skapandetid. Tidigare handskrivna koder ersätts. + +-- AlterEnum (de nya värdena används inte i den här migrationen) +ALTER TYPE "EntityKind" ADD VALUE 'VEHICLE'; +ALTER TYPE "EntityKind" ADD VALUE 'RESEARCH'; +ALTER TYPE "EntityKind" ADD VALUE 'REFERENCE'; +ALTER TYPE "EntityKind" ADD VALUE 'SKETCH'; +ALTER TYPE "EntityKind" ADD VALUE 'APP'; +ALTER TYPE "EntityKind" ADD VALUE 'WEBSITE'; + +-- DropIndex +DROP INDEX "Entity_bookId_code_idx"; + +-- AlterTable +ALTER TABLE "Relation" ADD COLUMN "code" TEXT; +ALTER TABLE "Shift" ADD COLUMN "scheduleCode" TEXT; +ALTER TABLE "BookMap" ADD COLUMN "code" TEXT; +ALTER TABLE "Marker" ADD COLUMN "code" TEXT; + +-- CreateTable +CREATE TABLE "IdCounter" ( + "bookId" TEXT NOT NULL, + "key" TEXT NOT NULL, + "next" INTEGER NOT NULL DEFAULT 0, + + CONSTRAINT "IdCounter_pkey" PRIMARY KEY ("bookId","key") +); + +-- AddForeignKey +ALTER TABLE "IdCounter" ADD CONSTRAINT "IdCounter_bookId_fkey" FOREIGN KEY ("bookId") REFERENCES "Book"("id") ON DELETE CASCADE ON UPDATE CASCADE; + +-- Backfill: poster (prefix enligt src/lib/ids.ts) +UPDATE "Entity" SET "code" = NULL; + +WITH numbered AS ( + SELECT id, + CASE kind::text + WHEN 'CHARACTER' THEN 'KI' WHEN 'COMPANY' THEN 'FI' WHEN 'HOME' THEN 'BI' + WHEN 'PET' THEN 'DI' WHEN 'PREMISES' THEN 'LI' WHEN 'EDUCATION' THEN 'UI' + WHEN 'PLACE' THEN 'PLI' WHEN 'SCENARIO' THEN 'SNI' + END AS prefix, + row_number() OVER (PARTITION BY "bookId", kind ORDER BY "createdAt", id) AS n + FROM "Entity" +) +UPDATE "Entity" e +SET "code" = numbered.prefix || '-' || lpad(numbered.n::text, 4, '0') +FROM numbered +WHERE e.id = numbered.id AND numbered.prefix IS NOT NULL; + +INSERT INTO "IdCounter" ("bookId", "key", "next") +SELECT "bookId", + split_part("code", '-', 1), + count(*) +FROM "Entity" +WHERE "code" IS NOT NULL +GROUP BY "bookId", split_part("code", '-', 1); + +-- Backfill: relationer (REI) +WITH numbered AS ( + SELECT id, row_number() OVER (PARTITION BY "bookId" ORDER BY "createdAt", id) AS n FROM "Relation" +) +UPDATE "Relation" r SET "code" = 'REI-' || lpad(numbered.n::text, 4, '0') FROM numbered WHERE r.id = numbered.id; + +INSERT INTO "IdCounter" ("bookId", "key", "next") +SELECT "bookId", 'REI', count(*) FROM "Relation" GROUP BY "bookId"; + +-- Backfill: kartor (KD-R_0001 för riktig karta, KD-E_0001 för egen kartbild) +WITH numbered AS ( + SELECT id, + CASE kind::text WHEN 'GEO' THEN 'R' ELSE 'E' END AS letter, + row_number() OVER (PARTITION BY "bookId", kind ORDER BY "createdAt", id) AS n + FROM "BookMap" +) +UPDATE "BookMap" m SET "code" = 'KD-' || numbered.letter || '_' || lpad(numbered.n::text, 4, '0') FROM numbered WHERE m.id = numbered.id; + +INSERT INTO "IdCounter" ("bookId", "key", "next") +SELECT "bookId", split_part("code", '_', 1), count(*) FROM "BookMap" GROUP BY "bookId", split_part("code", '_', 1); + +-- Backfill: placeringar (PI) +WITH numbered AS ( + SELECT mk.id, row_number() OVER (PARTITION BY bm."bookId" ORDER BY mk."createdAt", mk.id) AS n + FROM "Marker" mk JOIN "BookMap" bm ON bm.id = mk."mapId" +) +UPDATE "Marker" mk SET "code" = 'PI-' || lpad(numbered.n::text, 4, '0') FROM numbered WHERE mk.id = numbered.id; + +INSERT INTO "IdCounter" ("bookId", "key", "next") +SELECT bm."bookId", 'PI', count(*) FROM "Marker" mk JOIN "BookMap" bm ON bm.id = mk."mapId" GROUP BY bm."bookId"; + +-- Backfill: scheman (SCI), ett per person och arbetsplats +WITH groups AS ( + SELECT "bookId", "personId", "workplaceId", min("createdAt") AS first_at FROM "Shift" GROUP BY "bookId", "personId", "workplaceId" +), numbered AS ( + SELECT *, row_number() OVER (PARTITION BY "bookId" ORDER BY first_at, "personId", COALESCE("workplaceId", '')) AS n FROM groups +) +UPDATE "Shift" s SET "scheduleCode" = 'SCI-' || lpad(numbered.n::text, 4, '0') +FROM numbered +WHERE s."bookId" = numbered."bookId" AND s."personId" = numbered."personId" AND s."workplaceId" IS NOT DISTINCT FROM numbered."workplaceId"; + +INSERT INTO "IdCounter" ("bookId", "key", "next") +SELECT "bookId", 'SCI', count(DISTINCT "scheduleCode") FROM "Shift" GROUP BY "bookId"; + +-- CreateIndex (efter backfill) +CREATE UNIQUE INDEX "Entity_bookId_code_key" ON "Entity"("bookId", "code"); +CREATE UNIQUE INDEX "Relation_bookId_code_key" ON "Relation"("bookId", "code"); +CREATE UNIQUE INDEX "BookMap_bookId_code_key" ON "BookMap"("bookId", "code"); diff --git a/prisma/schema.prisma b/prisma/schema.prisma index c914548..1dbc050 100644 --- a/prisma/schema.prisma +++ b/prisma/schema.prisma @@ -17,6 +17,12 @@ enum EntityKind { SCENARIO EDUCATION PET + VEHICLE + RESEARCH + REFERENCE + SKETCH + APP + WEBSITE } enum MapKind { @@ -50,12 +56,13 @@ model Book { createdAt DateTime @default(now()) updatedAt DateTime @updatedAt - owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade) + owner User @relation(fields: [ownerId], references: [id], onDelete: Cascade) entities Entity[] relations Relation[] shifts Shift[] maps BookMap[] templates Template[] + counters IdCounter[] @@index([ownerId]) } @@ -69,27 +76,29 @@ model Entity { name String summary String? @db.Text imageFile String? + // Skapas automatiskt, t.ex. KI-0001 (se src/lib/ids.ts) code String? tags String[] data Json @default("{}") createdAt DateTime @default(now()) updatedAt DateTime @updatedAt - book Book @relation(fields: [bookId], references: [id], onDelete: Cascade) - outgoing Relation[] @relation("RelationFrom") - incoming Relation[] @relation("RelationTo") - shifts Shift[] @relation("ShiftPerson") - hostedShifts Shift[] @relation("ShiftWorkplace") + book Book @relation(fields: [bookId], references: [id], onDelete: Cascade) + outgoing Relation[] @relation("RelationFrom") + incoming Relation[] @relation("RelationTo") + shifts Shift[] @relation("ShiftPerson") + hostedShifts Shift[] @relation("ShiftWorkplace") markers Marker[] memberOf RelationMember[] + @@unique([bookId, code]) @@index([bookId, kind]) - @@index([bookId, code]) } model Relation { id String @id @default(cuid()) bookId String + code String? fromId String toId String type String @@ -97,12 +106,13 @@ model Relation { data Json @default("{}") createdAt DateTime @default(now()) - book Book @relation(fields: [bookId], references: [id], onDelete: Cascade) - from Entity @relation("RelationFrom", fields: [fromId], references: [id], onDelete: Cascade) - to Entity @relation("RelationTo", fields: [toId], references: [id], onDelete: Cascade) + book Book @relation(fields: [bookId], references: [id], onDelete: Cascade) + from Entity @relation("RelationFrom", fields: [fromId], references: [id], onDelete: Cascade) + to Entity @relation("RelationTo", fields: [toId], references: [id], onDelete: Cascade) // Fler deltagare utöver from/to, t.ex. i en vännergrupp members RelationMember[] + @@unique([bookId, code]) @@index([bookId]) @@index([fromId]) @@index([toId]) @@ -110,16 +120,18 @@ model Relation { // Arbetspass. weekday: 0 = måndag ... 6 = söndag. model Shift { - id String @id @default(cuid()) - bookId String - personId String - workplaceId String? - weekday Int - startTime String - endTime String - weeks WeekPattern @default(ALL) - label String? - createdAt DateTime @default(now()) + id String @id @default(cuid()) + bookId String + personId String + workplaceId String? + weekday Int + startTime String + endTime String + weeks WeekPattern @default(ALL) + label String? + // Schema-ID (SCI-0001), delas av en persons alla pass hos samma arbetsplats + scheduleCode String? + createdAt DateTime @default(now()) book Book @relation(fields: [bookId], references: [id], onDelete: Cascade) person Entity @relation("ShiftPerson", fields: [personId], references: [id], onDelete: Cascade) @@ -133,6 +145,7 @@ model Shift { model BookMap { id String @id @default(cuid()) bookId String + code String? name String kind MapKind imageFile String? @@ -144,6 +157,7 @@ model BookMap { book Book @relation(fields: [bookId], references: [id], onDelete: Cascade) markers Marker[] + @@unique([bookId, code]) @@index([bookId]) } @@ -151,6 +165,8 @@ model BookMap { model Marker { id String @id @default(cuid()) mapId String + // Placerings-ID, t.ex. PI-0001 + code String? entityId String? label String note String? @db.Text @@ -168,12 +184,12 @@ model Marker { // Egen mall för en typ i en bok. Saknas raden används standardmallen. model Template { - id String @id @default(cuid()) + id String @id @default(cuid()) bookId String // EntityKind eller "RELATION" kind String fields Json - updatedAt DateTime @updatedAt + updatedAt DateTime @updatedAt book Book @relation(fields: [bookId], references: [id], onDelete: Cascade) @@ -191,3 +207,14 @@ model RelationMember { @@unique([relationId, entityId]) @@index([entityId]) } + +// Löpande nummer per bok och ID-typ, t.ex. key "KI" eller "KD-R" +model IdCounter { + bookId String + key String + next Int @default(0) + + book Book @relation(fields: [bookId], references: [id], onDelete: Cascade) + + @@id([bookId, key]) +} diff --git a/src/actions/entities.ts b/src/actions/entities.ts index 95a93e8..71eb584 100644 --- a/src/actions/entities.ts +++ b/src/actions/entities.ts @@ -6,6 +6,7 @@ import { prisma } from "@/lib/db"; import { deleteImage, isUpload, saveImage } from "@/lib/files"; import { optStr, parseTags, revalidateBook, str } from "@/lib/form"; import { KIND_INFO, parseKind } from "@/lib/kinds"; +import { nextEntityCode } from "@/lib/ids"; import { requireBook, requireEntity } from "@/lib/session"; import { getTemplate } from "@/lib/templates"; import { getLocale } from "@/i18n/server"; @@ -52,16 +53,21 @@ export async function saveEntity(formData: FormData) { const values = { name, - code: optStr(formData, "code", 50), summary: optStr(formData, "summary"), tags: parseTags(str(formData, "tags", 1000)), data: data as Prisma.InputJsonObject, imageFile, }; - const saved = existing - ? await prisma.entity.update({ where: { id: existing.id }, data: values }) - : await prisma.entity.create({ data: { ...values, bookId: book.id, kind } }); + // ID skapas automatiskt vid första sparningen och ändras aldrig därefter + const saved = await prisma.$transaction(async (tx) => { + if (existing) { + const code = existing.code ?? (await nextEntityCode(book.id, kind, tx)); + return tx.entity.update({ where: { id: existing.id }, data: { ...values, code } }); + } + const code = await nextEntityCode(book.id, kind, tx); + return tx.entity.create({ data: { ...values, code, bookId: book.id, kind } }); + }); revalidateBook(book.id); redirect(`/books/${book.id}/entity/${saved.id}`); diff --git a/src/actions/maps.ts b/src/actions/maps.ts index b3949b5..be15f6f 100644 --- a/src/actions/maps.ts +++ b/src/actions/maps.ts @@ -5,6 +5,7 @@ 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"; async function requireMap(bookId: string, mapId: string) { @@ -27,7 +28,8 @@ export async function createMap(formData: FormData) { imageFile = await saveImage(upload); } - const map = await prisma.bookMap.create({ data: { bookId: book.id, name, kind, imageFile } }); + 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}`); } @@ -89,7 +91,8 @@ async function cleanMarker(bookId: string, input: MarkerInput) { export async function createMarker(bookId: string, mapId: string, input: MarkerInput) { const { book, map } = await requireMap(bookId, mapId); - await prisma.marker.create({ data: { ...(await cleanMarker(book.id, input)), mapId: map.id } }); + const data = await cleanMarker(book.id, input); + await prisma.marker.create({ data: { ...data, code: await nextMarkerCode(book.id), mapId: map.id } }); revalidateBook(book.id); } diff --git a/src/actions/relations.ts b/src/actions/relations.ts index 990d6f4..9eaf9d6 100644 --- a/src/actions/relations.ts +++ b/src/actions/relations.ts @@ -4,6 +4,7 @@ import type { Prisma } from "@prisma/client"; import { redirect } from "next/navigation"; import { prisma } from "@/lib/db"; import { optStr, revalidateBook, str } from "@/lib/form"; +import { nextRelationCode } from "@/lib/ids"; import { requireBook } from "@/lib/session"; import { getTemplate } from "@/lib/templates"; import { getLocale } from "@/i18n/server"; @@ -28,15 +29,18 @@ export async function addRelation(formData: FormData) { if (count !== 2) return; const memberIds = await cleanMemberIds(book.id, formData, [fromId, toId]); - await prisma.relation.create({ + await prisma.$transaction(async (tx) => { + await tx.relation.create({ data: { bookId: book.id, + code: await nextRelationCode(book.id, tx), fromId, toId, type, description: optStr(formData, "description", 2000), members: { create: memberIds.map((entityId) => ({ entityId })) }, }, + }); }); revalidateBook(book.id); } diff --git a/src/actions/shifts.ts b/src/actions/shifts.ts index 85ef23c..af6d288 100644 --- a/src/actions/shifts.ts +++ b/src/actions/shifts.ts @@ -3,6 +3,7 @@ import type { WeekPattern } from "@prisma/client"; import { prisma } from "@/lib/db"; import { optStr, revalidateBook, str } from "@/lib/form"; +import { nextScheduleCode } from "@/lib/ids"; import { requireBook } from "@/lib/session"; const TIME = /^([01]\d|2[0-3]):[0-5]\d$/; @@ -25,6 +26,13 @@ export async function addShifts(formData: FormData) { const found = await prisma.entity.count({ where: { bookId: book.id, id: { in: ids } } }); if (found !== ids.length) return; + // En persons pass hos samma arbetsplats hör till samma schema och delar Schema-ID + const existing = await prisma.shift.findFirst({ + where: { bookId: book.id, personId, workplaceId, scheduleCode: { not: null } }, + select: { scheduleCode: true }, + }); + const scheduleCode = existing?.scheduleCode ?? (await nextScheduleCode(book.id)); + const label = optStr(formData, "label", 100); await prisma.shift.createMany({ data: days.map((weekday) => ({ @@ -36,6 +44,7 @@ export async function addShifts(formData: FormData) { endTime, weeks, label, + scheduleCode, })), }); revalidateBook(book.id); diff --git a/src/app/books/[bookId]/entity/[entityId]/page.tsx b/src/app/books/[bookId]/entity/[entityId]/page.tsx index 63d8401..1a1f26f 100644 --- a/src/app/books/[bookId]/entity/[entityId]/page.tsx +++ b/src/app/books/[bookId]/entity/[entityId]/page.tsx @@ -266,6 +266,7 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId: {entity.shifts.map((s) => (
{t(`day.short.${s.weekday}`)} {s.startTime}–{s.endTime} + {s.scheduleCode ? {s.scheduleCode} : null} {s.weeks !== "ALL" ? {t(`schedule.weeks.${s.weeks}`)} : null}
{[s.workplace?.name, s.label].filter(Boolean).join(" · ")} @@ -318,6 +319,7 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId: {m.map.name} · {m.label} + {m.code ? {m.code} : null} ))} {maps.map((map) => ( diff --git a/src/app/books/[bookId]/maps/[mapId]/page.tsx b/src/app/books/[bookId]/maps/[mapId]/page.tsx index 5a55d73..05cf068 100644 --- a/src/app/books/[bookId]/maps/[mapId]/page.tsx +++ b/src/app/books/[bookId]/maps/[mapId]/page.tsx @@ -36,7 +36,15 @@ export default async function MapPage({ return ( <> - + + {t("map.title")} + {map.code ? {map.code} : null} + + } + /> ({ id: m.id, + code: m.code, label: m.label, note: m.note, color: m.color, diff --git a/src/app/books/[bookId]/maps/page.tsx b/src/app/books/[bookId]/maps/page.tsx index 91cf42d..a56f9da 100644 --- a/src/app/books/[bookId]/maps/page.tsx +++ b/src/app/books/[bookId]/maps/page.tsx @@ -36,7 +36,10 @@ export default async function MapsPage({ params }: { params: Promise<{ bookId: s {map.kind === "GEO" ? : }
-
{map.name}
+
+ {map.name} + {map.code ? {map.code} : null} +
{t(`map.kind.${map.kind}`)} · {t("map.markerCount", { n: map._count.markers })}
diff --git a/src/app/books/[bookId]/page.tsx b/src/app/books/[bookId]/page.tsx index 169c2c6..268e217 100644 --- a/src/app/books/[bookId]/page.tsx +++ b/src/app/books/[bookId]/page.tsx @@ -28,7 +28,45 @@ export default async function BookDashboard({ params }: { params: Promise<{ book {book.description ?

{book.description}

: null}
- {KINDS.map(({ kind, slug, color }) => { + {KINDS.filter((k) => k.group === "world").map(({ kind, slug, color }) => { + const Icon = kindIcons[kind]; + return ( +
+
+
+
+
+ + + +
+
+ + {t(`kind.${kind}.other`)} + +
{countOf[kind] ?? 0}
+
+
+ + + +
+
+
+
+
+ ); + })} +
+ +

{t("dashboard.registers")}

+
+ {KINDS.filter((k) => k.group === "register").map(({ kind, slug, color }) => { const Icon = kindIcons[kind]; return (
diff --git a/src/app/books/[bookId]/register/page.tsx b/src/app/books/[bookId]/register/page.tsx new file mode 100644 index 0000000..8375f41 --- /dev/null +++ b/src/app/books/[bookId]/register/page.tsx @@ -0,0 +1,175 @@ +import Link from "next/link"; +import { IconSearch } from "@tabler/icons-react"; +import { EmptyState, PageBody, PageHeader } from "@/components/page"; +import { getT } from "@/i18n/server"; +import { prisma } from "@/lib/db"; +import { ENTITY_PREFIX } from "@/lib/ids"; +import { KINDS } from "@/lib/kinds"; +import { requireBook } from "@/lib/session"; + +export const metadata = { title: "ID-register" }; + +type Row = { code: string; type: string; typeLabel: string; name: string; href: string; detail?: string }; + +const SPECIAL_TYPES = ["relation", "map", "marker", "schedule"] as const; + +export default async function RegisterPage({ + params, + searchParams, +}: { + params: Promise<{ bookId: string }>; + searchParams: Promise<{ q?: string; type?: string }>; +}) { + const { bookId } = await params; + const { q = "", type = "" } = await searchParams; + await requireBook(bookId); + const { t } = await getT(); + + const [entities, relations, maps, markers, shifts] = await Promise.all([ + prisma.entity.findMany({ where: { bookId, code: { not: null } }, select: { id: true, code: true, name: true, kind: true } }), + prisma.relation.findMany({ + where: { bookId, code: { not: null } }, + include: { from: { select: { name: true } }, to: { select: { name: true } } }, + }), + prisma.bookMap.findMany({ where: { bookId, code: { not: null } }, select: { id: true, code: true, name: true } }), + prisma.marker.findMany({ + where: { map: { bookId }, code: { not: null } }, + include: { map: { select: { id: true, name: true } } }, + }), + prisma.shift.findMany({ + where: { bookId, scheduleCode: { not: null } }, + include: { person: { select: { id: true, name: true } }, workplace: { select: { name: true } } }, + }), + ]); + + const rows: Row[] = [ + ...entities.map((e) => ({ + code: e.code!, + type: e.kind, + typeLabel: t(`kind.${e.kind}.one`), + name: e.name, + href: `/books/${bookId}/entity/${e.id}`, + })), + ...relations.map((r) => ({ + code: r.code!, + type: "relation", + typeLabel: t("register.relation"), + name: `${r.from.name} – ${r.to.name}`, + detail: r.type, + href: `/books/${bookId}/relations/${r.id}`, + })), + ...maps.map((m) => ({ + code: m.code!, + type: "map", + typeLabel: t("register.map"), + name: m.name, + href: `/books/${bookId}/maps/${m.id}`, + })), + ...markers.map((m) => ({ + code: m.code!, + type: "marker", + typeLabel: t("register.marker"), + name: m.label, + detail: m.map.name, + href: `/books/${bookId}/maps/${m.map.id}?marker=${m.id}`, + })), + ]; + + // Ett schema-ID gäller en persons alla pass hos samma arbetsplats + const schedules = new Map(); + for (const s of shifts) { + if (schedules.has(s.scheduleCode!)) continue; + schedules.set(s.scheduleCode!, { + code: s.scheduleCode!, + type: "schedule", + typeLabel: t("register.schedule"), + name: s.person.name, + detail: s.workplace?.name, + href: `/books/${bookId}/schedules?person=${s.person.id}`, + }); + } + rows.push(...schedules.values()); + + const needle = q.trim().toLowerCase(); + const visible = rows + .filter((r) => (!type || r.type === type) && (!needle || `${r.code} ${r.name} ${r.detail ?? ""}`.toLowerCase().includes(needle))) + .sort((a, b) => a.code.localeCompare(b.code, "sv", { numeric: true })); + + const typeOptions = [ + ...KINDS.filter((k) => ENTITY_PREFIX[k.kind]).map((k) => ({ value: k.kind as string, label: t(`kind.${k.kind}.other`) })), + ...SPECIAL_TYPES.map((s) => ({ value: s as string, label: t(`register.${s}`) })), + ]; + + return ( + <> + + +

{t("register.intro")}

+
+
+
+
+
+ + + + +
+
+
+ +
+
+ +
+
+
+ + {visible.length === 0 ? ( +
+ {t("register.empty")} +
+ ) : ( +
+ + + + + + + + + + {visible.map((r) => ( + + + + + + ))} + +
{t("register.id")}{t("register.type")}{t("register.name")}
+ {r.code} + {r.typeLabel} + + {r.name} + + {r.detail ? · {r.detail} : null} +
+
+ )} +
+
+ + ); +} + diff --git a/src/app/books/[bookId]/relations/[relationId]/page.tsx b/src/app/books/[bookId]/relations/[relationId]/page.tsx index 41b7302..0df8f7c 100644 --- a/src/app/books/[bookId]/relations/[relationId]/page.tsx +++ b/src/app/books/[bookId]/relations/[relationId]/page.tsx @@ -46,8 +46,10 @@ export default async function RelationPage({ pretitle={ {t("relation.title")} + {relation.code ? {relation.code} : null} } + title={ isGroup ? ( diff --git a/src/app/books/[bookId]/relations/page.tsx b/src/app/books/[bookId]/relations/page.tsx index d682d15..5d942c4 100644 --- a/src/app/books/[bookId]/relations/page.tsx +++ b/src/app/books/[bookId]/relations/page.tsx @@ -106,6 +106,7 @@ export default async function RelationsPage({ {r.type} + {r.code ? {r.code} : null} {[r.to, ...r.members.map((m) => m.entity)].map((e, i) => ( diff --git a/src/app/books/[bookId]/schedules/page.tsx b/src/app/books/[bookId]/schedules/page.tsx index 6468656..becc1c9 100644 --- a/src/app/books/[bookId]/schedules/page.tsx +++ b/src/app/books/[bookId]/schedules/page.tsx @@ -301,6 +301,13 @@ export default async function SchedulesPage({ {p.name} +
+ {[...new Set(rowShifts.map((s) => s.scheduleCode).filter(Boolean))].map((code) => ( + + {code} + + ))} +
{DAYS.map((d) => ( diff --git a/src/components/entity-form.tsx b/src/components/entity-form.tsx index 541f447..acd6cc1 100644 --- a/src/components/entity-form.tsx +++ b/src/components/entity-form.tsx @@ -79,8 +79,7 @@ export function EntityForm({
- -
{t("common.codeHelp")}
+
diff --git a/src/components/kind-icons.tsx b/src/components/kind-icons.tsx index 8bb1df5..ab20f09 100644 --- a/src/components/kind-icons.tsx +++ b/src/components/kind-icons.tsx @@ -1,12 +1,18 @@ import { + IconBookmark, IconBuildingSkyscraper, IconBuildingStore, + IconCar, + IconDeviceMobile, + IconFlask, IconHome, IconMapPin, IconMovie, IconPaw, + IconRuler2, IconSchool, IconUser, + IconWorld, type Icon, } from "@tabler/icons-react"; import type { EntityKind } from "@prisma/client"; @@ -20,4 +26,10 @@ export const kindIcons: Record = { PREMISES: IconBuildingStore, EDUCATION: IconSchool, SCENARIO: IconMovie, + VEHICLE: IconCar, + SKETCH: IconRuler2, + RESEARCH: IconFlask, + REFERENCE: IconBookmark, + APP: IconDeviceMobile, + WEBSITE: IconWorld, }; diff --git a/src/components/map-view.tsx b/src/components/map-view.tsx index 5c26db2..b43c28a 100644 --- a/src/components/map-view.tsx +++ b/src/components/map-view.tsx @@ -12,6 +12,7 @@ import { KINDS, MARKER_COLORS } from "@/lib/kinds"; export type MarkerDTO = { id: string; + code: string | null; label: string; note: string | null; color: string; @@ -372,6 +373,11 @@ export default function MapView(props: MapViewProps) {

{draft.id ? t("map.editMarker") : t("map.newMarker")}

+ {draft.id ? ( +
+ {markers.find((m) => m.id === draft.id)?.code} +
+ ) : null}
@@ -473,6 +479,7 @@ export default function MapView(props: MapViewProps) {   + {m.code ? {m.code} : null} {m.label} {m.entityId ? · {entityName(m.entityId)} : null} diff --git a/src/components/shell.tsx b/src/components/shell.tsx index 1380c5c..f2b9d1f 100644 --- a/src/components/shell.tsx +++ b/src/components/shell.tsx @@ -5,6 +5,7 @@ import { IconCalendarWeek, IconChartDots3, IconLayoutDashboard, + IconListDetails, IconLogout, IconMap2, IconSettings, @@ -80,7 +81,7 @@ export async function Shell({ user, book, children }: ShellProps) {
  • {t("nav.world")}
  • - {KINDS.map(({ kind, slug }) => { + {KINDS.filter((k) => k.group === "world").map(({ kind, slug }) => { const Icon = kindIcons[kind]; return ( }> @@ -89,6 +90,21 @@ export async function Shell({ user, book, children }: ShellProps) { ); })} +
  • +
    {t("nav.register")}
    +
  • + {KINDS.filter((k) => k.group === "register").map(({ kind, slug }) => { + const Icon = kindIcons[kind]; + return ( + }> + {t(`kind.${kind}.other`)} + + ); + })} + }> + {t("nav.idRegister")} + +
  • {t("nav.planning")}
  • diff --git a/src/i18n/en.ts b/src/i18n/en.ts index 14fcb6c..c088d99 100644 --- a/src/i18n/en.ts +++ b/src/i18n/en.ts @@ -4,8 +4,7 @@ export const en: Record = { "app.name": "Story Planner", "common.save": "Save", - "common.code": "ID / code", - "common.codeHelp": "Optional, e.g. K001. For cross-referencing between documents.", + "common.code": "ID", "common.saved": "Saved.", "common.cancel": "Cancel", "common.delete": "Delete", @@ -99,6 +98,39 @@ export const en: Record = { "kind.PET.one": "Pet", "kind.PET.other": "Pets", "kind.PET.new": "New pet", + "kind.VEHICLE.one": "Vehicle", + "kind.VEHICLE.other": "Vehicles", + "kind.VEHICLE.new": "New vehicle", + "kind.SKETCH.one": "Sketch", + "kind.SKETCH.other": "Sketches", + "kind.SKETCH.new": "New sketch", + "kind.RESEARCH.one": "Research", + "kind.RESEARCH.other": "Research", + "kind.RESEARCH.new": "New research", + "kind.REFERENCE.one": "Reference", + "kind.REFERENCE.other": "References", + "kind.REFERENCE.new": "New reference", + "kind.APP.one": "App", + "kind.APP.other": "Apps", + "kind.APP.new": "New app", + "kind.WEBSITE.one": "Website", + "kind.WEBSITE.other": "Websites", + "kind.WEBSITE.new": "New website", + "nav.register": "Registers", + "nav.idRegister": "ID register", + "dashboard.registers": "Registers", + "common.codeAuto": "Created automatically when the item is saved.", + "register.title": "ID register", + "register.intro": "All IDs in the book in one place. IDs are created automatically and used to cross-reference between documents.", + "register.search": "Search ID or name…", + "register.type": "Type", + "register.id": "ID", + "register.name": "Name", + "register.empty": "No IDs match.", + "register.relation": "Relationship", + "register.map": "Map", + "register.marker": "Placement", + "register.schedule": "Schedule", "entity.search": "Search by name or summary…", "entity.empty": "Nothing here yet. Create the first one!", diff --git a/src/i18n/sv.ts b/src/i18n/sv.ts index 4c545c0..a1d8cd7 100644 --- a/src/i18n/sv.ts +++ b/src/i18n/sv.ts @@ -2,8 +2,7 @@ export const sv = { "app.name": "Bokplanerare", "common.save": "Spara", - "common.code": "ID / kod", - "common.codeHelp": "Valfritt, t.ex. K001. För att hänvisa mellan dokument.", + "common.code": "ID", "common.saved": "Sparat.", "common.cancel": "Avbryt", "common.delete": "Ta bort", @@ -97,6 +96,39 @@ export const sv = { "kind.PET.one": "Husdjur", "kind.PET.other": "Husdjur", "kind.PET.new": "Nytt husdjur", + "kind.VEHICLE.one": "Fordon", + "kind.VEHICLE.other": "Fordon", + "kind.VEHICLE.new": "Nytt fordon", + "kind.SKETCH.one": "Skiss", + "kind.SKETCH.other": "Skisser", + "kind.SKETCH.new": "Ny skiss", + "kind.RESEARCH.one": "Research", + "kind.RESEARCH.other": "Research", + "kind.RESEARCH.new": "Ny research", + "kind.REFERENCE.one": "Referens", + "kind.REFERENCE.other": "Referenser", + "kind.REFERENCE.new": "Ny referens", + "kind.APP.one": "App", + "kind.APP.other": "Appar", + "kind.APP.new": "Ny app", + "kind.WEBSITE.one": "Hemsida", + "kind.WEBSITE.other": "Hemsidor", + "kind.WEBSITE.new": "Ny hemsida", + "nav.register": "Register", + "nav.idRegister": "ID-register", + "dashboard.registers": "Register", + "common.codeAuto": "Skapas automatiskt när posten sparas.", + "register.title": "ID-register", + "register.intro": "Alla ID i boken samlade på ett ställe. ID skapas automatiskt och används som referens mellan dokument.", + "register.search": "Sök ID eller namn…", + "register.type": "Typ", + "register.id": "ID", + "register.name": "Namn", + "register.empty": "Inga ID matchar.", + "register.relation": "Relation", + "register.map": "Karta", + "register.marker": "Placering", + "register.schedule": "Schema", "entity.search": "Sök på namn eller sammanfattning…", "entity.empty": "Inget här ännu. Skapa det första!", diff --git a/src/lib/ids.ts b/src/lib/ids.ts new file mode 100644 index 0000000..383166a --- /dev/null +++ b/src/lib/ids.ts @@ -0,0 +1,69 @@ +import type { EntityKind, Prisma, PrismaClient } from "@prisma/client"; +import { prisma } from "./db"; + +type Db = PrismaClient | Prisma.TransactionClient; + +// ID-schema enligt författarens idöversikt. Siffrorna räknas upp löpande per bok och typ. +// Plats och Scenario saknas i översikten, deras prefix är förslag (ändra här vid behov). +// Appar och Hemsidor har inget ID. +export const ENTITY_PREFIX: Partial> = { + CHARACTER: "KI", // Karaktärs ID + COMPANY: "FI", // Företag ID + HOME: "BI", // Bostads ID + PET: "DI", // Djur ID + PREMISES: "LI", // Lokal ID + EDUCATION: "UI", // Utbildnings ID + VEHICLE: "FD", // Fordons ID + RESEARCH: "RI", // Research ID + REFERENCE: "RD", // Referens ID + SKETCH: "SI", // Skiss ID + PLACE: "PLI", // Plats ID (förslag) + SCENARIO: "SNI", // Scenario ID (förslag) +}; + +export const RELATION_PREFIX = "REI"; // Relations ID +export const MARKER_PREFIX = "PI"; // Placerings ID +export const SCHEDULE_PREFIX = "SCI"; // Schema ID +export const MAP_PREFIX = "KD"; // Kart ID: KD-R_0001 (riktig karta) eller KD-E_0001 (egen kartbild) + +export function mapLetter(kind: "GEO" | "IMAGE"): "R" | "E" { + return kind === "GEO" ? "R" : "E"; +} + +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 { + const row = await db.idCounter.upsert({ + where: { bookId_key: { bookId, key } }, + create: { bookId, key, next: 1 }, + update: { next: { increment: 1 } }, + }); + return row.next; +} + +/** T.ex. KI-0001. Ger null för typer utan ID. */ +export async function nextEntityCode(bookId: string, kind: EntityKind, db: Db = prisma): Promise { + const prefix = ENTITY_PREFIX[kind]; + if (!prefix) return null; + return `${prefix}-${pad(await nextNumber(db, bookId, prefix))}`; +} + +export async function nextRelationCode(bookId: string, db: Db = prisma): Promise { + return `${RELATION_PREFIX}-${pad(await nextNumber(db, bookId, RELATION_PREFIX))}`; +} + +export async function nextMarkerCode(bookId: string, db: Db = prisma): Promise { + return `${MARKER_PREFIX}-${pad(await nextNumber(db, bookId, MARKER_PREFIX))}`; +} + +export async function nextScheduleCode(bookId: string, db: Db = prisma): Promise { + return `${SCHEDULE_PREFIX}-${pad(await nextNumber(db, bookId, SCHEDULE_PREFIX))}`; +} + +/** T.ex. KD-R_0001. Bokstaven anger kartans typ och räknas separat. */ +export async function nextMapCode(bookId: string, kind: "GEO" | "IMAGE", db: Db = prisma): Promise { + const letter = mapLetter(kind); + const key = `${MAP_PREFIX}-${letter}`; + return `${key}_${pad(await nextNumber(db, bookId, key))}`; +} diff --git a/src/lib/kinds.ts b/src/lib/kinds.ts index 27965e6..62c265e 100644 --- a/src/lib/kinds.ts +++ b/src/lib/kinds.ts @@ -4,18 +4,26 @@ export type KindInfo = { kind: EntityKind; slug: string; color: string; + // world = berättelsens värld, register = stödregister (fordon, research, skisser ...) + group: "world" | "register"; }; // Ordningen styr menyer och översikt. export const KINDS: KindInfo[] = [ - { kind: "CHARACTER", slug: "characters", color: "blue" }, - { kind: "PET", slug: "pets", color: "orange" }, - { kind: "HOME", slug: "homes", color: "green" }, - { kind: "PLACE", slug: "places", color: "red" }, - { kind: "COMPANY", slug: "companies", color: "purple" }, - { kind: "PREMISES", slug: "premises", color: "teal" }, - { kind: "EDUCATION", slug: "education", color: "cyan" }, - { kind: "SCENARIO", slug: "scenarios", color: "pink" }, + { kind: "CHARACTER", slug: "characters", color: "blue", group: "world" }, + { kind: "PET", slug: "pets", color: "orange", group: "world" }, + { kind: "HOME", slug: "homes", color: "green", group: "world" }, + { kind: "PLACE", slug: "places", color: "red", group: "world" }, + { kind: "COMPANY", slug: "companies", color: "purple", group: "world" }, + { kind: "PREMISES", slug: "premises", color: "teal", group: "world" }, + { kind: "EDUCATION", slug: "education", color: "cyan", group: "world" }, + { kind: "SCENARIO", slug: "scenarios", color: "pink", group: "world" }, + { kind: "VEHICLE", slug: "vehicles", color: "indigo", group: "register" }, + { kind: "SKETCH", slug: "sketches", color: "azure", group: "register" }, + { kind: "RESEARCH", slug: "research", color: "lime", group: "register" }, + { kind: "REFERENCE", slug: "references", color: "yellow", group: "register" }, + { kind: "APP", slug: "apps", color: "dark", group: "register" }, + { kind: "WEBSITE", slug: "websites", color: "secondary", group: "register" }, ]; export const KIND_BY_SLUG = new Map(KINDS.map((k) => [k.slug, k])); diff --git a/src/lib/templates.ts b/src/lib/templates.ts index c77a3cf..62280c7 100644 --- a/src/lib/templates.ts +++ b/src/lib/templates.ts @@ -206,6 +206,30 @@ const SPECS: Record = { area("impactAfter", ["Hur påverkas karaktärerna efter scenariot", "How the characters are affected afterwards"]), area("notes", ["Övrig information", "Other information"]), ], + VEHICLE: [ + f("model", ["Märke och modell", "Make and model"], "text", ["Grunduppgifter", "Basics"]), + pick("fuel", ["Drivmedel", "Fuel"], ["Bensin", "Diesel", "El"], ["Petrol", "Diesel", "Electric"]), + area("description", ["Beskrivning", "Description"]), + NOTES, + ], + SKETCH: [ + pick( + "sketchType", + ["Typ av skiss", "Type of sketch"], + ["Planritning", "Miljöskiss", "Annat"], + ["Floor plan", "Environment sketch", "Other"], + ["Grunduppgifter", "Basics"], + ), + area("description", ["Beskrivning", "Description"]), + NOTES, + ], + RESEARCH: [area("description", ["Beskrivning", "Description"], ["Research", "Research"])], + REFERENCE: [ + f("link", ["Länk eller källa", "Link or source"], "url", ["Referens", "Reference"]), + area("description", ["Beskrivning", "Description"]), + ], + APP: [area("description", ["Beskrivning", "Description"], ["Applikation på telefonen", "Phone application"])], + WEBSITE: [area("description", ["Beskrivning", "Description"], ["Hemsida", "Website"])], RELATION: [ pick( "category",