@cosmicdrift/kumiko-samples 0.422.0 → 0.424.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/package.json +1 -1
- package/packages/bundled-features/package.json +11 -1
- package/packages/bundled-features/src/document-draft/README.md +84 -0
- package/packages/bundled-features/src/document-draft/changes.json +8 -0
- package/packages/bundled-features/src/document-draft/entity.ts +125 -0
- package/packages/bundled-features/src/document-draft/feature.ts +56 -0
- package/packages/bundled-features/src/document-draft/handlers/blocks.query.ts +63 -0
- package/packages/bundled-features/src/document-draft/handlers/by-subject.query.ts +50 -0
- package/packages/bundled-features/src/document-draft/handlers/create.write.ts +110 -0
- package/packages/bundled-features/src/document-draft/handlers/discard.write.ts +32 -0
- package/packages/bundled-features/src/document-draft/handlers/finalize.write.ts +103 -0
- package/packages/bundled-features/src/document-draft/handlers/patch.write.ts +86 -0
- package/packages/bundled-features/src/document-draft/handlers/revise.write.ts +46 -0
- package/packages/bundled-features/src/document-draft/handlers/save.write.ts +53 -0
- package/packages/bundled-features/src/document-draft/i18n.ts +22 -0
- package/packages/bundled-features/src/document-draft/index.ts +21 -0
- package/packages/bundled-features/src/document-draft/lib.ts +77 -0
- package/packages/bundled-features/src/document-draft/options.ts +51 -0
- package/packages/bundled-features/src/document-draft/payloads.ts +45 -0
- package/packages/bundled-features/src/document-draft/screens/editor-screen.ts +17 -0
- package/packages/bundled-features/src/document-draft/user-data.ts +63 -0
- package/packages/bundled-features/src/document-draft/web/client-plugin.tsx +20 -0
- package/packages/bundled-features/src/document-draft/web/constants.ts +56 -0
- package/packages/bundled-features/src/document-draft/web/editor-screen.tsx +418 -0
- package/packages/bundled-features/src/document-draft/web/i18n.ts +54 -0
- package/packages/bundled-features/src/document-draft/web/index.ts +14 -0
- package/packages/bundled-features/src/helpdesk/changes.json +6 -0
- package/packages/bundled-features/src/shared/index.ts +6 -0
- package/packages/bundled-features/src/{signature → shared}/subject-scope.ts +17 -6
- package/packages/bundled-features/src/signature/changes.json +6 -0
- package/packages/bundled-features/src/signature/feature.ts +1 -1
- package/packages/bundled-features/src/signature/handlers/cancel.write.ts +1 -1
- package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +1 -1
- package/packages/bundled-features/src/signature/handlers/request.write.ts +1 -1
- package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +1 -1
- package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +1 -1
- package/packages/bundled-features/src/signature/options.ts +2 -1
- package/packages/bundled-features/src/signature/subject-queries.ts +1 -1
- package/packages/bundled-features/src/template-resolver/api.ts +3 -1
- package/packages/bundled-features/src/template-resolver/boot-rules.ts +5 -0
- package/packages/bundled-features/src/template-resolver/changes.json +30 -0
- package/packages/bundled-features/src/template-resolver/feature.ts +15 -1
- package/packages/bundled-features/src/template-resolver/handlers/create-variant.write.ts +134 -0
- package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +3 -0
- package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +44 -1
- package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +12 -1
- package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +111 -11
- package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +29 -4
- package/packages/bundled-features/src/template-resolver/handlers/upsert-tenant.write.ts +1 -0
- package/packages/bundled-features/src/template-resolver/handlers/variants.query.ts +89 -0
- package/packages/bundled-features/src/template-resolver/i18n.ts +1 -0
- package/packages/bundled-features/src/template-resolver/index.ts +22 -0
- package/packages/bundled-features/src/template-resolver/seeding.ts +16 -1
- package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +56 -6
- package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +5 -5
- package/packages/bundled-features/src/template-resolver/template-meta.ts +1 -0
- package/packages/bundled-features/src/template-resolver/template-variants.ts +50 -0
- package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +10 -1
- package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +10 -4
- package/packages/bundled-features/src/template-resolver/web/i18n.ts +26 -0
- package/packages/bundled-features/src/template-resolver/web/index.ts +5 -0
- package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +5 -0
- package/packages/bundled-features/src/template-resolver/web/system-placeholders.ts +17 -0
- package/packages/bundled-features/src/tenant/changes.json +7 -0
- package/packages/bundled-features/src/tenant/handlers/update-member-roles.write.ts +1 -1
- package/packages/bundled-features/src/tenant/i18n.ts +0 -1
- package/packages/bundled-features/src/tenant-inactivity/changes.json +7 -0
- package/packages/bundled-features/src/tenant-inactivity/constants.ts +1 -1
- package/packages/bundled-features/src/tenant-lifecycle/changes.json +7 -0
- package/packages/bundled-features/src/tenant-lifecycle/constants.ts +1 -1
- package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
- package/samples/apps/use-all-bundled/feature-manifest.json +37 -1
- package/samples/apps/use-all-bundled/kumiko/migrations/0069_document-draft.rebuild.json +4 -0
- package/samples/apps/use-all-bundled/src/app/client.tsx +3 -0
- package/samples/apps/use-all-bundled/src/run-config.ts +8 -0
|
@@ -8,9 +8,9 @@ import {
|
|
|
8
8
|
type SessionUser,
|
|
9
9
|
} from "@cosmicdrift/kumiko-framework/engine";
|
|
10
10
|
import { AccessDeniedError } from "@cosmicdrift/kumiko-framework/errors";
|
|
11
|
+
import type { SubjectScope } from "../shared/index.ts";
|
|
11
12
|
import { requestExecutor } from "./entity.ts";
|
|
12
13
|
import { openListCursor, sealListCursor } from "./list-cursor-seal.ts";
|
|
13
|
-
import type { SubjectScope } from "./subject-scope.ts";
|
|
14
14
|
|
|
15
15
|
type ListPayload = ReturnType<typeof entityListSchema.parse>;
|
|
16
16
|
type ListFilter = NonNullable<ListPayload["filter"]>;
|
|
@@ -160,7 +160,9 @@ export function createTemplateResolverApi(
|
|
|
160
160
|
};
|
|
161
161
|
}
|
|
162
162
|
|
|
163
|
-
type DeliveredRowKey = Pick<TemplateResourceRow, "tenantId" | "kind" | "slug"
|
|
163
|
+
type DeliveredRowKey = Pick<TemplateResourceRow, "tenantId" | "kind" | "slug"> & {
|
|
164
|
+
readonly meta?: string | null;
|
|
165
|
+
};
|
|
164
166
|
|
|
165
167
|
// The one delivery rule for a stored row: unlocked, and a collection entry never shadows a system
|
|
166
168
|
// template of the same slug that the app did not unlock.
|
|
@@ -16,4 +16,9 @@ export const TEMPLATE_RESOLVER_BOOT_RULES = {
|
|
|
16
16
|
summary: "Each tenantEditable entry has a non-empty slug and at least one access role.",
|
|
17
17
|
fix: "Give the entry a slug and roles.",
|
|
18
18
|
},
|
|
19
|
+
tenantEditableVariantsNeedPdf: {
|
|
20
|
+
id: "template-resolver/tenant-editable-variants-need-pdf",
|
|
21
|
+
summary: "Only tenantEditable entries of kind document-pdf may set variants.",
|
|
22
|
+
fix: "Remove variants from the entry or change its kind to document-pdf.",
|
|
23
|
+
},
|
|
19
24
|
} as const satisfies BootRuleTable;
|
|
@@ -1,4 +1,34 @@
|
|
|
1
1
|
[
|
|
2
|
+
{
|
|
3
|
+
"version": "0.424.0",
|
|
4
|
+
"type": "improvement",
|
|
5
|
+
"title": "document ops, sanitizer and block diff are exported",
|
|
6
|
+
"detail": "The barrel exports `applyDocumentOps`, `documentOpsSchema`, `documentBlocksOf`, `allowedBlocksFor`, `parseDocumentJson`, `serializeDocumentJson`, `diffTemplateBlocks`, `splitTemplateBlocks` and `VARIANT_UNKNOWN_REASON`, so a bundle that keeps its own copy of a document can edit it with the same operations."
|
|
7
|
+
},
|
|
8
|
+
{
|
|
9
|
+
"version": "0.424.0",
|
|
10
|
+
"type": "fix",
|
|
11
|
+
"title": "form-field document editor keeps tables in frame, scrolls its toolbar and leaves room for the repeat strip",
|
|
12
|
+
"detail": "Under md the toolbar rows of the form-field editor are one line that swipes sideways instead of wrapping. Wide tables scroll inside their wrapper instead of leaving the editor frame, and a table with a repeat strip gets a line of room above it so the strip no longer covers the previous paragraph. The document-draft editor shows the template's variable label (or the company-data name) on a placeholder chip that has no value yet."
|
|
13
|
+
},
|
|
14
|
+
{
|
|
15
|
+
"version": "0.424.0",
|
|
16
|
+
"type": "fix",
|
|
17
|
+
"title": "The variants query no longer requires TenantAdmin or User",
|
|
18
|
+
"detail": "`template-resolver:query:variants` is open to every authenticated user, because whoever may create a document from a base template must be able to list its variants and an app's role names are unknown to the framework. The result is unchanged: slug, title, scope and locale of the active system variants and the caller's own tenant's variants, never another tenant's."
|
|
19
|
+
},
|
|
20
|
+
{
|
|
21
|
+
"version": "0.423.0",
|
|
22
|
+
"type": "improvement",
|
|
23
|
+
"title": "Variants of a PDF template",
|
|
24
|
+
"detail": "A `tenantEditable` entry of kind `document-pdf` accepts `variants: true` (any other kind fails boot with `template-resolver/tenant-editable-variants-need-pdf`). A variant is a `document-pdf` row with the slug `<base>:<name>` (name: one kebab segment, at most 40 characters) and `meta.variantOf = <base>`; its title is the title column. The new write `template-resolver:write:create-variant` ({baseSlug, title, name?, locale?}; `name` is derived from the title when omitted, `locale` defaults to `de`) copies the base as the caller's tenant draft with the base's content, variables, linked images and settings, and is refused with `variants_not_enabled` when the base entry lacks `variants: true` (also for a TenantAdmin) and with `variant_exists` for a taken slug. A variant's `variableSchema` follows its base: every write without an explicit schema (`patch-draft`, `create-variant`, publish) stores the base's current effective schema, so a base that gains a variable does not lock its variants and publish gates the required placeholders against it. `setVariable` on a variant and an `upsert-tenant` schema that differs from the base are refused with `variables_inherited_from_base`; `patch-draft` also refuses a change of `variantOf` (`variant_of_immutable`). The overview query rows carry `variantOf` (base slug or null), `variantsEnabled` and `locale`, and list a variant right after its base; the document designer shows them and offers \"Variante anlegen\" on bases that allow variants. The new query `template-resolver:query:variants` ({baseSlug, locale}) returns the active variants as {slug, title, scope, locale}, system and own, never another tenant's. Editing and delivery of variants follow the base's entry, so removing the base from `tenantEditable` stops serving tenant variants. `seedSystemTemplate` takes `variantOf` for system variants."
|
|
25
|
+
},
|
|
26
|
+
{
|
|
27
|
+
"version": "0.423.0",
|
|
28
|
+
"type": "improvement",
|
|
29
|
+
"title": "patch-draft description tells agents to use heading blocks for section titles",
|
|
30
|
+
"detail": "The `patch-draft` description says that a heading stays with the block that follows it on print, so section titles should be `heading` blocks."
|
|
31
|
+
},
|
|
2
32
|
{
|
|
3
33
|
"version": "0.422.0",
|
|
4
34
|
"type": "improvement",
|
|
@@ -16,6 +16,7 @@ import { makeCollectionListQuery } from "./handlers/collection-list.query.ts";
|
|
|
16
16
|
import { makeCollectionSetWrite } from "./handlers/collection-set.write.ts";
|
|
17
17
|
import { makeCopyLocaleWrite } from "./handlers/copy-locale.write.ts";
|
|
18
18
|
import { makeCreateLayoutWrite } from "./handlers/create-layout.write.ts";
|
|
19
|
+
import { makeCreateVariantWrite } from "./handlers/create-variant.write.ts";
|
|
19
20
|
import { diffToSystemQuery } from "./handlers/diff-to-system.query.ts";
|
|
20
21
|
import {
|
|
21
22
|
makeDiscardDraftSystemWrite,
|
|
@@ -51,10 +52,12 @@ import { upsertSystemWrite } from "./handlers/upsert-system.write.ts";
|
|
|
51
52
|
import { makeUpsertTenantWrite } from "./handlers/upsert-tenant.write.ts";
|
|
52
53
|
import { makeUsageQuery } from "./handlers/usage.query.ts";
|
|
53
54
|
import { validateQuery } from "./handlers/validate.query.ts";
|
|
55
|
+
import { variantsQuery } from "./handlers/variants.query.ts";
|
|
54
56
|
import { TEMPLATE_RESOLVER_I18N } from "./i18n.ts";
|
|
55
57
|
import { templateResourceEntity } from "./table.ts";
|
|
56
58
|
import type { TemplateDeliveryPolicy } from "./template-delivery-policy.ts";
|
|
57
59
|
import type { TenantEditableTemplate } from "./template-edit-policy.ts";
|
|
60
|
+
import { VARIANT_KIND } from "./template-variants.ts";
|
|
58
61
|
import { userContentEntryEntity } from "./user-content-table.ts";
|
|
59
62
|
import { DEFAULT_COLLECTION_ACCESS, isCollectionRefusedKind } from "./web/constants.ts";
|
|
60
63
|
|
|
@@ -111,6 +114,11 @@ function assertTenantEditableValid(entries: readonly TenantEditableTemplate[]):
|
|
|
111
114
|
message: `template-resolver: tenantEditable entry of kind "${entry.kind}" has an empty slug`,
|
|
112
115
|
});
|
|
113
116
|
}
|
|
117
|
+
if (entry.variants === true && entry.kind !== VARIANT_KIND) {
|
|
118
|
+
throw bootRuleError(TEMPLATE_RESOLVER_BOOT_RULES.tenantEditableVariantsNeedPdf, {
|
|
119
|
+
message: `template-resolver: tenantEditable entry "${key}" sets variants, which only document-pdf templates support`,
|
|
120
|
+
});
|
|
121
|
+
}
|
|
114
122
|
if (entry.access.roles.length === 0) {
|
|
115
123
|
throw bootRuleError(TEMPLATE_RESOLVER_BOOT_RULES.tenantEditableInvalidEntry, {
|
|
116
124
|
message: `template-resolver: tenantEditable entry "${entry.kind}/${entry.slug}" has no roles in access`,
|
|
@@ -134,7 +142,11 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
|
|
|
134
142
|
assertTenantEditableValid(tenantEditable);
|
|
135
143
|
const policy = { tenantEditable };
|
|
136
144
|
const deliveryPolicy: TemplateDeliveryPolicy = {
|
|
137
|
-
tenantEditable: tenantEditable.map(({ kind, slug }) => ({
|
|
145
|
+
tenantEditable: tenantEditable.map(({ kind, slug, variants }) => ({
|
|
146
|
+
kind,
|
|
147
|
+
slug,
|
|
148
|
+
...(variants === true && { variants }),
|
|
149
|
+
})),
|
|
138
150
|
collectionKinds: collections
|
|
139
151
|
.filter((c) => c.ownership !== "user" && c.access !== undefined)
|
|
140
152
|
.map((c) => c.kind),
|
|
@@ -203,6 +215,7 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
|
|
|
203
215
|
applyLayout: r.writeHandler(makeApplyLayoutWrite(policy)),
|
|
204
216
|
createLayout: r.writeHandler(makeCreateLayoutWrite(policy)),
|
|
205
217
|
publishTemplates: r.writeHandler(makePublishTemplatesWrite(policy)),
|
|
218
|
+
createVariant: r.writeHandler(makeCreateVariantWrite(policy)),
|
|
206
219
|
};
|
|
207
220
|
|
|
208
221
|
const queries = {
|
|
@@ -222,6 +235,7 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
|
|
|
222
235
|
documentBlocks: r.queryHandler(documentBlocksQuery),
|
|
223
236
|
exportBundle: r.queryHandler(exportBundleQuery),
|
|
224
237
|
sendTestStatus: r.queryHandler(makeSendTestStatusQuery(policy)),
|
|
238
|
+
variants: r.queryHandler(variantsQuery),
|
|
225
239
|
};
|
|
226
240
|
|
|
227
241
|
for (const collection of collections) {
|
|
@@ -0,0 +1,134 @@
|
|
|
1
|
+
import { fetchOne } from "@cosmicdrift/kumiko-framework/db";
|
|
2
|
+
import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
|
|
3
|
+
import {
|
|
4
|
+
NotFoundError,
|
|
5
|
+
ValidationError,
|
|
6
|
+
type WriteFailure,
|
|
7
|
+
writeFailure,
|
|
8
|
+
} from "@cosmicdrift/kumiko-framework/errors";
|
|
9
|
+
import * as z from "zod";
|
|
10
|
+
import { patchIssue } from "../document-op-blocks.ts";
|
|
11
|
+
import { type TemplateResourceRow, templateResourcesTable } from "../table.ts";
|
|
12
|
+
import {
|
|
13
|
+
refuseTemplateEdit,
|
|
14
|
+
type TemplateEditPolicy,
|
|
15
|
+
templateEditAccess,
|
|
16
|
+
} from "../template-edit-policy.ts";
|
|
17
|
+
import { resolveTemplateVariables } from "../template-validation.ts";
|
|
18
|
+
import {
|
|
19
|
+
VARIANT_KIND,
|
|
20
|
+
variantNameFromTitle,
|
|
21
|
+
variantNameSchema,
|
|
22
|
+
variantSlug,
|
|
23
|
+
} from "../template-variants.ts";
|
|
24
|
+
import { FALLBACK_LOCALE } from "../web/constants.ts";
|
|
25
|
+
import { TemplateResolverErrors } from "../web/qualified-names.ts";
|
|
26
|
+
import { loadDocumentBase } from "./document-base.ts";
|
|
27
|
+
import { localeSchema, templateSlugSchema, titleSchema } from "./shared.ts";
|
|
28
|
+
import { writeTemplateRow } from "./template-write.ts";
|
|
29
|
+
|
|
30
|
+
function variantsNotEnabled(policy: TemplateEditPolicy, baseSlug: string): WriteFailure | null {
|
|
31
|
+
const entry = policy.tenantEditable.find(
|
|
32
|
+
(candidate) => candidate.kind === VARIANT_KIND && candidate.slug === baseSlug,
|
|
33
|
+
);
|
|
34
|
+
if (entry?.variants === true) return null;
|
|
35
|
+
return writeFailure(
|
|
36
|
+
new ValidationError({
|
|
37
|
+
fields: [
|
|
38
|
+
patchIssue("baseSlug", TemplateResolverErrors.variantsNotEnabled, { slug: baseSlug }),
|
|
39
|
+
],
|
|
40
|
+
}),
|
|
41
|
+
);
|
|
42
|
+
}
|
|
43
|
+
|
|
44
|
+
function variantNameInvalid(): WriteFailure {
|
|
45
|
+
return writeFailure(
|
|
46
|
+
new ValidationError({
|
|
47
|
+
fields: [patchIssue("name", TemplateResolverErrors.variantNameInvalid)],
|
|
48
|
+
}),
|
|
49
|
+
);
|
|
50
|
+
}
|
|
51
|
+
|
|
52
|
+
export function makeCreateVariantWrite(policy: TemplateEditPolicy) {
|
|
53
|
+
return defineWriteHandler({
|
|
54
|
+
name: "create-variant",
|
|
55
|
+
schema: z.object({
|
|
56
|
+
baseSlug: templateSlugSchema,
|
|
57
|
+
// A form sends an untouched text field as "": same as no name, the title then supplies it.
|
|
58
|
+
name: z.union([variantNameSchema, z.literal("")]).optional(),
|
|
59
|
+
title: titleSchema,
|
|
60
|
+
locale: localeSchema.default(FALLBACK_LOCALE),
|
|
61
|
+
}),
|
|
62
|
+
access: templateEditAccess(policy.tenantEditable),
|
|
63
|
+
agent: { risk: "low", effect: "proposal" },
|
|
64
|
+
description:
|
|
65
|
+
"Creates a variant of a PDF document template of the caller's tenant (a second version of the same document, e.g. a rental contract for commercial use) as a draft under the slug <baseSlug>:<name> (name is kebab-case, at most 40 characters, and is derived from the title when omitted; locale defaults to de) with the given title. The draft starts as a copy of the base template as the caller sees it (content, variables, linked images and settings including the layout); the variables stay those of the base and cannot be changed on the variant. It fails with variants_not_enabled when the app did not allow variants for the base template (this also applies to a TenantAdmin) and with variant_exists when the tenant already has that slug. Returns the variant slug, locale, kind, title and base ({scope, version}) for the next call. Next steps: change the text with patch-draft (kind document-pdf, the returned slug), then let a person publish it with publish-templates; a variant needs the same required placeholders as its base before it can be published. The variants query lists the published variants of a base.",
|
|
66
|
+
handler: async (event, ctx) => {
|
|
67
|
+
const { baseSlug, title, locale } = event.payload;
|
|
68
|
+
const name = event.payload.name || variantNameFromTitle(title);
|
|
69
|
+
if (!variantNameSchema.safeParse(name).success) return variantNameInvalid();
|
|
70
|
+
const refused = refuseTemplateEdit(policy, event.user, {
|
|
71
|
+
slug: baseSlug,
|
|
72
|
+
kind: VARIANT_KIND,
|
|
73
|
+
});
|
|
74
|
+
if (refused !== null) return refused;
|
|
75
|
+
const disabled = variantsNotEnabled(policy, baseSlug);
|
|
76
|
+
if (disabled !== null) return disabled;
|
|
77
|
+
|
|
78
|
+
const slug = variantSlug(baseSlug, name);
|
|
79
|
+
if (!templateSlugSchema.safeParse(slug).success) return variantNameInvalid();
|
|
80
|
+
const existing = await fetchOne<TemplateResourceRow>(ctx.db, templateResourcesTable, {
|
|
81
|
+
tenantId: event.user.tenantId,
|
|
82
|
+
slug,
|
|
83
|
+
kind: VARIANT_KIND,
|
|
84
|
+
locale,
|
|
85
|
+
});
|
|
86
|
+
if (existing !== undefined) {
|
|
87
|
+
return writeFailure(
|
|
88
|
+
new ValidationError({
|
|
89
|
+
fields: [patchIssue("name", TemplateResolverErrors.variantExists, { slug })],
|
|
90
|
+
}),
|
|
91
|
+
);
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const loaded = await loadDocumentBase(ctx, event.user, {
|
|
95
|
+
slug: baseSlug,
|
|
96
|
+
kind: VARIANT_KIND,
|
|
97
|
+
locale,
|
|
98
|
+
});
|
|
99
|
+
if (loaded === null) return writeFailure(new NotFoundError("template-resource", baseSlug));
|
|
100
|
+
|
|
101
|
+
const written = await writeTemplateRow({
|
|
102
|
+
linkedResources: loaded.linkedResources ?? "{}",
|
|
103
|
+
ctx,
|
|
104
|
+
user: event.user,
|
|
105
|
+
tenantId: event.user.tenantId,
|
|
106
|
+
scope: "tenant",
|
|
107
|
+
status: "draft",
|
|
108
|
+
variables: resolveTemplateVariables(ctx.registry, slug, loaded.variableSchema),
|
|
109
|
+
payload: {
|
|
110
|
+
slug,
|
|
111
|
+
kind: VARIANT_KIND,
|
|
112
|
+
locale,
|
|
113
|
+
content: loaded.content,
|
|
114
|
+
contentFormat: "html",
|
|
115
|
+
variableSchema: loaded.variableSchema,
|
|
116
|
+
meta: { ...loaded.meta, variantOf: baseSlug },
|
|
117
|
+
title,
|
|
118
|
+
},
|
|
119
|
+
expectedVersion: null,
|
|
120
|
+
});
|
|
121
|
+
if (!written.isSuccess) return written;
|
|
122
|
+
return {
|
|
123
|
+
isSuccess: true as const,
|
|
124
|
+
data: {
|
|
125
|
+
slug,
|
|
126
|
+
locale,
|
|
127
|
+
kind: VARIANT_KIND,
|
|
128
|
+
title,
|
|
129
|
+
base: { scope: "tenant" as const, version: written.data.version },
|
|
130
|
+
},
|
|
131
|
+
};
|
|
132
|
+
},
|
|
133
|
+
});
|
|
134
|
+
}
|
|
@@ -29,6 +29,7 @@ export type LoadedDocument = {
|
|
|
29
29
|
readonly title: string | null;
|
|
30
30
|
readonly folder: string | null;
|
|
31
31
|
readonly parentTemplateId: string | null;
|
|
32
|
+
readonly linkedResources: string | null;
|
|
32
33
|
};
|
|
33
34
|
|
|
34
35
|
function recordOrEmpty(raw: string | null): Readonly<Record<string, unknown>> {
|
|
@@ -64,6 +65,7 @@ export async function loadDocumentBase(
|
|
|
64
65
|
title: working.title,
|
|
65
66
|
folder: working.folder,
|
|
66
67
|
parentTemplateId: working.parentTemplateId,
|
|
68
|
+
linkedResources: own.linkedResources,
|
|
67
69
|
};
|
|
68
70
|
}
|
|
69
71
|
const system = await fetchOne<TemplateResourceRow>(ctx.db, templateResourcesTable, {
|
|
@@ -89,5 +91,6 @@ export async function loadDocumentBase(
|
|
|
89
91
|
title: system.title,
|
|
90
92
|
folder: system.folder,
|
|
91
93
|
parentTemplateId: String(system.id),
|
|
94
|
+
linkedResources: system.linkedResources,
|
|
92
95
|
};
|
|
93
96
|
}
|
|
@@ -24,6 +24,7 @@ import {
|
|
|
24
24
|
} from "../template-edit-policy.ts";
|
|
25
25
|
import { isSystemOnlyTemplateHiddenFrom } from "../template-system-only.ts";
|
|
26
26
|
import { collectTemplateUsage, type EffectiveMailLayoutSlugs } from "../template-usage.ts";
|
|
27
|
+
import { readVariantOf, VARIANT_KIND } from "../template-variants.ts";
|
|
27
28
|
import {
|
|
28
29
|
DEFAULT_MAIL_LAYOUT_SLUG,
|
|
29
30
|
FALLBACK_LOCALE,
|
|
@@ -74,6 +75,12 @@ export type OverviewRow = {
|
|
|
74
75
|
readonly modifiedAt: string;
|
|
75
76
|
readonly usedBy: readonly OverviewUsage[];
|
|
76
77
|
readonly usedByCount: number;
|
|
78
|
+
/** Locale of the row the overview shows (German first); a row action that acts on one locale starts from it. */
|
|
79
|
+
readonly locale: string;
|
|
80
|
+
/** Base slug when this row is a variant of a PDF template. */
|
|
81
|
+
readonly variantOf: string | null;
|
|
82
|
+
/** The app allows variants of this PDF template, so "create variant" applies to the row. */
|
|
83
|
+
readonly variantsEnabled: boolean;
|
|
77
84
|
/** SystemAdmin only, system-origin rows: tenants overriding this template; total is null without the tenant feature. */
|
|
78
85
|
readonly overriddenBy?: { readonly active: number; readonly total: number | null };
|
|
79
86
|
};
|
|
@@ -276,11 +283,24 @@ function versionFieldsOf(
|
|
|
276
283
|
};
|
|
277
284
|
}
|
|
278
285
|
|
|
286
|
+
function variantFieldsOf(
|
|
287
|
+
preferred: TemplateResourceRow,
|
|
288
|
+
variantBaseSlugs: ReadonlySet<string>,
|
|
289
|
+
): Pick<OverviewRow, "locale" | "variantOf" | "variantsEnabled"> {
|
|
290
|
+
const isPdf = preferred.kind === VARIANT_KIND;
|
|
291
|
+
return {
|
|
292
|
+
locale: preferred.locale,
|
|
293
|
+
variantOf: isPdf ? readVariantOf(storedRecord(preferred.meta)) : null,
|
|
294
|
+
variantsEnabled: isPdf && variantBaseSlugs.has(preferred.slug),
|
|
295
|
+
};
|
|
296
|
+
}
|
|
297
|
+
|
|
279
298
|
function buildDrafts(
|
|
280
299
|
groups: ReadonlyMap<string, readonly TemplateResourceRow[]>,
|
|
281
300
|
user: { readonly tenantId: string; readonly roles: readonly string[] },
|
|
282
301
|
policy: TemplateDeliveryPolicy,
|
|
283
302
|
defaultPdfLayoutSlug: string,
|
|
303
|
+
variantBaseSlugs: ReadonlySet<string>,
|
|
284
304
|
): {
|
|
285
305
|
readonly drafts: OverviewDraft[];
|
|
286
306
|
readonly layoutSlugByDocument: Map<string, string>;
|
|
@@ -318,6 +338,7 @@ function buildDrafts(
|
|
|
318
338
|
lockedOverrideId: effective.lockedOverrideId,
|
|
319
339
|
canResetLockedOverride: effective.lockedOverrideId !== null,
|
|
320
340
|
modifiedAt: modifiedAtOf(preferred),
|
|
341
|
+
...variantFieldsOf(preferred, variantBaseSlugs),
|
|
321
342
|
});
|
|
322
343
|
}
|
|
323
344
|
return { drafts, layoutSlugByDocument };
|
|
@@ -398,6 +419,22 @@ const filterSchema = z.object({
|
|
|
398
419
|
value: z.array(z.string()),
|
|
399
420
|
});
|
|
400
421
|
|
|
422
|
+
// A variant follows its base in the list, so the designer reads them as one group; a variant whose
|
|
423
|
+
// base the filter dropped keeps its sorted place. Slugs repeat across kinds (a mail and a PDF may
|
|
424
|
+
// share one), so only PDF rows count as a base.
|
|
425
|
+
function variantsUnderTheirBase(rows: readonly OverviewRow[]): OverviewRow[] {
|
|
426
|
+
const isPdfBase = (row: OverviewRow) => row.kind === VARIANT_KIND && row.variantOf === null;
|
|
427
|
+
const baseSlugs = new Set(rows.filter(isPdfBase).map((row) => row.slug));
|
|
428
|
+
const isGrouped = (row: OverviewRow) => row.variantOf !== null && baseSlugs.has(row.variantOf);
|
|
429
|
+
return rows
|
|
430
|
+
.filter((row) => !isGrouped(row))
|
|
431
|
+
.flatMap((row) =>
|
|
432
|
+
isPdfBase(row)
|
|
433
|
+
? [row, ...rows.filter((r) => isGrouped(r) && r.variantOf === row.slug)]
|
|
434
|
+
: [row],
|
|
435
|
+
);
|
|
436
|
+
}
|
|
437
|
+
|
|
401
438
|
export function makeOverviewQuery(policy: TemplateEditPolicy) {
|
|
402
439
|
return defineQueryHandler({
|
|
403
440
|
name: "overview",
|
|
@@ -439,6 +476,11 @@ export function makeOverviewQuery(policy: TemplateEditPolicy) {
|
|
|
439
476
|
query.user,
|
|
440
477
|
deliveryPolicy,
|
|
441
478
|
await defaultPdfLayoutSlug(ctx, query.user.tenantId),
|
|
479
|
+
new Set(
|
|
480
|
+
policy.tenantEditable
|
|
481
|
+
.filter((entry) => entry.kind === VARIANT_KIND && entry.variants === true)
|
|
482
|
+
.map((entry) => entry.slug),
|
|
483
|
+
),
|
|
442
484
|
);
|
|
443
485
|
const effectiveLayouts = effectiveMailLayoutSlugs(visibleRows, deliveryPolicy);
|
|
444
486
|
const rowsWithUsage = drafts.map((draft) =>
|
|
@@ -470,9 +512,10 @@ export function makeOverviewQuery(policy: TemplateEditPolicy) {
|
|
|
470
512
|
(a, b) => direction * compareBy(sortField, a, b, shownTitle) || a.id.localeCompare(b.id),
|
|
471
513
|
);
|
|
472
514
|
|
|
515
|
+
const ordered = variantsUnderTheirBase(filtered);
|
|
473
516
|
const offset = payload.offset ?? 0;
|
|
474
517
|
return {
|
|
475
|
-
rows:
|
|
518
|
+
rows: ordered.slice(offset, offset + payload.limit),
|
|
476
519
|
nextCursor: null,
|
|
477
520
|
total: filtered.length,
|
|
478
521
|
truncated,
|
|
@@ -7,6 +7,7 @@ import {
|
|
|
7
7
|
writeFailure,
|
|
8
8
|
} from "@cosmicdrift/kumiko-framework/errors";
|
|
9
9
|
import * as z from "zod";
|
|
10
|
+
import { patchIssue } from "../document-op-blocks.ts";
|
|
10
11
|
import { applyDocumentOps, documentOpsSchema } from "../document-ops.ts";
|
|
11
12
|
import { parseDocumentJson, serializeDocumentJson } from "../document-sanitizer.ts";
|
|
12
13
|
import {
|
|
@@ -15,6 +16,7 @@ import {
|
|
|
15
16
|
templateEditAccess,
|
|
16
17
|
} from "../template-edit-policy.ts";
|
|
17
18
|
import { resolveTemplateVariables } from "../template-validation.ts";
|
|
19
|
+
import { readVariantOf } from "../template-variants.ts";
|
|
18
20
|
import { loadDocumentBase } from "./document-base.ts";
|
|
19
21
|
import {
|
|
20
22
|
contentWithEditedHtml,
|
|
@@ -46,7 +48,7 @@ export function makePatchDraftWrite(policy: TemplateEditPolicy) {
|
|
|
46
48
|
access: templateEditAccess(policy.tenantEditable),
|
|
47
49
|
agent: { risk: "low", effect: "proposal" },
|
|
48
50
|
description:
|
|
49
|
-
'Changes a mail template, a PDF document template (kind document-pdf) or one region of a PDF layout (kind pdf-layout with region header, signature or footer; a tenant edits its own layouts under the slug tenant-layout-<name>, created with create-layout) with structured operations instead of a full rewrite and saves the result as the caller\'s tenant draft (never published, an active version keeps being served until publish). Never send raw HTML: every block goes through the same checks as the editor. Block forms: paragraph and heading {text} or {runs:[{text,bold,italic,underline,font,sizePt,color,dateStyle (short prints a date placeholder in that run as 15.01.2026, long is the default 15. January 2026; both follow the document locale)}]} with optional align, style {lineHeight,spaceBeforePt,spaceAfterPt} and textStyle {font,sizePt,color}; list {ordered,items:[text or runs]}; table {borders:"none",cellPaddingMm (0 to 10, padding inside every cell),widthMm (0.1 to 210, table width),align:left|center|right (placement of a table narrower than the text area),columnWidthsPx,header:{cells:[{text|runs,background,align}]},rows:[{cells,lineAbove:{color #rrggbb,weightPt 0.25 to 4},lineBelow:{...}}],repeat:{each:<list variable>,row},rowsAfterRepeat:[{cells,lineAbove,lineBelow}]} (a row line is a rule on the top or bottom edge of that row; it beats tableLineColor there and works on the header, repeat and rowsAfterRepeat rows too) (repeat is the row printed once per list entry; header repeats on every page; rowsAfterRepeat are printed once below the repeated rows, e.g. total lines, and need a repeat); a run is {text,bold,italic,underline,font,sizePt,color} or {hardBreak:true}, which starts a new line inside the paragraph or table cell, e.g. a description followed by a small grey second line; frame {xMm,yMm,widthMm,heightMm,preset:address|text,reserveFlow,blocks} only in document-pdf, at the top level (the DIN address window is x20 y45 w85 h45 with preset address); image {resource,alt,widthMm (0.1 to 210, printed width; without it the image keeps its natural size, in a layout region at most 20 mm high),align:left|center|right,bleed (true runs the image from paper edge to paper edge, flush with the top in a header and with the bottom in a footer; only in the header or footer region of a pdf-layout, refused elsewhere with bleed_not_allowed)}; button {text,href} mails only; divider {color #rrggbb,weightPt 0.25 to 4}; pageBreak PDF only. Fonts, sizes, colors (#rrggbb), line spacing, borders, backgrounds and frames are print styling: PDF only, a mail refuses them with print_style_not_allowed. Operations: insertBlock after a block id (null = at the start), replaceBody {blocks} (replaces the whole content, at most 300 blocks including the ones inside frames; read ids no longer apply afterwards), formatBlock {blockId,align,style,textStyle} on a paragraph, heading or list, replaceText inside one block (the text must occur exactly once within one formatting run and cannot contain a {{placeholder}}: a find across a formatting change fails with text_spans_formatting, a find with a placeholder with placeholder_not_replaceable, and the formatting of the replaced text is kept), removeBlock, setResource on an image block, setMeta (flat merge, null removes a key; layout keys are listed with create-layout) and setVariable (adds, replaces or with null removes a variable definition; refused when a notification declares the variables). Block ids and base come from document-blocks and refer to the state that was read; if the template changed since, the call fails with version_conflict and nothing is written. A patch that removes a required placeholder is refused. A TenantAdmin may patch only templates the app lists in tenantEditable, otherwise SystemAdmin only. Returns the written row.',
|
|
51
|
+
'Changes a mail template, a PDF document template (kind document-pdf) or one region of a PDF layout (kind pdf-layout with region header, signature or footer; a tenant edits its own layouts under the slug tenant-layout-<name>, created with create-layout) with structured operations instead of a full rewrite and saves the result as the caller\'s tenant draft (never published, an active version keeps being served until publish). Never send raw HTML: every block goes through the same checks as the editor. Block forms: paragraph and heading {text} or {runs:[{text,bold,italic,underline,font,sizePt,color,dateStyle (short prints a date placeholder in that run as 15.01.2026, long is the default 15. January 2026; both follow the document locale)}]} with optional align, style {lineHeight,spaceBeforePt,spaceAfterPt} and textStyle {font,sizePt,color}; list {ordered,items:[text or runs]}; table {borders:"none",cellPaddingMm (0 to 10, padding inside every cell),widthMm (0.1 to 210, table width),align:left|center|right (placement of a table narrower than the text area),columnWidthsPx,header:{cells:[{text|runs,background,align}]},rows:[{cells,lineAbove:{color #rrggbb,weightPt 0.25 to 4},lineBelow:{...}}],repeat:{each:<list variable>,row},rowsAfterRepeat:[{cells,lineAbove,lineBelow}]} (a row line is a rule on the top or bottom edge of that row; it beats tableLineColor there and works on the header, repeat and rowsAfterRepeat rows too) (repeat is the row printed once per list entry; header repeats on every page; rowsAfterRepeat are printed once below the repeated rows, e.g. total lines, and need a repeat); a run is {text,bold,italic,underline,font,sizePt,color} or {hardBreak:true}, which starts a new line inside the paragraph or table cell, e.g. a description followed by a small grey second line; frame {xMm,yMm,widthMm,heightMm,preset:address|text,reserveFlow,blocks} only in document-pdf, at the top level (the DIN address window is x20 y45 w85 h45 with preset address); image {resource,alt,widthMm (0.1 to 210, printed width; without it the image keeps its natural size, in a layout region at most 20 mm high),align:left|center|right,bleed (true runs the image from paper edge to paper edge, flush with the top in a header and with the bottom in a footer; only in the header or footer region of a pdf-layout, refused elsewhere with bleed_not_allowed)}; button {text,href} mails only; divider {color #rrggbb,weightPt 0.25 to 4}; pageBreak PDF only. Fonts, sizes, colors (#rrggbb), line spacing, borders, backgrounds and frames are print styling: PDF only, a mail refuses them with print_style_not_allowed. Operations: insertBlock after a block id (null = at the start), replaceBody {blocks} (replaces the whole content, at most 300 blocks including the ones inside frames; read ids no longer apply afterwards), formatBlock {blockId,align,style,textStyle} on a paragraph, heading or list, replaceText inside one block (the text must occur exactly once within one formatting run and cannot contain a {{placeholder}}: a find across a formatting change fails with text_spans_formatting, a find with a placeholder with placeholder_not_replaceable, and the formatting of the replaced text is kept), removeBlock, setResource on an image block, setMeta (flat merge, null removes a key; layout keys are listed with create-layout) and setVariable (adds, replaces or with null removes a variable definition; refused when a notification declares the variables and on a variant, which keeps the variables of its base with variables_inherited_from_base; the variantOf setting of a variant cannot be changed). Section titles should be heading blocks, not bold paragraphs: on print a heading stays with the block that follows it instead of ending a page on its own. Block ids and base come from document-blocks and refer to the state that was read; if the template changed since, the call fails with version_conflict and nothing is written. A patch that removes a required placeholder is refused. A TenantAdmin may patch only templates the app lists in tenantEditable, otherwise SystemAdmin only. Returns the written row.',
|
|
50
52
|
handler: async (event, ctx) => {
|
|
51
53
|
const { slug, kind, region, locale, base, ops } = event.payload;
|
|
52
54
|
const misplacedRegion = regionIssue(kind, region);
|
|
@@ -78,6 +80,12 @@ export function makePatchDraftWrite(policy: TemplateEditPolicy) {
|
|
|
78
80
|
});
|
|
79
81
|
}
|
|
80
82
|
|
|
83
|
+
if (variableOpIndex !== -1 && readVariantOf(loaded.meta) !== null) {
|
|
84
|
+
return validationFailure(
|
|
85
|
+
patchIssue(`ops.${variableOpIndex}`, "variables_inherited_from_base", { slug }),
|
|
86
|
+
);
|
|
87
|
+
}
|
|
88
|
+
|
|
81
89
|
const applied = applyDocumentOps({
|
|
82
90
|
doc: parseDocumentJson(editableHtmlOf(kind, region, loaded.content)),
|
|
83
91
|
meta: loaded.meta,
|
|
@@ -87,6 +95,9 @@ export function makePatchDraftWrite(policy: TemplateEditPolicy) {
|
|
|
87
95
|
ops,
|
|
88
96
|
});
|
|
89
97
|
if (!applied.ok) return writeFailure(new ValidationError({ fields: applied.issues }));
|
|
98
|
+
if (readVariantOf(applied.meta) !== readVariantOf(loaded.meta)) {
|
|
99
|
+
return validationFailure(patchIssue("ops", "variant_of_immutable", { slug }));
|
|
100
|
+
}
|
|
90
101
|
const content = contentWithEditedHtml(
|
|
91
102
|
kind,
|
|
92
103
|
region,
|
|
@@ -1,3 +1,4 @@
|
|
|
1
|
+
import { isDeepStrictEqual } from "node:util";
|
|
1
2
|
import { fetchOne } from "@cosmicdrift/kumiko-framework/db";
|
|
2
3
|
import {
|
|
3
4
|
type HandlerContext,
|
|
@@ -6,6 +7,7 @@ import {
|
|
|
6
7
|
SYSTEM_TENANT_ID,
|
|
7
8
|
type TemplateVariables,
|
|
8
9
|
type TenantId,
|
|
10
|
+
type TenantWriteTarget,
|
|
9
11
|
type WriteResult,
|
|
10
12
|
} from "@cosmicdrift/kumiko-framework/engine";
|
|
11
13
|
import {
|
|
@@ -15,18 +17,23 @@ import {
|
|
|
15
17
|
type WriteFailure,
|
|
16
18
|
writeFailure,
|
|
17
19
|
} from "@cosmicdrift/kumiko-framework/errors";
|
|
20
|
+
import { isPlainObject, propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
|
|
18
21
|
import { requireForTenant } from "../../shared/index.ts";
|
|
22
|
+
import { patchIssue } from "../document-op-blocks.ts";
|
|
19
23
|
import type { TemplateWriteScope } from "../layout-regions.ts";
|
|
20
24
|
import { type TemplateResourceRow, templateResourcesTable } from "../table.ts";
|
|
21
|
-
import {
|
|
25
|
+
import { deliveryPolicyOf, findVariantsEntry } from "../template-delivery-policy.ts";
|
|
26
|
+
import { activationChanges, serializeTemplateDraft, toWorkingRow } from "../template-draft.ts";
|
|
22
27
|
import { refuseReservedSystemLayoutSlug } from "../template-edit-policy.ts";
|
|
23
28
|
import { isSystemOnlyTemplate } from "../template-system-only.ts";
|
|
24
|
-
import type
|
|
29
|
+
import { resolveTemplateVariables, type TemplateValidation } from "../template-validation.ts";
|
|
30
|
+
import { readVariantOf, VARIANT_KIND, variantOfMatchesSlug } from "../template-variants.ts";
|
|
25
31
|
import type { ContentFormat, TemplateKind } from "../web/constants.ts";
|
|
26
32
|
import { TemplateResolverErrors } from "../web/qualified-names.ts";
|
|
27
33
|
import { executor } from "./shared.ts";
|
|
28
34
|
import {
|
|
29
35
|
evaluateTemplateWrite,
|
|
36
|
+
parseStoredJson,
|
|
30
37
|
type TemplateWriteInput,
|
|
31
38
|
type TemplateWriteResult,
|
|
32
39
|
} from "./template-gates.ts";
|
|
@@ -48,6 +55,7 @@ export type WrittenTemplateRow = {
|
|
|
48
55
|
readonly id: string;
|
|
49
56
|
readonly slug: string;
|
|
50
57
|
readonly isNew: boolean;
|
|
58
|
+
readonly version: number;
|
|
51
59
|
readonly validation: TemplateValidation | null;
|
|
52
60
|
};
|
|
53
61
|
|
|
@@ -59,6 +67,10 @@ export type TemplateRowWrite = {
|
|
|
59
67
|
readonly status: "draft" | "active";
|
|
60
68
|
readonly variables: TemplateVariables;
|
|
61
69
|
readonly payload: TemplateRowPayload;
|
|
70
|
+
/** Stored linkedResources JSON for a row that is created; an update never touches them. */
|
|
71
|
+
readonly linkedResources?: string;
|
|
72
|
+
/** The caller typed this schema itself (upsert); a variant then must match its base instead of being re-synced. */
|
|
73
|
+
readonly explicitVariableSchema?: true;
|
|
62
74
|
/** The row version the edit was made against; null means no own row may exist yet. */
|
|
63
75
|
readonly expectedVersion?: number | null;
|
|
64
76
|
};
|
|
@@ -170,6 +182,91 @@ function versionConflictFor(
|
|
|
170
182
|
);
|
|
171
183
|
}
|
|
172
184
|
|
|
185
|
+
// A tenant row under `<base>:<name>` of a base with variants must declare that base; otherwise the
|
|
186
|
+
// policy would serve it as a variant while schema sync never runs for it.
|
|
187
|
+
function refuseVariantOfSlugMismatch(
|
|
188
|
+
registry: HandlerContext["registry"],
|
|
189
|
+
scope: TemplateWriteScope,
|
|
190
|
+
payload: TemplateRowWrite["payload"],
|
|
191
|
+
): WriteFailure | null {
|
|
192
|
+
const declaredBase = readVariantOf(payload.meta);
|
|
193
|
+
const requiredBase =
|
|
194
|
+
scope === "tenant"
|
|
195
|
+
? findVariantsEntry(deliveryPolicyOf(registry).tenantEditable, payload)?.slug
|
|
196
|
+
: undefined;
|
|
197
|
+
const missesRequiredBase = requiredBase !== undefined && declaredBase !== requiredBase;
|
|
198
|
+
if (!missesRequiredBase && variantOfMatchesSlug(payload.slug, payload.meta)) return null;
|
|
199
|
+
return writeFailure(
|
|
200
|
+
new ValidationError({ fields: [patchIssue("meta.variantOf", "invalid_variant_of")] }),
|
|
201
|
+
);
|
|
202
|
+
}
|
|
203
|
+
|
|
204
|
+
function storedKeyOf(data: unknown): { readonly id: string; readonly version: number } {
|
|
205
|
+
const id = propertyOf(data, "id");
|
|
206
|
+
const version = propertyOf(propertyOf(data, "data"), "version");
|
|
207
|
+
if ((typeof id !== "string" && typeof id !== "number") || typeof version !== "number") {
|
|
208
|
+
throw new Error("template write: executor result carries no id and version");
|
|
209
|
+
}
|
|
210
|
+
return { id: String(id), version };
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
// The base as the tenant sees it: its own row (open draft included), else the served system default.
|
|
214
|
+
export async function baseVariableSchemaOf(
|
|
215
|
+
db: TenantWriteTarget["db"],
|
|
216
|
+
tenantId: string,
|
|
217
|
+
baseSlug: string,
|
|
218
|
+
locale: string,
|
|
219
|
+
): Promise<unknown> {
|
|
220
|
+
const where = { slug: baseSlug, kind: VARIANT_KIND, locale };
|
|
221
|
+
const own = await fetchOne<TemplateResourceRow>(db, templateResourcesTable, {
|
|
222
|
+
...where,
|
|
223
|
+
tenantId,
|
|
224
|
+
});
|
|
225
|
+
if (own !== undefined) return parseStoredJson(toWorkingRow(own, tenantId).variableSchema);
|
|
226
|
+
const system = await fetchOne<TemplateResourceRow>(db, templateResourcesTable, {
|
|
227
|
+
...where,
|
|
228
|
+
tenantId: SYSTEM_TENANT_ID,
|
|
229
|
+
scope: "system",
|
|
230
|
+
status: "active",
|
|
231
|
+
});
|
|
232
|
+
return system === undefined ? undefined : parseStoredJson(system.variableSchema);
|
|
233
|
+
}
|
|
234
|
+
|
|
235
|
+
type VariantSchemaOutcome =
|
|
236
|
+
| { readonly refused: WriteFailure }
|
|
237
|
+
| { readonly payload: TemplateRowWrite["payload"]; readonly variables: TemplateVariables };
|
|
238
|
+
|
|
239
|
+
// A variant follows its base: a write that sends no schema of its own stores the base's current one,
|
|
240
|
+
// so a base that gains a variable does not lock its variants. A caller that sends a different
|
|
241
|
+
// schema explicitly is refused.
|
|
242
|
+
async function syncVariantSchema(
|
|
243
|
+
args: TemplateRowWrite,
|
|
244
|
+
db: TenantWriteTarget["db"],
|
|
245
|
+
): Promise<VariantSchemaOutcome> {
|
|
246
|
+
const { payload } = args;
|
|
247
|
+
const baseSlug = readVariantOf(payload.meta);
|
|
248
|
+
const unchanged = { payload, variables: args.variables };
|
|
249
|
+
if (args.scope !== "tenant" || baseSlug === null) return unchanged;
|
|
250
|
+
const baseSchema = await baseVariableSchemaOf(db, args.tenantId, baseSlug, payload.locale);
|
|
251
|
+
if (!isPlainObject(baseSchema)) return unchanged;
|
|
252
|
+
if (args.explicitVariableSchema === true) {
|
|
253
|
+
if (isDeepStrictEqual(baseSchema, payload.variableSchema)) return unchanged;
|
|
254
|
+
return {
|
|
255
|
+
refused: writeFailure(
|
|
256
|
+
new ValidationError({
|
|
257
|
+
fields: [
|
|
258
|
+
patchIssue("variableSchema", "variables_inherited_from_base", { slug: baseSlug }),
|
|
259
|
+
],
|
|
260
|
+
}),
|
|
261
|
+
),
|
|
262
|
+
};
|
|
263
|
+
}
|
|
264
|
+
return {
|
|
265
|
+
payload: { ...payload, variableSchema: baseSchema },
|
|
266
|
+
variables: resolveTemplateVariables(args.ctx.registry, payload.slug, baseSchema),
|
|
267
|
+
};
|
|
268
|
+
}
|
|
269
|
+
|
|
173
270
|
function refuseScopeViolation(
|
|
174
271
|
registry: HandlerContext["registry"],
|
|
175
272
|
scope: TemplateWriteScope,
|
|
@@ -177,6 +274,7 @@ function refuseScopeViolation(
|
|
|
177
274
|
payload: TemplateRowWrite["payload"],
|
|
178
275
|
): WriteResult<never> | WriteFailure | null {
|
|
179
276
|
return (
|
|
277
|
+
refuseVariantOfSlugMismatch(registry, scope, payload) ??
|
|
180
278
|
refuseTenantScopeUnderSystemTenant(scope, tenantId) ??
|
|
181
279
|
refuseReservedSystemLayoutSlug(scope, payload, "slug") ??
|
|
182
280
|
refuseSystemOnlyTenantOverride(registry, scope, payload.slug, payload.kind)
|
|
@@ -190,10 +288,13 @@ function refuseScopeViolation(
|
|
|
190
288
|
export async function writeTemplateRow(
|
|
191
289
|
args: TemplateRowWrite,
|
|
192
290
|
): Promise<WriteResult<WrittenTemplateRow>> {
|
|
193
|
-
const { ctx, user, tenantId, scope, status
|
|
194
|
-
const refused = refuseScopeViolation(ctx.registry, scope, tenantId, payload);
|
|
291
|
+
const { ctx, user, tenantId, scope, status } = args;
|
|
292
|
+
const refused = refuseScopeViolation(ctx.registry, scope, tenantId, args.payload);
|
|
195
293
|
if (refused !== null) return refused;
|
|
196
294
|
const { db, streamTenantId } = requireForTenant(ctx, tenantId);
|
|
295
|
+
const synced = await syncVariantSchema(args, db);
|
|
296
|
+
if ("refused" in synced) return synced.refused;
|
|
297
|
+
const { payload, variables } = synced;
|
|
197
298
|
|
|
198
299
|
const gated = gateTemplateWrite(
|
|
199
300
|
{
|
|
@@ -202,7 +303,7 @@ export async function writeTemplateRow(
|
|
|
202
303
|
contentFormat: payload.contentFormat,
|
|
203
304
|
content: payload.content,
|
|
204
305
|
rawMeta: payload.meta,
|
|
205
|
-
variables
|
|
306
|
+
variables,
|
|
206
307
|
},
|
|
207
308
|
status,
|
|
208
309
|
);
|
|
@@ -250,6 +351,7 @@ export async function writeTemplateRow(
|
|
|
250
351
|
isSuccess: true,
|
|
251
352
|
data: {
|
|
252
353
|
id: String(existing.id),
|
|
354
|
+
version: storedKeyOf(result.data).version,
|
|
253
355
|
slug: payload.slug,
|
|
254
356
|
isNew: false,
|
|
255
357
|
validation: evaluated.validation,
|
|
@@ -260,7 +362,7 @@ export async function writeTemplateRow(
|
|
|
260
362
|
const result = await executor.create(
|
|
261
363
|
{
|
|
262
364
|
...fields,
|
|
263
|
-
linkedResources: "{}",
|
|
365
|
+
linkedResources: args.linkedResources ?? "{}",
|
|
264
366
|
tenantId,
|
|
265
367
|
draft: null,
|
|
266
368
|
...(status === "active" ? activationChanges(null) : {}),
|
|
@@ -270,14 +372,12 @@ export async function writeTemplateRow(
|
|
|
270
372
|
{ streamTenantId },
|
|
271
373
|
);
|
|
272
374
|
if (!result.isSuccess) return result;
|
|
273
|
-
|
|
274
|
-
// INSERT RETURNING; the { id } shape is guaranteed because the primary key is in the
|
|
275
|
-
// RETURNING clause.
|
|
276
|
-
const createdRow = result.data as { id: string | number };
|
|
375
|
+
const created = storedKeyOf(result.data);
|
|
277
376
|
return {
|
|
278
377
|
isSuccess: true,
|
|
279
378
|
data: {
|
|
280
|
-
id:
|
|
379
|
+
id: created.id,
|
|
380
|
+
version: created.version,
|
|
281
381
|
slug: payload.slug,
|
|
282
382
|
isNew: true,
|
|
283
383
|
validation: evaluated.validation,
|