@cosmicdrift/kumiko-samples 0.417.0 → 0.419.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 (114) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +6 -1
  3. package/packages/bundled-features/src/agent-tools/api-docs/schema-fields.ts +14 -0
  4. package/packages/bundled-features/src/agent-tools/changes.json +6 -0
  5. package/packages/bundled-features/src/auth-email-password/index.ts +1 -1
  6. package/packages/bundled-features/src/auth-email-password/signup-activation.ts +2 -5
  7. package/packages/bundled-features/src/auth-email-password/signup-token-store.ts +0 -6
  8. package/packages/bundled-features/src/cap-counter/changes.json +6 -0
  9. package/packages/bundled-features/src/cap-counter/stock-cap-guard.ts +46 -13
  10. package/packages/bundled-features/src/channel-whatsapp/changes.json +1 -1
  11. package/packages/bundled-features/src/document-ingest-foundation/changes.json +6 -0
  12. package/packages/bundled-features/src/document-ingest-foundation/feature.ts +13 -1
  13. package/packages/bundled-features/src/document-ingest-foundation/report-ingest-progress.ts +23 -6
  14. package/packages/bundled-features/src/signature/README.md +4 -4
  15. package/packages/bundled-features/src/signature/changes.json +18 -0
  16. package/packages/bundled-features/src/signature/entity.ts +3 -1
  17. package/packages/bundled-features/src/signature/feature.ts +16 -3
  18. package/packages/bundled-features/src/signature/handlers/lifecycle.write.ts +33 -1
  19. package/packages/bundled-features/src/signature/i18n.ts +1 -0
  20. package/packages/bundled-features/src/signature/list-cursor-seal.ts +59 -0
  21. package/packages/bundled-features/src/signature/options.ts +2 -2
  22. package/packages/bundled-features/src/signature/payloads.ts +14 -2
  23. package/packages/bundled-features/src/signature/png.ts +25 -4
  24. package/packages/bundled-features/src/signature/subject-queries.ts +47 -7
  25. package/packages/bundled-features/src/signature/sweep.ts +32 -8
  26. package/packages/bundled-features/src/signature/web/constants.ts +12 -0
  27. package/packages/bundled-features/src/subscription-paddle/changes.json +1 -1
  28. package/packages/bundled-features/src/subscription-stripe/changes.json +6 -0
  29. package/packages/bundled-features/src/subscription-stripe/plugin-methods.ts +2 -0
  30. package/packages/bundled-features/src/subscription-stripe/verify-webhook.ts +21 -16
  31. package/packages/bundled-features/src/template-resolver/changes.json +38 -0
  32. package/packages/bundled-features/src/template-resolver/compile-document-body.ts +3 -8
  33. package/packages/bundled-features/src/template-resolver/compile-document-styles.ts +102 -0
  34. package/packages/bundled-features/src/template-resolver/document-frames.ts +25 -0
  35. package/packages/bundled-features/src/template-resolver/document-op-blocks.ts +568 -0
  36. package/packages/bundled-features/src/template-resolver/document-ops.ts +136 -126
  37. package/packages/bundled-features/src/template-resolver/document-print-only.ts +41 -0
  38. package/packages/bundled-features/src/template-resolver/document-sanitizer.ts +41 -19
  39. package/packages/bundled-features/src/template-resolver/feature.ts +15 -0
  40. package/packages/bundled-features/src/template-resolver/handlers/apply-layout.write.ts +137 -0
  41. package/packages/bundled-features/src/template-resolver/handlers/create-layout.write.ts +87 -0
  42. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +2 -2
  43. package/packages/bundled-features/src/template-resolver/handlers/document-blocks.query.ts +13 -8
  44. package/packages/bundled-features/src/template-resolver/handlers/document-region.ts +47 -0
  45. package/packages/bundled-features/src/template-resolver/handlers/failure-reason.ts +13 -0
  46. package/packages/bundled-features/src/template-resolver/handlers/import-bundle-system.write.ts +3 -0
  47. package/packages/bundled-features/src/template-resolver/handlers/layout-source.query.ts +17 -5
  48. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +16 -4
  49. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +19 -6
  50. package/packages/bundled-features/src/template-resolver/handlers/publish-templates.write.ts +69 -0
  51. package/packages/bundled-features/src/template-resolver/handlers/set.write.ts +7 -0
  52. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +15 -3
  53. package/packages/bundled-features/src/template-resolver/handlers/tenant-settings.ts +122 -0
  54. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +25 -10
  55. package/packages/bundled-features/src/template-resolver/handlers/upsert-system.write.ts +7 -3
  56. package/packages/bundled-features/src/template-resolver/handlers/usage.query.ts +131 -18
  57. package/packages/bundled-features/src/template-resolver/handlers/validate.query.ts +10 -0
  58. package/packages/bundled-features/src/template-resolver/i18n.ts +3 -0
  59. package/packages/bundled-features/src/template-resolver/index.ts +29 -0
  60. package/packages/bundled-features/src/template-resolver/layout-regions.ts +54 -16
  61. package/packages/bundled-features/src/template-resolver/print-document.ts +3 -1
  62. package/packages/bundled-features/src/template-resolver/seeding.ts +4 -0
  63. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +11 -1
  64. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +37 -1
  65. package/packages/bundled-features/src/template-resolver/template-meta.ts +25 -6
  66. package/packages/bundled-features/src/template-resolver/template-preview.ts +6 -7
  67. package/packages/bundled-features/src/template-resolver/template-validation.ts +10 -3
  68. package/packages/bundled-features/src/template-resolver/web/constants.ts +29 -0
  69. package/packages/bundled-features/src/template-resolver/web/document-blocks.ts +5 -0
  70. package/packages/bundled-features/src/template-resolver/web/document-editor-extensions.ts +34 -2
  71. package/packages/bundled-features/src/template-resolver/web/document-editor-fonts.ts +13 -0
  72. package/packages/bundled-features/src/template-resolver/web/document-fonts.ts +21 -0
  73. package/packages/bundled-features/src/template-resolver/web/document-frame-control.ts +428 -0
  74. package/packages/bundled-features/src/template-resolver/web/document-frame-node-view.tsx +207 -0
  75. package/packages/bundled-features/src/template-resolver/web/document-print-decorations.ts +196 -0
  76. package/packages/bundled-features/src/template-resolver/web/document-print-defaults.ts +59 -0
  77. package/packages/bundled-features/src/template-resolver/web/document-print-style.ts +246 -0
  78. package/packages/bundled-features/src/template-resolver/web/document-repeat-strip.ts +104 -0
  79. package/packages/bundled-features/src/template-resolver/web/document-schema.ts +29 -9
  80. package/packages/bundled-features/src/template-resolver/web/document-style-css.ts +107 -0
  81. package/packages/bundled-features/src/template-resolver/web/document-tiptap-bubble.tsx +24 -2
  82. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +66 -7
  83. package/packages/bundled-features/src/template-resolver/web/document-tiptap-context.ts +13 -1
  84. package/packages/bundled-features/src/template-resolver/web/document-tiptap-editor.tsx +24 -4
  85. package/packages/bundled-features/src/template-resolver/web/document-tiptap-helpers.ts +149 -4
  86. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar-groups.tsx +290 -10
  87. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +90 -8
  88. package/packages/bundled-features/src/template-resolver/web/document-toolbar-blocks.ts +20 -0
  89. package/packages/bundled-features/src/template-resolver/web/fontsource-css.d.ts +2 -0
  90. package/packages/bundled-features/src/template-resolver/web/i18n.ts +28 -0
  91. package/packages/bundled-features/src/template-resolver/web/index.ts +34 -0
  92. package/packages/bundled-features/src/template-resolver/web/pdf-constants.ts +6 -0
  93. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +7 -0
  94. package/packages/bundled-features/src/template-resolver/web/use-document-tiptap-model.ts +74 -5
  95. package/packages/bundled-features/src/tenant/company-config.ts +48 -0
  96. package/packages/bundled-features/src/tenant/feature.ts +11 -0
  97. package/packages/bundled-features/src/tenant/i18n.ts +14 -0
  98. package/packages/bundled-features/src/tenant-inactivity/handlers/keep-account.write.ts +7 -3
  99. package/packages/bundled-features/src/tenant-lifecycle/changes.json +6 -0
  100. package/packages/bundled-features/src/tenant-lifecycle/run-tenant-destroy.ts +90 -42
  101. package/samples/apps/ui-walkthrough/src/app/auth-constants.ts +51 -0
  102. package/samples/apps/ui-walkthrough/src/app/seed-print-editor-tenants.ts +118 -0
  103. package/samples/apps/ui-walkthrough/src/app/seed-templates.ts +2 -0
  104. package/samples/apps/ui-walkthrough/src/app/server.ts +9 -1
  105. package/samples/apps/ui-walkthrough/src/app/template-seed-data.ts +27 -1
  106. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  107. package/samples/apps/use-all-bundled/feature-manifest.json +238 -1
  108. package/samples/recipes/crypto-shredding-hr/README.md +1 -1
  109. package/samples/recipes/crypto-shredding-hr/src/feature.ts +1 -1
  110. package/samples/recipes/list-table-options/README.md +9 -3
  111. package/samples/recipes/list-table-options/src/feature.ts +123 -3
  112. package/samples/recipes/pdf-letterhead/README.md +23 -0
  113. package/samples/recipes/pdf-letterhead/package.json +12 -0
  114. package/samples/recipes/pdf-letterhead/src/letterhead.ts +92 -0
