@cosmicdrift/kumiko-bundled-features 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.
- package/dist/shared/index.d.ts +1 -0
- package/dist/shared/index.js +1 -0
- package/dist/shared/tenant-scoped-subject.d.ts +11 -0
- package/dist/shared/tenant-scoped-subject.js +18 -0
- package/dist/signature/feature.js +1 -1
- package/dist/signature/grant.d.ts +1 -1
- package/dist/signature/grant.js +7 -12
- package/dist/signature/png.js +35 -10
- package/dist/template-resolver/api.d.ts +2 -0
- package/dist/template-resolver/api.js +11 -7
- package/dist/template-resolver/compile-document-body.js +9 -11
- package/dist/template-resolver/compile-document-styles.d.ts +3 -0
- package/dist/template-resolver/compile-document-styles.js +122 -0
- package/dist/template-resolver/document-frames.d.ts +4 -0
- package/dist/template-resolver/document-frames.js +56 -0
- package/dist/template-resolver/document-op-blocks.d.ts +729 -0
- package/dist/template-resolver/document-op-blocks.js +521 -0
- package/dist/template-resolver/document-ops.d.ts +2743 -37
- package/dist/template-resolver/document-ops.js +128 -106
- package/dist/template-resolver/document-print-only.d.ts +11 -0
- package/dist/template-resolver/document-print-only.js +47 -0
- package/dist/template-resolver/document-sanitizer.d.ts +1 -1
- package/dist/template-resolver/document-sanitizer.js +29 -13
- package/dist/template-resolver/feature.d.ts +3 -0
- package/dist/template-resolver/feature.js +14 -1
- package/dist/template-resolver/handlers/apply-layout.write.d.ts +29 -0
- package/dist/template-resolver/handlers/apply-layout.write.js +118 -0
- package/dist/template-resolver/handlers/create-layout.write.d.ts +15 -0
- package/dist/template-resolver/handlers/create-layout.write.js +78 -0
- package/dist/template-resolver/handlers/document-base.d.ts +2 -2
- package/dist/template-resolver/handlers/document-blocks.query.d.ts +10 -3
- package/dist/template-resolver/handlers/document-blocks.query.js +13 -8
- package/dist/template-resolver/handlers/document-region.d.ts +19 -0
- package/dist/template-resolver/handlers/document-region.js +27 -0
- package/dist/template-resolver/handlers/failure-reason.d.ts +2 -0
- package/dist/template-resolver/handlers/failure-reason.js +12 -0
- package/dist/template-resolver/handlers/import-bundle-system.write.js +4 -0
- package/dist/template-resolver/handlers/layout-source.query.d.ts +3 -3
- package/dist/template-resolver/handlers/layout-source.query.js +6 -2
- package/dist/template-resolver/handlers/overview.query.d.ts +8 -0
- package/dist/template-resolver/handlers/overview.query.js +12 -6
- package/dist/template-resolver/handlers/patch-draft.write.d.ts +1369 -4
- package/dist/template-resolver/handlers/patch-draft.write.js +11 -6
- package/dist/template-resolver/handlers/publish-templates.write.d.ts +40 -0
- package/dist/template-resolver/handlers/publish-templates.write.js +61 -0
- package/dist/template-resolver/handlers/set.write.js +4 -1
- package/dist/template-resolver/handlers/template-write.js +7 -2
- package/dist/template-resolver/handlers/tenant-settings.d.ts +23 -0
- package/dist/template-resolver/handlers/tenant-settings.js +101 -0
- package/dist/template-resolver/handlers/toggle-status.write.d.ts +14 -9
- package/dist/template-resolver/handlers/toggle-status.write.js +11 -7
- package/dist/template-resolver/handlers/upsert-system.write.js +15 -9
- package/dist/template-resolver/handlers/usage.query.d.ts +14 -0
- package/dist/template-resolver/handlers/usage.query.js +80 -12
- package/dist/template-resolver/handlers/validate.query.d.ts +2 -0
- package/dist/template-resolver/handlers/validate.query.js +10 -0
- package/dist/template-resolver/i18n.js +3 -0
- package/dist/template-resolver/index.d.ts +7 -2
- package/dist/template-resolver/index.js +6 -2
- package/dist/template-resolver/layout-regions.d.ts +4 -5
- package/dist/template-resolver/layout-regions.js +38 -11
- package/dist/template-resolver/print-document.js +3 -1
- package/dist/template-resolver/seeding.js +4 -0
- package/dist/template-resolver/template-delivery-policy.d.ts +1 -0
- package/dist/template-resolver/template-delivery-policy.js +9 -1
- package/dist/template-resolver/template-edit-policy.d.ts +5 -1
- package/dist/template-resolver/template-edit-policy.js +29 -1
- package/dist/template-resolver/template-meta.d.ts +37 -2
- package/dist/template-resolver/template-meta.js +27 -5
- package/dist/template-resolver/template-preview.js +22 -10
- package/dist/template-resolver/template-validation.js +10 -3
- package/dist/template-resolver/web/constants.d.ts +7 -1
- package/dist/template-resolver/web/constants.js +21 -1
- package/dist/template-resolver/web/document-blocks.d.ts +1 -0
- package/dist/template-resolver/web/document-blocks.js +2 -0
- package/dist/template-resolver/web/document-editor-extensions.d.ts +9 -1
- package/dist/template-resolver/web/document-editor-extensions.js +69 -19
- package/dist/template-resolver/web/document-editor-fonts.d.ts +10 -0
- package/dist/template-resolver/web/document-editor-fonts.js +13 -0
- package/dist/template-resolver/web/document-editor.js +3 -1
- package/dist/template-resolver/web/document-fonts.d.ts +4 -0
- package/dist/template-resolver/web/document-fonts.js +18 -0
- package/dist/template-resolver/web/document-frame-control.d.ts +61 -0
- package/dist/template-resolver/web/document-frame-control.js +329 -0
- package/dist/template-resolver/web/document-frame-node-view.d.ts +4 -0
- package/dist/template-resolver/web/document-frame-node-view.js +173 -0
- package/dist/template-resolver/web/document-print-decorations.d.ts +12 -0
- package/dist/template-resolver/web/document-print-decorations.js +194 -0
- package/dist/template-resolver/web/document-print-defaults.d.ts +14 -0
- package/dist/template-resolver/web/document-print-defaults.js +25 -0
- package/dist/template-resolver/web/document-print-style.d.ts +150 -0
- package/dist/template-resolver/web/document-print-style.js +311 -0
- package/dist/template-resolver/web/document-repeat-strip.d.ts +8 -0
- package/dist/template-resolver/web/document-repeat-strip.js +54 -0
- package/dist/template-resolver/web/document-schema.d.ts +5 -0
- package/dist/template-resolver/web/document-schema.js +70 -19
- package/dist/template-resolver/web/document-style-css.d.ts +62 -0
- package/dist/template-resolver/web/document-style-css.js +140 -0
- package/dist/template-resolver/web/document-tiptap-bubble.js +83 -10
- package/dist/template-resolver/web/document-tiptap-content.d.ts +2 -1
- package/dist/template-resolver/web/document-tiptap-content.js +39 -4
- package/dist/template-resolver/web/document-tiptap-context.d.ts +6 -2
- package/dist/template-resolver/web/document-tiptap-context.js +2 -1
- package/dist/template-resolver/web/document-tiptap-editor.d.ts +1 -1
- package/dist/template-resolver/web/document-tiptap-editor.js +13 -5
- package/dist/template-resolver/web/document-tiptap-helpers.d.ts +62 -3
- package/dist/template-resolver/web/document-tiptap-helpers.js +199 -23
- package/dist/template-resolver/web/document-tiptap-toolbar-groups.d.ts +16 -0
- package/dist/template-resolver/web/document-tiptap-toolbar-groups.js +127 -6
- package/dist/template-resolver/web/document-tiptap-toolbar.js +57 -15
- package/dist/template-resolver/web/document-toolbar-blocks.d.ts +17 -0
- package/dist/template-resolver/web/i18n.js +21 -0
- package/dist/template-resolver/web/index.d.ts +8 -2
- package/dist/template-resolver/web/index.js +6 -1
- package/dist/template-resolver/web/pdf-constants.d.ts +8 -0
- package/dist/template-resolver/web/pdf-constants.js +9 -0
- package/dist/template-resolver/web/placeholder-text.d.ts +2 -1
- package/dist/template-resolver/web/placeholder-text.js +5 -2
- package/dist/template-resolver/web/qualified-names.d.ts +7 -0
- package/dist/template-resolver/web/qualified-names.js +6 -0
- package/dist/template-resolver/web/use-document-tiptap-model.d.ts +6 -2
- package/dist/template-resolver/web/use-document-tiptap-model.js +38 -3
- package/dist/tenant/company-config.d.ts +6 -0
- package/dist/tenant/company-config.js +41 -0
- package/dist/tenant/feature.js +11 -0
- package/dist/tenant/i18n.js +14 -0
- package/package.json +24 -11
- package/src/signature/changes.json +6 -0
- package/src/template-resolver/changes.json +62 -0
|
@@ -5,8 +5,8 @@ import { applyDocumentOps, documentOpsSchema } from "../document-ops.js";
|
|
|
5
5
|
import { parseDocumentJson, serializeDocumentJson } from "../document-sanitizer.js";
|
|
6
6
|
import { refuseTemplateEdit, templateEditAccess, } from "../template-edit-policy.js";
|
|
7
7
|
import { resolveTemplateVariables } from "../template-validation.js";
|
|
8
|
-
import { DOCUMENT_HTML_KINDS } from "../web/constants.js";
|
|
9
8
|
import { loadDocumentBase } from "./document-base.js";
|
|
9
|
+
import { contentWithEditedHtml, documentTargetShape, editableHtmlOf, regionIssue, } from "./document-region.js";
|
|
10
10
|
import { localeSchema, templateSlugSchema } from "./shared.js";
|
|
11
11
|
import { writeTemplateRow } from "./template-write.js";
|
|
12
12
|
import { validateTemplateDraft } from "./validate.query.js";
|
|
@@ -18,7 +18,7 @@ export function makePatchDraftWrite(policy) {
|
|
|
18
18
|
name: "patch-draft",
|
|
19
19
|
schema: z.object({
|
|
20
20
|
slug: templateSlugSchema,
|
|
21
|
-
|
|
21
|
+
...documentTargetShape,
|
|
22
22
|
locale: localeSchema,
|
|
23
23
|
base: z.object({
|
|
24
24
|
scope: z.enum(["tenant", "system"]),
|
|
@@ -27,9 +27,13 @@ export function makePatchDraftWrite(policy) {
|
|
|
27
27
|
ops: documentOpsSchema,
|
|
28
28
|
}),
|
|
29
29
|
access: templateEditAccess(policy.tenantEditable),
|
|
30
|
-
|
|
30
|
+
agent: { risk: "low", effect: "proposal" },
|
|
31
|
+
description: '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.',
|
|
31
32
|
handler: async (event, ctx) => {
|
|
32
|
-
const { slug, kind, locale, base, ops } = event.payload;
|
|
33
|
+
const { slug, kind, region, locale, base, ops } = event.payload;
|
|
34
|
+
const misplacedRegion = regionIssue(kind, region);
|
|
35
|
+
if (misplacedRegion !== null)
|
|
36
|
+
return validationFailure(misplacedRegion);
|
|
33
37
|
const refused = refuseTemplateEdit(policy, event.user, { slug, kind });
|
|
34
38
|
if (refused !== null)
|
|
35
39
|
return refused;
|
|
@@ -54,15 +58,16 @@ export function makePatchDraftWrite(policy) {
|
|
|
54
58
|
});
|
|
55
59
|
}
|
|
56
60
|
const applied = applyDocumentOps({
|
|
57
|
-
doc: parseDocumentJson(loaded.content),
|
|
61
|
+
doc: parseDocumentJson(editableHtmlOf(kind, region, loaded.content)),
|
|
58
62
|
meta: loaded.meta,
|
|
59
63
|
variableSchema: loaded.variableSchema,
|
|
60
64
|
kind,
|
|
65
|
+
region,
|
|
61
66
|
ops,
|
|
62
67
|
});
|
|
63
68
|
if (!applied.ok)
|
|
64
69
|
return writeFailure(new ValidationError({ fields: applied.issues }));
|
|
65
|
-
const content = serializeDocumentJson(applied.doc);
|
|
70
|
+
const content = contentWithEditedHtml(kind, region, loaded.content, serializeDocumentJson(applied.doc));
|
|
66
71
|
const draftOf = (draftContent, meta, variableSchema) => validateTemplateDraft(ctx, event.user, {
|
|
67
72
|
slug,
|
|
68
73
|
kind,
|
|
@@ -0,0 +1,40 @@
|
|
|
1
|
+
import * as z from "zod";
|
|
2
|
+
import { type TemplateEditPolicy } from "../template-edit-policy.ts";
|
|
3
|
+
declare const templateRefSchema: z.ZodObject<{
|
|
4
|
+
slug: z.ZodString;
|
|
5
|
+
kind: z.ZodEnum<{
|
|
6
|
+
"ai-prompt": "ai-prompt";
|
|
7
|
+
"document-pdf": "document-pdf";
|
|
8
|
+
"image-snapshot": "image-snapshot";
|
|
9
|
+
mail: "mail";
|
|
10
|
+
"mail-layout": "mail-layout";
|
|
11
|
+
"pdf-layout": "pdf-layout";
|
|
12
|
+
}>;
|
|
13
|
+
locale: z.ZodString;
|
|
14
|
+
}, z.core.$strip>;
|
|
15
|
+
type TemplateRef = z.infer<typeof templateRefSchema>;
|
|
16
|
+
type FailedTemplate = TemplateRef & {
|
|
17
|
+
readonly reason: string;
|
|
18
|
+
};
|
|
19
|
+
export declare function makePublishTemplatesWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<"publish-templates", z.ZodObject<{
|
|
20
|
+
templates: z.ZodArray<z.ZodObject<{
|
|
21
|
+
slug: z.ZodString;
|
|
22
|
+
kind: z.ZodEnum<{
|
|
23
|
+
"ai-prompt": "ai-prompt";
|
|
24
|
+
"document-pdf": "document-pdf";
|
|
25
|
+
"image-snapshot": "image-snapshot";
|
|
26
|
+
mail: "mail";
|
|
27
|
+
"mail-layout": "mail-layout";
|
|
28
|
+
"pdf-layout": "pdf-layout";
|
|
29
|
+
}>;
|
|
30
|
+
locale: z.ZodString;
|
|
31
|
+
}, z.core.$strip>>;
|
|
32
|
+
}, z.core.$strip>, {
|
|
33
|
+
published: {
|
|
34
|
+
slug: string;
|
|
35
|
+
kind: "ai-prompt" | "document-pdf" | "image-snapshot" | "mail" | "mail-layout" | "pdf-layout";
|
|
36
|
+
locale: string;
|
|
37
|
+
}[];
|
|
38
|
+
failed: FailedTemplate[];
|
|
39
|
+
}, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
|
|
40
|
+
export {};
|
|
@@ -0,0 +1,61 @@
|
|
|
1
|
+
import { fetchOne } from "@cosmicdrift/kumiko-framework/db";
|
|
2
|
+
import { defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
|
|
3
|
+
import * as z from "zod";
|
|
4
|
+
import { templateResourcesTable } from "../table.js";
|
|
5
|
+
import { parseTemplateDraft } from "../template-draft.js";
|
|
6
|
+
import { refuseTemplateEdit, templateEditAccess, } from "../template-edit-policy.js";
|
|
7
|
+
import { TemplateResolverErrors } from "../web/qualified-names.js";
|
|
8
|
+
import { failureReason } from "./failure-reason.js";
|
|
9
|
+
import { kindSchema, localeSchema, templateSlugSchema } from "./shared.js";
|
|
10
|
+
import { changeRowStatus } from "./toggle-status.write.js";
|
|
11
|
+
const MAX_PUBLISHED_TEMPLATES = 200;
|
|
12
|
+
const templateRefSchema = z.object({
|
|
13
|
+
slug: templateSlugSchema,
|
|
14
|
+
kind: kindSchema,
|
|
15
|
+
locale: localeSchema,
|
|
16
|
+
});
|
|
17
|
+
export function makePublishTemplatesWrite(policy) {
|
|
18
|
+
return defineWriteHandler({
|
|
19
|
+
name: "publish-templates",
|
|
20
|
+
schema: z.object({
|
|
21
|
+
templates: z.array(templateRefSchema).min(1).max(MAX_PUBLISHED_TEMPLATES),
|
|
22
|
+
}),
|
|
23
|
+
access: templateEditAccess(policy.tenantEditable),
|
|
24
|
+
description: "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.",
|
|
25
|
+
handler: async (event, ctx) => {
|
|
26
|
+
const published = [];
|
|
27
|
+
const failed = [];
|
|
28
|
+
const seen = new Set();
|
|
29
|
+
for (const ref of event.payload.templates) {
|
|
30
|
+
const key = `${ref.kind}\u0000${ref.slug}\u0000${ref.locale}`;
|
|
31
|
+
if (seen.has(key))
|
|
32
|
+
continue;
|
|
33
|
+
seen.add(key);
|
|
34
|
+
const refused = refuseTemplateEdit(policy, event.user, ref);
|
|
35
|
+
if (refused !== null) {
|
|
36
|
+
failed.push({ ...ref, reason: failureReason(refused) });
|
|
37
|
+
continue;
|
|
38
|
+
}
|
|
39
|
+
const row = await fetchOne(ctx.db, templateResourcesTable, {
|
|
40
|
+
tenantId: event.user.tenantId,
|
|
41
|
+
...ref,
|
|
42
|
+
});
|
|
43
|
+
if (row === undefined || row.scope !== "tenant") {
|
|
44
|
+
failed.push({ ...ref, reason: TemplateResolverErrors.notFound });
|
|
45
|
+
continue;
|
|
46
|
+
}
|
|
47
|
+
if (row.status === "active" && parseTemplateDraft(row.draft) === null) {
|
|
48
|
+
failed.push({ ...ref, reason: TemplateResolverErrors.alreadyActive });
|
|
49
|
+
continue;
|
|
50
|
+
}
|
|
51
|
+
const ownRowTarget = { db: ctx.db, scoped: null };
|
|
52
|
+
const result = await changeRowStatus(ctx, event.user, ownRowTarget, row, "active");
|
|
53
|
+
if (result.isSuccess)
|
|
54
|
+
published.push(ref);
|
|
55
|
+
else
|
|
56
|
+
failed.push({ ...ref, reason: failureReason(result) });
|
|
57
|
+
}
|
|
58
|
+
return { isSuccess: true, data: { published, failed } };
|
|
59
|
+
},
|
|
60
|
+
});
|
|
61
|
+
}
|
|
@@ -4,7 +4,7 @@ import { isOneOf } from "@cosmicdrift/kumiko-types/type-guards";
|
|
|
4
4
|
import * as z from "zod";
|
|
5
5
|
import { requireForTenant } from "../../shared/index.js";
|
|
6
6
|
import { templateResourcesTable } from "../table.js";
|
|
7
|
-
import { refuseTemplateEdit, templateEditAccess, } from "../template-edit-policy.js";
|
|
7
|
+
import { refuseReservedSystemLayoutSlug, refuseTemplateEdit, templateEditAccess, } from "../template-edit-policy.js";
|
|
8
8
|
import { resolveTemplateVariables } from "../template-validation.js";
|
|
9
9
|
import { TEMPLATE_KINDS, TEXT_BLOCK_KIND, UPSERT_KINDS } from "../web/constants.js";
|
|
10
10
|
import { contentFormatSchema, executor, folderSchema, localeSchema, slugSchema } from "./shared.js";
|
|
@@ -67,6 +67,9 @@ export function makeSetWrite(policy) {
|
|
|
67
67
|
locale: event.payload.locale,
|
|
68
68
|
});
|
|
69
69
|
const scope = tenantId === SYSTEM_TENANT_ID ? "system" : "tenant";
|
|
70
|
+
const reserved = refuseReservedSystemLayoutSlug(scope, { slug: event.payload.slug, kind }, "slug");
|
|
71
|
+
if (reserved !== null)
|
|
72
|
+
return reserved;
|
|
70
73
|
let content = event.payload.content;
|
|
71
74
|
if (isOneOf(UPSERT_KINDS, kind)) {
|
|
72
75
|
const gated = gateTemplateWrite({
|
|
@@ -4,6 +4,7 @@ import { AccessDeniedError, ValidationError, VersionConflictError, writeFailure,
|
|
|
4
4
|
import { requireForTenant } from "../../shared/index.js";
|
|
5
5
|
import { templateResourcesTable } from "../table.js";
|
|
6
6
|
import { activationChanges, serializeTemplateDraft } from "../template-draft.js";
|
|
7
|
+
import { refuseReservedSystemLayoutSlug } from "../template-edit-policy.js";
|
|
7
8
|
import { isSystemOnlyTemplate } from "../template-system-only.js";
|
|
8
9
|
import { TemplateResolverErrors } from "../web/qualified-names.js";
|
|
9
10
|
import { executor } from "./shared.js";
|
|
@@ -76,14 +77,18 @@ function versionConflictFor(expectedVersion, existing, slug) {
|
|
|
76
77
|
currentVersion: existing?.version ?? 0,
|
|
77
78
|
}));
|
|
78
79
|
}
|
|
80
|
+
function refuseScopeViolation(registry, scope, tenantId, payload) {
|
|
81
|
+
return (refuseTenantScopeUnderSystemTenant(scope, tenantId) ??
|
|
82
|
+
refuseReservedSystemLayoutSlug(scope, payload, "slug") ??
|
|
83
|
+
refuseSystemOnlyTenantOverride(registry, scope, payload.slug, payload.kind));
|
|
84
|
+
}
|
|
79
85
|
// Shared by every template write: validate through the one pipeline, then
|
|
80
86
|
// create or update the (tenant, slug, kind, locale) row via the event-store
|
|
81
87
|
// executor. linkedResources is never part of an update; resources are attached
|
|
82
88
|
// separately.
|
|
83
89
|
export async function writeTemplateRow(args) {
|
|
84
90
|
const { ctx, user, tenantId, scope, status, payload } = args;
|
|
85
|
-
const refused =
|
|
86
|
-
refuseSystemOnlyTenantOverride(ctx.registry, scope, payload.slug, payload.kind);
|
|
91
|
+
const refused = refuseScopeViolation(ctx.registry, scope, tenantId, payload);
|
|
87
92
|
if (refused !== null)
|
|
88
93
|
return refused;
|
|
89
94
|
const { db, streamTenantId } = requireForTenant(ctx, tenantId);
|
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
import type { HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { createTemplateResolverApi, type TemplateResource } from "../api.ts";
|
|
3
|
+
export declare function companyConfigKey(name: string): string;
|
|
4
|
+
export declare function readTenantConfigText(ctx: Pick<HandlerContext, "config" | "registry">, qualifiedKey: string): Promise<string>;
|
|
5
|
+
type DefaultLayoutContext = Pick<HandlerContext, "config" | "registry"> & {
|
|
6
|
+
readonly db: Parameters<typeof createTemplateResolverApi>[0];
|
|
7
|
+
};
|
|
8
|
+
export type DefaultPdfLayout = {
|
|
9
|
+
readonly slug: string;
|
|
10
|
+
readonly resolved: TemplateResource | null;
|
|
11
|
+
};
|
|
12
|
+
export declare function resolveDefaultPdfLayout(ctx: DefaultLayoutContext, tenantId: string, locale?: string, working?: boolean): Promise<DefaultPdfLayout>;
|
|
13
|
+
export declare function effectivePdfLayout(ctx: DefaultLayoutContext, tenantId: string, ownSlug: string | undefined, locale?: string, working?: boolean): Promise<DefaultPdfLayout>;
|
|
14
|
+
export declare function defaultPdfLayoutSlug(ctx: DefaultLayoutContext, tenantId: string, locale?: string): Promise<string>;
|
|
15
|
+
export declare function isCompanyPlaceholder(name: string): boolean;
|
|
16
|
+
export declare function emptyCompanyData(ctx: HandlerContext, input: {
|
|
17
|
+
readonly kind: string;
|
|
18
|
+
readonly body: string;
|
|
19
|
+
readonly meta: unknown;
|
|
20
|
+
readonly locale: string | undefined;
|
|
21
|
+
readonly tenantId: string;
|
|
22
|
+
}): Promise<readonly string[]>;
|
|
23
|
+
export {};
|
|
@@ -0,0 +1,101 @@
|
|
|
1
|
+
import { toKebab } from "@cosmicdrift/kumiko-types/kebab-case";
|
|
2
|
+
import { createTemplateResolverApi, TemplateNotFoundError } from "../api.js";
|
|
3
|
+
import { withParsedDocument } from "../document-sanitizer.js";
|
|
4
|
+
import { parseTemplateMeta, readPdfTemplateMeta } from "../template-meta.js";
|
|
5
|
+
import { COMPANY_PLACEHOLDERS, DEFAULT_PDF_LAYOUT_SLUG, DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY, FALLBACK_LOCALE, } from "../web/constants.js";
|
|
6
|
+
const TENANT_CONFIG_PREFIX = "tenant:config:";
|
|
7
|
+
export function companyConfigKey(name) {
|
|
8
|
+
return `${TENANT_CONFIG_PREFIX}${toKebab(name)}`;
|
|
9
|
+
}
|
|
10
|
+
// A key only exists in the registry when its feature is mounted; reading an unregistered key
|
|
11
|
+
// through the accessor would throw instead of falling back.
|
|
12
|
+
export async function readTenantConfigText(ctx, qualifiedKey) {
|
|
13
|
+
if (ctx.config === undefined || ctx.registry.getConfigKey(qualifiedKey) === undefined)
|
|
14
|
+
return "";
|
|
15
|
+
const value = await ctx.config(qualifiedKey);
|
|
16
|
+
return typeof value === "string" ? value : "";
|
|
17
|
+
}
|
|
18
|
+
export async function resolveDefaultPdfLayout(ctx, tenantId, locale = FALLBACK_LOCALE, working = false) {
|
|
19
|
+
const slug = await readTenantConfigText(ctx, DEFAULT_PDF_LAYOUT_SLUG_CONFIG_KEY);
|
|
20
|
+
if (slug === "")
|
|
21
|
+
return { slug: DEFAULT_PDF_LAYOUT_SLUG, resolved: null };
|
|
22
|
+
try {
|
|
23
|
+
const resolved = await createTemplateResolverApi(ctx.db, ctx.registry).resolveLayout({
|
|
24
|
+
tenantId,
|
|
25
|
+
slug,
|
|
26
|
+
kind: "pdf-layout",
|
|
27
|
+
locale,
|
|
28
|
+
working,
|
|
29
|
+
});
|
|
30
|
+
return { slug, resolved };
|
|
31
|
+
}
|
|
32
|
+
catch (e) {
|
|
33
|
+
if (e instanceof TemplateNotFoundError) {
|
|
34
|
+
return { slug: DEFAULT_PDF_LAYOUT_SLUG, resolved: null };
|
|
35
|
+
}
|
|
36
|
+
throw e;
|
|
37
|
+
}
|
|
38
|
+
}
|
|
39
|
+
// A layout the document names itself wins; only without one is the tenant default resolved (once, so callers reuse it).
|
|
40
|
+
export async function effectivePdfLayout(ctx, tenantId, ownSlug, locale = FALLBACK_LOCALE, working = false) {
|
|
41
|
+
if (ownSlug !== undefined)
|
|
42
|
+
return { slug: ownSlug, resolved: null };
|
|
43
|
+
return resolveDefaultPdfLayout(ctx, tenantId, locale, working);
|
|
44
|
+
}
|
|
45
|
+
export async function defaultPdfLayoutSlug(ctx, tenantId, locale = FALLBACK_LOCALE) {
|
|
46
|
+
return (await resolveDefaultPdfLayout(ctx, tenantId, locale)).slug;
|
|
47
|
+
}
|
|
48
|
+
export function isCompanyPlaceholder(name) {
|
|
49
|
+
return COMPANY_PLACEHOLDERS.some((candidate) => candidate === name);
|
|
50
|
+
}
|
|
51
|
+
function companyPlaceholdersIn(html) {
|
|
52
|
+
return withParsedDocument(html, (body) => [
|
|
53
|
+
...Array.from(body.querySelectorAll("span[data-variable]")).flatMap((element) => {
|
|
54
|
+
const name = element.getAttribute("data-variable") ?? "";
|
|
55
|
+
return isCompanyPlaceholder(name) ? [name] : [];
|
|
56
|
+
}),
|
|
57
|
+
]);
|
|
58
|
+
}
|
|
59
|
+
// The layout the document is rendered into: its own choice, else the tenant default, else the built-in one.
|
|
60
|
+
async function layoutHtmlOf(ctx, tenantId, meta, locale) {
|
|
61
|
+
const parsedMeta = parseTemplateMeta("document-pdf", meta);
|
|
62
|
+
const pdfMeta = parsedMeta.ok ? readPdfTemplateMeta(parsedMeta.meta) : null;
|
|
63
|
+
const effectiveLocale = locale ?? FALLBACK_LOCALE;
|
|
64
|
+
const { slug, resolved } = await effectivePdfLayout(ctx, tenantId, pdfMeta?.layoutSlug, effectiveLocale);
|
|
65
|
+
try {
|
|
66
|
+
const layout = resolved ??
|
|
67
|
+
(await createTemplateResolverApi(ctx.db, ctx.registry).resolveLayout({
|
|
68
|
+
tenantId,
|
|
69
|
+
slug,
|
|
70
|
+
kind: "pdf-layout",
|
|
71
|
+
locale: effectiveLocale,
|
|
72
|
+
}));
|
|
73
|
+
return layout.content ?? "";
|
|
74
|
+
}
|
|
75
|
+
catch (e) {
|
|
76
|
+
if (e instanceof TemplateNotFoundError)
|
|
77
|
+
return "";
|
|
78
|
+
throw e;
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
// Company placeholders the draft or its layout prints without the tenant having entered a value.
|
|
82
|
+
export async function emptyCompanyData(ctx, input) {
|
|
83
|
+
if (input.kind !== "document-pdf" && input.kind !== "pdf-layout")
|
|
84
|
+
return [];
|
|
85
|
+
const layoutHtml = input.kind === "document-pdf"
|
|
86
|
+
? await layoutHtmlOf(ctx, input.tenantId, input.meta, input.locale)
|
|
87
|
+
: "";
|
|
88
|
+
const used = new Set([
|
|
89
|
+
...companyPlaceholdersIn(input.body),
|
|
90
|
+
...companyPlaceholdersIn(layoutHtml),
|
|
91
|
+
]);
|
|
92
|
+
const empty = [];
|
|
93
|
+
for (const name of COMPANY_PLACEHOLDERS) {
|
|
94
|
+
if (!used.has(name))
|
|
95
|
+
continue;
|
|
96
|
+
const value = await readTenantConfigText(ctx, companyConfigKey(name));
|
|
97
|
+
if (value.trim() === "")
|
|
98
|
+
empty.push(name);
|
|
99
|
+
}
|
|
100
|
+
return empty;
|
|
101
|
+
}
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { type HandlerContext } from "@cosmicdrift/kumiko-framework/engine";
|
|
1
|
+
import { type HandlerContext, type SessionUser, type WriteResult } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
2
|
import * as z from "zod";
|
|
3
3
|
import type { TemplateResourceRow } from "../table.ts";
|
|
4
4
|
import { type TemplateEditPolicy } from "../template-edit-policy.ts";
|
|
@@ -12,28 +12,33 @@ export declare function loadTargetRow(ctx: HandlerContext, target: StatusTarget,
|
|
|
12
12
|
scoped: import("@cosmicdrift/kumiko-types/handlers").TenantWriteTarget | null;
|
|
13
13
|
row: TemplateResourceRow | null;
|
|
14
14
|
}>;
|
|
15
|
+
type LoadedTarget = Pick<Awaited<ReturnType<typeof loadTargetRow>>, "db" | "scoped">;
|
|
16
|
+
export declare function changeRowStatus(ctx: HandlerContext, user: SessionUser, target: LoadedTarget, row: TemplateResourceRow, status: TemplateStatus): Promise<WriteResult<{
|
|
17
|
+
readonly id: string;
|
|
18
|
+
readonly status: TemplateStatus;
|
|
19
|
+
}>>;
|
|
15
20
|
export declare function makeArchiveWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<string, z.ZodObject<{
|
|
16
21
|
id: z.ZodString;
|
|
17
22
|
}, z.core.$strip>, {
|
|
18
|
-
id: string;
|
|
19
|
-
status: TemplateStatus;
|
|
23
|
+
readonly id: string;
|
|
24
|
+
readonly status: TemplateStatus;
|
|
20
25
|
}, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
|
|
21
26
|
export declare function makePublishWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<string, z.ZodObject<{
|
|
22
27
|
id: z.ZodString;
|
|
23
28
|
}, z.core.$strip>, {
|
|
24
|
-
id: string;
|
|
25
|
-
status: TemplateStatus;
|
|
29
|
+
readonly id: string;
|
|
30
|
+
readonly status: TemplateStatus;
|
|
26
31
|
}, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
|
|
27
32
|
export declare function makeArchiveSystemWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<string, z.ZodObject<{
|
|
28
33
|
id: z.ZodString;
|
|
29
34
|
}, z.core.$strip>, {
|
|
30
|
-
id: string;
|
|
31
|
-
status: TemplateStatus;
|
|
35
|
+
readonly id: string;
|
|
36
|
+
readonly status: TemplateStatus;
|
|
32
37
|
}, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
|
|
33
38
|
export declare function makePublishSystemWrite(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").WriteHandlerDefinition<string, z.ZodObject<{
|
|
34
39
|
id: z.ZodString;
|
|
35
40
|
}, z.core.$strip>, {
|
|
36
|
-
id: string;
|
|
37
|
-
status: TemplateStatus;
|
|
41
|
+
readonly id: string;
|
|
42
|
+
readonly status: TemplateStatus;
|
|
38
43
|
}, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap, undefined, undefined>;
|
|
39
44
|
export {};
|
|
@@ -37,6 +37,16 @@ function planStatusChange(ctx, row, status) {
|
|
|
37
37
|
}
|
|
38
38
|
return { ok: true, changes: { ...parseTemplateDraft(row.draft), ...activationChanges(row) } };
|
|
39
39
|
}
|
|
40
|
+
// The gated status change every publish and archive path shares.
|
|
41
|
+
export async function changeRowStatus(ctx, user, target, row, status) {
|
|
42
|
+
const plan = planStatusChange(ctx, row, status);
|
|
43
|
+
if (!plan.ok)
|
|
44
|
+
return plan.failure;
|
|
45
|
+
const result = await executor.update({ id: row.id, version: row.version, changes: plan.changes }, user, target.db, target.scoped ? { streamTenantId: target.scoped.streamTenantId } : undefined);
|
|
46
|
+
if (!result.isSuccess)
|
|
47
|
+
return result;
|
|
48
|
+
return { isSuccess: true, data: { id: String(row.id), status } };
|
|
49
|
+
}
|
|
40
50
|
function createStatusUpdateHandler(policy, name, target, status, description) {
|
|
41
51
|
return defineWriteHandler({
|
|
42
52
|
name,
|
|
@@ -56,13 +66,7 @@ function createStatusUpdateHandler(policy, name, target, status, description) {
|
|
|
56
66
|
if (refused !== null)
|
|
57
67
|
return refused;
|
|
58
68
|
}
|
|
59
|
-
|
|
60
|
-
if (!plan.ok)
|
|
61
|
-
return plan.failure;
|
|
62
|
-
const result = await executor.update({ id: row.id, version: row.version, changes: plan.changes }, event.user, db, scoped ? { streamTenantId: scoped.streamTenantId } : undefined);
|
|
63
|
-
if (!result.isSuccess)
|
|
64
|
-
return result;
|
|
65
|
-
return { isSuccess: true, data: { id: String(row.id), status } };
|
|
69
|
+
return changeRowStatus(ctx, event.user, { db, scoped }, row, status);
|
|
66
70
|
},
|
|
67
71
|
});
|
|
68
72
|
}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { defineWriteHandler, SYSTEM_TENANT_ID } from "@cosmicdrift/kumiko-framework/engine";
|
|
2
|
+
import { refuseReservedLayoutSlug } from "../template-edit-policy.js";
|
|
2
3
|
import { resolveTemplateVariables } from "../template-validation.js";
|
|
3
4
|
import { upsertPayloadSchema } from "./shared.js";
|
|
4
5
|
import { writeTemplateRow } from "./template-write.js";
|
|
@@ -10,13 +11,18 @@ export const upsertSystemWrite = defineWriteHandler({
|
|
|
10
11
|
schema: upsertPayloadSchema,
|
|
11
12
|
access: { roles: ["SystemAdmin"] },
|
|
12
13
|
description: "Creates or overwrites a system-default template under the system tenant with its full variable schema (resource files go through the resource upload), active straight away with no draft stage; SystemAdmin only, since tenants shadow these defaults through upsert-tenant instead.",
|
|
13
|
-
handler: (event, ctx) =>
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
17
|
-
|
|
18
|
-
|
|
19
|
-
|
|
20
|
-
|
|
21
|
-
|
|
14
|
+
handler: async (event, ctx) => {
|
|
15
|
+
const refused = refuseReservedLayoutSlug(event.payload, "slug");
|
|
16
|
+
if (refused !== null)
|
|
17
|
+
return refused;
|
|
18
|
+
return writeTemplateRow({
|
|
19
|
+
ctx,
|
|
20
|
+
user: event.user,
|
|
21
|
+
tenantId: SYSTEM_TENANT_ID,
|
|
22
|
+
scope: "system",
|
|
23
|
+
status: "active",
|
|
24
|
+
variables: resolveTemplateVariables(ctx.registry, event.payload.slug, event.payload.variableSchema),
|
|
25
|
+
payload: event.payload,
|
|
26
|
+
});
|
|
27
|
+
},
|
|
22
28
|
});
|
|
@@ -1,5 +1,15 @@
|
|
|
1
1
|
import * as z from "zod";
|
|
2
2
|
import type { TemplateEditPolicy } from "../template-edit-policy.ts";
|
|
3
|
+
export type PdfLayoutUser = {
|
|
4
|
+
readonly slug: string;
|
|
5
|
+
readonly locale: string;
|
|
6
|
+
readonly title: string;
|
|
7
|
+
readonly hasOwnLayout: boolean;
|
|
8
|
+
readonly isSystem: boolean;
|
|
9
|
+
/** "draft" when an open draft names this layout, else the served status. */
|
|
10
|
+
readonly status: "draft" | "active";
|
|
11
|
+
readonly version: number;
|
|
12
|
+
};
|
|
3
13
|
export declare function makeUsageQuery(policy: TemplateEditPolicy): import("@cosmicdrift/kumiko-types/define-handler").QueryHandlerDefinition<"usage", z.ZodObject<{
|
|
4
14
|
slug: z.ZodString;
|
|
5
15
|
kind: z.ZodEnum<{
|
|
@@ -14,5 +24,9 @@ export declare function makeUsageQuery(policy: TemplateEditPolicy): import("@cos
|
|
|
14
24
|
"text-block": "text-block";
|
|
15
25
|
}>;
|
|
16
26
|
}, z.core.$strip>, {
|
|
27
|
+
usedBy: never[];
|
|
28
|
+
usedByTemplates: PdfLayoutUser[];
|
|
29
|
+
} | {
|
|
30
|
+
usedByTemplates?: undefined;
|
|
17
31
|
usedBy: import("../template-usage.ts").TemplateUsageEntry[];
|
|
18
32
|
}, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap>;
|
|
@@ -3,30 +3,98 @@ import { defineQueryHandler } from "@cosmicdrift/kumiko-framework/engine";
|
|
|
3
3
|
import * as z from "zod";
|
|
4
4
|
import { templateResourcesTable } from "../table.js";
|
|
5
5
|
import { deliveryPolicyOf } from "../template-delivery-policy.js";
|
|
6
|
+
import { draftViewerTenantId, parseTemplateDraft, servedVersionOf } from "../template-draft.js";
|
|
6
7
|
import { templateSlugSchema } from "../template-meta.js";
|
|
7
8
|
import { collectTemplateUsage } from "../template-usage.js";
|
|
8
9
|
import { TEMPLATE_KINDS } from "../web/constants.js";
|
|
9
|
-
import { effectiveMailLayoutSlugs, isRowVisibleToCaller } from "./overview.query.js";
|
|
10
|
-
|
|
10
|
+
import { effectiveMailLayoutSlugs, effectiveRowsOf, isRowVisibleToCaller, ownLayoutSlugOf, } from "./overview.query.js";
|
|
11
|
+
import { storedRecord } from "./template-gates.js";
|
|
12
|
+
import { defaultPdfLayoutSlug } from "./tenant-settings.js";
|
|
13
|
+
const USAGE_ROW_LIMIT = 5000;
|
|
14
|
+
async function visibleRowsOfKind(ctx, policy, user, kind) {
|
|
15
|
+
const fetchedRows = await selectMany(ctx.db, templateResourcesTable, { kind }, { orderBy: { col: "id", direction: "asc" }, limit: USAGE_ROW_LIMIT + 1 });
|
|
16
|
+
if (fetchedRows.length > USAGE_ROW_LIMIT) {
|
|
17
|
+
ctx.obs.log?.warn("template usage: row limit reached, result is incomplete", {
|
|
18
|
+
limit: USAGE_ROW_LIMIT,
|
|
19
|
+
});
|
|
20
|
+
}
|
|
21
|
+
return fetchedRows
|
|
22
|
+
.slice(0, USAGE_ROW_LIMIT)
|
|
23
|
+
.filter((row) => isRowVisibleToCaller(policy, user, ctx.registry, row));
|
|
24
|
+
}
|
|
25
|
+
// An open draft lives beside the served row, so its layout choice sits in the draft's own meta.
|
|
26
|
+
function draftLayoutOf(user, row) {
|
|
27
|
+
if (row.tenantId !== draftViewerTenantId(user, row))
|
|
28
|
+
return null;
|
|
29
|
+
const draft = parseTemplateDraft(row.draft);
|
|
30
|
+
if (draft === null)
|
|
31
|
+
return null;
|
|
32
|
+
const layoutSlug = storedRecord(draft.meta)["layoutSlug"];
|
|
33
|
+
return { layoutSlug: typeof layoutSlug === "string" ? layoutSlug : null };
|
|
34
|
+
}
|
|
35
|
+
function servedRowOf(group, policy) {
|
|
36
|
+
const effective = effectiveRowsOf(group, policy);
|
|
37
|
+
if (effective === null || (effective.lockedOverride && effective.origin === "tenant"))
|
|
38
|
+
return null;
|
|
39
|
+
const served = effective.rows[0];
|
|
40
|
+
if (served === undefined || served.status === "archived")
|
|
41
|
+
return null;
|
|
42
|
+
return { served, isSystem: effective.origin === "system" };
|
|
43
|
+
}
|
|
44
|
+
function pdfLayoutUserOf(group, layoutSlug, defaultSlug, policy, user) {
|
|
45
|
+
const found = servedRowOf(group, policy);
|
|
46
|
+
if (found === null)
|
|
47
|
+
return null;
|
|
48
|
+
const { served, isSystem } = found;
|
|
49
|
+
const ownLayout = ownLayoutSlugOf(served);
|
|
50
|
+
const servedUses = (ownLayout ?? defaultSlug) === layoutSlug;
|
|
51
|
+
const draft = draftLayoutOf(user, served);
|
|
52
|
+
const draftUses = draft !== null && (draft.layoutSlug ?? defaultSlug) === layoutSlug;
|
|
53
|
+
if (!servedUses && !draftUses)
|
|
54
|
+
return null;
|
|
55
|
+
return {
|
|
56
|
+
slug: served.slug,
|
|
57
|
+
locale: served.locale,
|
|
58
|
+
title: served.title ?? served.slug,
|
|
59
|
+
hasOwnLayout: draftUses ? draft.layoutSlug !== null : ownLayout !== null,
|
|
60
|
+
isSystem,
|
|
61
|
+
status: draftUses || served.status === "draft" ? "draft" : "active",
|
|
62
|
+
version: draftUses ? served.version : servedVersionOf(served),
|
|
63
|
+
};
|
|
64
|
+
}
|
|
65
|
+
// The served version of every document and locale decides: its own layout, else the tenant default.
|
|
66
|
+
// A saved draft that names the layout counts too, so a template shows up as soon as it is applied.
|
|
67
|
+
function pdfLayoutUsers(rows, layoutSlug, defaultSlug, policy, user) {
|
|
68
|
+
const groups = new Map();
|
|
69
|
+
for (const row of rows) {
|
|
70
|
+
const key = `${row.slug}\u0000${row.locale}`;
|
|
71
|
+
groups.set(key, [...(groups.get(key) ?? []), row]);
|
|
72
|
+
}
|
|
73
|
+
const users = [...groups.values()].flatMap((group) => {
|
|
74
|
+
const layoutUser = pdfLayoutUserOf(group, layoutSlug, defaultSlug, policy, user);
|
|
75
|
+
return layoutUser === null ? [] : [layoutUser];
|
|
76
|
+
});
|
|
77
|
+
return users.sort((a, b) => a.slug.localeCompare(b.slug) || a.locale.localeCompare(b.locale));
|
|
78
|
+
}
|
|
11
79
|
export function makeUsageQuery(policy) {
|
|
12
80
|
return defineQueryHandler({
|
|
13
81
|
name: "usage",
|
|
14
82
|
schema: z.object({ slug: templateSlugSchema, kind: z.enum(TEMPLATE_KINDS) }),
|
|
15
83
|
access: { roles: ["TenantAdmin", "SystemAdmin"] },
|
|
16
|
-
description: "Lists
|
|
84
|
+
description: "Lists what uses one template: a mail template is used by the notification whose qualified name is its slug and that has a code template, a mail layout by every mail notification whose effective template (own override, else system) names it, or whose code meta does when no stored template exists, or that falls back to the default layout (`usedBy`); a PDF layout is used by every visible PDF template and locale whose served version names it or, naming none, falls back to it through the tenant's default PDF layout (`usedByTemplates` with slug, locale, title, `hasOwnLayout`, `isSystem`, `status` and `version`; a template whose saved draft names the layout is listed too, with status draft); use it to show what a change to a template affects.",
|
|
17
85
|
handler: async (query, ctx) => {
|
|
18
86
|
const { slug, kind } = query.payload;
|
|
87
|
+
if (kind === "pdf-layout") {
|
|
88
|
+
const defaultSlug = await defaultPdfLayoutSlug(ctx, query.user.tenantId);
|
|
89
|
+
const rows = await visibleRowsOfKind(ctx, policy, query.user, "document-pdf");
|
|
90
|
+
return {
|
|
91
|
+
usedBy: [],
|
|
92
|
+
usedByTemplates: pdfLayoutUsers(rows, slug, defaultSlug, deliveryPolicyOf(ctx.registry), query.user),
|
|
93
|
+
};
|
|
94
|
+
}
|
|
19
95
|
if (kind !== "mail-layout")
|
|
20
96
|
return { usedBy: collectTemplateUsage(ctx.registry, slug, kind) };
|
|
21
|
-
const
|
|
22
|
-
if (fetchedRows.length > MAIL_ROW_LIMIT) {
|
|
23
|
-
ctx.obs.log?.warn("template usage: row limit reached, result is incomplete", {
|
|
24
|
-
limit: MAIL_ROW_LIMIT,
|
|
25
|
-
});
|
|
26
|
-
}
|
|
27
|
-
const visibleRows = fetchedRows
|
|
28
|
-
.slice(0, MAIL_ROW_LIMIT)
|
|
29
|
-
.filter((row) => isRowVisibleToCaller(policy, query.user, ctx.registry, row));
|
|
97
|
+
const visibleRows = await visibleRowsOfKind(ctx, policy, query.user, "mail");
|
|
30
98
|
return {
|
|
31
99
|
usedBy: collectTemplateUsage(ctx.registry, slug, kind, effectiveMailLayoutSlugs(visibleRows, deliveryPolicyOf(ctx.registry))),
|
|
32
100
|
};
|
|
@@ -34,6 +34,7 @@ export declare function validateTemplateDraft(ctx: HandlerContext, user: Session
|
|
|
34
34
|
}[];
|
|
35
35
|
variables: Readonly<Record<string, import("@cosmicdrift/kumiko-types/config").TemplateVariableDef>>;
|
|
36
36
|
systemPlaceholders: string[];
|
|
37
|
+
emptyCompanyData: string[];
|
|
37
38
|
};
|
|
38
39
|
evaluation: import("./template-gates.ts").TemplateWriteResult;
|
|
39
40
|
}>;
|
|
@@ -76,5 +77,6 @@ export declare const validateQuery: import("@cosmicdrift/kumiko-types/define-han
|
|
|
76
77
|
}[];
|
|
77
78
|
variables: Readonly<Record<string, import("@cosmicdrift/kumiko-types/config").TemplateVariableDef>>;
|
|
78
79
|
systemPlaceholders: string[];
|
|
80
|
+
emptyCompanyData: string[];
|
|
79
81
|
}, import("@cosmicdrift/kumiko-types/event-type-map").KumikoEventTypeMap>;
|
|
80
82
|
export {};
|
|
@@ -9,6 +9,7 @@ import { isSystemAdmin } from "../template-draft.js";
|
|
|
9
9
|
import { resolveTemplateVariables, systemPlaceholdersFor } from "../template-validation.js";
|
|
10
10
|
import { contentFormatSchema, kindSchema, localeSchema, templateSlugSchema } from "./shared.js";
|
|
11
11
|
import { evaluateTemplateWrite } from "./template-gates.js";
|
|
12
|
+
import { emptyCompanyData } from "./tenant-settings.js";
|
|
12
13
|
async function knownResourceKeys(db, where) {
|
|
13
14
|
const rows = await selectMany(db, templateResourcesTable, {
|
|
14
15
|
tenantId: where.tenantId,
|
|
@@ -73,6 +74,15 @@ export async function validateTemplateDraft(ctx, user, payload) {
|
|
|
73
74
|
})),
|
|
74
75
|
variables,
|
|
75
76
|
systemPlaceholders: [...systemPlaceholdersFor(kind)].sort(),
|
|
77
|
+
emptyCompanyData: [
|
|
78
|
+
...(await emptyCompanyData(ctx, {
|
|
79
|
+
kind,
|
|
80
|
+
body: payload.contentFormat === "html" ? payload.content : "",
|
|
81
|
+
meta: payload.meta,
|
|
82
|
+
locale,
|
|
83
|
+
tenantId: user.tenantId,
|
|
84
|
+
})),
|
|
85
|
+
],
|
|
76
86
|
};
|
|
77
87
|
return { response, evaluation };
|
|
78
88
|
}
|
|
@@ -21,4 +21,7 @@ export const TEMPLATE_RESOLVER_I18N = {
|
|
|
21
21
|
[handlerTitleKey(H.resourceLinkPdf)]: { en: "Attach PDF template" },
|
|
22
22
|
[handlerTitleKey(H.sendTest)]: { en: "Send test mail" },
|
|
23
23
|
[handlerTitleKey(H.patchDraft)]: { en: "Edit template draft" },
|
|
24
|
+
[handlerTitleKey(H.applyLayout)]: { en: "Apply PDF layout" },
|
|
25
|
+
[handlerTitleKey(H.createLayout)]: { en: "Create PDF layout" },
|
|
26
|
+
[handlerTitleKey(H.publishTemplates)]: { en: "Publish several templates" },
|
|
24
27
|
};
|