@cosmicdrift/kumiko-samples 0.418.0 → 0.420.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.
Files changed (90) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +11 -1
  3. package/packages/bundled-features/src/shared/index.ts +6 -0
  4. package/packages/bundled-features/src/shared/tenant-scoped-subject.ts +28 -0
  5. package/packages/bundled-features/src/signature/changes.json +6 -0
  6. package/packages/bundled-features/src/signature/feature.ts +1 -1
  7. package/packages/bundled-features/src/signature/grant.ts +13 -14
  8. package/packages/bundled-features/src/signature/png.ts +33 -12
  9. package/packages/bundled-features/src/template-resolver/api.ts +17 -7
  10. package/packages/bundled-features/src/template-resolver/changes.json +62 -0
  11. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +10 -9
  12. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +170 -0
  13. package/packages/bundled-features/src/template-resolver/document-frames.ts +68 -0
  14. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +682 -0
  15. package/packages/bundled-features/src/template-resolver/document-ops.ts +170 -128
  16. package/packages/bundled-features/src/template-resolver/document-print-only.ts +65 -0
  17. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +53 -19
  18. package/packages/bundled-features/src/template-resolver/feature.ts +15 -0
  19. package/packages/bundled-features/src/template-resolver/handlers/apply-layout.write.ts +137 -0
  20. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +87 -0
  21. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +2 -2
  22. package/packages/bundled-features/src/template-resolver/handlers/document-blocks.query.ts +13 -8
  23. package/packages/bundled-features/src/template-resolver/handlers/document-region.ts +47 -0
  24. package/packages/bundled-features/src/template-resolver/handlers/failure-reason.ts +13 -0
  25. package/packages/bundled-features/src/template-resolver/handlers/import-bundle-system.write.ts +3 -0
  26. package/packages/bundled-features/src/template-resolver/handlers/layout-source.query.ts +17 -5
  27. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +16 -4
  28. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +20 -6
  29. package/packages/bundled-features/src/template-resolver/handlers/publish-templates.write.ts +69 -0
  30. package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +7 -0
  31. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +15 -3
  32. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +159 -0
  33. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +25 -10
  34. package/packages/bundled-features/src/template-resolver/handlers/upsert-system.write.ts +7 -3
  35. package/packages/bundled-features/src/template-resolver/handlers/usage.query.ts +131 -18
  36. package/packages/bundled-features/src/template-resolver/handlers/validate.query.ts +10 -0
  37. package/packages/bundled-features/src/template-resolver/i18n.ts +3 -0
  38. package/packages/bundled-features/src/template-resolver/index.ts +39 -0
  39. package/packages/bundled-features/src/template-resolver/layout-regions.ts +54 -16
  40. package/packages/bundled-features/src/template-resolver/print-document.ts +3 -1
  41. package/packages/bundled-features/src/template-resolver/seeding.ts +4 -0
  42. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +11 -1
  43. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +37 -1
  44. package/packages/bundled-features/src/template-resolver/template-meta.ts +31 -6
  45. package/packages/bundled-features/src/template-resolver/template-preview.ts +29 -9
  46. package/packages/bundled-features/src/template-resolver/template-validation.ts +10 -3
  47. package/packages/bundled-features/src/template-resolver/web/constants.ts +33 -0
  48. package/packages/bundled-features/src/template-resolver/web/document-blocks.ts +5 -0
  49. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +93 -25
  50. package/packages/bundled-features/src/template-resolver/web/document-editor-fonts.ts +13 -0
  51. package/packages/bundled-features/src/template-resolver/web/document-editor.tsx +4 -1
  52. package/packages/bundled-features/src/template-resolver/web/document-fonts.ts +21 -0
  53. package/packages/bundled-features/src/template-resolver/web/document-frame-control.ts +428 -0
  54. package/packages/bundled-features/src/template-resolver/web/document-frame-node-view.tsx +207 -0
  55. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +246 -0
  56. package/packages/bundled-features/src/template-resolver/web/document-print-defaults.ts +59 -0
  57. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +381 -0
  58. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +80 -0
  59. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +87 -19
  60. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +214 -0
  61. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +185 -16
  62. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +70 -7
  63. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +13 -1
  64. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +25 -4
  65. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +276 -23
  66. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +449 -10
  67. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +108 -17
  68. package/packages/bundled-features/src/template-resolver/web/document-toolbar-blocks.ts +20 -0
  69. package/packages/bundled-features/src/template-resolver/web/fontsource-css.d.ts +2 -0
  70. package/packages/bundled-features/src/template-resolver/web/i18n.ts +32 -0
  71. package/packages/bundled-features/src/template-resolver/web/index.ts +38 -0
  72. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +16 -0
  73. package/packages/bundled-features/src/template-resolver/web/placeholder-text.ts +6 -3
  74. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +7 -0
  75. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +74 -5
  76. package/packages/bundled-features/src/tenant/company-config.ts +48 -0
  77. package/packages/bundled-features/src/tenant/feature.ts +11 -0
  78. package/packages/bundled-features/src/tenant/i18n.ts +14 -0
  79. package/samples/apps/ui-walkthrough/src/app/auth-constants.ts +51 -0
  80. package/samples/apps/ui-walkthrough/src/app/seed-print-editor-tenants.ts +118 -0
  81. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  82. package/samples/apps/ui-walkthrough/src/app/server.ts +9 -1
  83. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +27 -1
  84. package/samples/apps/ui-walkthrough/src/features/rental/i18n.ts +8 -0
  85. package/samples/apps/ui-walkthrough/src/features/rental/screens.ts +1 -0
  86. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  87. package/samples/apps/use-all-bundled/feature-manifest.json +236 -0
  88. package/samples/recipes/pdf-letterhead/README.md +23 -0
  89. package/samples/recipes/pdf-letterhead/package.json +12 -0
  90. package/samples/recipes/pdf-letterhead/src/letterhead.ts +92 -0
