@endora-commerce/contracts 0.103.0 → 0.104.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 (63) hide show
  1. package/dist/admin-actions.d.ts +5 -0
  2. package/dist/admin-actions.d.ts.map +1 -1
  3. package/dist/admin-actions.js +5 -0
  4. package/dist/admin-actions.js.map +1 -1
  5. package/dist/admin-contributions.d.ts +41 -0
  6. package/dist/admin-contributions.d.ts.map +1 -1
  7. package/dist/admin-contributions.js +58 -0
  8. package/dist/admin-contributions.js.map +1 -1
  9. package/dist/admin-notifications.d.ts +37 -0
  10. package/dist/admin-notifications.d.ts.map +1 -1
  11. package/dist/assets-library.d.ts +8 -0
  12. package/dist/assets-library.d.ts.map +1 -1
  13. package/dist/assets-library.js +2 -0
  14. package/dist/assets-library.js.map +1 -1
  15. package/dist/auth.d.ts +17 -1
  16. package/dist/auth.d.ts.map +1 -1
  17. package/dist/carts.d.ts +26 -1
  18. package/dist/carts.d.ts.map +1 -1
  19. package/dist/catalog.d.ts +64 -3
  20. package/dist/catalog.d.ts.map +1 -1
  21. package/dist/catalog.js +92 -0
  22. package/dist/catalog.js.map +1 -1
  23. package/dist/common.d.ts +17 -0
  24. package/dist/common.d.ts.map +1 -1
  25. package/dist/common.js +22 -0
  26. package/dist/common.js.map +1 -1
  27. package/dist/crm.d.ts +2903 -0
  28. package/dist/crm.d.ts.map +1 -0
  29. package/dist/crm.js +1191 -0
  30. package/dist/crm.js.map +1 -0
  31. package/dist/custom-fields.d.ts +4 -0
  32. package/dist/custom-fields.d.ts.map +1 -1
  33. package/dist/custom-fields.js +4 -0
  34. package/dist/custom-fields.js.map +1 -1
  35. package/dist/errors.d.ts +29 -0
  36. package/dist/errors.d.ts.map +1 -1
  37. package/dist/errors.js +32 -0
  38. package/dist/errors.js.map +1 -1
  39. package/dist/index.d.ts +2 -0
  40. package/dist/index.d.ts.map +1 -1
  41. package/dist/index.js +3 -0
  42. package/dist/index.js.map +1 -1
  43. package/dist/languages.d.ts +39 -4
  44. package/dist/languages.d.ts.map +1 -1
  45. package/dist/modules.d.ts +3 -0
  46. package/dist/modules.d.ts.map +1 -1
  47. package/dist/orders.d.ts +15 -0
  48. package/dist/orders.d.ts.map +1 -1
  49. package/dist/orders.js +7 -1
  50. package/dist/orders.js.map +1 -1
  51. package/dist/pim-connector.d.ts +1 -1
  52. package/dist/product-feeds.d.ts +15 -15
  53. package/dist/quote-requests.d.ts +20 -0
  54. package/dist/quote-requests.d.ts.map +1 -1
  55. package/dist/quote-requests.js +9 -1
  56. package/dist/quote-requests.js.map +1 -1
  57. package/dist/storefront-cache-tags.d.ts +65 -0
  58. package/dist/storefront-cache-tags.d.ts.map +1 -0
  59. package/dist/storefront-cache-tags.js +47 -0
  60. package/dist/storefront-cache-tags.js.map +1 -0
  61. package/dist/webhooks.d.ts +40 -0
  62. package/dist/webhooks.d.ts.map +1 -1
  63. package/package.json +1 -1
