@cosmicdrift/kumiko-samples 0.422.0 → 0.424.1

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 (82) hide show
  1. package/package.json +1 -1
  2. package/packages/bundled-features/package.json +11 -1
  3. package/packages/bundled-features/src/auth-email-password/handlers/login.write.ts +52 -0
  4. package/packages/bundled-features/src/auth-email-password/index.ts +4 -0
  5. package/packages/bundled-features/src/channel-push/changes.json +8 -1
  6. package/packages/bundled-features/src/channel-push/push-channel.ts +2 -3
  7. package/packages/bundled-features/src/document-draft/README.md +84 -0
  8. package/packages/bundled-features/src/document-draft/changes.json +8 -0
  9. package/packages/bundled-features/src/document-draft/entity.ts +125 -0
  10. package/packages/bundled-features/src/document-draft/feature.ts +56 -0
  11. package/packages/bundled-features/src/document-draft/handlers/blocks.query.ts +63 -0
  12. package/packages/bundled-features/src/document-draft/handlers/by-subject.query.ts +50 -0
  13. package/packages/bundled-features/src/document-draft/handlers/create.write.ts +110 -0
  14. package/packages/bundled-features/src/document-draft/handlers/discard.write.ts +32 -0
  15. package/packages/bundled-features/src/document-draft/handlers/finalize.write.ts +103 -0
  16. package/packages/bundled-features/src/document-draft/handlers/patch.write.ts +86 -0
  17. package/packages/bundled-features/src/document-draft/handlers/revise.write.ts +46 -0
  18. package/packages/bundled-features/src/document-draft/handlers/save.write.ts +53 -0
  19. package/packages/bundled-features/src/document-draft/i18n.ts +22 -0
  20. package/packages/bundled-features/src/document-draft/index.ts +21 -0
  21. package/packages/bundled-features/src/document-draft/lib.ts +77 -0
  22. package/packages/bundled-features/src/document-draft/options.ts +51 -0
  23. package/packages/bundled-features/src/document-draft/payloads.ts +45 -0
  24. package/packages/bundled-features/src/document-draft/screens/editor-screen.ts +17 -0
  25. package/packages/bundled-features/src/document-draft/user-data.ts +63 -0
  26. package/packages/bundled-features/src/document-draft/web/client-plugin.tsx +20 -0
  27. package/packages/bundled-features/src/document-draft/web/constants.ts +56 -0
  28. package/packages/bundled-features/src/document-draft/web/editor-screen.tsx +418 -0
  29. package/packages/bundled-features/src/document-draft/web/i18n.ts +54 -0
  30. package/packages/bundled-features/src/document-draft/web/index.ts +14 -0
  31. package/packages/bundled-features/src/helpdesk/changes.json +6 -0
  32. package/packages/bundled-features/src/shared/index.ts +6 -0
  33. package/packages/bundled-features/src/{signature → shared}/subject-scope.ts +17 -6
  34. package/packages/bundled-features/src/signature/changes.json +6 -0
  35. package/packages/bundled-features/src/signature/feature.ts +1 -1
  36. package/packages/bundled-features/src/signature/handlers/cancel.write.ts +1 -1
  37. package/packages/bundled-features/src/signature/handlers/issue-link.write.ts +1 -1
  38. package/packages/bundled-features/src/signature/handlers/request.write.ts +1 -1
  39. package/packages/bundled-features/src/signature/handlers/revoke-link.write.ts +1 -1
  40. package/packages/bundled-features/src/signature/handlers/sign-in-person.write.ts +1 -1
  41. package/packages/bundled-features/src/signature/options.ts +2 -1
  42. package/packages/bundled-features/src/signature/subject-queries.ts +1 -1
  43. package/packages/bundled-features/src/template-resolver/api.ts +3 -1
  44. package/packages/bundled-features/src/template-resolver/boot-rules.ts +5 -0
  45. package/packages/bundled-features/src/template-resolver/changes.json +30 -0
  46. package/packages/bundled-features/src/template-resolver/feature.ts +15 -1
  47. package/packages/bundled-features/src/template-resolver/handlers/create-variant.write.ts +134 -0
  48. package/packages/bundled-features/src/template-resolver/handlers/document-base.ts +3 -0
  49. package/packages/bundled-features/src/template-resolver/handlers/overview.query.ts +44 -1
  50. package/packages/bundled-features/src/template-resolver/handlers/patch-draft.write.ts +12 -1
  51. package/packages/bundled-features/src/template-resolver/handlers/template-write.ts +111 -11
  52. package/packages/bundled-features/src/template-resolver/handlers/toggle-status.write.ts +29 -4
  53. package/packages/bundled-features/src/template-resolver/handlers/upsert-tenant.write.ts +1 -0
  54. package/packages/bundled-features/src/template-resolver/handlers/variants.query.ts +89 -0
  55. package/packages/bundled-features/src/template-resolver/i18n.ts +1 -0
  56. package/packages/bundled-features/src/template-resolver/index.ts +22 -0
  57. package/packages/bundled-features/src/template-resolver/seeding.ts +16 -1
  58. package/packages/bundled-features/src/template-resolver/template-delivery-policy.ts +56 -6
  59. package/packages/bundled-features/src/template-resolver/template-edit-policy.ts +5 -5
  60. package/packages/bundled-features/src/template-resolver/template-meta.ts +1 -0
  61. package/packages/bundled-features/src/template-resolver/template-variants.ts +50 -0
  62. package/packages/bundled-features/src/template-resolver/web/document-tiptap-content.tsx +10 -1
  63. package/packages/bundled-features/src/template-resolver/web/document-tiptap-toolbar.tsx +10 -4
  64. package/packages/bundled-features/src/template-resolver/web/i18n.ts +26 -0
  65. package/packages/bundled-features/src/template-resolver/web/index.ts +5 -0
  66. package/packages/bundled-features/src/template-resolver/web/qualified-names.ts +5 -0
  67. package/packages/bundled-features/src/template-resolver/web/system-placeholders.ts +17 -0
  68. package/packages/bundled-features/src/tenant/changes.json +7 -0
  69. package/packages/bundled-features/src/tenant/handlers/update-member-roles.write.ts +1 -1
  70. package/packages/bundled-features/src/tenant/i18n.ts +0 -1
  71. package/packages/bundled-features/src/tenant-inactivity/changes.json +7 -0
  72. package/packages/bundled-features/src/tenant-inactivity/constants.ts +1 -1
  73. package/packages/bundled-features/src/tenant-lifecycle/changes.json +7 -0
  74. package/packages/bundled-features/src/tenant-lifecycle/constants.ts +1 -1
  75. package/samples/apps/ui-walkthrough/src/run-config.ts +1 -0
  76. package/samples/apps/use-all-bundled/feature-manifest.json +37 -1
  77. package/samples/apps/use-all-bundled/kumiko/migrations/0069_document-draft.rebuild.json +4 -0
  78. package/samples/apps/use-all-bundled/src/app/client.tsx +3 -0
  79. package/samples/apps/use-all-bundled/src/run-config.ts +8 -0
  80. package/samples/recipes/session-exchange/README.md +34 -0
  81. package/samples/recipes/session-exchange/package.json +12 -0
  82. package/samples/recipes/session-exchange/src/feature.ts +54 -0