@@ -2,10 +2,12 @@ import {
2
2
  bootRuleError,
3
3
  type ContentCollectionDefinition,
4
4
  createSystemConfig,
5
+ createTenantConfig,
5
6
  defineFeature,
6
7
  type TreeAction,
7
8
  } from "@cosmicdrift/kumiko-framework/engine";
8
9
  import { TEMPLATE_RESOLVER_BOOT_RULES } from "./boot-rules.ts";
10
+ import { makeApplyLayoutWrite } from "./handlers/apply-layout.write.ts";
9
11
  import { makeBodyPreviewQuery } from "./handlers/body-preview.query.ts";
10
12
  import { bySlugQuery } from "./handlers/by-slug.query.ts";
11
13
  import { byTenantQuery } from "./handlers/by-tenant.query.ts";
@@ -13,6 +15,7 @@ import { makeCollectionItemQuery } from "./handlers/collection-item.query.ts";
13
15
  import { makeCollectionListQuery } from "./handlers/collection-list.query.ts";
14
16
  import { makeCollectionSetWrite } from "./handlers/collection-set.write.ts";
15
17
  import { makeCopyLocaleWrite } from "./handlers/copy-locale.write.ts";
18
+ import { makeCreateLayoutWrite } from "./handlers/create-layout.write.ts";
16
19
  import { diffToSystemQuery } from "./handlers/diff-to-system.query.ts";
