Fälttyp för koppling till post i mallar
- Ny fälttyp reference med valfri posttyp (refKind): rullista i formuläret, länk med ID på postsidan och rutan "Används av" på den kopplade posten - Server kontrollerar att kopplad post finns i boken och har rätt typ - Gemensam hantering av fältvärden (lib/field-values.ts) för poster och relationer - Standardmallar använder kopplingar för Lokal, Skiss, Företag, Ägare och Referens - Mallredigerare, översättningar och README Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
6cea76899f
commit
e840adf526
13 files changed
+235
-57
No files matched your search
@@ -74,6 +74,12 @@ Under **Mallar** kan du ändra fält, ordning, rubriker och fälttyper (text, te
|
||||
]
|
||||
```
|
||||
|
||||
### Kopplingar till andra poster
|
||||
|
||||
Fälttypen **Koppling till post** pekar direkt på en annan post, till exempel *Lokal* i en företagsmall. Du väljer den i mallredigeraren och anger vilken posttyp som får väljas (eller alla). I formuläret blir fältet en rullista med posterna och deras ID, och på postens sida visas länken. På den kopplade posten visas var den används, till exempel vilka företag och skolor som använder en lokal (*Används av*). Till skillnad från en relation är det ett fält i mallen, med en tydlig roll som *Lokal*, *Skiss* eller *Ägare*.
|
||||
|
||||
Standardmallarna använder det för Lokal och Skiss i Företag, Lokal, Bostad och Utbildning, Företag i Utbildning, Ägare och Referens i Fordon och Kopplat till i Scenario. I JSON ser ett sådant fält ut så här: `{ "key": "premises", "label": "Lokal", "type": "reference", "refKind": "PREMISES" }` (utan `refKind` kan alla typer väljas).
|
||||
|
||||
Ändrar du en mall försvinner ingen data: värden för borttagna fält finns kvar i databasen.
|
||||
|
||||
## Automatiska ID
|
||||
|
||||
+2
-17
@@ -5,6 +5,7 @@ import { redirect } from "next/navigation";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { deleteImage, isUpload, saveImage } from "@/lib/files";
|
||||
import { optStr, parseTags, revalidateBook, str } from "@/lib/form";
|
||||
import { collectFieldData } from "@/lib/field-values";
|
||||
import { KIND_INFO, parseKind } from "@/lib/kinds";
|
||||
import { nextEntityCode } from "@/lib/ids";
|
||||
import { requireBook, requireEntity } from "@/lib/session";
|
||||
@@ -22,23 +23,7 @@ export async function saveEntity(formData: FormData) {
|
||||
if (!name) throw new Error("Name is required");
|
||||
|
||||
const { fields } = await getTemplate(book.id, kind, await getLocale());
|
||||
const data: Record<string, unknown> = { ...((existing?.data as Record<string, unknown> | null) ?? {}) };
|
||||
for (const field of fields) {
|
||||
const name = `f_${field.key}`;
|
||||
if (field.type === "checkbox") {
|
||||
data[field.key] = formData.has(name);
|
||||
continue;
|
||||
}
|
||||
const raw = str(formData, name, 20000);
|
||||
if (raw === "") {
|
||||
delete data[field.key];
|
||||
} else if (field.type === "number") {
|
||||
const n = Number(raw.replace(",", "."));
|
||||
if (Number.isFinite(n)) data[field.key] = n;
|
||||
} else {
|
||||
data[field.key] = raw;
|
||||
}
|
||||
}
|
||||
const data = await collectFieldData(book.id, fields, formData, (existing?.data as Record<string, unknown> | null) ?? null);
|
||||
|
||||
let imageFile = existing?.imageFile ?? null;
|
||||
const upload = formData.get("image");
|
||||
|
||||
@@ -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 { collectFieldData } from "@/lib/field-values";
|
||||
import { nextRelationCode } from "@/lib/ids";
|
||||
import { requireBook } from "@/lib/session";
|
||||
import { getTemplate } from "@/lib/templates";
|
||||
@@ -53,23 +54,7 @@ export async function saveRelation(formData: FormData) {
|
||||
if (!type) return;
|
||||
|
||||
const { fields } = await getTemplate(book.id, "RELATION", await getLocale());
|
||||
const data: Record<string, unknown> = { ...((relation.data as Record<string, unknown> | null) ?? {}) };
|
||||
for (const field of fields) {
|
||||
const name = `f_${field.key}`;
|
||||
if (field.type === "checkbox") {
|
||||
data[field.key] = formData.has(name);
|
||||
continue;
|
||||
}
|
||||
const raw = str(formData, name, 20000);
|
||||
if (raw === "") {
|
||||
delete data[field.key];
|
||||
} else if (field.type === "number") {
|
||||
const n = Number(raw.replace(",", "."));
|
||||
if (Number.isFinite(n)) data[field.key] = n;
|
||||
} else {
|
||||
data[field.key] = raw;
|
||||
}
|
||||
}
|
||||
const data = await collectFieldData(book.id, fields, formData, (relation.data as Record<string, unknown> | null) ?? null);
|
||||
|
||||
const memberIds = await cleanMemberIds(book.id, formData, [relation.fromId, relation.toId]);
|
||||
await prisma.$transaction([
|
||||
|
||||
@@ -3,6 +3,7 @@ import { saveEntity } from "@/actions/entities";
|
||||
import { EntityForm } from "@/components/entity-form";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { KIND_BY_SLUG } from "@/lib/kinds";
|
||||
import { requireBook } from "@/lib/session";
|
||||
import { getTemplate } from "@/lib/templates";
|
||||
@@ -21,6 +22,11 @@ export default async function NewEntityPage({
|
||||
if (!info) notFound();
|
||||
const { t, locale } = await getT();
|
||||
const { fields } = await getTemplate(bookId, info.kind, locale);
|
||||
const refEntities = await prisma.entity.findMany({
|
||||
where: { bookId },
|
||||
select: { id: true, name: true, kind: true, code: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -31,6 +37,7 @@ export default async function NewEntityPage({
|
||||
bookId={bookId}
|
||||
kind={info.kind}
|
||||
fields={fields}
|
||||
refEntities={refEntities}
|
||||
defaultName={name?.slice(0, 200)}
|
||||
cancelHref={`/books/${bookId}/e/${slug}`}
|
||||
t={t}
|
||||
|
||||
@@ -2,6 +2,7 @@ import { saveEntity } from "@/actions/entities";
|
||||
import { EntityForm } from "@/components/entity-form";
|
||||
import { PageBody, PageHeader } from "@/components/page";
|
||||
import { getT } from "@/i18n/server";
|
||||
import { prisma } from "@/lib/db";
|
||||
import { requireEntity } from "@/lib/session";
|
||||
import { getTemplate } from "@/lib/templates";
|
||||
|
||||
@@ -10,6 +11,11 @@ export default async function EditEntityPage({ params }: { params: Promise<{ boo
|
||||
const entity = await requireEntity(bookId, entityId);
|
||||
const { t, locale } = await getT();
|
||||
const { fields } = await getTemplate(bookId, entity.kind, locale);
|
||||
const refEntities = await prisma.entity.findMany({
|
||||
where: { bookId },
|
||||
select: { id: true, name: true, kind: true, code: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
|
||||
return (
|
||||
<>
|
||||
@@ -21,6 +27,7 @@ export default async function EditEntityPage({ params }: { params: Promise<{ boo
|
||||
kind={entity.kind}
|
||||
entity={entity}
|
||||
fields={fields}
|
||||
refEntities={refEntities}
|
||||
cancelHref={`/books/${bookId}/entity/${entity.id}`}
|
||||
t={t}
|
||||
/>
|
||||
|
||||
@@ -13,9 +13,10 @@ import { KIND_INFO, WORKPLACE_KINDS } from "@/lib/kinds";
|
||||
import { requireEntity } from "@/lib/session";
|
||||
import { formatFieldValue, getTemplate, type FieldDef } from "@/lib/templates";
|
||||
|
||||
type Group = { section?: string; items: { field: FieldDef; value: string }[] };
|
||||
type RefTarget = { id: string; name: string; code: string | null };
|
||||
type Group = { section?: string; items: { field: FieldDef; value: string; target?: RefTarget }[] };
|
||||
|
||||
function groupFields(fields: FieldDef[], data: Record<string, unknown>): Group[] {
|
||||
function groupFields(fields: FieldDef[], data: Record<string, unknown>, byId: Map<string, RefTarget>): Group[] {
|
||||
const groups: Group[] = [];
|
||||
let current: Group = { items: [] };
|
||||
for (const field of fields) {
|
||||
@@ -23,6 +24,11 @@ function groupFields(fields: FieldDef[], data: Record<string, unknown>): Group[]
|
||||
if (current.items.length > 0) groups.push(current);
|
||||
current = { section: field.section, items: [] };
|
||||
}
|
||||
if (field.type === "reference") {
|
||||
const target = typeof data[field.key] === "string" ? byId.get(data[field.key] as string) : undefined;
|
||||
if (target) current.items.push({ field, value: target.name, target });
|
||||
continue;
|
||||
}
|
||||
const value = formatFieldValue(field, data[field.key]);
|
||||
if (value) current.items.push({ field, value });
|
||||
}
|
||||
@@ -35,7 +41,7 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
|
||||
const base = await requireEntity(bookId, entityId);
|
||||
const { t, locale } = await getT();
|
||||
|
||||
const [entity, template, allEntities, maps] = await Promise.all([
|
||||
const [entity, template, bookEntities, maps] = await Promise.all([
|
||||
prisma.entity.findUniqueOrThrow({
|
||||
where: { id: base.id },
|
||||
include: {
|
||||
@@ -52,7 +58,7 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
|
||||
getTemplate(bookId, base.kind, locale),
|
||||
prisma.entity.findMany({
|
||||
where: { bookId },
|
||||
select: { id: true, name: true, kind: true },
|
||||
select: { id: true, name: true, kind: true, code: true, data: true },
|
||||
orderBy: { name: "asc" },
|
||||
}),
|
||||
prisma.bookMap.findMany({ where: { bookId }, orderBy: { name: "asc" } }),
|
||||
@@ -61,7 +67,27 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
|
||||
const info = KIND_INFO[entity.kind];
|
||||
const Icon = kindIcons[entity.kind];
|
||||
const image = fileUrl(entity.imageFile);
|
||||
const groups = groupFields(template.fields, (entity.data ?? {}) as Record<string, unknown>);
|
||||
const allEntities = bookEntities.map(({ data: _data, ...rest }) => rest);
|
||||
const groups = groupFields(
|
||||
template.fields,
|
||||
(entity.data ?? {}) as Record<string, unknown>,
|
||||
new Map(allEntities.map((e) => [e.id, e])),
|
||||
);
|
||||
|
||||
// Poster som pekar hit via ett kopplingsfält i sin mall, t.ex. företag som använder den här lokalen
|
||||
const referencing = bookEntities.filter(
|
||||
(e) => e.id !== entity.id && Object.values((e.data ?? {}) as Record<string, unknown>).some((v) => v === entity.id),
|
||||
);
|
||||
const referencingTemplates = new Map(
|
||||
await Promise.all(
|
||||
[...new Set(referencing.map((e) => e.kind))].map(async (kind) => [kind, (await getTemplate(bookId, kind, locale)).fields] as const),
|
||||
),
|
||||
);
|
||||
const backlinks = referencing.map((e) => {
|
||||
const data = (e.data ?? {}) as Record<string, unknown>;
|
||||
const field = (referencingTemplates.get(e.kind) ?? []).find((f) => f.type === "reference" && data[f.key] === entity.id);
|
||||
return { entity: e, label: field?.label ?? null };
|
||||
});
|
||||
const isWorkplace = WORKPLACE_KINDS.includes(entity.kind);
|
||||
type Person = { id: string; name: string };
|
||||
type RelationItem = {
|
||||
@@ -176,11 +202,16 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
|
||||
<div key={i} className={i > 0 ? "mt-4" : ""}>
|
||||
{group.section ? <h4 className="subheader border-bottom pb-2 mb-3">{group.section}</h4> : null}
|
||||
<dl className="mb-0">
|
||||
{group.items.map(({ field, value }) => (
|
||||
{group.items.map(({ field, value, target }) => (
|
||||
<div className="row mb-2" key={field.key}>
|
||||
<dt className="col-sm-4 text-secondary fw-normal">{field.label}</dt>
|
||||
<dd className={`col-sm-8 mb-0 ${field.type === "textarea" ? "bm-prewrap" : ""}`}>
|
||||
{field.type === "url" ? (
|
||||
{target ? (
|
||||
<Link href={entityHref(target.id)} className="fw-bold">
|
||||
{target.code ? <span className="badge me-2">{target.code}</span> : null}
|
||||
{target.name}
|
||||
</Link>
|
||||
) : field.type === "url" ? (
|
||||
<a href={value} target="_blank" rel="noopener noreferrer nofollow">
|
||||
{value}
|
||||
</a>
|
||||
@@ -196,6 +227,23 @@ export default async function EntityPage({ params }: { params: Promise<{ bookId:
|
||||
)}
|
||||
</div>
|
||||
</div>
|
||||
{backlinks.length > 0 ? (
|
||||
<div className="card mt-3">
|
||||
<div className="card-header">
|
||||
<h3 className="card-title">{t("entity.referencedBy")}</h3>
|
||||
</div>
|
||||
<div className="list-group list-group-flush">
|
||||
{backlinks.map(({ entity: e, label }) => (
|
||||
<Link key={e.id} href={entityHref(e.id)} className="list-group-item list-group-item-action d-flex align-items-center gap-2">
|
||||
{e.code ? <span className="badge">{e.code}</span> : null}
|
||||
<span className="fw-bold">{e.name}</span>
|
||||
<span className="text-secondary">{t(`kind.${e.kind}.one`)}</span>
|
||||
{label ? <span className="badge bg-azure-lt ms-auto">{label}</span> : null}
|
||||
</Link>
|
||||
))}
|
||||
</div>
|
||||
</div>
|
||||
) : null}
|
||||
</div>
|
||||
|
||||
<div className="col-lg-4">
|
||||
|
||||
@@ -34,6 +34,11 @@ export default async function RelationPage({
|
||||
select: { id: true, name: true, kind: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
const refEntities = await prisma.entity.findMany({
|
||||
where: { bookId },
|
||||
select: { id: true, name: true, kind: true, code: true },
|
||||
orderBy: { name: "asc" },
|
||||
});
|
||||
const memberEntities = relation.members.map((m) => m.entity);
|
||||
const isGroup = memberEntities.length > 0;
|
||||
const { fields } = await getTemplate(bookId, "RELATION", locale);
|
||||
@@ -139,7 +144,7 @@ export default async function RelationPage({
|
||||
) : null}
|
||||
<div className={field.type === "textarea" ? "col-12" : "col-md-6"}>
|
||||
{field.type !== "checkbox" ? <label className="form-label">{field.label}</label> : null}
|
||||
<FieldInput field={field} value={data[field.key]} />
|
||||
<FieldInput field={field} value={data[field.key]} refs={{ entities: refEntities, t }} />
|
||||
</div>
|
||||
</Fragment>
|
||||
))}
|
||||
|
||||
@@ -4,9 +4,23 @@ import type { Entity, EntityKind } from "@prisma/client";
|
||||
import type { TFunction } from "@/i18n/core";
|
||||
import { NameFill } from "./name-fill";
|
||||
import { fileUrl } from "@/lib/files";
|
||||
import { KINDS } from "@/lib/kinds";
|
||||
import type { FieldDef } from "@/lib/templates";
|
||||
|
||||
export function FieldInput({ field, value }: { field: FieldDef; value: unknown }) {
|
||||
export type RefOption = { id: string; name: string; kind: EntityKind; code: string | null };
|
||||
|
||||
const refLabel = (e: RefOption) => (e.code ? `${e.code} · ${e.name}` : e.name);
|
||||
|
||||
export function FieldInput({
|
||||
field,
|
||||
value,
|
||||
refs,
|
||||
}: {
|
||||
field: FieldDef;
|
||||
value: unknown;
|
||||
// Poster som kan väljas i fält av typen reference
|
||||
refs?: { entities: RefOption[]; t: TFunction };
|
||||
}) {
|
||||
const name = `f_${field.key}`;
|
||||
const text = value === null || value === undefined ? "" : String(value);
|
||||
|
||||
@@ -26,6 +40,34 @@ export function FieldInput({ field, value }: { field: FieldDef; value: unknown }
|
||||
<span className="form-check-label">{field.label}</span>
|
||||
</label>
|
||||
);
|
||||
case "reference": {
|
||||
const candidates = (refs?.entities ?? []).filter((e) => !field.refKind || e.kind === field.refKind);
|
||||
const selected = typeof value === "string" ? value : "";
|
||||
return (
|
||||
<select name={name} className="form-select" defaultValue={selected}>
|
||||
<option value="" />
|
||||
{field.refKind
|
||||
? candidates.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{refLabel(e)}
|
||||
</option>
|
||||
))
|
||||
: KINDS.map(({ kind }) => {
|
||||
const group = candidates.filter((e) => e.kind === kind);
|
||||
if (group.length === 0) return null;
|
||||
return (
|
||||
<optgroup key={kind} label={refs?.t(`kind.${kind}.other`)}>
|
||||
{group.map((e) => (
|
||||
<option key={e.id} value={e.id}>
|
||||
{refLabel(e)}
|
||||
</option>
|
||||
))}
|
||||
</optgroup>
|
||||
);
|
||||
})}
|
||||
</select>
|
||||
);
|
||||
}
|
||||
case "select": {
|
||||
const options = field.options ?? [];
|
||||
const extra = text && !options.includes(text) ? [text] : [];
|
||||
@@ -53,6 +95,7 @@ export function EntityForm({
|
||||
fields,
|
||||
cancelHref,
|
||||
defaultName,
|
||||
refEntities,
|
||||
t,
|
||||
}: {
|
||||
action: (formData: FormData) => Promise<void>;
|
||||
@@ -62,6 +105,7 @@ export function EntityForm({
|
||||
fields: FieldDef[];
|
||||
cancelHref: string;
|
||||
defaultName?: string;
|
||||
refEntities: RefOption[];
|
||||
t: TFunction;
|
||||
}) {
|
||||
const data = (entity?.data ?? {}) as Record<string, unknown>;
|
||||
@@ -139,7 +183,11 @@ export function EntityForm({
|
||||
) : null}
|
||||
<div className={field.type === "textarea" ? "col-12" : "col-md-6"}>
|
||||
{field.type !== "checkbox" ? <label className="form-label">{field.label}</label> : null}
|
||||
<FieldInput field={field} value={data[field.key]} />
|
||||
<FieldInput
|
||||
field={field}
|
||||
value={data[field.key]}
|
||||
refs={{ entities: refEntities.filter((e) => e.id !== entity?.id), t }}
|
||||
/>
|
||||
</div>
|
||||
</Fragment>
|
||||
))}
|
||||
|
||||
@@ -6,6 +6,7 @@ import type { TemplateKind } from "@/lib/kinds";
|
||||
import { resetTemplate, saveTemplate } from "@/actions/templates";
|
||||
import { ConfirmSubmit } from "@/components/confirm-submit";
|
||||
import { useT } from "@/i18n/client";
|
||||
import { KINDS, parseKind } from "@/lib/kinds";
|
||||
import { FIELD_TYPES, type FieldDef, type FieldType } from "@/lib/templates";
|
||||
|
||||
type Row = FieldDef & { optionsText: string; rowId: number };
|
||||
@@ -54,6 +55,7 @@ export function TemplateEditor({
|
||||
.map((o) => o.trim())
|
||||
.filter(Boolean);
|
||||
}
|
||||
if (f.type === "reference" && f.refKind) field.refKind = f.refKind;
|
||||
if (f.section) field.section = f.section;
|
||||
return field;
|
||||
});
|
||||
@@ -83,6 +85,7 @@ export function TemplateEditor({
|
||||
label: String(f.label ?? ""),
|
||||
type: FIELD_TYPES.includes(f.type) ? f.type : "text",
|
||||
section: f.section,
|
||||
refKind: parseKind(f.refKind) ?? undefined,
|
||||
optionsText: Array.isArray(f.options) ? f.options.join(", ") : "",
|
||||
rowId: id++,
|
||||
})),
|
||||
@@ -149,9 +152,24 @@ export function TemplateEditor({
|
||||
</select>
|
||||
</div>
|
||||
<div className="col-md-3">
|
||||
<label className="form-label">{row.type === "select" ? t("template.fieldOptions") : t("template.fieldSection")}</label>
|
||||
<label className="form-label">
|
||||
{row.type === "select" ? t("template.fieldOptions") : row.type === "reference" ? t("template.refKind") : t("template.fieldSection")}
|
||||
</label>
|
||||
{row.type === "select" ? (
|
||||
<input className="form-control" value={row.optionsText} onChange={(e) => update(row.rowId, { optionsText: e.target.value })} />
|
||||
) : row.type === "reference" ? (
|
||||
<select
|
||||
className="form-select"
|
||||
value={row.refKind ?? ""}
|
||||
onChange={(e) => update(row.rowId, { refKind: parseKind(e.target.value) ?? undefined })}
|
||||
>
|
||||
<option value="">{t("template.refKind.any")}</option>
|
||||
{KINDS.map(({ kind }) => (
|
||||
<option key={kind} value={kind}>
|
||||
{t(`kind.${kind}.one`)}
|
||||
</option>
|
||||
))}
|
||||
</select>
|
||||
) : (
|
||||
<input className="form-control" value={row.section ?? ""} onChange={(e) => update(row.rowId, { section: e.target.value })} />
|
||||
)}
|
||||
@@ -174,7 +192,7 @@ export function TemplateEditor({
|
||||
</button>
|
||||
</div>
|
||||
</div>
|
||||
{row.type === "select" ? (
|
||||
{row.type === "select" || row.type === "reference" ? (
|
||||
<div className="mt-2">
|
||||
<label className="form-label">{t("template.fieldSection")}</label>
|
||||
<input className="form-control" value={row.section ?? ""} onChange={(e) => update(row.rowId, { section: e.target.value })} />
|
||||
|
||||
@@ -304,6 +304,10 @@ export const en: Record<keyof typeof sv, string> = {
|
||||
"template.type.select": "Choice",
|
||||
"template.type.checkbox": "Checkbox",
|
||||
"template.type.url": "Link",
|
||||
"template.type.reference": "Link to item",
|
||||
"template.refKind": "Points to type",
|
||||
"template.refKind.any": "All types",
|
||||
"entity.referencedBy": "Used by",
|
||||
"template.empty": "The template has no fields yet.",
|
||||
|
||||
"settings.title": "Book settings",
|
||||
|
||||
@@ -302,6 +302,10 @@ export const sv = {
|
||||
"template.type.select": "Val",
|
||||
"template.type.checkbox": "Kryssruta",
|
||||
"template.type.url": "Länk",
|
||||
"template.type.reference": "Koppling till post",
|
||||
"template.refKind": "Pekar på typ",
|
||||
"template.refKind.any": "Alla typer",
|
||||
"entity.referencedBy": "Används av",
|
||||
"template.empty": "Mallen har inga fält ännu.",
|
||||
|
||||
"settings.title": "Bokinställningar",
|
||||
|
||||
@@ -0,0 +1,46 @@
|
||||
import { prisma } from "./db";
|
||||
import { str } from "./form";
|
||||
import type { FieldDef } from "./templates";
|
||||
|
||||
/**
|
||||
* Läser mallfälten (f_<nyckel>) ur ett formulär och lägger dem ovanpå befintlig data.
|
||||
* Data för fält som inte finns i mallen lämnas orörd. Kopplingar till poster kontrolleras:
|
||||
* posten måste finnas i boken och vara av rätt typ, annars sparas ingen koppling.
|
||||
*/
|
||||
export async function collectFieldData(
|
||||
bookId: string,
|
||||
fields: FieldDef[],
|
||||
formData: FormData,
|
||||
existing: Record<string, unknown> | null,
|
||||
): Promise<Record<string, unknown>> {
|
||||
const data: Record<string, unknown> = { ...(existing ?? {}) };
|
||||
|
||||
for (const field of fields) {
|
||||
const name = `f_${field.key}`;
|
||||
if (field.type === "checkbox") {
|
||||
data[field.key] = formData.has(name);
|
||||
continue;
|
||||
}
|
||||
const raw = str(formData, name, 20000);
|
||||
if (raw === "") {
|
||||
delete data[field.key];
|
||||
} else if (field.type === "number") {
|
||||
const n = Number(raw.replace(",", "."));
|
||||
if (Number.isFinite(n)) data[field.key] = n;
|
||||
} else {
|
||||
data[field.key] = raw;
|
||||
}
|
||||
}
|
||||
|
||||
const refFields = fields.filter((f) => f.type === "reference" && typeof data[f.key] === "string");
|
||||
if (refFields.length > 0) {
|
||||
const ids = [...new Set(refFields.map((f) => data[f.key] as string))];
|
||||
const found = await prisma.entity.findMany({ where: { bookId, id: { in: ids } }, select: { id: true, kind: true } });
|
||||
const kindOf = new Map(found.map((e) => [e.id, e.kind]));
|
||||
for (const field of refFields) {
|
||||
const kind = kindOf.get(data[field.key] as string);
|
||||
if (!kind || (field.refKind && kind !== field.refKind)) delete data[field.key];
|
||||
}
|
||||
}
|
||||
return data;
|
||||
}
|
||||
+26
-11
@@ -1,24 +1,29 @@
|
||||
import { prisma } from "./db";
|
||||
import type { EntityKind } from "@prisma/client";
|
||||
import type { Locale } from "@/i18n/core";
|
||||
import type { TemplateKind } from "./kinds";
|
||||
import { parseKind, type TemplateKind } from "./kinds";
|
||||
|
||||
export type FieldType = "text" | "textarea" | "number" | "date" | "select" | "checkbox" | "url";
|
||||
// reference = koppling till en annan post (t.ex. en lokal). Värdet är postens id.
|
||||
export type FieldType = "text" | "textarea" | "number" | "date" | "select" | "checkbox" | "url" | "reference";
|
||||
|
||||
export const FIELD_TYPES: FieldType[] = ["text", "textarea", "number", "date", "select", "checkbox", "url"];
|
||||
export const FIELD_TYPES: FieldType[] = ["text", "textarea", "number", "date", "select", "checkbox", "url", "reference"];
|
||||
|
||||
export type FieldDef = {
|
||||
key: string;
|
||||
label: string;
|
||||
type: FieldType;
|
||||
options?: string[];
|
||||
// För reference: vilken typ av post som kan väljas. Saknas den kan alla typer väljas.
|
||||
refKind?: EntityKind;
|
||||
// Ett fält med section startar en ny rubrik i formuläret och på sidan.
|
||||
section?: string;
|
||||
};
|
||||
|
||||
type L = [string, string]; // [svenska, engelska]
|
||||
type Spec = { k: string; l: L; t?: FieldType; o?: [string[], string[]]; s?: L };
|
||||
type Spec = { k: string; l: L; t?: FieldType; o?: [string[], string[]]; s?: L; r?: EntityKind };
|
||||
|
||||
const f = (k: string, l: L, t: FieldType = "text", s?: L, o?: [string[], string[]]): Spec => ({ k, l, t, s, o });
|
||||
const ref = (k: string, l: L, r?: EntityKind, s?: L): Spec => ({ ...f(k, l, "reference", s), r });
|
||||
const yes = (k: string, l: L, s?: L): Spec => f(k, l, "checkbox", s);
|
||||
const area = (k: string, l: L, s?: L): Spec => f(k, l, "textarea", s);
|
||||
const pick = (k: string, l: L, sv: string[], en: string[], s?: L): Spec => f(k, l, "select", s, [sv, en]);
|
||||
@@ -77,7 +82,7 @@ const SPECS: Record<TemplateKind, Spec[]> = {
|
||||
f("address", ["Adress", "Address"]),
|
||||
f("rooms", ["Antal rum", "Number of rooms"], "number"),
|
||||
f("livingArea", ["Boarea (m²)", "Living area (m²)"], "number"),
|
||||
f("sketchId", ["Skiss-ID", "Sketch ID"]),
|
||||
ref("sketch", ["Skiss", "Sketch"], "SKETCH"),
|
||||
area("buildingLook", ["Byggnadsutseende", "Building appearance"], ["Byggnaden", "The building"]),
|
||||
area("buildingHistory", ["Byggnadsinformation (historia)", "Building information (history)"]),
|
||||
f("floor", ["Våning", "Floor"], "text", ["Lägenhet och hus", "Apartment and building"]),
|
||||
@@ -129,8 +134,9 @@ const SPECS: Record<TemplateKind, Spec[]> = {
|
||||
],
|
||||
COMPANY: [
|
||||
f("industry", ["Bransch", "Industry"], "text", ["Grunduppgifter", "Basics"]),
|
||||
ref("premises", ["Lokal", "Premises"], "PREMISES"),
|
||||
yes("hasSketches", ["Finns skisser", "Has sketches"]),
|
||||
f("sketchId", ["Skiss-ID", "Sketch ID"]),
|
||||
ref("sketch", ["Skiss", "Sketch"], "SKETCH"),
|
||||
yes("workplaceForCharacters", ["Arbetsplats för karaktärer", "Workplace for characters"], ["Annan information", "Other information"]),
|
||||
yes("socialPlace", ["Plats för karaktärerna att umgås", "Place for the characters to socialise"]),
|
||||
yes("alcohol", ["Alkoholservering (restaurang/hotell)", "Serves alcohol (restaurant/hotel)"]),
|
||||
@@ -154,7 +160,7 @@ const SPECS: Record<TemplateKind, Spec[]> = {
|
||||
f("area", ["Yta (m²)", "Area (m²)"], "number"),
|
||||
pick("tenure", ["Ägande", "Ownership"], ["Hyr", "Äga"], ["Rent", "Own"]),
|
||||
f("floors", ["Antal våningar", "Number of floors"], "number"),
|
||||
f("sketchId", ["Skiss-ID", "Sketch ID"]),
|
||||
ref("sketch", ["Skiss", "Sketch"], "SKETCH"),
|
||||
f("owner", ["Ägare", "Owner"]),
|
||||
yes("loadingDock", ["Lastkaj", "Loading dock"], ["Faciliteter", "Facilities"]),
|
||||
yes("coldStorage", ["Kyl och frys", "Cold storage"]),
|
||||
@@ -182,9 +188,9 @@ const SPECS: Record<TemplateKind, Spec[]> = {
|
||||
pick("ownership", ["Ägande", "Ownership"], ["Kommunal", "Privat"], ["Public", "Private"], ["Om skolan", "About the school"]),
|
||||
f("grades", ["Årskurs", "Grades"]),
|
||||
f("classCount", ["Antal klasser", "Number of classes"], "number"),
|
||||
f("premisesId", ["Lokal-ID", "Premises ID"]),
|
||||
f("companyId", ["Företags-ID (om privat)", "Company ID (if private)"]),
|
||||
f("sketchId", ["Skiss-ID", "Sketch ID"]),
|
||||
ref("premises", ["Lokal", "Premises"], "PREMISES"),
|
||||
ref("company", ["Företag (om privat)", "Company (if private)"], "COMPANY"),
|
||||
ref("sketch", ["Skiss", "Sketch"], "SKETCH"),
|
||||
yes("cafeteria", ["Finns cafeteria", "Has cafeteria"]),
|
||||
yes("youthCentre", ["Finns fritidsgård", "Has youth centre"]),
|
||||
area("computerUse", ["Hur används datorer", "How computers are used"]),
|
||||
@@ -199,7 +205,7 @@ const SPECS: Record<TemplateKind, Spec[]> = {
|
||||
["Argument", "Accident", "Death", "Infidelity", "Crime", "Other"],
|
||||
["Grunduppgifter", "Basics"],
|
||||
),
|
||||
f("linkedId", ["Kopplat ID", "Linked ID"]),
|
||||
ref("linkedEntity", ["Kopplat till (post)", "Linked to (item)"]),
|
||||
f("when", ["När (tid i berättelsen)", "When (story time)"]),
|
||||
area("description", ["Beskriv scenariot", "Describe the scenario"], ["Innehåll", "Content"]),
|
||||
area("impactDuring", ["Hur påverkas karaktärerna under scenariot", "How the characters are affected during"]),
|
||||
@@ -208,6 +214,8 @@ const SPECS: Record<TemplateKind, Spec[]> = {
|
||||
],
|
||||
VEHICLE: [
|
||||
f("model", ["Märke och modell", "Make and model"], "text", ["Grunduppgifter", "Basics"]),
|
||||
ref("owner", ["Ägare", "Owner"], "CHARACTER"),
|
||||
ref("reference", ["Referens", "Reference"], "REFERENCE"),
|
||||
pick("fuel", ["Drivmedel", "Fuel"], ["Bensin", "Diesel", "El"], ["Petrol", "Diesel", "Electric"]),
|
||||
area("description", ["Beskrivning", "Description"]),
|
||||
NOTES,
|
||||
@@ -258,6 +266,7 @@ function build(specs: Spec[], locale: Locale): FieldDef[] {
|
||||
label: s.l[i],
|
||||
type: s.t ?? "text",
|
||||
...(s.o ? { options: s.o[i] } : {}),
|
||||
...(s.r ? { refKind: s.r } : {}),
|
||||
...(s.s ? { section: s.s[i] } : {}),
|
||||
}));
|
||||
}
|
||||
@@ -300,6 +309,11 @@ export function validateFields(input: unknown): FieldDef[] {
|
||||
const options = Array.isArray(r.options) ? r.options.map((o) => String(o).trim()).filter(Boolean) : [];
|
||||
field.options = options.slice(0, 50);
|
||||
}
|
||||
if (type === "reference" && r.refKind) {
|
||||
const refKind = parseKind(r.refKind);
|
||||
if (!refKind) throw new Error(`refKind (${key})`);
|
||||
field.refKind = refKind;
|
||||
}
|
||||
const section = typeof r.section === "string" ? r.section.trim() : "";
|
||||
if (section) field.section = section.slice(0, 120);
|
||||
return field;
|
||||
@@ -325,5 +339,6 @@ export async function getTemplate(
|
||||
export function formatFieldValue(field: FieldDef, value: unknown): string {
|
||||
if (value === null || value === undefined || value === "") return "";
|
||||
if (field.type === "checkbox") return value ? "✓" : "";
|
||||
if (field.type === "reference") return ""; // visas som länk, se postsidan
|
||||
return String(value);
|
||||
}
|
||||
Reference in new issue
Block a user