@@ -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, fontFamily, fontSizePt, textColor, tableStyle, tableHeaderBackground), 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}]} with optional align, style {lineHeight,spaceBeforePt,spaceAfterPt} and textStyle {font,sizePt,color}; list {ordered,items:[text or runs]}; table {borders:"none",columnWidthsPx,header:{cells:[{text|runs,background,align}]},rows:[{cells}],repeat:{each:<list variable>,row}} (repeat is the row printed once per list entry; header repeats on every page); 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}; button {text,href} mails only; divider; 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) 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,19 @@ 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,
78
86
  ops,
79
87
  });
80
88
  if (!applied.ok) return writeFailure(new ValidationError({ fields: applied.issues }));
81
- const content = serializeDocumentJson(applied.doc);
89
+ const content = contentWithEditedHtml(
90
+ kind,
91
+ region,
92
+ loaded.content,
93
+ serializeDocumentJson(applied.doc),
94
+ );
82
95
 
83
96
  const draftOf = (
84
97
  draftContent: string,
@@ -0,0 +1,69 @@
1
+ import { fetchOne } from "@cosmicdrift/kumiko-framework/db";
2
+ import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
3
+ import * as z from "zod";
4
+ import { type TemplateResourceRow, templateResourcesTable } from "../table.ts";
5
+ import { parseTemplateDraft } from "../template-draft.ts";
6
+ import {
7
+ refuseTemplateEdit,
8
+ type TemplateEditPolicy,
9
+ templateEditAccess,
10
+ } from "../template-edit-policy.ts";
11
+ import { TemplateResolverErrors } from "../web/qualified-names.ts";
12
+ import { failureReason } from "./failure-reason.ts";
13
+ import { kindSchema, localeSchema, templateSlugSchema } from "./shared.ts";
14
+ import { changeRowStatus } from "./toggle-status.write.ts";
15
+
16
+ const MAX_PUBLISHED_TEMPLATES = 200;
17
+
18
+ const templateRefSchema = z.object({
19
+ slug: templateSlugSchema,
20
+ kind: kindSchema,
21
+ locale: localeSchema,
22
+ });
23
+
24
+ type TemplateRef = z.infer<typeof templateRefSchema>;
25
+ type FailedTemplate = TemplateRef & { readonly reason: string };
26
+
27
+ export function makePublishTemplatesWrite(policy: TemplateEditPolicy) {
28
+ return defineWriteHandler({
29
+ name: "publish-templates",
30
+ schema: z.object({
31
+ templates: z.array(templateRefSchema).min(1).max(MAX_PUBLISHED_TEMPLATES),
32
+ }),
33
+ access: templateEditAccess(policy.tenantEditable),
34
+ description:
35
+ "Publishes the open drafts of several tenant templates in one call, each exactly as publish would: the same edit right per template and the same gate (unknown placeholders, unused required variables). A template that is refused or fails the gate lands in failed with the reason and does not stop the others; a template without an open draft that is already active is reported as failed with template_already_active. Returns published and failed.",
36
+ handler: async (event, ctx) => {
37
+ const published: TemplateRef[] = [];
38
+ const failed: FailedTemplate[] = [];
39
+ const seen = new Set<string>();
40
+ for (const ref of event.payload.templates) {
41
+ const key = `${ref.kind}\u0000${ref.slug}\u0000${ref.locale}`;
42
+ if (seen.has(key)) continue;
43
+ seen.add(key);
44
+ const refused = refuseTemplateEdit(policy, event.user, ref);
45
+ if (refused !== null) {
46
+ failed.push({ ...ref, reason: failureReason(refused) });
47
+ continue;
48
+ }
49
+ const row = await fetchOne<TemplateResourceRow>(ctx.db, templateResourcesTable, {
50
+ tenantId: event.user.tenantId,
51
+ ...ref,
52
+ });
53
+ if (row === undefined || row.scope !== "tenant") {
54
+ failed.push({ ...ref, reason: TemplateResolverErrors.notFound });
55
+ continue;
56
+ }
57
+ if (row.status === "active" && parseTemplateDraft(row.draft) === null) {
58
+ failed.push({ ...ref, reason: TemplateResolverErrors.alreadyActive });
59
+ continue;
60
+ }
61
+ const ownRowTarget = { db: ctx.db, scoped: null };
62
+ const result = await changeRowStatus(ctx, event.user, ownRowTarget, row, "active");
63
+ if (result.isSuccess) published.push(ref);
64
+ else failed.push({ ...ref, reason: failureReason(result) });
65
+ }
66
+ return { isSuccess: true as const, data: { published, failed } };
67
+ },
68
+ });
69
+ }
@@ -9,6 +9,7 @@ import * as z from "zod";
9
9
  import { requireForTenant } from "../../shared/index.ts";
10
10
  import { type TemplateResourceRow, templateResourcesTable } from "../table.ts";
11
11
  import {
12
+ refuseReservedSystemLayoutSlug,
12
13
  refuseTemplateEdit,
13
14
  type TemplateEditPolicy,
14
15
  templateEditAccess,
@@ -78,6 +79,12 @@ export function makeSetWrite(policy: TemplateEditPolicy) {
78
79
  });
79
80
 
80
81
  const scope = tenantId === SYSTEM_TENANT_ID ? ("system" as const) : ("tenant" as const);
82
+ const reserved = refuseReservedSystemLayoutSlug(
83
+ scope,
84
+ { slug: event.payload.slug, kind },
85
+ "slug",
86
+ );
87
+ if (reserved !== null) return reserved;
81
88
  let content = event.payload.content;
82
89
  if (isOneOf(UPSERT_KINDS, kind)) {
83
90
  const gated = gateTemplateWrite(