17
20
  import {
18
21
  makeDiscardDraftSystemWrite,
@@ -28,6 +31,7 @@ import { listQuery } from "./handlers/list.query.ts";
28
31
  import { makeOverviewQuery } from "./handlers/overview.query.ts";
29
32
  import { makePatchDraftWrite } from "./handlers/patch-draft.write.ts";
30
33
  import { previewQuery } from "./handlers/preview.query.ts";
34
+ import { makePublishTemplatesWrite } from "./handlers/publish-templates.write.ts";
31
35
  import { makeResetToSystemWrite } from "./handlers/reset-to-system.write.ts";
32
36
  import { makeResourceLinkPdfWrite } from "./handlers/resource-link-pdf.write.ts";
33
37
  import { makeResourceRemoveWrite } from "./handlers/resource-remove.write.ts";
@@ -159,6 +163,14 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
159
163
  r.config({
160
164
  keys: {
161
165
  resourceMaxBytes: createSystemConfig("number", { default: 2_097_152, bounds: { min: 1 } }),
166
+ // Empty means the built-in default layout.
167
+ defaultPdfLayoutSlug: createTenantConfig("text", {
168
+ default: "",
169
+ pattern: {
170
+ regex:
171
+ "^(?:[a-z0-9]{1,40}(?:-[a-z0-9]{1,40}){0,5}(?::[a-z0-9]{1,40}(?:-[a-z0-9]{1,40}){0,5}){0,3})?$",
172
+ },
173
+ }),
162
174
  },
163
175
  });
164
176
  r.translations({ keys: TEMPLATE_RESOLVER_I18N });
@@ -188,6 +200,9 @@ export function createTemplateResolverFeature(opts: TemplateResolverOptions = {}
188
200
  resourceLinkPdf: r.writeHandler(makeResourceLinkPdfWrite(policy)),
189
201
  sendTest: r.writeHandler(makeSendTestWrite(policy)),
190
202
  patchDraft: r.writeHandler(makePatchDraftWrite(policy)),
203
+ applyLayout: r.writeHandler(makeApplyLayoutWrite(policy)),
204
+ createLayout: r.writeHandler(makeCreateLayoutWrite(policy)),
205
+ publishTemplates: r.writeHandler(makePublishTemplatesWrite(policy)),
191
206
  };
192
207
 
193
208
  const queries = {
@@ -0,0 +1,137 @@
1
+ import { defineWriteHandler, type HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
2
+ import { ValidationError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import * as z from "zod";
4
+ import { createTemplateResolverApi, TemplateNotFoundError } from "../api.ts";
5
+ import {
6
+ refuseTemplateEdit,
7
+ type TemplateEditPolicy,
8
+ templateEditAccess,
9
+ } from "../template-edit-policy.ts";
10
+ import { resolveTemplateVariables } from "../template-validation.ts";
11
+ import {
12
+ DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY,
13
+ FALLBACK_LOCALE,
14
+ MAX_SELECTED_TEMPLATES,
15
+ } from "../web/constants.ts";
16
+ import { ConfigHandlers, TemplateResolverErrors } from "../web/qualified-names.ts";
17
+ import { loadDocumentBase } from "./document-base.ts";
18
+ import { failureReason } from "./failure-reason.ts";
19
+ import { localeSchema, templateSlugSchema } from "./shared.ts";
20
+ import { writeTemplateRow } from "./template-write.ts";
21
+
22
+ const templateRefSchema = z.object({ slug: templateSlugSchema, locale: localeSchema });
23
+
24
+ type TemplateRef = z.infer<typeof templateRefSchema>;
25
+ type SkippedTemplate = TemplateRef & { readonly reason: string };
26
+
27
+ async function applyLayoutToDraft(
28
+ ctx: HandlerContext,
29
+ user: HandlerContext["user"],
30
+ layoutSlug: string,
31
+ { slug, locale }: TemplateRef,
32
+ ): Promise<SkippedTemplate | null> {
33
+ const loaded = await loadDocumentBase(ctx, user, { slug, kind: "document-pdf", locale });
34
+ if (loaded === null) return { slug, locale, reason: TemplateResolverErrors.notFound };
35
+ const written = await writeTemplateRow({
36
+ ctx,
37
+ user,
38
+ tenantId: user.tenantId,
39
+ scope: "tenant",
40
+ status: "draft",
41
+ variables: resolveTemplateVariables(ctx.registry, slug, loaded.variableSchema),
42
+ payload: {
43
+ slug,
44
+ kind: "document-pdf",
45
+ locale,
46
+ content: loaded.content,
47
+ contentFormat: "html",
48
+ variableSchema: loaded.variableSchema,
49
+ meta: { ...loaded.meta, layoutSlug },
50
+ title: loaded.title,
51
+ folder: loaded.folder,
52
+ parentTemplateId: loaded.parentTemplateId,
53
+ },
54
+ expectedVersion: loaded.base.scope === "tenant" ? loaded.base.version : null,
55
+ });
56
+ return written.isSuccess ? null : { slug, locale, reason: failureReason(written) };
57
+ }
58
+
59
+ export function makeApplyLayoutWrite(policy: TemplateEditPolicy) {
60
+ return defineWriteHandler({
61
+ name: "apply-layout",
62
+ schema: z.object({
63
+ layoutSlug: templateSlugSchema,
64
+ target: z.discriminatedUnion("mode", [
65
+ z.object({ mode: z.literal("all") }),
66
+ z.object({
67
+ mode: z.literal("selected"),
68
+ templates: z.array(templateRefSchema).min(1).max(MAX_SELECTED_TEMPLATES),
69
+ }),
70
+ ]),
71
+ }),
72
+ access: templateEditAccess(policy.tenantEditable),
73
+ description:
74
+ "Applies a PDF layout to the caller's PDF templates without copying it. Mode all sets the tenant's default PDF layout, which every PDF template that names no layout of its own follows; mode selected saves a tenant draft per listed template and locale that names the layout (text and placeholders stay as they are, a system template gets its own tenant version first) and returns the ones it refused or could not write in skipped with the reason. Nothing is published; use publish-templates for that. The caller needs the right to edit the layout, and for selected also each template. Returns applied and skipped (both empty for mode all).",
75
+ handler: async (event, ctx) => {
76
+ const { layoutSlug, target } = event.payload;
77
+ const refused = refuseTemplateEdit(policy, event.user, {
78
+ slug: layoutSlug,
79
+ kind: "pdf-layout",
80
+ });
81
+ if (refused !== null) return refused;
82
+ try {
83
+ await createTemplateResolverApi(ctx.db, ctx.registry).resolveLayout({
84
+ tenantId: event.user.tenantId,
85
+ slug: layoutSlug,
86
+ kind: "pdf-layout",
87
+ locale: FALLBACK_LOCALE,
88
+ });
89
+ } catch (e) {
90
+ if (!(e instanceof TemplateNotFoundError)) throw e;
91
+ return writeFailure(
92
+ new ValidationError(
93
+ {
94
+ fields: [
95
+ {
96
+ path: "layoutSlug",
97
+ code: TemplateResolverErrors.layoutNotPublished,
98
+ i18nKey: "templateResolver.errors.layout_not_published",
99
+ },
100
+ ],
101
+ },
102
+ { i18nKey: "templateResolver.errors.layout_not_published" },
103
+ ),
104
+ );
105
+ }
106
+
107
+ const applied: TemplateRef[] = [];
108
+ const skipped: SkippedTemplate[] = [];
109
+ if (target.mode === "all") {
110
+ const pointer = await ctx.dispatch.write(ConfigHandlers.set, {
111
+ key: DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY,
112
+ value: layoutSlug,
113
+ });
114
+ if (!pointer.isSuccess) return pointer;
115
+ return {
116
+ isSuccess: true as const,
117
+ data: { applied, skipped },
118
+ };
119
+ }
120
+
121
+ const seen = new Set<string>();
122
+ for (const ref of target.templates) {
123
+ const key = `${ref.slug}\u0000${ref.locale}`;
124
+ if (seen.has(key)) continue;
125
+ seen.add(key);
126
+ if (refuseTemplateEdit(policy, event.user, { slug: ref.slug, kind: "document-pdf" })) {
127
+ skipped.push({ ...ref, reason: TemplateResolverErrors.templateNotTenantEditable });
128
+ continue;
129
+ }
130
+ const skip = await applyLayoutToDraft(ctx, event.user, layoutSlug, ref);
131
+ if (skip === null) applied.push(ref);
132
+ else skipped.push(skip);
133
+ }
134
+ return { isSuccess: true as const, data: { applied, skipped } };
135
+ },
136
+ });
137
+ }
@@ -0,0 +1,87 @@
1
+ import { fetchOne } from "@cosmicdrift/kumiko-framework/db";
2
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
3
+ import { ValidationError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
4
+ import * as z from "zod";
5
+ import { patchIssue } from "../document-op-blocks.ts";
6
+ import { composeLayoutHtml } from "../layout-regions.ts";
7
+ import { type TemplateResourceRow, templateResourcesTable } from "../table.ts";
8
+ import {
9
+ refuseTemplateEdit,
10
+ type TemplateEditPolicy,
11
+ templateEditAccess,
12
+ } from "../template-edit-policy.ts";
13
+ import { resolveTemplateVariables } from "../template-validation.ts";
14
+ import { PDF_DEFAULT_FONT_SIZE_PT, TENANT_LAYOUT_SLUG_PREFIX } from "../web/constants.ts";
15
+ import { localeSchema, slugSchema, titleSchema } from "./shared.ts";
16
+ import { writeTemplateRow } from "./template-write.ts";
17
+
18
+ const PDF_LAYOUT_KIND = "pdf-layout" as const;
19
+
20
+ const STANDARD_LAYOUT_META = {
21
+ fontFamily: "arial",
22
+ fontSizePt: PDF_DEFAULT_FONT_SIZE_PT,
23
+ tableStyle: "plain",
24
+ } as const;
25
+
26
+ export function makeCreateLayoutWrite(policy: TemplateEditPolicy) {
27
+ return defineWriteHandler({
28
+ name: "create-layout",
29
+ schema: z.object({ name: slugSchema, title: titleSchema, locale: localeSchema }),
30
+ access: templateEditAccess(policy.tenantEditable),
31
+ agent: { risk: "low", effect: "proposal" },
32
+ description:
33
+ "Creates a new PDF layout of the caller's tenant as a draft under the slug tenant-layout-<name> (name is kebab-case) with empty header, signature and footer regions and the standard look (font, size, table style); it fails with layout_exists when the tenant already has that layout. A TenantAdmin may create layouts as soon as they may edit any PDF template; every other caller is refused. Returns the full slug, locale, kind and base ({scope, version}) for the next call. Next steps: fill the regions with patch-draft (kind pdf-layout, the returned slug, region header, signature or footer; setMeta changes margins {top,right,bottom,left in mm}, fontFamily, fontSizePt, textColor, tableStyle, tableHeaderBackground, tableLineColor (#rrggbb, line color of the table style, default #bbb), foldMarks (none|din-a|din-b: DIN 5008 fold and punch marks at the left paper edge on every page, form A folds at 87 and 192 mm, form B at 105 and 210 mm), cornerMarks (boolean, default false; angles of 5 mm legs, 0.5 pt, 10 mm from the paper edge in all four corners of every page), paperColor (#rrggbb when the whole page has a tinted paper background, margins, header and footer included; default white), headerOnFirstPage and footerOnFirstPage (booleans, default true; false prints the header or footer only from page 2, margins stay the same)), then let a person publish the layout and point a PDF template at it with patch-draft setMeta {layoutSlug: <returned slug>}.",
34
+ handler: async (event, ctx) => {
35
+ const { name, title, locale } = event.payload;
36
+ const slug = `${TENANT_LAYOUT_SLUG_PREFIX}${name}`;
37
+ const refused = refuseTemplateEdit(policy, event.user, { slug, kind: PDF_LAYOUT_KIND });
38
+ if (refused !== null) return refused;
39
+
40
+ const existing = await fetchOne<TemplateResourceRow>(ctx.db, templateResourcesTable, {
41
+ tenantId: event.user.tenantId,
42
+ slug,
43
+ kind: PDF_LAYOUT_KIND,
44
+ });
45
+ if (existing !== undefined) {
46
+ return writeFailure(
47
+ new ValidationError({ fields: [patchIssue("name", "layout_exists", { slug })] }),
48
+ );
49
+ }
50
+
51
+ const written = await writeTemplateRow({
52
+ ctx,
53
+ user: event.user,
54
+ tenantId: event.user.tenantId,
55
+ scope: "tenant",
56
+ status: "draft",
57
+ variables: resolveTemplateVariables(ctx.registry, slug, {}),
58
+ payload: {
59
+ slug,
60
+ kind: PDF_LAYOUT_KIND,
61
+ locale,
62
+ content: composeLayoutHtml({ header: "", signature: "", footer: "" }),
63
+ contentFormat: "html",
64
+ variableSchema: {},
65
+ meta: STANDARD_LAYOUT_META,
66
+ title,
67
+ },
68
+ expectedVersion: null,
69
+ });
70
+ if (!written.isSuccess) return written;
71
+ const created = await fetchOne<TemplateResourceRow>(ctx.db, templateResourcesTable, {
72
+ tenantId: event.user.tenantId,
73
+ id: written.data.id,
74
+ });
75
+ if (created === undefined) throw new Error(`create-layout: row ${slug} missing after write`);
76
+ return {
77
+ isSuccess: true as const,
78
+ data: {
79
+ slug,
80
+ locale,
81
+ kind: PDF_LAYOUT_KIND,
82
+ base: { scope: "tenant" as const, version: created.version },
83
+ },
84
+ };
85
+ },
86
+ });
87
+ }
@@ -10,7 +10,7 @@ import { type TemplateResourceRow, templateResourcesTable } from "../table.ts";
10
10
  import { deliveryPolicyOf } from "../template-delivery-policy.ts";
11
11
  import { isHiddenSystemDraft, toWorkingRow } from "../template-draft.ts";
12
12
  import { isSystemOnlyTemplateHiddenFrom } from "../template-system-only.ts";
13
- import type { DocumentHtmlKind } from "../web/constants.ts";
13
+ import type { DocumentOpsKind } from "../web/constants.ts";
14
14
  import { parseStoredJson } from "./template-gates.ts";
15
15
 
16
16
  export type DocumentBase = {
@@ -41,7 +41,7 @@ function recordOrEmpty(raw: string | null): Readonly<Record<string, unknown>> {
41
41
  export async function loadDocumentBase(
42
42
  ctx: HandlerContext,
43
43
  user: SessionUser,
44
- where: { readonly slug: string; readonly kind: DocumentHtmlKind; readonly locale: string },
44
+ where: { readonly slug: string; readonly kind: DocumentOpsKind; readonly locale: string },
45
45
  ): Promise<LoadedDocument | null> {
46
46
  const own = await fetchOne<TemplateResourceRow>(ctx.db, templateResourcesTable, {
47
47
  tenantId: user.tenantId,
@@ -1,12 +1,12 @@
1
1
  import { defineQueryHandler } from "@cosmicdrift/kumiko-framework/engine";
2
- import { NotFoundError } from "@cosmicdrift/kumiko-framework/errors";
2
+ import { NotFoundError, ValidationError } from "@cosmicdrift/kumiko-framework/errors";
3
3
  import * as z from "zod";
4
+ import { allowedBlocksFor } from "../document-op-blocks.ts";
4
5
  import { documentBlocksOf } from "../document-ops.ts";
5
6
  import { parseDocumentJson } from "../document-sanitizer.ts";
6
7
  import { resolveTemplateVariables } from "../template-validation.ts";
7
- import { DOCUMENT_HTML_KINDS } from "../web/constants.ts";
8
- import { documentBlocksForKind } from "../web/document-blocks.ts";
9
8
  import { loadDocumentBase } from "./document-base.ts";
9
+ import { documentTargetShape, editableHtmlOf, regionIssue } from "./document-region.ts";
10
10
  import { localeSchema, templateSlugSchema } from "./shared.ts";
11
11
  import { knownResourceKeysFor } from "./validate.query.ts";
12
12
 
@@ -14,29 +14,34 @@ export const documentBlocksQuery = defineQueryHandler({
14
14
  name: "document-blocks",
15
15
  schema: z.object({
16
16
  slug: templateSlugSchema,
17
- kind: z.enum(DOCUMENT_HTML_KINDS),
17
+ ...documentTargetShape,
18
18
  locale: localeSchema,
19
19
  }),
20
20
  access: { roles: ["TenantAdmin", "SystemAdmin"] },
21
21
  description:
22
- "Reads a mail or PDF document template as a list of blocks with stable ids (b0, b1, ...) for structured editing: each block has its type (paragraph, heading, list, table, repeat, image, button, divider, pageBreak, steps), its text with {{name}} placeholders and its settings, plus the meta, the stored and effective variables (variablesDeclaredByFeature is true when a notification declares them, so they cannot be changed), the block types allowed for the kind and the uploaded image keys. It reads the caller's own version (the open draft if there is one), else the served system default; base carries the scope and version that patch-draft expects back.",
22
+ "Reads a mail template, a PDF document template or, with kind pdf-layout and a region (header, signature, footer), one region of a PDF layout as a list of blocks with stable ids (b0, b1, ...) for structured editing with patch-draft: each block has its type (paragraph, heading, list, table, repeat, frame with its position in mm, image, button, divider, pageBreak, steps), its text with {{name}} placeholders and its settings, plus the meta, the stored and effective variables (variablesDeclaredByFeature is true when a notification declares them, so they cannot be changed), the block types allowed for the kind (a frame only in document-pdf) and the uploaded image keys. It reads the caller's own version (the open draft if there is one), else the served system default; base carries the scope and version that patch-draft expects back.",
23
23
  handler: async (query, ctx) => {
24
- const { slug, kind, locale } = query.payload;
24
+ const { slug, kind, region, locale } = query.payload;
25
+ const misplacedRegion = regionIssue(kind, region);
26
+ if (misplacedRegion !== null) {
27
+ throw new ValidationError({ fields: [misplacedRegion] });
28
+ }
25
29
  const loaded = await loadDocumentBase(ctx, query.user, { slug, kind, locale });
26
30
  if (loaded === null) throw new NotFoundError("template-resource", slug);
27
31
  return {
28
32
  slug,
29
33
  kind,
34
+ ...(region === undefined ? {} : { region }),
30
35
  locale,
31
36
  base: loaded.base,
32
37
  status: loaded.status,
33
- blocks: documentBlocksOf(parseDocumentJson(loaded.content)),
38
+ blocks: documentBlocksOf(parseDocumentJson(editableHtmlOf(kind, region, loaded.content))),
34
39
  meta: loaded.meta,
35
40
  variableSchema: loaded.variableSchema,
36
41
  variables: resolveTemplateVariables(ctx.registry, slug, loaded.variableSchema),
37
42
  variablesDeclaredByFeature:
38
43
  ctx.registry.getAllNotifications().get(slug)?.variables !== undefined,
39
- allowedBlocks: documentBlocksForKind(kind),
44
+ allowedBlocks: allowedBlocksFor(kind),
40
45
  resourceKeys: await knownResourceKeysFor(ctx, query.user, {
41
46
  slug,
42
47
  kind,
@@ -0,0 +1,47 @@
1
+ import type { FieldIssue } from "@cosmicdrift/kumiko-framework/errors";
2
+ import * as z from "zod";
3
+ import { patchIssue } from "../document-op-blocks.ts";
4
+ import {
5
+ composeLayoutHtml,
6
+ LAYOUT_REGION_NAMES,
7
+ type LayoutRegionName,
8
+ readLayoutRegions,
9
+ } from "../layout-regions.ts";
10
+ import { DOCUMENT_OPS_KINDS, type DocumentOpsKind } from "../web/constants.ts";
11
+
12
+ export const documentTargetShape = {
13
+ kind: z.enum(DOCUMENT_OPS_KINDS),
14
+ region: z.enum(LAYOUT_REGION_NAMES).optional(),
15
+ };
16
+
17
+ // A pdf-layout is edited one region at a time; every other kind is the whole body.
18
+ export function regionIssue(
19
+ kind: DocumentOpsKind,
20
+ region: LayoutRegionName | undefined,
21
+ ): FieldIssue | null {
22
+ if (kind === "pdf-layout" && region === undefined) return patchIssue("region", "region_required");
23
+ if (kind !== "pdf-layout" && region !== undefined) {
24
+ return patchIssue("region", "region_not_allowed", { kind });
25
+ }
26
+ return null;
27
+ }
28
+
29
+ export function editableHtmlOf(
30
+ kind: DocumentOpsKind,
31
+ region: LayoutRegionName | undefined,
32
+ content: string,
33
+ ): string {
34
+ return kind === "pdf-layout" && region !== undefined
35
+ ? readLayoutRegions(content)[region]
36
+ : content;
37
+ }
38
+
39
+ export function contentWithEditedHtml(
40
+ kind: DocumentOpsKind,
41
+ region: LayoutRegionName | undefined,
42
+ content: string,
43
+ editedHtml: string,
44
+ ): string {
45
+ if (kind !== "pdf-layout" || region === undefined) return editedHtml;
46
+ return composeLayoutHtml({ ...readLayoutRegions(content), [region]: editedHtml });
47
+ }
@@ -0,0 +1,13 @@
1
+ import type { WriteFailure } from "@cosmicdrift/kumiko-framework/errors";
2
+ import { isPlainObject } from "@cosmicdrift/kumiko-types/type-guards";
3
+
4
+ // A batch reports what went wrong per template instead of aborting: the first field issue's code
5
+ // for a validation failure, else the error's own reason or code.
6
+ export function failureReason(failure: WriteFailure): string {
7
+ const { details } = failure.error;
8
+ if (!isPlainObject(details)) return failure.error.code;
9
+ const firstField = Array.isArray(details["fields"]) ? details["fields"][0] : undefined;
10
+ if (isPlainObject(firstField) && typeof firstField["code"] === "string")
11
+ return firstField["code"];
12
+ return typeof details["reason"] === "string" ? details["reason"] : failure.error.code;
13
+ }
@@ -2,6 +2,7 @@ import { defineWriteHandler, SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framew
2
2
  import { ValidationError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
3
  import * as z from "zod";
4
4
  import { templateBundleSchema } from "../template-bundle.ts";
5
+ import { refuseReservedLayoutSlug } from "../template-edit-policy.ts";
5
6
  import { importTemplateBundle, prepareTemplateBundleBeforeTransaction } from "./bundle-import.ts";
6
7
 
7
8
  export const importBundleSystemWrite = defineWriteHandler({
@@ -14,6 +15,8 @@ export const importBundleSystemWrite = defineWriteHandler({
14
15
  "Imports a template bundle as system-default templates, active straight away and overwriting existing system rows; SystemAdmin only. Bundles with resource files need a caller in the system tenant, because the files are stored in the caller's file space.",
15
16
  beforeTransaction: async (event, ctx) => {
16
17
  const { bundle } = event.payload;
18
+ const reserved = refuseReservedLayoutSlug(bundle, "bundle.slug");
19
+ if (reserved !== null) return reserved;
17
20
  // Must run before any upload.
18
21
  if (Object.keys(bundle.resources).length > 0 && event.user.tenantId !== SYSTEM_TENANT_ID) {
19
22
  return writeFailure(
@@ -13,7 +13,12 @@ import {
13
13
  toWorkingRow,
14
14
  type WorkingRow,
15
15
  } from "../template-draft.ts";
16
- import { type MailLayoutMeta, readMailLayoutMeta } from "../template-meta.ts";
16
+ import {
17
+ type MailLayoutMeta,
18
+ type PdfLayoutMeta,
19
+ readMailLayoutMeta,
20
+ readPdfLayoutMeta,
21
+ } from "../template-meta.ts";
17
22
  import { FALLBACK_LOCALE } from "../web/constants.ts";
18
23
  import { TemplateResolverErrors } from "../web/qualified-names.ts";
19
24
  import { localeSchema, templateSlugSchema } from "./shared.ts";
@@ -33,8 +38,8 @@ export type LayoutSourceResponse = {
33
38
  readonly regions: LayoutRegions;
34
39
  readonly effectiveFormat: "html" | "mjml" | null;
35
40
  readonly mjmlSource: string | null;
36
- /** Appearance of the effective mail layout; invalid stored meta reads as defaults (empty). */
37
- readonly meta: MailLayoutMeta;
41
+ /** Appearance of the effective layout; invalid stored meta reads as defaults (empty). */
42
+ readonly meta: MailLayoutMeta | PdfLayoutMeta;
38
43
  readonly locale: string;
39
44
  };
40
45
 
@@ -116,6 +121,14 @@ function readMjmlSource(systemRow: WorkingRow | null, isSystemAdmin: boolean): s
116
121
  return exposesMjml ? (systemRow.content ?? "") : null;
117
122
  }
118
123
 
124
+ function readLayoutMeta(
125
+ kind: "mail-layout" | "pdf-layout",
126
+ effective: WorkingRow | null,
127
+ ): MailLayoutMeta | PdfLayoutMeta {
128
+ const stored = parseStoredJson(effective?.meta ?? null);
129
+ return kind === "mail-layout" ? readMailLayoutMeta(stored) : readPdfLayoutMeta(stored);
130
+ }
131
+
119
132
  function buildLayoutSource(input: {
120
133
  readonly kind: "mail-layout" | "pdf-layout";
121
134
  readonly locale: string | undefined;
@@ -135,8 +148,7 @@ function buildLayoutSource(input: {
135
148
  regions: readEffectiveRegions(effective, effectiveFormat),
136
149
  effectiveFormat,
137
150
  mjmlSource: readMjmlSource(systemRow, isSystemAdmin),
138
- meta:
139
- kind === "mail-layout" ? readMailLayoutMeta(parseStoredJson(effective?.meta ?? null)) : {},
151
+ meta: readLayoutMeta(kind, effective),
140
152
  locale: effective?.locale ?? locale ?? FALLBACK_LOCALE,
141
153
  };
142
154
  }
@@ -32,6 +32,7 @@ import {
32
32
  import { TemplateResolverQueries } from "../web/qualified-names.ts";
33
33
  import { storedRecord } from "./template-gates.ts";
34
34
  import { tenantOverrideCountsResultSchema } from "./tenant-override-counts.query.ts";
35
+ import { defaultPdfLayoutSlug } from "./tenant-settings.ts";
35
36
 
36
37
  const OVERVIEW_KINDS = ["mail", "document-pdf", "mail-layout", "pdf-layout"] as const;
37
38
  type OverviewKind = (typeof OVERVIEW_KINDS)[number];
@@ -103,9 +104,13 @@ function isTemplateStatus(status: string): status is TemplateStatus {
103
104
  return status === "draft" || status === "active" || status === "archived";
104
105
  }
105
106
 
106
- function layoutSlugOf(row: TemplateResourceRow): string {
107
+ export function ownLayoutSlugOf(row: TemplateResourceRow): string | null {
107
108
  const layoutSlug = storedRecord(row.meta)["layoutSlug"];
108
- return typeof layoutSlug === "string" ? layoutSlug : DEFAULT_MAIL_LAYOUT_SLUG;
109
+ return typeof layoutSlug === "string" ? layoutSlug : null;
110
+ }
111
+
112
+ function layoutSlugOf(row: TemplateResourceRow, fallback = DEFAULT_MAIL_LAYOUT_SLUG): string {
113
+ return ownLayoutSlugOf(row) ?? fallback;
109
114
  }
110
115
 
111
116
  function preferredRow(rows: readonly TemplateResourceRow[]): TemplateResourceRow | undefined {
@@ -123,7 +128,7 @@ type EffectiveRows = {
123
128
  };
124
129
 
125
130
  // A tenant row of a template that is not unlocked is not delivered, so the system version is the effective one.
126
- function effectiveRowsOf(
131
+ export function effectiveRowsOf(
127
132
  rows: readonly TemplateResourceRow[],
128
133
  policy: TemplateDeliveryPolicy,
129
134
  ): EffectiveRows | null {
@@ -275,6 +280,7 @@ function buildDrafts(
275
280
  groups: ReadonlyMap<string, readonly TemplateResourceRow[]>,
276
281
  user: { readonly tenantId: string; readonly roles: readonly string[] },
277
282
  policy: TemplateDeliveryPolicy,
283
+ defaultPdfLayoutSlug: string,
278
284
  ): {
279
285
  readonly drafts: OverviewDraft[];
280
286
  readonly layoutSlugByDocument: Map<string, string>;
@@ -287,7 +293,12 @@ function buildDrafts(
287
293
  if (effective === null || preferred === undefined) continue;
288
294
  if (!isOverviewKind(preferred.kind) || !isTemplateStatus(preferred.status)) continue;
289
295
  const isDocument = preferred.kind === "mail" || preferred.kind === "document-pdf";
290
- const layoutSlug = isDocument ? layoutSlugOf(preferred) : null;
296
+ const layoutSlug = isDocument
297
+ ? layoutSlugOf(
298
+ preferred,
299
+ preferred.kind === "document-pdf" ? defaultPdfLayoutSlug : DEFAULT_MAIL_LAYOUT_SLUG,
300
+ )
301
+ : null;
291
302
  if (layoutSlug !== null && preferred.kind === "document-pdf") {
292
303
  layoutSlugByDocument.set(preferred.slug, layoutSlug);
293
304
  }
@@ -427,6 +438,7 @@ export function makeOverviewQuery(policy: TemplateEditPolicy) {
427
438
  groupBySlugAndKind(visibleRows),
428
439
  query.user,
429
440
  deliveryPolicy,
441
+ await defaultPdfLayoutSlug(ctx, query.user.tenantId),
430
442
  );
431
443
  const effectiveLayouts = effectiveMailLayoutSlugs(visibleRows, deliveryPolicy);
432
444
  const rowsWithUsage = drafts.map((draft) =>
@@ -15,8 +15,13 @@ import {
15
15
  templateEditAccess,
16
16
  } from "../template-edit-policy.ts";
17
17
  import { resolveTemplateVariables } from "../template-validation.ts";
18
- import { DOCUMENT_HTML_KINDS } from "../web/constants.ts";
19
18
  import { loadDocumentBase } from "./document-base.ts";
19
+ import {
20
+ contentWithEditedHtml,
21
+ documentTargetShape,
22
+ editableHtmlOf,
23
+ regionIssue,
24
+ } from "./document-region.ts";
20
25
  import { localeSchema, templateSlugSchema } from "./shared.ts";
21
26
  import { writeTemplateRow } from "./template-write.ts";
22
27
  import { validateTemplateDraft } from "./validate.query.ts";
@@ -30,7 +35,7 @@ export function makePatchDraftWrite(policy: TemplateEditPolicy) {
30
35
  name: "patch-draft",
31
36
  schema: z.object({
32
37
  slug: templateSlugSchema,
33
- kind: z.enum(DOCUMENT_HTML_KINDS),
38
+ ...documentTargetShape,
34
39
  locale: localeSchema,
35
40
  base: z.object({
36
41
  scope: z.enum(["tenant", "system"]),
@@ -39,10 +44,13 @@ export function makePatchDraftWrite(policy: TemplateEditPolicy) {
39
44
  ops: documentOpsSchema,
40
45
  }),
41
46
  access: templateEditAccess(policy.tenantEditable),
47
+ agent: { risk: "low", effect: "proposal" },
42
48
  description:
43
- "Changes a mail or PDF document template 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): insertBlock after a block id (null = at the start; paragraph, heading, image, button, divider, pageBreak), 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) 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.",
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.',
44
50
  handler: async (event, ctx) => {
45
- const { slug, kind, locale, base, ops } = event.payload;
51
+ const { slug, kind, region, locale, base, ops } = event.payload;
52
+ const misplacedRegion = regionIssue(kind, region);
53
+ if (misplacedRegion !== null) return validationFailure(misplacedRegion);
46
54
  const refused = refuseTemplateEdit(policy, event.user, { slug, kind });
47
55
  if (refused !== null) return refused;
48
56
  const loaded = await loadDocumentBase(ctx, event.user, { slug, kind, locale });
@@ -71,14 +79,20 @@ export function makePatchDraftWrite(policy: TemplateEditPolicy) {
71
79
  }
72
80
 
73
81
  const applied = applyDocumentOps({
74
- doc: parseDocumentJson(loaded.content),
82
+ doc: parseDocumentJson(editableHtmlOf(kind, region, loaded.content)),
75
83
  meta: loaded.meta,
76
84
  variableSchema: loaded.variableSchema,
77
85
  kind,
86
+ region,
78
87
  ops,
79
88
  });
80
89
  if (!applied.ok) return writeFailure(new ValidationError({ fields: applied.issues }));
81
- const content = serializeDocumentJson(applied.doc);
90
+ const content = contentWithEditedHtml(
91
+ kind,
92
+ region,
93
+ loaded.content,
94
+ serializeDocumentJson(applied.doc),
95
+ );
82
96
 
83
97
  const draftOf = (
84
98
  draftContent: string,