@@ -0,0 +1,56 @@
1
+ // Pure string constants, safe for browser code.
2
+ export const DOCUMENT_DRAFT_FEATURE = "document-draft" as const;
3
+
4
+ export const DOCUMENT_DRAFT_ENTITY = "documentDraft" as const;
5
+
6
+ export const DOCUMENT_DRAFT_STATUS = {
7
+ Open: "open",
8
+ Finalized: "finalized",
9
+ Discarded: "discarded",
10
+ } as const;
11
+
12
+ export type DocumentDraftStatus =
13
+ (typeof DOCUMENT_DRAFT_STATUS)[keyof typeof DOCUMENT_DRAFT_STATUS];
14
+
15
+ export const DOCUMENT_DRAFT_STATUS_TONE = {
16
+ [DOCUMENT_DRAFT_STATUS.Open]: "warn",
17
+ [DOCUMENT_DRAFT_STATUS.Finalized]: "ok",
18
+ [DOCUMENT_DRAFT_STATUS.Discarded]: "neutral",
19
+ } as const;
20
+
21
+ export const DOCUMENT_DRAFT_LAST_CHANGE_SOURCE = {
22
+ Create: "create",
23
+ Ops: "ops",
24
+ Editor: "editor",
25
+ } as const;
26
+
27
+ export const DocumentDraftHandlers = {
28
+ create: `${DOCUMENT_DRAFT_FEATURE}:write:create`,
29
+ patch: `${DOCUMENT_DRAFT_FEATURE}:write:patch`,
30
+ save: `${DOCUMENT_DRAFT_FEATURE}:write:save`,
31
+ finalize: `${DOCUMENT_DRAFT_FEATURE}:write:finalize`,
32
+ revise: `${DOCUMENT_DRAFT_FEATURE}:write:revise`,
33
+ discard: `${DOCUMENT_DRAFT_FEATURE}:write:discard`,
34
+ } as const;
35
+
36
+ export const DocumentDraftQueries = {
37
+ blocks: `${DOCUMENT_DRAFT_FEATURE}:query:blocks`,
38
+ bySubject: `${DOCUMENT_DRAFT_FEATURE}:query:by-subject`,
39
+ } as const;
40
+
41
+ export const DOCUMENT_DRAFT_ERROR = {
42
+ NotOpen: "document_draft_not_open",
43
+ NotFinalized: "document_draft_not_finalized",
44
+ TemplateNotFound: "template_not_found",
45
+ OpNotAllowed: "op_not_allowed",
46
+ } as const;
47
+
48
+ export const DOCUMENT_DRAFT_DEFAULT_LOCALE = "de";
49
+ export const DOCUMENT_DRAFT_MAX_CONTENT_LENGTH = 200_000;
50
+
51
+ // Short screen id as in the URL and in `r.screen`; the qualified name is `document-draft:screen:<id>`.
52
+ export const DOCUMENT_DRAFT_EDITOR_SCREEN_ID = "document-draft-editor" as const;
53
+
54
+ /** Qualified name for targets in other features, e.g. an app actionForm `redirect`. */
55
+ export const DOCUMENT_DRAFT_EDITOR_SCREEN_QN =
56
+ `${DOCUMENT_DRAFT_FEATURE}:screen:${DOCUMENT_DRAFT_EDITOR_SCREEN_ID}` as const;
@@ -0,0 +1,418 @@
1
+ import {
2
+ dispatcherErrorTextWithFieldIssues,
3
+ PreviewPane,
4
+ statusToneForOptionTone,
5
+ useMutation,
6
+ useNav,
7
+ usePrimitives,
8
+ useQuery,
9
+ useTenantCurrency,
10
+ useTranslation,
11
+ useUnsavedInputSource,
12
+ } from "@cosmicdrift/kumiko-renderer";
13
+ import {
14
+ type DispatcherError,
15
+ DOCUMENT_FALLBACK_CURRENCY,
16
+ formatDocumentDate,
17
+ formatDocumentMoney,
18
+ formatDocumentPercent,
19
+ type Translate,
20
+ } from "@cosmicdrift/kumiko-renderer/headless";
21
+ import {
22
+ EditorWorkbench,
23
+ LoadingState,
24
+ RailField,
25
+ RailRow,
26
+ RailSection,
27
+ StatusBadge,
28
+ } from "@cosmicdrift/kumiko-renderer/web";
29
+ import { isPlainObject, propertyOf } from "@cosmicdrift/kumiko-types/type-guards";
30
+ import { type ReactNode, useRef, useState } from "react";
31
+ import {
32
+ COMPANY_PLACEHOLDERS,
33
+ DocumentContentEditor,
34
+ PDF_DOCUMENT_BLOCKS,
35
+ systemPlaceholderLabel,
36
+ translatedOr,
37
+ } from "../../template-resolver/web/index.ts";
38
+ import {
39
+ DOCUMENT_DRAFT_STATUS,
40
+ DOCUMENT_DRAFT_STATUS_TONE,
41
+ DocumentDraftHandlers,
42
+ DocumentDraftQueries,
43
+ type DocumentDraftStatus,
44
+ } from "./constants.ts";
45
+
46
+ type Deviation = { readonly change: "same" | "added" | "removed"; readonly content: string };
47
+
48
+ type DraftRecord = {
49
+ readonly id: string;
50
+ readonly subjectId: string;
51
+ readonly subjectScreen: string | null;
52
+ readonly templateSlug: string;
53
+ readonly templateTitle: string | null;
54
+ readonly locale: string;
55
+ readonly templateVariant: string | null;
56
+ readonly status: DocumentDraftStatus;
57
+ readonly revision: number;
58
+ readonly version: number;
59
+ readonly fileName: string | null;
60
+ readonly body: string;
61
+ readonly variables: Readonly<Record<string, unknown>>;
62
+ readonly variableSchema: Readonly<Record<string, unknown>>;
63
+ readonly deviations: readonly Deviation[];
64
+ };
65
+
66
+ const TEST_ID = "document-draft-workbench";
67
+ const BODY_EDITOR_ID = "document-draft-body";
68
+ const MAX_DEVIATION_TEXT_LENGTH = 120;
69
+
70
+ function isShownValue(value: unknown): value is string | number | boolean {
71
+ return typeof value === "string" || typeof value === "number" || typeof value === "boolean";
72
+ }
73
+
74
+ function hasMoneyVariable(record: DraftRecord): boolean {
75
+ return Object.values(record.variableSchema).some(
76
+ (definition) => propertyOf(definition, "type") === "money",
77
+ );
78
+ }
79
+
80
+ // Same formatting the printed PDF applies, so the chip shows what the document will say.
81
+ // A money amount waits for the tenant currency instead of showing a raw number.
82
+ function formatVariable(
83
+ value: string | number | boolean,
84
+ type: unknown,
85
+ locale: string,
86
+ currency: string | undefined,
87
+ ): string {
88
+ if (type === "money" && currency !== undefined)
89
+ return formatDocumentMoney(value, currency, locale);
90
+ if (type === "date") return formatDocumentDate(value, locale);
91
+ if (type === "percent") return formatDocumentPercent(value, locale);
92
+ return String(value);
93
+ }
94
+
95
+ // Filled in only when the PDF is printed, so the chip names them like the template editor does.
96
+ const SYSTEM_VARIABLES: readonly string[] = ["tenantName", ...COMPANY_PLACEHOLDERS];
97
+
98
+ function addDeclaredLabel(
99
+ t: Translate,
100
+ labels: Record<string, string>,
101
+ key: string,
102
+ label: unknown,
103
+ ): void {
104
+ if (typeof label === "string" && label !== "") labels[key] = translatedOr(t, label, label);
105
+ }
106
+
107
+ // A chip with a value shows it formatted; without one it shows what the variable is called, never
108
+ // the raw key.
109
+ function variableLabelsOf(
110
+ t: Translate,
111
+ record: DraftRecord,
112
+ currency: string | undefined,
113
+ ): Readonly<Record<string, string>> {
114
+ const labels: Record<string, string> = {};
115
+ for (const name of SYSTEM_VARIABLES) {
116
+ labels[name] = systemPlaceholderLabel(t, name);
117
+ }
118
+ for (const [name, definition] of Object.entries(record.variableSchema)) {
119
+ const value = record.variables[name];
120
+ if (isShownValue(value) && String(value) !== "") {
121
+ labels[name] = formatVariable(value, propertyOf(definition, "type"), record.locale, currency);
122
+ continue;
123
+ }
124
+ addDeclaredLabel(t, labels, name, propertyOf(definition, "label"));
125
+ // A chip inside a repeat row is addressed as `list.field`, like the template editor does.
126
+ const item = propertyOf(definition, "item");
127
+ if (isPlainObject(item)) {
128
+ for (const [itemName, itemDefinition] of Object.entries(item)) {
129
+ addDeclaredLabel(t, labels, `${name}.${itemName}`, propertyOf(itemDefinition, "label"));
130
+ }
131
+ }
132
+ }
133
+ return labels;
134
+ }
135
+
136
+ // A title may be an i18n key or plain text; t() returns the key itself without a translation.
137
+ function templateLabelOf(t: Translate, record: DraftRecord): string {
138
+ if (hasNoTitle(record)) return record.templateSlug;
139
+ return t(record.templateTitle ?? record.templateSlug);
140
+ }
141
+
142
+ function statusBadgeToneOf(status: DocumentDraftStatus) {
143
+ return statusToneForOptionTone(DOCUMENT_DRAFT_STATUS_TONE[status]) ?? "muted";
144
+ }
145
+
146
+ function hasNoTitle(record: DraftRecord): boolean {
147
+ return record.templateTitle === null || record.templateTitle === "";
148
+ }
149
+
150
+ function plainTextOf(html: string): string {
151
+ const text = html
152
+ .replace(/<[^>]*>/g, " ")
153
+ .replace(/\s+/g, " ")
154
+ .trim();
155
+ return text.length > MAX_DEVIATION_TEXT_LENGTH
156
+ ? `${text.slice(0, MAX_DEVIATION_TEXT_LENGTH)}…`
157
+ : text;
158
+ }
159
+
160
+ // Deviations carry no id and two blocks can be identical, so the key counts repeats.
161
+ function keyedDeviations(
162
+ deviations: readonly Deviation[],
163
+ ): readonly { readonly key: string; readonly deviation: Deviation }[] {
164
+ const seen = new Map<string, number>();
165
+ return deviations.map((deviation) => {
166
+ const base = `${deviation.change}:${deviation.content}`;
167
+ const count = (seen.get(base) ?? 0) + 1;
168
+ seen.set(base, count);
169
+ return { key: `${base}#${count}`, deviation };
170
+ });
171
+ }
172
+
173
+ function DraftRail({
174
+ record,
175
+ actions,
176
+ testId,
177
+ }: {
178
+ readonly record: DraftRecord;
179
+ readonly actions: ReactNode;
180
+ readonly testId: string;
181
+ }): ReactNode {
182
+ const t = useTranslation();
183
+ const changed = record.deviations.filter((deviation) => deviation.change !== "same");
184
+ return (
185
+ <>
186
+ <RailSection title={t("document-draft:editor.railTemplate")} testId={`${testId}-template`}>
187
+ <RailRow
188
+ label={t("document-draft:editor.template")}
189
+ trailing={templateLabelOf(t, record)}
190
+ />
191
+ {record.templateVariant !== null && hasNoTitle(record) && (
192
+ <RailRow label={t("document-draft:editor.variant")} trailing={record.templateVariant} />
193
+ )}
194
+ <RailRow label={t("document-draft:editor.revision")} trailing={String(record.revision)} />
195
+ {record.fileName !== null && (
196
+ <RailRow
197
+ label={t("document-draft:editor.file")}
198
+ trailing={record.fileName}
199
+ testId={`${testId}-file`}
200
+ />
201
+ )}
202
+ </RailSection>
203
+ <RailSection
204
+ title={t("document-draft:editor.railDeviations")}
205
+ testId={`${testId}-deviations`}
206
+ >
207
+ {changed.length === 0 ? (
208
+ <RailRow label={t("document-draft:editor.noDeviations")} />
209
+ ) : (
210
+ keyedDeviations(changed).map(({ key, deviation }) => (
211
+ <RailRow
212
+ key={key}
213
+ label={t(`document-draft:editor.deviation.${deviation.change}`)}
214
+ trailing={plainTextOf(deviation.content)}
215
+ testId={`${testId}-deviation`}
216
+ />
217
+ ))
218
+ )}
219
+ </RailSection>
220
+ {actions}
221
+ </>
222
+ );
223
+ }
224
+
225
+ function DraftEditor({
226
+ record,
227
+ onChanged,
228
+ }: {
229
+ readonly record: DraftRecord;
230
+ readonly onChanged: () => void;
231
+ }): ReactNode {
232
+ const t = useTranslation();
233
+ const { Button } = usePrimitives();
234
+ const nav = useNav();
235
+ const [html, setHtml] = useState(record.body);
236
+ const [resetCount, setResetCount] = useState(0);
237
+ const [actionError, setActionError] = useState<string | null>(null);
238
+ const savedRef = useRef(false);
239
+ const tenantCurrency = useTenantCurrency(hasMoneyVariable(record), DOCUMENT_FALLBACK_CURRENCY);
240
+ const currency = tenantCurrency.status === "ready" ? tenantCurrency.currency : undefined;
241
+ const save = useMutation(DocumentDraftHandlers.save);
242
+ const finalize = useMutation(DocumentDraftHandlers.finalize);
243
+ const revise = useMutation(DocumentDraftHandlers.revise);
244
+ const discard = useMutation(DocumentDraftHandlers.discard);
245
+ const open = record.status === DOCUMENT_DRAFT_STATUS.Open;
246
+ const dirty = open && html !== record.body;
247
+ const busy = save.pending || finalize.pending || revise.pending || discard.pending;
248
+ useUnsavedInputSource(() => dirty && !savedRef.current);
249
+
250
+ const failureText = (error: DispatcherError): string =>
251
+ error.code === "version_conflict"
252
+ ? t("document-draft:editor.versionConflict")
253
+ : dispatcherErrorTextWithFieldIssues(error, t);
254
+
255
+ const leaveToSubject = (): void => {
256
+ if (record.subjectScreen === null) {
257
+ onChanged();
258
+ return;
259
+ }
260
+ nav.navigate({ screenId: record.subjectScreen, entityId: record.subjectId });
261
+ };
262
+
263
+ const run = async (
264
+ mutation: typeof save,
265
+ payload: Readonly<Record<string, unknown>>,
266
+ onDone: () => void,
267
+ ): Promise<void> => {
268
+ setActionError(null);
269
+ const result = await mutation.mutate({ id: record.id, ...payload });
270
+ if (!result.isSuccess) {
271
+ setActionError(failureText(result.error));
272
+ return;
273
+ }
274
+ onDone();
275
+ };
276
+
277
+ const onSave = (): void => {
278
+ void run(save, { base: record.version, content: html }, () => {
279
+ savedRef.current = true;
280
+ onChanged();
281
+ });
282
+ };
283
+ const onFinalize = (): void => {
284
+ void run(finalize, { base: record.version }, leaveToSubject);
285
+ };
286
+ const onDiscardDraft = (): void => {
287
+ void run(discard, { base: record.version }, leaveToSubject);
288
+ };
289
+ const onRevise = (): void => {
290
+ void run(revise, { base: record.version }, onChanged);
291
+ };
292
+ const onRevert = (): void => {
293
+ setHtml(record.body);
294
+ setActionError(null);
295
+ setResetCount((count) => count + 1);
296
+ };
297
+
298
+ const actions = (
299
+ <RailSection title={t("document-draft:editor.railActions")} testId={`${TEST_ID}-actions`}>
300
+ <RailField>
301
+ {open ? (
302
+ <>
303
+ <Button
304
+ variant="primary"
305
+ width="full"
306
+ disabled={dirty || busy}
307
+ loading={finalize.pending}
308
+ onClick={onFinalize}
309
+ testId={`${TEST_ID}-finalize`}
310
+ >
311
+ {t("document-draft:editor.finalize")}
312
+ </Button>
313
+ {dirty && <RailRow label={t("document-draft:editor.finalizeNeedsSave")} />}
314
+ <Button
315
+ variant="danger-ghost"
316
+ width="full"
317
+ disabled={busy}
318
+ loading={discard.pending}
319
+ onClick={onDiscardDraft}
320
+ testId={`${TEST_ID}-discard`}
321
+ >
322
+ {t("document-draft:editor.discardDraft")}
323
+ </Button>
324
+ </>
325
+ ) : (
326
+ <Button
327
+ variant="primary"
328
+ width="full"
329
+ disabled={busy || record.status !== DOCUMENT_DRAFT_STATUS.Finalized}
330
+ loading={revise.pending}
331
+ onClick={onRevise}
332
+ testId={`${TEST_ID}-revise`}
333
+ >
334
+ {t("document-draft:editor.revise")}
335
+ </Button>
336
+ )}
337
+ </RailField>
338
+ </RailSection>
339
+ );
340
+ const rail = <DraftRail record={record} actions={actions} testId={`${TEST_ID}-rail`} />;
341
+
342
+ return (
343
+ <EditorWorkbench
344
+ testId={TEST_ID}
345
+ title={
346
+ hasNoTitle(record) && record.templateVariant !== null
347
+ ? `${record.templateSlug} / ${record.templateVariant}`
348
+ : templateLabelOf(t, record)
349
+ }
350
+ status={
351
+ <StatusBadge tone={statusBadgeToneOf(record.status)} testId={`${TEST_ID}-status`}>
352
+ {t(`document-draft:editor.status.${record.status}`)}
353
+ </StatusBadge>
354
+ }
355
+ info={{
356
+ edit: open ? t("document-draft:editor.infoEdit") : t("document-draft:editor.infoFinalized"),
357
+ preview: t("document-draft:editor.infoPreview"),
358
+ }}
359
+ edit={
360
+ <div className="min-h-0 min-w-0 flex-1 overflow-auto px-4 py-4 md:px-6">
361
+ <DocumentContentEditor
362
+ key={resetCount}
363
+ id={BODY_EDITOR_ID}
364
+ value={html}
365
+ onChange={setHtml}
366
+ variables={Object.keys(record.variableSchema)}
367
+ variableLabels={variableLabelsOf(t, record, currency)}
368
+ systemVariables={SYSTEM_VARIABLES}
369
+ blocks={PDF_DOCUMENT_BLOCKS}
370
+ readOnly={!open}
371
+ />
372
+ </div>
373
+ }
374
+ preview={
375
+ <PreviewPane
376
+ target="web"
377
+ content={html}
378
+ editFormat="document"
379
+ variables={record.variables}
380
+ subject={{ kind: "body" }}
381
+ />
382
+ }
383
+ rail={{ edit: rail, preview: rail }}
384
+ save={{
385
+ busy: save.pending,
386
+ canSave: dirty && !busy,
387
+ dirty,
388
+ onSave,
389
+ onDiscard: onRevert,
390
+ saveError: actionError,
391
+ saveLabel: t("document-draft:editor.save"),
392
+ }}
393
+ />
394
+ );
395
+ }
396
+
397
+ export function DocumentDraftEditorScreen(): ReactNode {
398
+ const t = useTranslation();
399
+ const { Banner } = usePrimitives();
400
+ const nav = useNav();
401
+ const entityId = nav.route?.entityId;
402
+ const detail = useQuery<DraftRecord | null>(
403
+ DocumentDraftQueries.blocks,
404
+ { id: entityId ?? "" },
405
+ { enabled: entityId !== undefined },
406
+ );
407
+ if (entityId === undefined || detail.error !== null) {
408
+ return <Banner variant="error">{t("document-draft:editor.loadFailed")}</Banner>;
409
+ }
410
+ if (detail.data === null) return <LoadingState />;
411
+ return (
412
+ <DraftEditor
413
+ key={`${detail.data.id}:${detail.data.version}`}
414
+ record={detail.data}
415
+ onChanged={() => void detail.refetch()}
416
+ />
417
+ );
418
+ }
@@ -0,0 +1,54 @@
1
+ import { translationsByLocaleFromKeys } from "@cosmicdrift/kumiko-renderer";
2
+
3
+ export const DOCUMENT_DRAFT_EDITOR_I18N = {
4
+ "document-draft:editor.railActions": { en: "Actions", de: "Aktionen" },
5
+ "screen:document-draft-editor.title": { en: "Document draft", de: "Dokumententwurf" },
6
+ "document-draft:editor.infoEdit": {
7
+ en: "Edit the text. The placeholders keep the values the draft was created with.",
8
+ de: "Text bearbeiten. Die Platzhalter behalten die Werte, mit denen der Entwurf angelegt wurde.",
9
+ },
10
+ "document-draft:editor.infoPreview": {
11
+ en: "Preview of the draft text.",
12
+ de: "Vorschau des Entwurfstexts.",
13
+ },
14
+ "document-draft:editor.infoFinalized": {
15
+ en: "This draft is finalized. Reopen it to change the text.",
16
+ de: "Dieser Entwurf ist abgeschlossen. Zum Ändern erneut bearbeiten.",
17
+ },
18
+ "document-draft:editor.loadFailed": {
19
+ en: "The draft could not be loaded.",
20
+ de: "Der Entwurf konnte nicht geladen werden.",
21
+ },
22
+ "document-draft:editor.railTemplate": { en: "Template", de: "Vorlage" },
23
+ "document-draft:editor.template": { en: "Template", de: "Vorlage" },
24
+ "document-draft:editor.variant": { en: "Variant", de: "Variante" },
25
+ "document-draft:editor.revision": { en: "Revision", de: "Revision" },
26
+ "document-draft:editor.file": { en: "File", de: "Datei" },
27
+ "document-draft:editor.railDeviations": {
28
+ en: "Deviations from the template",
29
+ de: "Abweichungen von der Vorlage",
30
+ },
31
+ "document-draft:editor.noDeviations": {
32
+ en: "The draft matches the template.",
33
+ de: "Der Entwurf entspricht der Vorlage.",
34
+ },
35
+ "document-draft:editor.deviation.added": { en: "Added", de: "Hinzugefügt" },
36
+ "document-draft:editor.deviation.removed": { en: "Removed", de: "Entfernt" },
37
+ "document-draft:editor.status.open": { en: "Open", de: "Offen" },
38
+ "document-draft:editor.status.finalized": { en: "Finalized", de: "Abgeschlossen" },
39
+ "document-draft:editor.status.discarded": { en: "Discarded", de: "Verworfen" },
40
+ "document-draft:editor.save": { en: "Save", de: "Speichern" },
41
+ "document-draft:editor.finalize": { en: "Finalize", de: "Abschließen" },
42
+ "document-draft:editor.finalizeNeedsSave": {
43
+ en: "Save your changes before finalizing.",
44
+ de: "Änderungen vor dem Abschließen speichern.",
45
+ },
46
+ "document-draft:editor.discardDraft": { en: "Discard draft", de: "Entwurf verwerfen" },
47
+ "document-draft:editor.revise": { en: "Edit again", de: "Erneut bearbeiten" },
48
+ "document-draft:editor.versionConflict": {
49
+ en: "The draft was changed elsewhere in the meantime. Reload it to continue with the current text.",
50
+ de: "Der Entwurf wurde zwischenzeitlich anderswo geändert. Neu laden, um mit dem aktuellen Text weiterzuarbeiten.",
51
+ },
52
+ } as const;
53
+
54
+ export const defaultTranslations = translationsByLocaleFromKeys(DOCUMENT_DRAFT_EDITOR_I18N);
@@ -0,0 +1,14 @@
1
+ export { type DocumentDraftClientOptions, documentDraftClient } from "./client-plugin.tsx";
2
+ export {
3
+ DOCUMENT_DRAFT_EDITOR_SCREEN_ID,
4
+ DOCUMENT_DRAFT_EDITOR_SCREEN_QN,
5
+ DOCUMENT_DRAFT_ENTITY,
6
+ DOCUMENT_DRAFT_ERROR,
7
+ DOCUMENT_DRAFT_FEATURE,
8
+ DOCUMENT_DRAFT_LAST_CHANGE_SOURCE,
9
+ DOCUMENT_DRAFT_STATUS,
10
+ DocumentDraftHandlers,
11
+ DocumentDraftQueries,
12
+ type DocumentDraftStatus,
13
+ } from "./constants.ts";
14
+ export { defaultTranslations } from "./i18n.ts";
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.424.0",
4
+ "type": "fix",
5
+ "title": "helpdesk tests no longer flake on a guessed wrong nonce",
6
+ "detail": "A guessed wrong nonce still solved the challenge with probability 2^-bits at the low test difficulty, so the dropped-submit and wrong-nonce tests failed now and then. The tests now search for a nonce that fails verification. No runtime change."
7
+ },
2
8
  {
3
9
  "version": "0.415.0",
4
10
  "type": "fix",
@@ -128,6 +128,12 @@ export {
128
128
  type StreamBackfillStepFailure,
129
129
  stepFailures,
130
130
  } from "./stream-tenant-derived-state.ts";
131
+ export {
132
+ createSubjectScope,
133
+ type SubjectScope,
134
+ type SubjectScopeContext,
135
+ type SubjectScopeOptions,
136
+ } from "./subject-scope.ts";
131
137
  export type { SystemQueryFn } from "./system-query.ts";
132
138
  export { createTenantDbCache } from "./tenant-db-cache.ts";
133
139
  export {
@@ -1,16 +1,29 @@
1
1
  import type { HandlerContext, SessionUser } from "@cosmicdrift/kumiko-framework/engine";
2
- import type { SignatureOptions } from "./options.ts";
2
+
3
+ /** The part of the handler context that exists in `beforeTransaction` too, so scope checks can run before printing. */
4
+ export type SubjectScopeContext = Pick<HandlerContext, "db" | "registry" | "services">;
5
+
6
+ export type SubjectScopeOptions = {
7
+ /** Runs for every signed-in handler and query on a subject, except for `unscopedRoles`. `false` answers like "does not exist". */
8
+ readonly authorizeSubject?: (
9
+ ctx: SubjectScopeContext,
10
+ user: SessionUser,
11
+ subject: { readonly subjectType: string; readonly subjectId: string },
12
+ ) => Promise<boolean>;
13
+ /** Roles that skip `authorizeSubject`, e.g. admins. */
14
+ readonly unscopedRoles?: readonly string[];
15
+ };
3
16
 
4
17
  export type SubjectScope = {
5
18
  isScoped(user: SessionUser): boolean;
6
19
  allows(
7
- ctx: HandlerContext,
20
+ ctx: SubjectScopeContext,
8
21
  user: SessionUser,
9
22
  subjectType: unknown,
10
23
  subjectId: unknown,
11
24
  ): Promise<boolean>;
12
25
  allowsRequest(
13
- ctx: HandlerContext,
26
+ ctx: SubjectScopeContext,
14
27
  user: SessionUser,
15
28
  request: { readonly subjectType?: unknown; readonly subjectId?: unknown },
16
29
  ): Promise<boolean>;
@@ -20,9 +33,7 @@ function isNonEmptyString(value: unknown): value is string {
20
33
  return typeof value === "string" && value !== "";
21
34
  }
22
35
 
23
- export function createSubjectScope(
24
- opts: Pick<SignatureOptions, "authorizeSubject" | "unscopedRoles">,
25
- ): SubjectScope {
36
+ export function createSubjectScope(opts: SubjectScopeOptions): SubjectScope {
26
37
  const { authorizeSubject } = opts;
27
38
  const unscopedRoles = opts.unscopedRoles ?? [];
28
39
  const isScoped = (user: SessionUser): boolean =>
@@ -1,4 +1,10 @@
1
1
  [
2
+ {
3
+ "version": "0.424.0",
4
+ "type": "breaking",
5
+ "title": "authorizeSubject receives the subject scope context instead of the full handler context",
6
+ "migration": "The ctx argument of `authorizeSubject` (`AuthorizeSignatureSubject`, `AuthorizeDocumentDraftSubject`) is now `SubjectScopeContext` from the shared barrel: `db`, `registry` and `services` only, because the check also runs in `beforeTransaction`, before a draft is printed. A callback that reads only these compiles unchanged; one that used `ctx.user`, `ctx.dispatch` or `ctx.events` takes the user from its second argument and reads through `ctx.db` instead."
7
+ },
2
8
  {
3
9
  "version": "0.420.0",
4
10
  "type": "fix",
@@ -6,6 +6,7 @@ import {
6
6
  type FeatureDefinition,
7
7
  i18nKey,
8
8
  } from "@cosmicdrift/kumiko-framework/engine";
9
+ import { createSubjectScope } from "../shared/index.ts";
9
10
  import { createSignatureRequestEntity, createSignatureSignerEntity } from "./entity.ts";
10
11
  import { createAnonymousLinkHandlers } from "./handlers/anonymous.write.ts";
11
12
  import { createCancelHandler } from "./handlers/cancel.write.ts";
@@ -31,7 +32,6 @@ import {
31
32
  } from "./payloads.ts";
32
33
  import { createSignatureDetailScreen, createSignatureListScreen } from "./screens.ts";
33
34
  import { scopeRequestDetail, scopeRequestList, scopeSignerList } from "./subject-queries.ts";
34
- import { createSubjectScope } from "./subject-scope.ts";
35
35
  import { sweepSignatureRequests } from "./sweep.ts";
36
36
  import { signatureDeleteHook, signatureExportHook } from "./user-data.ts";
37
37
  import {
@@ -1,9 +1,9 @@
1
1
  import { type AccessRule, defineWriteHandler } from "@cosmicdrift/kumiko-framework/engine";
2
2
  import { NotFoundError, writeFailure } from "@cosmicdrift/kumiko-framework/errors";
3
+ import type { SubjectScope } from "../../shared/index.ts";
3
4
  import { requestExecutor, signerExecutor } from "../entity.ts";
4
5
  import { isUnsignedSigner, listSigners, setRequestStatus } from "../lib.ts";
5
6
  import { RequestIdSchema } from "../payloads.ts";
6
- import type { SubjectScope } from "../subject-scope.ts";
7
7
  import { SIGNATURE_REQUEST_ENTITY, SIGNATURE_REQUEST_STATUS } from "../web/constants.ts";
8
8
 
9
9
  // Cancelling moves the request out of `open`, which already makes every link of it fail; the
@@ -5,12 +5,12 @@ import {
5
5
  writeFailure,
6
6
  } from "@cosmicdrift/kumiko-framework/errors";
7
7
  import { generateId } from "@cosmicdrift/kumiko-framework/utils";
8
+ import type { SubjectScope } from "../../shared/index.ts";
8
9
  import { signerExecutor } from "../entity.ts";
9
10
  import { signSignatureLinkToken } from "../grant.ts";
10
11
  import { isOpenRequest, isUnsignedSigner, loadRequestOfSigner } from "../lib.ts";
11
12
  import type { SignatureOptions } from "../options.ts";
12
13
  import { SignerIdSchema } from "../payloads.ts";
13
- import type { SubjectScope } from "../subject-scope.ts";
14
14
 
15
15
  export type IssueLinkData = { readonly signerId: string; readonly linkSentAt: string };
16
16
 
@@ -16,10 +16,10 @@ import {
16
16
  fileRefsTable,
17
17
  } from "@cosmicdrift/kumiko-framework/files";
18
18
  import { PDFDocument } from "pdf-lib";
19
+ import type { SubjectScope } from "../../shared/index.ts";
19
20
  import { requestExecutor, signerExecutor } from "../entity.ts";
20
21
  import { readTenantFile, sha256Hex } from "../files.ts";
21
22
  import { RequestSignatureSchema } from "../payloads.ts";
22
- import type { SubjectScope } from "../subject-scope.ts";
23
23
  import {
24
24
  SIGNATURE_DEFAULT_VALIDITY_DAYS,
25
25
  SIGNATURE_REQUEST_ENTITY,