package/dist/crm.js ADDED
@@ -0,0 +1,1191 @@
1
+ import { z } from 'zod';
2
+ import { isoDateTimeSchema } from './common.js';
3
+ import { collectionEnvelope, dataEnvelope } from './envelopes.js';
4
+ import { customFieldValuesSchema } from './custom-fields.js';
5
+ /**
6
+ * CRM — Sales Opportunities (`specs/143-crm-sales-opportunities/`).
7
+ *
8
+ * Every request, response, event and port shape of the `crm` module, written
9
+ * before the first route (Constitution II). The normative prose is
10
+ * `specs/143-crm-sales-opportunities/contracts/admin-api.md` and
11
+ * `contracts/events-and-ports.md`; this file is what the backend validates
12
+ * with and what the admin types its calls from.
13
+ *
14
+ * Base path of the HTTP API: `/api/v1/admin/crm`. There is no storefront or
15
+ * customer route.
16
+ */
17
+ // ---------------------------------------------------------------------------
18
+ // Vocabulary
19
+ // ---------------------------------------------------------------------------
20
+ /**
21
+ * A status code — stable, snake_case, immutable after create. The grammar is
22
+ * what lets a templated event name be built without escaping.
23
+ */
24
+ export const opportunityStatusCodeSchema = z
25
+ .string()
26
+ .min(1)
27
+ .max(64)
28
+ .regex(/^[a-z][a-z0-9_]*$/, 'Status code must be snake_case and start with a letter');
29
+ /** What a status means for the Opportunity: still worked, or closed as won / lost. */
30
+ export const opportunityStatusKindSchema = z.enum(['open', 'won', 'lost']);
31
+ export const opportunityClosedKindSchema = z.enum(['won', 'lost']);
32
+ export const opportunityValueModeSchema = z.enum(['manual', 'computed']);
33
+ export const opportunitySourceSchema = z.enum(['manual', 'order', 'quote_request']);
34
+ export const opportunityDocumentKindSchema = z.enum(['order', 'quote_request']);
35
+ export const opportunityLinkSourceSchema = z.enum([
36
+ 'manual',
37
+ 'auto',
38
+ 'created_from_opportunity',
39
+ 'quote_conversion',
40
+ ]);
41
+ export const orderStatusMappingDirectionSchema = z.enum([
42
+ 'opportunity_to_order',
43
+ 'order_to_opportunity',
44
+ ]);
45
+ /**
46
+ * What became of one attempt to carry a status across the Opportunity ↔ Order
47
+ * link. The first six are `OrderTransitionOutcome`'s answers, recorded
48
+ * verbatim; `failed` is a call that did not return one, `skipped` is the
49
+ * reverse direction declining to move the Opportunity, and `pending` is a row
50
+ * written before the call that has not been resolved yet.
51
+ */
52
+ export const propagationOutcomeKindSchema = z.enum([
53
+ 'pending',
54
+ 'applied',
55
+ 'already_there',
56
+ 'not_found',
57
+ 'unknown_status',
58
+ 'not_permitted',
59
+ 'vetoed',
60
+ 'skipped',
61
+ 'failed',
62
+ ]);
63
+ export const opportunityCommentKindSchema = z.enum(['note', 'message']);
64
+ /**
65
+ * What a free text can refer to. `admin_user` is a person — a user of the Admin
66
+ * UI, under the name the platform has for one everywhere else (the bell's
67
+ * audience, `assignedAdminUserId`); `user` alone would also read as a customer.
68
+ */
69
+ export const opportunityReferenceTypeSchema = z.enum(['product', 'order', 'admin_user']);
70
+ /** The six `QuoteRequestStatus` values — a fixed union, unlike Order statuses. */
71
+ export const QUOTE_REQUEST_STATUS_VALUES = [
72
+ 'Created from admin',
73
+ 'Pending',
74
+ 'Canceled',
75
+ 'Approved',
76
+ 'Completed',
77
+ 'Expired',
78
+ ];
79
+ const quoteRequestStatusValueSchema = z.enum(QUOTE_REQUEST_STATUS_VALUES);
80
+ // ---------------------------------------------------------------------------
81
+ // Field primitives
82
+ // ---------------------------------------------------------------------------
83
+ const colorSchema = z
84
+ .string()
85
+ .regex(/^#[0-9a-fA-F]{6}$/, 'Colour must be a #rrggbb hex value');
86
+ const currencyCodeSchema = z
87
+ .string()
88
+ .regex(/^[A-Z]{3}$/, 'Currency must be an ISO 4217 code, e.g. PLN');
89
+ /** Whether `YYYY-MM-DD` names a day the calendar has: `2026-02-31` and `2026-13-01` do not. */
90
+ function isCalendarDate(value) {
91
+ const [year = 0, month = 0, day = 0] = value.split('-').map(Number);
92
+ if (year < 1)
93
+ return false;
94
+ const date = new Date(0);
95
+ date.setUTCFullYear(year, month - 1, day);
96
+ return date.getUTCFullYear() === year && date.getUTCMonth() === month - 1 && date.getUTCDate() === day;
97
+ }
98
+ const calendarDateSchema = z
99
+ .string()
100
+ .regex(/^\d{4}-\d{2}-\d{2}$/, 'YYYY-MM-DD')
101
+ .refine(isCalendarDate, 'Not a date of the calendar');
102
+ /** A non-negative decimal held as a string, as `numeric(14,2)` money is everywhere. */
103
+ const decimalAmountSchema = z
104
+ .string()
105
+ .regex(/^\d{1,12}(\.\d{1,2})?$/, 'Amount must be a non-negative decimal with at most two places');
106
+ const isoTimestampSchema = z.string();
107
+ /**
108
+ * A query-string field that may repeat. One occurrence arrives as a string and
109
+ * several as an array; both normalise to an array.
110
+ */
111
+ function repeatable(item) {
112
+ return z.preprocess((value) => (value === undefined || Array.isArray(value) ? value : [value]), z.array(item).max(50).optional());
113
+ }
114
+ const statusNameSchema = z.record(z.string().min(2).max(16), z.string().min(1).max(120));
115
+ // ---------------------------------------------------------------------------
116
+ // §9 References
117
+ // ---------------------------------------------------------------------------
118
+ /**
119
+ * The reference-token grammar: `[[product:<uuid>]]`, `[[order:<uuid>]]`,
120
+ * `[[admin_user:<uuid>]]`.
121
+ *
122
+ * Free text (`description`, a comment `body`) is stored as plain text carrying
123
+ * these tokens. This is the one place the grammar is written; the backend
124
+ * extracts with it and the admin's composer inserts with it. What a person
125
+ * types to get one — `@`, `@@`, `@@@` — is the composer's and is never stored.
126
+ */
127
+ const REFERENCE_TOKEN_SOURCE = '\\[\\[(product|order|admin_user):([0-9a-fA-F]{8}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{4}-[0-9a-fA-F]{12})\\]\\]';
128
+ export function formatOpportunityReferenceToken(type, id) {
129
+ return `[[${type}:${id}]]`;
130
+ }
131
+ /** Every well-formed token in `text`, in first-appearance order, each target once. */
132
+ export function extractOpportunityReferenceTokens(text) {
133
+ const seen = new Set();
134
+ const tokens = [];
135
+ // A fresh expression per call: a shared global one carries `lastIndex`.
136
+ for (const match of text.matchAll(new RegExp(REFERENCE_TOKEN_SOURCE, 'g'))) {
137
+ const type = match[1];
138
+ const id = match[2].toLowerCase();
139
+ const key = `${type}:${id}`;
140
+ if (seen.has(key))
141
+ continue;
142
+ seen.add(key);
143
+ tokens.push({ type, id });
144
+ }
145
+ return tokens;
146
+ }
147
+ /**
148
+ * `text` cut at its well-formed tokens, for a screen that shows each token as
149
+ * a link: the parts, joined back, are the text. A malformed token stays text.
150
+ */
151
+ export function splitOpportunityReferenceText(text) {
152
+ const parts = [];
153
+ let cursor = 0;
154
+ for (const match of text.matchAll(new RegExp(REFERENCE_TOKEN_SOURCE, 'g'))) {
155
+ const start = match.index ?? 0;
156
+ if (start > cursor)
157
+ parts.push({ kind: 'text', text: text.slice(cursor, start) });
158
+ parts.push({
159
+ kind: 'reference',
160
+ type: match[1],
161
+ id: match[2].toLowerCase(),
162
+ });
163
+ cursor = start + match[0].length;
164
+ }
165
+ if (cursor < text.length)
166
+ parts.push({ kind: 'text', text: text.slice(cursor) });
167
+ return parts;
168
+ }
169
+ /** The people a text mentions, each once, in first-appearance order. */
170
+ export function mentionedAdminUserIds(text) {
171
+ if (!text)
172
+ return [];
173
+ return extractOpportunityReferenceTokens(text)
174
+ .filter((token) => token.type === 'admin_user')
175
+ .map((token) => token.id);
176
+ }
177
+ /**
178
+ * A resolved reference, returned beside every free-text field. A target the
179
+ * reader may not see, or that is gone, is `available: false` with no label.
180
+ * A person has a `label` — their name — and never a `url`: the screen of an
181
+ * administrator is `admin_users`', behind a permission of its own.
182
+ */
183
+ export const OpportunityReferenceSchema = z.object({
184
+ type: opportunityReferenceTypeSchema,
185
+ id: z.string().uuid(),
186
+ available: z.boolean(),
187
+ label: z.string().nullable(),
188
+ url: z.string().nullable(),
189
+ });
190
+ // ---------------------------------------------------------------------------
191
+ // §1 Opportunities
192
+ // ---------------------------------------------------------------------------
193
+ export const opportunityStateSchema = opportunityStatusKindSchema;
194
+ export const opportunitySortSchema = z.enum([
195
+ 'createdAt',
196
+ 'updatedAt',
197
+ 'value',
198
+ 'expectedCloseDate',
199
+ 'number',
200
+ ]);
201
+ /** `me` and `unassigned` are tokens the service resolves; anything else is a user id. */
202
+ const assigneeFilterSchema = z.union([z.literal('me'), z.literal('unassigned'), z.string().uuid()]);
203
+ // --- §12c Board card fields (US19) — declared here because the field filters
204
+ // are among the filters the list and the board share.
205
+ /** How many fields a board card shows at most, the title besides. */
206
+ export const OPPORTUNITY_BOARD_CARD_MAX_FIELDS = 6;
207
+ /** The fields every Opportunity has that a board card can show, in the order they are offered. */
208
+ export const OPPORTUNITY_BOARD_BUILTIN_FIELD_KEYS = [
209
+ 'number',
210
+ 'organization',
211
+ 'contact',
212
+ 'assignee',
213
+ 'value',
214
+ 'salesChannel',
215
+ 'tags',
216
+ 'expectedCloseDate',
217
+ 'source',
218
+ 'createdAt',
219
+ 'updatedAt',
220
+ 'closedAt',
221
+ 'linkedOrders',
222
+ 'linkedQuoteRequests',
223
+ ];
224
+ /** `builtin:<key>` or `custom:<definition key>`. */
225
+ export const opportunityBoardFieldRefSchema = z
226
+ .string()
227
+ .regex(/^(builtin:[A-Za-z]{1,40}|custom:[a-z][a-z0-9_]{0,63})$/, 'Not a board field reference');
228
+ export function opportunityBoardBuiltinFieldRef(key) {
229
+ return `builtin:${key}`;
230
+ }
231
+ export function opportunityBoardCustomFieldRef(definitionKey) {
232
+ return `custom:${definitionKey}`;
233
+ }
234
+ /** The card as it was before it could be configured — what an untouched instance shows. */
235
+ export const OPPORTUNITY_BOARD_DEFAULT_CARD_FIELDS = [
236
+ 'builtin:number',
237
+ 'builtin:organization',
238
+ 'builtin:value',
239
+ 'builtin:assignee',
240
+ 'builtin:tags',
241
+ ];
242
+ /** What a field is to a renderer and to a filter. */
243
+ export const opportunityBoardFieldKindSchema = z.enum([
244
+ 'text',
245
+ 'number',
246
+ 'money',
247
+ 'boolean',
248
+ 'date',
249
+ 'select',
250
+ 'multiselect',
251
+ 'organization',
252
+ 'assignee',
253
+ 'salesChannel',
254
+ 'tags',
255
+ 'contact',
256
+ ]);
257
+ export const OpportunityBoardCardFieldSchema = z.object({
258
+ ref: opportunityBoardFieldRefSchema,
259
+ source: z.enum(['builtin', 'custom']),
260
+ key: z.string(),
261
+ kind: opportunityBoardFieldKindSchema,
262
+ /** A custom field's labels per language; empty for a built-in field, which the Admin UI names. */
263
+ label: z.record(z.string(), z.string()),
264
+ labelDefault: z.string().nullable(),
265
+ options: z.array(z.object({ value: z.string(), label: z.record(z.string(), z.string()), labelDefault: z.string() })),
266
+ });
267
+ export const SetOpportunityBoardCardFieldsRequestSchema = z
268
+ .object({
269
+ fields: z
270
+ .array(opportunityBoardFieldRefSchema)
271
+ .max(OPPORTUNITY_BOARD_CARD_MAX_FIELDS)
272
+ .refine((refs) => new Set(refs).size === refs.length, 'A field can be shown once'),
273
+ })
274
+ .strict();
275
+ export const OpportunityBoardCardConfigSchema = z.object({
276
+ /** The stored choice, resolved, in order. */
277
+ fields: z.array(OpportunityBoardCardFieldSchema),
278
+ /** Everything that can be chosen. */
279
+ available: z.array(OpportunityBoardCardFieldSchema),
280
+ maxFields: z.number().int().positive(),
281
+ });
282
+ export const OpportunityBoardCardConfigResponseSchema = dataEnvelope(OpportunityBoardCardConfigSchema);
283
+ /** A bound of a number or an amount, as a decimal string. */
284
+ const fieldFilterNumberSchema = z.string().regex(/^-?\d{1,12}(\.\d{1,4})?$/, 'Not a decimal number');
285
+ /**
286
+ * One field's filter: the operators of every kind in one object. Which of them
287
+ * apply is the field's kind to say; the others are ignored by the server.
288
+ */
289
+ export const OpportunityFieldFilterSchema = z
290
+ .object({
291
+ contains: z.string().trim().min(1).max(200).optional(),
292
+ in: z.array(z.string().min(1).max(200)).min(1).max(50).optional(),
293
+ is: z.boolean().optional(),
294
+ min: fieldFilterNumberSchema.optional(),
295
+ max: fieldFilterNumberSchema.optional(),
296
+ from: calendarDateSchema.optional(),
297
+ to: calendarDateSchema.optional(),
298
+ })
299
+ .strict();
300
+ export const OpportunityFieldFiltersSchema = z
301
+ .record(opportunityBoardFieldRefSchema, OpportunityFieldFilterSchema)
302
+ .refine((filters) => Object.keys(filters).length <= 20, 'Too many field filters');
303
+ /** The `fieldFilters` query parameter: {@link OpportunityFieldFiltersSchema} as JSON. */
304
+ const fieldFiltersParamSchema = z
305
+ .string()
306
+ .max(8000)
307
+ .optional()
308
+ .transform((raw, ctx) => {
309
+ if (raw === undefined || raw === '')
310
+ return undefined;
311
+ let parsed;
312
+ try {
313
+ parsed = JSON.parse(raw);
314
+ }
315
+ catch {
316
+ ctx.addIssue({ code: 'custom', message: 'fieldFilters is not JSON' });
317
+ return z.NEVER;
318
+ }
319
+ const result = OpportunityFieldFiltersSchema.safeParse(parsed);
320
+ if (!result.success) {
321
+ for (const issue of result.error.issues) {
322
+ // Relative to this parameter: the query schema names it already.
323
+ ctx.addIssue({ code: 'custom', message: issue.message, path: [...issue.path] });
324
+ }
325
+ return z.NEVER;
326
+ }
327
+ return result.data;
328
+ });
329
+ /** The filters the list and the board share. */
330
+ const opportunityFilterShape = {
331
+ q: z.string().trim().min(1).max(200).optional(),
332
+ organizationId: z.string().uuid().optional(),
333
+ assignedAdminUserId: assigneeFilterSchema.optional(),
334
+ salesChannelId: z.string().uuid().optional(),
335
+ /** Every tag must be carried (AND). */
336
+ tagId: repeatable(z.string().uuid()),
337
+ createdFrom: calendarDateSchema.optional(),
338
+ createdTo: calendarDateSchema.optional(),
339
+ /** §12c — filters on the fields the board card shows; a field that is not shown is ignored. */
340
+ fieldFilters: fieldFiltersParamSchema,
341
+ };
342
+ export const OpportunityListQuerySchema = z.object({
343
+ ...opportunityFilterShape,
344
+ /** §12c — `true` adds `cardValues` to every summary, as the board answers them. */
345
+ cardValues: z
346
+ .enum(['true', 'false'])
347
+ .optional()
348
+ .transform((flag) => (flag === 'true' ? true : undefined)),
349
+ statusCode: repeatable(opportunityStatusCodeSchema),
350
+ state: opportunityStateSchema.optional(),
351
+ sort: opportunitySortSchema.optional(),
352
+ order: z.enum(['asc', 'desc']).optional(),
353
+ cursor: z.string().optional(),
354
+ limit: z.coerce.number().int().positive().max(200).default(50),
355
+ });
356
+ export const CreateOpportunityRequestSchema = z.object({
357
+ title: z.string().trim().min(1).max(200),
358
+ organizationId: z.string().uuid(),
359
+ currency: currencyCodeSchema,
360
+ description: z.string().max(20_000).nullable().optional(),
361
+ customerAccountId: z.string().uuid().nullable().optional(),
362
+ salesChannelId: z.string().uuid().nullable().optional(),
363
+ /** `null` = explicitly unassigned; absent = apply the default-assignee rule. */
364
+ assignedAdminUserId: z.string().uuid().nullable().optional(),
365
+ valueMode: opportunityValueModeSchema.optional(),
366
+ manualValue: decimalAmountSchema.nullable().optional(),
367
+ expectedCloseDate: calendarDateSchema.nullable().optional(),
368
+ tagIds: z.array(z.string().uuid()).max(50).optional(),
369
+ // §12a (US15) — operator-defined fields, keyed by definition key. On an edit,
370
+ // absent means "leave the values as they are".
371
+ customFieldValues: customFieldValuesSchema.optional(),
372
+ });
373
+ /**
374
+ * Every create field except the two immutable ones. Strict, so a body naming
375
+ * `organizationId` or `currency` is refused instead of silently ignored.
376
+ */
377
+ export const UpdateOpportunityRequestSchema = CreateOpportunityRequestSchema.omit({
378
+ organizationId: true,
379
+ currency: true,
380
+ })
381
+ .partial()
382
+ .strict();
383
+ export const OpportunityStatusRefSchema = z.object({
384
+ code: z.string(),
385
+ name: z.string(),
386
+ color: z.string(),
387
+ kind: opportunityStatusKindSchema,
388
+ });
389
+ export const OpportunityTagRefSchema = z.object({
390
+ id: z.string().uuid(),
391
+ name: z.string(),
392
+ color: z.string(),
393
+ });
394
+ export const OpportunitySummarySchema = z.object({
395
+ id: z.string().uuid(),
396
+ number: z.string(),
397
+ title: z.string(),
398
+ organization: z.object({ id: z.string().uuid(), name: z.string() }),
399
+ status: OpportunityStatusRefSchema,
400
+ assignee: z.object({ id: z.string().uuid(), name: z.string(), active: z.boolean() }).nullable(),
401
+ /** The effective value: `manualValue` or `computedValue`, by `valueMode`. */
402
+ value: z.string().nullable(),
403
+ valueMode: opportunityValueModeSchema,
404
+ currency: z.string(),
405
+ salesChannelId: z.string().uuid().nullable(),
406
+ expectedCloseDate: z.string().nullable(),
407
+ tags: z.array(OpportunityTagRefSchema),
408
+ closedAt: isoTimestampSchema.nullable(),
409
+ closedKind: opportunityClosedKindSchema.nullable(),
410
+ createdAt: isoTimestampSchema,
411
+ updatedAt: isoTimestampSchema,
412
+ /**
413
+ * §12c — the values of the board card's chosen fields this summary does not
414
+ * carry as a member of its own, keyed by field reference. Present only where
415
+ * it was asked for: the board, and the list with `cardValues=true`.
416
+ */
417
+ cardValues: z.record(z.string(), z.unknown()).optional(),
418
+ });
419
+ // ---------------------------------------------------------------------------
420
+ // §3 Links
421
+ // ---------------------------------------------------------------------------
422
+ export const CreateOpportunityLinkRequestSchema = z.object({
423
+ documentKind: opportunityDocumentKindSchema,
424
+ documentId: z.string().uuid(),
425
+ syncStatus: z.boolean().optional(),
426
+ });
427
+ export const UpdateOpportunityLinkRequestSchema = z.object({
428
+ syncStatus: z.boolean(),
429
+ });
430
+ /**
431
+ * A linked document. `number`, `status`, `total` and `currency` are present
432
+ * only when `available` — a document the reader may not see, or whose owning
433
+ * module is switched off, renders as unavailable.
434
+ */
435
+ export const OpportunityLinkSchema = z.object({
436
+ id: z.string().uuid(),
437
+ documentKind: opportunityDocumentKindSchema,
438
+ documentId: z.string().uuid(),
439
+ available: z.boolean(),
440
+ number: z.string().optional(),
441
+ status: z.string().optional(),
442
+ total: z.string().optional(),
443
+ currency: z.string().optional(),
444
+ syncStatus: z.boolean(),
445
+ linkSource: opportunityLinkSourceSchema,
446
+ createdAt: isoTimestampSchema,
447
+ });
448
+ // ---------------------------------------------------------------------------
449
+ // §2 Transition
450
+ // ---------------------------------------------------------------------------
451
+ export const TransitionOpportunityRequestSchema = z.object({
452
+ to: opportunityStatusCodeSchema,
453
+ reason: z.string().max(2000).nullable().optional(),
454
+ });
455
+ export const PropagationOutcomeSchema = z.object({
456
+ id: z.string().uuid(),
457
+ orderId: z.string().uuid(),
458
+ orderNumber: z.string().nullable(),
459
+ direction: orderStatusMappingDirectionSchema,
460
+ orderStatusCode: z.string(),
461
+ outcome: propagationOutcomeKindSchema.exclude(['pending']),
462
+ detail: z.string().nullable(),
463
+ createdAt: isoTimestampSchema,
464
+ });
465
+ export const OpportunityExcludedDocumentSchema = z.object({
466
+ kind: opportunityDocumentKindSchema,
467
+ id: z.string().uuid(),
468
+ reason: z.string(),
469
+ });
470
+ export const OpportunityDetailSchema = OpportunitySummarySchema.extend({
471
+ description: z.string().nullable(),
472
+ references: z.array(OpportunityReferenceSchema),
473
+ customerAccount: z
474
+ .object({ id: z.string().uuid(), name: z.string(), email: z.string() })
475
+ .nullable(),
476
+ manualValue: z.string().nullable(),
477
+ computedValue: z.string(),
478
+ excludedDocuments: z.array(OpportunityExcludedDocumentSchema),
479
+ source: opportunitySourceSchema,
480
+ version: z.number().int(),
481
+ allowedTransitions: z.array(OpportunityStatusRefSchema),
482
+ links: z.array(OpportunityLinkSchema),
483
+ unresolvedPropagations: z.array(PropagationOutcomeSchema),
484
+ // §12a (US15) — the values of the fields defined today; a value whose
485
+ // definition was removed is not returned.
486
+ customFieldValues: customFieldValuesSchema,
487
+ // §12d (US21) — the Opportunity's Events that have not ended yet. It is what
488
+ // the *Events* tab's label carries, so the tab strip needs no second request.
489
+ upcomingEventCount: z.number().int().nonnegative(),
490
+ });
491
+ export const OpportunityTransitionResultSchema = z.object({
492
+ opportunity: OpportunityDetailSchema,
493
+ from: z.string(),
494
+ to: z.string(),
495
+ propagation: z.array(PropagationOutcomeSchema),
496
+ });
497
+ export const OpportunityListResponseSchema = collectionEnvelope(OpportunitySummarySchema);
498
+ // §12b (US17) — the Opportunity a document is linked to, or `null` for a
499
+ // document that exists, is visible to the caller and is linked to none.
500
+ export const OpportunityOfDocumentResponseSchema = dataEnvelope(OpportunitySummarySchema.nullable());
501
+ export const OpportunityDetailResponseSchema = dataEnvelope(OpportunityDetailSchema);
502
+ export const OpportunityLinkResponseSchema = dataEnvelope(OpportunityLinkSchema);
503
+ export const OpportunityTransitionResponseSchema = dataEnvelope(OpportunityTransitionResultSchema);
504
+ export const PropagationOutcomeResponseSchema = dataEnvelope(PropagationOutcomeSchema);
505
+ // ---------------------------------------------------------------------------
506
+ // §4 Workflow configuration
507
+ // ---------------------------------------------------------------------------
508
+ export const CreateOpportunityStatusRequestSchema = z.object({
509
+ code: opportunityStatusCodeSchema,
510
+ name: statusNameSchema.optional(),
511
+ defaultName: z.string().trim().min(1).max(120),
512
+ kind: opportunityStatusKindSchema,
513
+ isInitial: z.boolean().optional(),
514
+ weight: z.number().int().min(0).max(100_000).optional(),
515
+ color: colorSchema.optional(),
516
+ });
517
+ /** `code` is immutable; strict, so a body naming it is refused. */
518
+ export const UpdateOpportunityStatusRequestSchema = CreateOpportunityStatusRequestSchema.omit({
519
+ code: true,
520
+ })
521
+ .partial()
522
+ .strict();
523
+ export const OpportunityTransitionEdgeSchema = z
524
+ .object({
525
+ fromStatusCode: opportunityStatusCodeSchema,
526
+ toStatusCode: opportunityStatusCodeSchema,
527
+ })
528
+ .refine((edge) => edge.fromStatusCode !== edge.toStatusCode, {
529
+ message: 'A transition must connect two different statuses',
530
+ });
531
+ export const SetOpportunityTransitionsRequestSchema = z.object({
532
+ add: z.array(OpportunityTransitionEdgeSchema).max(500).optional(),
533
+ remove: z.array(OpportunityTransitionEdgeSchema).max(500).optional(),
534
+ });
535
+ export const OrderStatusMappingSchema = z.object({
536
+ direction: orderStatusMappingDirectionSchema,
537
+ opportunityStatusCode: opportunityStatusCodeSchema,
538
+ /** An Order status code, by value — the Order workflow is the operator's. */
539
+ orderStatusCode: z.string().min(1).max(64),
540
+ /** Meaningful for `order_to_opportunity` only. */
541
+ requireAllOrders: z.boolean().optional(),
542
+ });
543
+ /** Replaces the whole set. */
544
+ export const SetOrderStatusMappingsRequestSchema = z.object({
545
+ mappings: z.array(OrderStatusMappingSchema).max(500),
546
+ });
547
+ export const SetValueCountingStatusesRequestSchema = z.object({
548
+ order: z.array(z.string().min(1).max(64)).max(200),
549
+ quoteRequest: z.array(quoteRequestStatusValueSchema).max(QUOTE_REQUEST_STATUS_VALUES.length),
550
+ });
551
+ export const OpportunityWorkflowStatusSchema = z.object({
552
+ code: z.string(),
553
+ name: z.record(z.string(), z.string()),
554
+ defaultName: z.string(),
555
+ kind: opportunityStatusKindSchema,
556
+ isInitial: z.boolean(),
557
+ weight: z.number().int(),
558
+ color: z.string(),
559
+ /** Opportunities currently in this status that the caller may see. */
560
+ inUseCount: z.number().int().nonnegative(),
561
+ });
562
+ export const OpportunityWorkflowSchema = z.object({
563
+ statuses: z.array(OpportunityWorkflowStatusSchema),
564
+ transitions: z.array(z.object({ fromStatusCode: z.string(), toStatusCode: z.string() })),
565
+ orderStatusMappings: z.array(z.object({
566
+ direction: orderStatusMappingDirectionSchema,
567
+ opportunityStatusCode: z.string(),
568
+ orderStatusCode: z.string(),
569
+ requireAllOrders: z.boolean(),
570
+ /** `false` once the Order status the mapping names no longer exists. */
571
+ orderStatusKnown: z.boolean(),
572
+ })),
573
+ valueCountingStatuses: z.object({
574
+ order: z.array(z.string()),
575
+ quoteRequest: z.array(z.string()),
576
+ }),
577
+ });
578
+ export const OpportunityWorkflowResponseSchema = dataEnvelope(OpportunityWorkflowSchema);
579
+ // ---------------------------------------------------------------------------
580
+ // §5 Assignment
581
+ // ---------------------------------------------------------------------------
582
+ export const AssignOpportunityRequestSchema = z.object({
583
+ adminUserId: z.string().uuid().nullable(),
584
+ });
585
+ // ---------------------------------------------------------------------------
586
+ // §6 Notes and messages
587
+ // ---------------------------------------------------------------------------
588
+ const commentBodySchema = z.string().min(1).max(10_000);
589
+ export const OpportunityCommentListQuerySchema = z.object({
590
+ kind: opportunityCommentKindSchema,
591
+ });
592
+ export const CreateOpportunityCommentRequestSchema = z.object({
593
+ kind: opportunityCommentKindSchema,
594
+ body: commentBodySchema,
595
+ });
596
+ export const UpdateOpportunityCommentRequestSchema = z.object({
597
+ body: commentBodySchema,
598
+ });
599
+ export const OpportunityCommentSchema = z.object({
600
+ id: z.string().uuid(),
601
+ kind: opportunityCommentKindSchema,
602
+ author: z.object({ id: z.string().uuid(), name: z.string() }),
603
+ body: z.string(),
604
+ references: z.array(OpportunityReferenceSchema),
605
+ editedAt: isoTimestampSchema.nullable(),
606
+ createdAt: isoTimestampSchema,
607
+ });
608
+ export const OpportunityCommentResponseSchema = dataEnvelope(OpportunityCommentSchema);
609
+ export const OpportunityCommentListResponseSchema = dataEnvelope(z.array(OpportunityCommentSchema));
610
+ // ---------------------------------------------------------------------------
611
+ // §7 Attachments
612
+ // ---------------------------------------------------------------------------
613
+ export const CreateOpportunityAttachmentRequestSchema = z.object({
614
+ assetId: z.string().uuid(),
615
+ });
616
+ export const OpportunityAttachmentSchema = z.object({
617
+ id: z.string().uuid(),
618
+ assetId: z.string().uuid(),
619
+ fileName: z.string(),
620
+ mimeType: z.string(),
621
+ sizeBytes: z.number().int().nonnegative(),
622
+ url: z.string().nullable(),
623
+ uploadedBy: z.object({ id: z.string().uuid(), name: z.string() }),
624
+ createdAt: isoTimestampSchema,
625
+ });
626
+ export const OpportunityAttachmentResponseSchema = dataEnvelope(OpportunityAttachmentSchema);
627
+ export const OpportunityAttachmentListResponseSchema = dataEnvelope(z.array(OpportunityAttachmentSchema));
628
+ /**
629
+ * §7a — the largest file `POST /opportunities/:id/attachments/upload` reads,
630
+ * in bytes (25 MB). The route holds the whole file in memory before the media
631
+ * library decides anything about it, so this is the bound on what one request
632
+ * may make the process allocate; what a file may otherwise *be* — its type, a
633
+ * smaller size limit — is the media library's upload policy, applied as it is
634
+ * for any other upload. The screen reads it to refuse a larger file before
635
+ * sending it. Above it: 413 `CRM_ATTACHMENT_TOO_LARGE`.
636
+ */
637
+ export const OPPORTUNITY_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
638
+ // ---------------------------------------------------------------------------
639
+ // §8 Tags
640
+ // ---------------------------------------------------------------------------
641
+ const tagNameSchema = z.string().trim().min(1).max(64);
642
+ export const CreateOpportunityTagRequestSchema = z.object({
643
+ name: tagNameSchema,
644
+ color: colorSchema.optional(),
645
+ });
646
+ export const UpdateOpportunityTagRequestSchema = z.object({
647
+ name: tagNameSchema.optional(),
648
+ color: colorSchema.optional(),
649
+ });
650
+ /** Replaces the Opportunity's whole tag set. */
651
+ export const SetOpportunityTagsRequestSchema = z.object({
652
+ tagIds: z.array(z.string().uuid()).max(50),
653
+ });
654
+ export const OpportunityTagSchema = OpportunityTagRefSchema.extend({
655
+ /** Opportunities carrying the tag that the caller may see. */
656
+ usageCount: z.number().int().nonnegative(),
657
+ });
658
+ export const OpportunityTagResponseSchema = dataEnvelope(OpportunityTagSchema);
659
+ export const OpportunityTagListResponseSchema = dataEnvelope(z.array(OpportunityTagSchema));
660
+ // ---------------------------------------------------------------------------
661
+ // §10 Board
662
+ // ---------------------------------------------------------------------------
663
+ /** The list filters minus `statusCode` / `state` — the columns *are* the statuses. */
664
+ export const OpportunityBoardQuerySchema = z.object({
665
+ ...opportunityFilterShape,
666
+ perColumn: z.coerce.number().int().positive().max(200).default(50),
667
+ });
668
+ export const OpportunityCurrencyTotalSchema = z.object({
669
+ currency: z.string(),
670
+ total: z.string(),
671
+ });
672
+ export const OpportunityBoardColumnSchema = z.object({
673
+ status: OpportunityStatusRefSchema,
674
+ count: z.number().int().nonnegative(),
675
+ valueTotals: z.array(OpportunityCurrencyTotalSchema),
676
+ items: z.array(OpportunitySummarySchema),
677
+ hasMore: z.boolean(),
678
+ });
679
+ export const OpportunityBoardSchema = z.object({
680
+ columns: z.array(OpportunityBoardColumnSchema),
681
+ /** §12c — the fields a card shows, in order; what `cardValues` and `fieldFilters` refer to. */
682
+ cardFields: z.array(OpportunityBoardCardFieldSchema),
683
+ });
684
+ export const OpportunityBoardResponseSchema = dataEnvelope(OpportunityBoardSchema);
685
+ // ---------------------------------------------------------------------------
686
+ // §10a Lookups — what the CRM screens' pickers choose from
687
+ // ---------------------------------------------------------------------------
688
+ //
689
+ // The Organization, Sales Channel, assignee and contact-person pickers of the
690
+ // CRM screens read from CRM's own endpoints, gated by CRM's own codes, and not
691
+ // from the admin lists of the modules that own those rows: a Sales Rep holding
692
+ // `crm:read` / `crm:write` holds neither `customers:read`, `sales_channels:read`
693
+ // nor `admin_users:manage`, and must not need them to fill in a form
694
+ // (`specs/143-crm-sales-opportunities/research.md` N-D4). Each answer is the
695
+ // minimum a picker shows — an id and a label.
696
+ const lookupLimitSchema = z.coerce.number().int().positive().max(50).default(20);
697
+ const lookupSearchSchema = z.string().trim().max(200).optional();
698
+ /** `id` asks for one Organization by id (the label of a preselection); `q` searches by name. */
699
+ export const OpportunityOrganizationLookupQuerySchema = z.object({
700
+ q: lookupSearchSchema,
701
+ id: z.string().uuid().optional(),
702
+ limit: lookupLimitSchema,
703
+ });
704
+ export const OpportunityOrganizationOptionSchema = z.object({
705
+ id: z.string().uuid(),
706
+ name: z.string(),
707
+ });
708
+ export const OpportunityOrganizationLookupResponseSchema = dataEnvelope(z.array(OpportunityOrganizationOptionSchema));
709
+ /** `name` is per language, as the channel stores it; the screen resolves it. */
710
+ export const OpportunitySalesChannelOptionSchema = z.object({
711
+ id: z.string().uuid(),
712
+ code: z.string(),
713
+ name: z.record(z.string(), z.string()),
714
+ active: z.boolean(),
715
+ systemDefault: z.boolean(),
716
+ /** The currencies the channel sells in — what an Opportunity's currency is chosen from. */
717
+ defaultCurrency: z.string(),
718
+ currencies: z.array(z.string()),
719
+ });
720
+ export const OpportunitySalesChannelLookupResponseSchema = dataEnvelope(z.array(OpportunitySalesChannelOptionSchema));
721
+ export const OpportunityAssigneeLookupQuerySchema = z.object({
722
+ q: lookupSearchSchema,
723
+ limit: lookupLimitSchema,
724
+ });
725
+ /** An administrator who may be assigned — active ones only, by name. */
726
+ export const OpportunityAssigneeOptionSchema = z.object({
727
+ id: z.string().uuid(),
728
+ name: z.string(),
729
+ });
730
+ export const OpportunityAssigneeLookupResponseSchema = dataEnvelope(z.array(OpportunityAssigneeOptionSchema));
731
+ /**
732
+ * Who may be mentioned in a text (User Story 18). With `organizationId` — the
733
+ * Opportunity's — only people who may see that Organization are offered.
734
+ */
735
+ export const OpportunityMentionLookupQuerySchema = z.object({
736
+ q: lookupSearchSchema,
737
+ organizationId: z.string().uuid().optional(),
738
+ limit: lookupLimitSchema,
739
+ });
740
+ /** A person to mention: a name to choose by — no e-mail address, no role. */
741
+ export const OpportunityMentionOptionSchema = z.object({
742
+ id: z.string().uuid(),
743
+ name: z.string(),
744
+ });
745
+ export const OpportunityMentionLookupResponseSchema = dataEnvelope(z.array(OpportunityMentionOptionSchema));
746
+ export const OpportunityContactLookupQuerySchema = z.object({
747
+ organizationId: z.string().uuid(),
748
+ q: lookupSearchSchema,
749
+ limit: lookupLimitSchema,
750
+ });
751
+ /** A member of the Organization who may be the Opportunity's contact person. */
752
+ export const OpportunityContactOptionSchema = z.object({
753
+ id: z.string().uuid(),
754
+ name: z.string(),
755
+ email: z.string(),
756
+ });
757
+ export const OpportunityContactLookupResponseSchema = dataEnvelope(z.array(OpportunityContactOptionSchema));
758
+ /**
759
+ * The Quote Requests of one Organization that can still be linked — the open
760
+ * ones, plus the one whose number is typed in full. Gated by CRM's own code:
761
+ * the quote desk's list is behind `rfqs:handle`, the right to handle quotes,
762
+ * which linking one to an Opportunity does not need (research N-H2).
763
+ */
764
+ export const OpportunityQuoteRequestLookupQuerySchema = z.object({
765
+ organizationId: z.string().uuid(),
766
+ q: lookupSearchSchema,
767
+ limit: lookupLimitSchema,
768
+ });
769
+ export const OpportunityQuoteRequestOptionSchema = z.object({
770
+ id: z.string().uuid(),
771
+ number: z.string(),
772
+ status: z.string(),
773
+ });
774
+ export const OpportunityQuoteRequestLookupResponseSchema = dataEnvelope(z.array(OpportunityQuoteRequestOptionSchema));
775
+ // ---------------------------------------------------------------------------
776
+ // §11 History
777
+ // ---------------------------------------------------------------------------
778
+ export const OpportunityHistoryQuerySchema = z.object({
779
+ limit: z.coerce.number().int().positive().max(200).default(50),
780
+ cursor: z.string().optional(),
781
+ });
782
+ export const OpportunityHistoryEntrySchema = z.object({
783
+ id: z.string(),
784
+ actedAt: isoTimestampSchema,
785
+ action: z.string(),
786
+ actor: z.object({
787
+ kind: z.string(),
788
+ id: z.string().nullable(),
789
+ name: z.string().nullable(),
790
+ }),
791
+ before: z.unknown().nullable(),
792
+ after: z.unknown().nullable(),
793
+ /**
794
+ * What the tokens in this entry's texts — a description as it was and as it
795
+ * is — name for this reader (§9), so the history shows names and not codes.
796
+ */
797
+ references: z.array(OpportunityReferenceSchema),
798
+ });
799
+ /**
800
+ * `truncated` is beside `pagination` and not part of it: `hasMore` goes on
801
+ * meaning "there is a next page to ask for". It is `true` on the last page a
802
+ * history can serve when the Opportunity has earlier entries beyond it — the
803
+ * history reaches a fixed way back — and `false` on every other page.
804
+ */
805
+ export const OpportunityHistoryResponseSchema = collectionEnvelope(OpportunityHistoryEntrySchema).extend({
806
+ truncated: z.boolean(),
807
+ });
808
+ // ---------------------------------------------------------------------------
809
+ // §12 Analytics
810
+ // ---------------------------------------------------------------------------
811
+ const analyticsRangeShape = {
812
+ from: calendarDateSchema,
813
+ to: calendarDateSchema,
814
+ salesChannelId: z.string().uuid().optional(),
815
+ assignedAdminUserId: z.string().uuid().optional(),
816
+ };
817
+ export const OpportunityAnalyticsQuerySchema = z.object(analyticsRangeShape);
818
+ export const OpportunityTimeInStatusQuerySchema = z.object({
819
+ ...analyticsRangeShape,
820
+ statusCode: repeatable(opportunityStatusCodeSchema),
821
+ });
822
+ export const TopOpportunitiesQuerySchema = z.object({
823
+ ...analyticsRangeShape,
824
+ limit: z.coerce.number().int().positive().max(100).default(10),
825
+ basis: z.enum(['created', 'closed']).default('created'),
826
+ });
827
+ export const OpportunityHandlingTimeSchema = z.object({
828
+ averageSeconds: z.number().nullable(),
829
+ closedCount: z.number().int().nonnegative(),
830
+ byOutcome: z.object({
831
+ won: z.object({ averageSeconds: z.number().nullable(), closedCount: z.number().int() }),
832
+ lost: z.object({ averageSeconds: z.number().nullable(), closedCount: z.number().int() }),
833
+ }),
834
+ });
835
+ export const OpportunityTimeInStatusRowSchema = z.object({
836
+ statusCode: z.string(),
837
+ averageSeconds: z.number().nullable(),
838
+ sampleCount: z.number().int().nonnegative(),
839
+ });
840
+ export const OpportunityRepEffectivenessRowSchema = z.object({
841
+ /** `YYYY-MM`. */
842
+ month: z.string(),
843
+ adminUser: z.object({ id: z.string().uuid(), name: z.string() }),
844
+ wonCount: z.number().int().nonnegative(),
845
+ wonValue: z.array(OpportunityCurrencyTotalSchema),
846
+ });
847
+ export const OpportunityAverageValueRowSchema = z.object({
848
+ currency: z.string(),
849
+ average: z.string(),
850
+ count: z.number().int().nonnegative(),
851
+ });
852
+ export const OpportunityHandlingTimeResponseSchema = dataEnvelope(OpportunityHandlingTimeSchema);
853
+ export const OpportunityTimeInStatusResponseSchema = dataEnvelope(z.array(OpportunityTimeInStatusRowSchema));
854
+ export const OpportunityRepEffectivenessResponseSchema = dataEnvelope(z.array(OpportunityRepEffectivenessRowSchema));
855
+ export const TopOpportunitiesResponseSchema = dataEnvelope(z.array(OpportunitySummarySchema));
856
+ export const OpportunityAverageValueResponseSchema = dataEnvelope(z.array(OpportunityAverageValueRowSchema));
857
+ // ---------------------------------------------------------------------------
858
+ // §12d Events on an Opportunity and the Calendar (US21, US22)
859
+ // ---------------------------------------------------------------------------
860
+ //
861
+ // "Event" here is an entry in a calendar — a meeting, a call, a deadline. The
862
+ // in-process events the module publishes are the next section's.
863
+ /**
864
+ * The longest an Event may be. An Event is one calendar day in its own zone,
865
+ * and the day a clock goes back is 25 hours long — so this is the bound that
866
+ * needs no zone data, and "one local day" is the service's to refuse.
867
+ */
868
+ export const OPPORTUNITY_EVENT_MAX_SPAN_HOURS = 25;
869
+ /**
870
+ * The widest range a Calendar read may ask for: the six-week month grid (42
871
+ * days), a day each side for an all-day Event of a far zone, and one.
872
+ */
873
+ export const CALENDAR_EVENTS_MAX_RANGE_DAYS = 45;
874
+ /** A Calendar read answers this many Events at most, and says when it cut. */
875
+ export const CALENDAR_EVENTS_MAX_RESULTS = 500;
876
+ const HOUR_MS = 60 * 60 * 1000;
877
+ const DAY_MS = 24 * HOUR_MS;
878
+ /**
879
+ * Why a well-formed Event is refused — `details.rule` of a 422
880
+ * `VALIDATION_FAILED`, beside `details.field`. The first is also refused by
881
+ * the schema when both instants arrive in one body (400); the service repeats
882
+ * it for an edit that names one of them.
883
+ */
884
+ export const opportunityEventRuleSchema = z.enum([
885
+ 'ends_before_start',
886
+ 'spans_days',
887
+ 'not_whole_day',
888
+ 'unknown_time_zone',
889
+ 'reminder_in_past',
890
+ ]);
891
+ /**
892
+ * What became of an Event's reminder, folded for a reader: `paused` is
893
+ * `scheduled` on a closed Opportunity and is derived on read, and a reminder
894
+ * being sent right now is reported as `scheduled`.
895
+ */
896
+ export const opportunityEventReminderStateSchema = z.enum([
897
+ 'scheduled',
898
+ 'paused',
899
+ 'sent',
900
+ 'missed',
901
+ 'no_recipient',
902
+ 'undeliverable',
903
+ 'interrupted',
904
+ ]);
905
+ export const opportunityEventReminderChannelSchema = z.enum(['bell', 'email']);
906
+ export const calendarScopeSchema = z.enum(['mine', 'all']);
907
+ /**
908
+ * An instant of an Event, of a reminder or of a Calendar range: one the
909
+ * database holds and every zone can date.
910
+ *
911
+ * `isoDateTimeSchema` accepts any four-digit year **as written**, and an offset
912
+ * carries `9999-12-31T22:00:00-14:00` into the year 10000 — which JavaScript
913
+ * serialises with a signed six-digit year and PostgreSQL refuses, so the
914
+ * request used to end in a 500 (research N-CALR4). The range is the years
915
+ * 0001 – 9999 in UTC **less two days at each end**: the local date of an
916
+ * instant in any zone, and the 25 hours the Calendar read looks back before
917
+ * its `from`, then stay inside four-digit years as well.
918
+ */
919
+ const EVENT_INSTANT_MIN_MS = Date.parse('0001-01-03T00:00:00.000Z');
920
+ const EVENT_INSTANT_MAX_MS = Date.parse('9999-12-30T00:00:00.000Z');
921
+ const eventInstantSchema = isoDateTimeSchema
922
+ .refine((value) => {
923
+ const instant = Date.parse(value);
924
+ return instant >= EVENT_INSTANT_MIN_MS && instant < EVENT_INSTANT_MAX_MS;
925
+ }, 'The instant must lie between 0001-01-03 and 9999-12-30 (UTC)')
926
+ .describe('ISO-8601 datetime with offset, e.g. 2026-04-23T10:15:30.000Z');
927
+ const opportunityEventWriteShape = {
928
+ name: z.string().trim().min(1).max(200),
929
+ /** Plain text; reference tokens are not parsed. */
930
+ description: z.string().max(5000).nullable().optional(),
931
+ allDay: z.boolean(),
932
+ /** For an all-day Event, the local midnight that starts its date. */
933
+ startsAt: eventInstantSchema,
934
+ /** Exclusive. For an all-day Event, the next local midnight. */
935
+ endsAt: eventInstantSchema,
936
+ /**
937
+ * The IANA zone the times were chosen in —
938
+ * `Intl.DateTimeFormat().resolvedOptions().timeZone` in the browser. Whether
939
+ * the runtime knows the zone is the service's to say (`unknown_time_zone`).
940
+ */
941
+ timeZone: z.string().min(1).max(64),
942
+ /** `null` or absent = no reminder. Must be later than now — the service's rule. */
943
+ remindAt: eventInstantSchema.nullable().optional(),
944
+ };
945
+ /**
946
+ * The two rules that need neither a clock nor zone data. They are judged only
947
+ * when both instants are present, which on a create is always and on an edit
948
+ * is when the body names both.
949
+ */
950
+ function refineEventSpan(value, ctx) {
951
+ if (value.startsAt === undefined || value.endsAt === undefined)
952
+ return;
953
+ const span = Date.parse(value.endsAt) - Date.parse(value.startsAt);
954
+ if (span <= 0) {
955
+ ctx.addIssue({ code: 'custom', path: ['endsAt'], message: 'An Event ends after it starts' });
956
+ }
957
+ else if (span > OPPORTUNITY_EVENT_MAX_SPAN_HOURS * HOUR_MS) {
958
+ ctx.addIssue({
959
+ code: 'custom',
960
+ path: ['endsAt'],
961
+ message: `An Event is at most ${OPPORTUNITY_EVENT_MAX_SPAN_HOURS} hours long`,
962
+ });
963
+ }
964
+ }
965
+ export const CreateOpportunityEventRequestSchema = z
966
+ .object(opportunityEventWriteShape)
967
+ .superRefine(refineEventSpan);
968
+ /**
969
+ * Every member of the create, all optional; strict, so a body naming anything
970
+ * else is refused instead of ignored. The rules are applied by the service to
971
+ * the Event **as it would be after the change**; `remindAt: null` removes the
972
+ * reminder and a different `remindAt` arms it again.
973
+ */
974
+ export const UpdateOpportunityEventRequestSchema = z
975
+ .object(opportunityEventWriteShape)
976
+ .partial()
977
+ .strict()
978
+ .superRefine(refineEventSpan);
979
+ export const OpportunityEventReminderSchema = z
980
+ .object({
981
+ at: isoDateTimeSchema,
982
+ state: opportunityEventReminderStateSchema,
983
+ handledAt: isoDateTimeSchema.nullable(),
984
+ channels: z.array(opportunityEventReminderChannelSchema),
985
+ })
986
+ .refine((reminder) => (reminder.state === 'sent') === reminder.channels.length > 0, {
987
+ path: ['channels'],
988
+ message: 'channels is non-empty exactly when the reminder was sent',
989
+ });
990
+ export const OpportunityEventSchema = z.object({
991
+ id: z.string().uuid(),
992
+ opportunityId: z.string().uuid(),
993
+ name: z.string(),
994
+ description: z.string().nullable(),
995
+ allDay: z.boolean(),
996
+ /** UTC instants ("Z"); `endsAt` is exclusive. */
997
+ startsAt: isoDateTimeSchema,
998
+ endsAt: isoDateTimeSchema,
999
+ timeZone: z.string(),
1000
+ /**
1001
+ * The date of an all-day Event, computed by the server in `timeZone`; `null`
1002
+ * for a timed one. A calendar places an all-day Event by this, whatever the
1003
+ * reader's own zone.
1004
+ */
1005
+ allDayDate: calendarDateSchema.nullable(),
1006
+ reminder: OpportunityEventReminderSchema.nullable(),
1007
+ createdBy: z.object({ id: z.string().uuid(), name: z.string() }).nullable(),
1008
+ createdAt: isoTimestampSchema,
1009
+ updatedAt: isoTimestampSchema,
1010
+ });
1011
+ export const OpportunityEventResponseSchema = dataEnvelope(OpportunityEventSchema);
1012
+ export const OpportunityEventListResponseSchema = dataEnvelope(z.array(OpportunityEventSchema));
1013
+ /**
1014
+ * `GET /calendar/events`. `from` is inclusive and `to` exclusive; an Event is
1015
+ * in the answer when it overlaps the range. `scope` absent = the caller's
1016
+ * default, and the server decides what is honoured: `all` asked by a caller
1017
+ * confined to some Organizations is answered as `mine`, not refused.
1018
+ *
1019
+ * Write the instants in UTC (`Date#toISOString`): a `+` of an offset in a
1020
+ * query string that is not percent-encoded arrives as a space.
1021
+ */
1022
+ export const CalendarEventsQuerySchema = z
1023
+ .object({
1024
+ from: eventInstantSchema,
1025
+ to: eventInstantSchema,
1026
+ scope: calendarScopeSchema.optional(),
1027
+ })
1028
+ .superRefine((value, ctx) => {
1029
+ const span = Date.parse(value.to) - Date.parse(value.from);
1030
+ if (span <= 0) {
1031
+ ctx.addIssue({ code: 'custom', path: ['to'], message: 'The range ends after it starts' });
1032
+ }
1033
+ else if (span > CALENDAR_EVENTS_MAX_RANGE_DAYS * DAY_MS) {
1034
+ ctx.addIssue({
1035
+ code: 'custom',
1036
+ path: ['to'],
1037
+ message: `The range is at most ${CALENDAR_EVENTS_MAX_RANGE_DAYS} days`,
1038
+ });
1039
+ }
1040
+ });
1041
+ /** What a calendar draws and nothing more — deliberately no description. */
1042
+ export const CalendarEventSchema = z.object({
1043
+ id: z.string().uuid(),
1044
+ name: z.string(),
1045
+ allDay: z.boolean(),
1046
+ startsAt: isoDateTimeSchema,
1047
+ endsAt: isoDateTimeSchema,
1048
+ allDayDate: calendarDateSchema.nullable(),
1049
+ hasReminder: z.boolean(),
1050
+ opportunity: z.object({
1051
+ id: z.string().uuid(),
1052
+ number: z.string(),
1053
+ title: z.string(),
1054
+ assignee: z.object({ id: z.string().uuid(), name: z.string() }).nullable(),
1055
+ }),
1056
+ });
1057
+ /**
1058
+ * `scope` is the one applied and `scopes` the ones this caller may ask for;
1059
+ * `truncated` says more than `CALENDAR_EVENTS_MAX_RESULTS` Events matched and
1060
+ * the first by `startsAt`, then `id`, were returned.
1061
+ */
1062
+ export const CalendarEventsMetaSchema = z.object({
1063
+ scope: calendarScopeSchema,
1064
+ scopes: z.array(calendarScopeSchema).min(1),
1065
+ truncated: z.boolean(),
1066
+ });
1067
+ export const CalendarEventsResponseSchema = z.object({
1068
+ data: z.array(CalendarEventSchema),
1069
+ meta: CalendarEventsMetaSchema,
1070
+ });
1071
+ /**
1072
+ * The concrete name of one of the four templated status events. Statuses are
1073
+ * configured at runtime, so the names are not known at compile time — this is
1074
+ * the one place the scheme is written, for the emitter and every subscriber.
1075
+ */
1076
+ export function opportunityStatusEventName(kind, p) {
1077
+ switch (kind) {
1078
+ case 'fromToBefore':
1079
+ return `crm.opportunity.status.from_${p.from}_to_${p.to}.before`;
1080
+ case 'fromBefore':
1081
+ return `crm.opportunity.status.from_${p.from}.before`;
1082
+ case 'fromToAfter':
1083
+ return `crm.opportunity.status.from_${p.from}_to_${p.to}.after`;
1084
+ case 'toAfter':
1085
+ return `crm.opportunity.status.to_${p.to}.after`;
1086
+ }
1087
+ }
1088
+ /** The fixed event names CRM emits. */
1089
+ export const CRM_EVENTS = {
1090
+ STATUS_CHANGED: 'crm.opportunity.status_changed.v1',
1091
+ CREATED: 'crm.opportunity.created.v1',
1092
+ CLOSED: 'crm.opportunity.closed.v1',
1093
+ ASSIGNED: 'crm.opportunity.assigned.v1',
1094
+ DOCUMENT_LINKED: 'crm.opportunity.document_linked.v1',
1095
+ };
1096
+ // ---------------------------------------------------------------------------
1097
+ // Events offered to outbound webhooks (`contracts/events-and-ports.md` §6)
1098
+ // ---------------------------------------------------------------------------
1099
+ //
1100
+ // The webhook delivery bridge serialises an event whole, so for these three
1101
+ // **the event payload is the webhook payload** — a public, versioned contract.
1102
+ // Each has a strict schema, the payload type is inferred from it (one
1103
+ // definition), and a test holds every event the module emits to it. Adding a
1104
+ // field is a reviewed change here; removing or renaming one is a new `.v2`
1105
+ // event offered beside the old. No description, title, note or message is in
1106
+ // any of them: `reason` is the short text somebody typed for one transition.
1107
+ const webhookEventEnvelopeShape = {
1108
+ eventId: z.string().min(1),
1109
+ occurredAt: isoDateTimeSchema,
1110
+ };
1111
+ /** Payload of `crm.opportunity.status_changed.v1`. */
1112
+ export const OpportunityStatusChangedEventV1Schema = z
1113
+ .object({
1114
+ ...webhookEventEnvelopeShape,
1115
+ opportunityId: z.string().uuid(),
1116
+ number: z.string().min(1),
1117
+ /** Always present — what lets a subscription bound to one Organization receive only its own events. */
1118
+ organizationId: z.string().uuid(),
1119
+ salesChannelId: z.string().uuid().nullable(),
1120
+ from: z.string().min(1),
1121
+ to: z.string().min(1),
1122
+ fromKind: opportunityStatusKindSchema,
1123
+ toKind: opportunityStatusKindSchema,
1124
+ actor: z
1125
+ .object({ kind: z.enum(['admin', 'system']), adminUserId: z.string().uuid().optional() })
1126
+ .strict(),
1127
+ cause: z.enum(['manual', 'order_status', 'system']),
1128
+ /** The Order whose status caused the move, when `cause` is `order_status`. */
1129
+ causeOrderId: z.string().uuid().optional(),
1130
+ reason: z.string().max(2000).nullable(),
1131
+ })
1132
+ .strict();
1133
+ /** Payload of `crm.opportunity.created.v1`. */
1134
+ export const OpportunityCreatedEventV1Schema = z
1135
+ .object({
1136
+ ...webhookEventEnvelopeShape,
1137
+ opportunityId: z.string().uuid(),
1138
+ number: z.string().min(1),
1139
+ organizationId: z.string().uuid(),
1140
+ source: opportunitySourceSchema,
1141
+ })
1142
+ .strict();
1143
+ /**
1144
+ * Payload of `crm.opportunity.closed.v1` — one event for won and lost, told
1145
+ * apart by `outcome`.
1146
+ */
1147
+ export const OpportunityClosedEventV1Schema = z
1148
+ .object({
1149
+ ...webhookEventEnvelopeShape,
1150
+ opportunityId: z.string().uuid(),
1151
+ organizationId: z.string().uuid(),
1152
+ outcome: opportunityClosedKindSchema,
1153
+ /** The Opportunity's effective value when it closed; `null` when it has none. */
1154
+ value: z.string().nullable(),
1155
+ currency: currencyCodeSchema,
1156
+ })
1157
+ .strict();
1158
+ /** The event types CRM offers to outbound webhooks, in the order they are offered. */
1159
+ export const CRM_WEBHOOK_EVENT_TYPES = [
1160
+ CRM_EVENTS.STATUS_CHANGED,
1161
+ CRM_EVENTS.CREATED,
1162
+ CRM_EVENTS.CLOSED,
1163
+ ];
1164
+ /** The strict schema of each offered event's payload, by event type. */
1165
+ export const CRM_WEBHOOK_EVENT_SCHEMAS = {
1166
+ [CRM_EVENTS.STATUS_CHANGED]: OpportunityStatusChangedEventV1Schema,
1167
+ [CRM_EVENTS.CREATED]: OpportunityCreatedEventV1Schema,
1168
+ [CRM_EVENTS.CLOSED]: OpportunityClosedEventV1Schema,
1169
+ };
1170
+ // ---------------------------------------------------------------------------
1171
+ // The guard registry (`contracts/events-and-ports.md` §3)
1172
+ // ---------------------------------------------------------------------------
1173
+ /** Thrown by a guard to refuse a transition; the message is what the Sales Rep reads. */
1174
+ export class OpportunityTransitionVetoError extends Error {
1175
+ from;
1176
+ to;
1177
+ constructor(message, from, to) {
1178
+ super(message);
1179
+ this.from = from;
1180
+ this.to = to;
1181
+ this.name = 'OpportunityTransitionVetoError';
1182
+ }
1183
+ }
1184
+ /** Why a requested transition did not happen. */
1185
+ export const OPPORTUNITY_TRANSITION_REFUSALS = [
1186
+ 'not_found',
1187
+ 'unknown_status',
1188
+ 'not_permitted',
1189
+ 'vetoed',
1190
+ ];
1191
+ //# sourceMappingURL=crm.js.map