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) => (
{book.description}
: null}{t("register.intro")}
+| {t("register.id")} | +{t("register.type")} | +{t("register.name")} | +
|---|---|---|
| + {r.code} + | +{r.typeLabel} | ++ + {r.name} + + {r.detail ? · {r.detail} : null} + | +