@endora-commerce/contracts 0.103.1 → 0.105.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/admin-actions.d.ts +5 -0
- package/dist/admin-actions.d.ts.map +1 -1
- package/dist/admin-actions.js +5 -0
- package/dist/admin-actions.js.map +1 -1
- package/dist/admin-contributions.d.ts +41 -0
- package/dist/admin-contributions.d.ts.map +1 -1
- package/dist/admin-contributions.js +58 -0
- package/dist/admin-contributions.js.map +1 -1
- package/dist/admin-notifications.d.ts +37 -0
- package/dist/admin-notifications.d.ts.map +1 -1
- package/dist/admin-users.d.ts +87 -1
- package/dist/admin-users.d.ts.map +1 -1
- package/dist/admin.d.ts +55 -1
- package/dist/admin.d.ts.map +1 -1
- package/dist/admin.js +42 -2
- package/dist/admin.js.map +1 -1
- package/dist/assets-library.d.ts +8 -0
- package/dist/assets-library.d.ts.map +1 -1
- package/dist/assets-library.js +2 -0
- package/dist/assets-library.js.map +1 -1
- package/dist/auth.d.ts +69 -4
- package/dist/auth.d.ts.map +1 -1
- package/dist/auth.js +15 -0
- package/dist/auth.js.map +1 -1
- package/dist/carts.d.ts +26 -1
- package/dist/carts.d.ts.map +1 -1
- package/dist/catalog.d.ts +122 -3
- package/dist/catalog.d.ts.map +1 -1
- package/dist/catalog.js +165 -0
- package/dist/catalog.js.map +1 -1
- package/dist/common.d.ts +17 -0
- package/dist/common.d.ts.map +1 -1
- package/dist/common.js +22 -0
- package/dist/common.js.map +1 -1
- package/dist/credit-limits.d.ts +27 -0
- package/dist/credit-limits.d.ts.map +1 -1
- package/dist/credit-limits.js +41 -0
- package/dist/credit-limits.js.map +1 -1
- package/dist/crm.d.ts +2934 -0
- package/dist/crm.d.ts.map +1 -0
- package/dist/crm.js +1216 -0
- package/dist/crm.js.map +1 -0
- package/dist/custom-fields.d.ts +46 -1
- package/dist/custom-fields.d.ts.map +1 -1
- package/dist/custom-fields.js +34 -6
- package/dist/custom-fields.js.map +1 -1
- package/dist/customer-accounts.d.ts +12 -1
- package/dist/customer-accounts.d.ts.map +1 -1
- package/dist/email.d.ts +19 -2
- package/dist/email.d.ts.map +1 -1
- package/dist/email.js +9 -2
- package/dist/email.js.map +1 -1
- package/dist/errors.d.ts +50 -0
- package/dist/errors.d.ts.map +1 -1
- package/dist/errors.js +53 -0
- package/dist/errors.js.map +1 -1
- package/dist/index.d.ts +3 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/index.js.map +1 -1
- package/dist/invoices.d.ts +6 -2
- package/dist/invoices.d.ts.map +1 -1
- package/dist/invoices.js +4 -2
- package/dist/invoices.js.map +1 -1
- package/dist/languages.d.ts +39 -4
- package/dist/languages.d.ts.map +1 -1
- package/dist/modules.d.ts +3 -0
- package/dist/modules.d.ts.map +1 -1
- package/dist/orders.d.ts +170 -2
- package/dist/orders.d.ts.map +1 -1
- package/dist/orders.js +78 -3
- package/dist/orders.js.map +1 -1
- package/dist/payment-methods.d.ts +8 -0
- package/dist/payment-methods.d.ts.map +1 -1
- package/dist/payment-methods.js +7 -0
- package/dist/payment-methods.js.map +1 -1
- package/dist/pim-connector.d.ts +1 -1
- package/dist/platform-info.d.ts +19 -0
- package/dist/platform-info.d.ts.map +1 -0
- package/dist/platform-info.js +18 -0
- package/dist/platform-info.js.map +1 -0
- package/dist/product-feeds.d.ts +15 -15
- package/dist/pwa.d.ts +10 -0
- package/dist/pwa.d.ts.map +1 -1
- package/dist/pwa.js +12 -0
- package/dist/pwa.js.map +1 -1
- package/dist/quote-requests.d.ts +66 -4
- package/dist/quote-requests.d.ts.map +1 -1
- package/dist/quote-requests.js +73 -4
- package/dist/quote-requests.js.map +1 -1
- package/dist/sales-channels.d.ts +18 -0
- package/dist/sales-channels.d.ts.map +1 -1
- package/dist/sales-channels.js +17 -0
- package/dist/sales-channels.js.map +1 -1
- package/dist/shipping-methods.d.ts +105 -0
- package/dist/shipping-methods.d.ts.map +1 -1
- package/dist/shipping-methods.js +59 -0
- package/dist/shipping-methods.js.map +1 -1
- package/dist/storefront-cache-tags.d.ts +65 -0
- package/dist/storefront-cache-tags.d.ts.map +1 -0
- package/dist/storefront-cache-tags.js +47 -0
- package/dist/storefront-cache-tags.js.map +1 -0
- package/dist/transactional-emails.d.ts +12 -2
- package/dist/transactional-emails.d.ts.map +1 -1
- package/dist/webhooks.d.ts +71 -0
- package/dist/webhooks.d.ts.map +1 -1
- package/dist/webhooks.js +32 -0
- package/dist/webhooks.js.map +1 -1
- package/package.json +1 -1
package/dist/crm.js
ADDED
|
@@ -0,0 +1,1216 @@
|
|
|
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
|
+
// What the other tabs of the Opportunity screen carry on their labels, for the
|
|
491
|
+
// same reason: the strip is drawn before any tab is opened. Each is a count
|
|
492
|
+
// in the database and never the length of a list. `noteCount` leaves out
|
|
493
|
+
// deleted notes and counts no message; the linked documents need no member of
|
|
494
|
+
// their own, `links` being whole.
|
|
495
|
+
noteCount: z.number().int().nonnegative(),
|
|
496
|
+
attachmentCount: z.number().int().nonnegative(),
|
|
497
|
+
// The messages of the Opportunity that **the administrator asking** has not
|
|
498
|
+
// read: written by somebody else, after the point they have read up to. It is
|
|
499
|
+
// the reader's and nobody else's — two administrators get two numbers — and a
|
|
500
|
+
// caller that is no administrator gets 0.
|
|
501
|
+
unreadMessageCount: z.number().int().nonnegative(),
|
|
502
|
+
});
|
|
503
|
+
export const OpportunityTransitionResultSchema = z.object({
|
|
504
|
+
opportunity: OpportunityDetailSchema,
|
|
505
|
+
from: z.string(),
|
|
506
|
+
to: z.string(),
|
|
507
|
+
propagation: z.array(PropagationOutcomeSchema),
|
|
508
|
+
});
|
|
509
|
+
export const OpportunityListResponseSchema = collectionEnvelope(OpportunitySummarySchema);
|
|
510
|
+
// §12b (US17) — the Opportunity a document is linked to, or `null` for a
|
|
511
|
+
// document that exists, is visible to the caller and is linked to none.
|
|
512
|
+
export const OpportunityOfDocumentResponseSchema = dataEnvelope(OpportunitySummarySchema.nullable());
|
|
513
|
+
export const OpportunityDetailResponseSchema = dataEnvelope(OpportunityDetailSchema);
|
|
514
|
+
export const OpportunityLinkResponseSchema = dataEnvelope(OpportunityLinkSchema);
|
|
515
|
+
export const OpportunityTransitionResponseSchema = dataEnvelope(OpportunityTransitionResultSchema);
|
|
516
|
+
export const PropagationOutcomeResponseSchema = dataEnvelope(PropagationOutcomeSchema);
|
|
517
|
+
// ---------------------------------------------------------------------------
|
|
518
|
+
// §4 Workflow configuration
|
|
519
|
+
// ---------------------------------------------------------------------------
|
|
520
|
+
export const CreateOpportunityStatusRequestSchema = z.object({
|
|
521
|
+
code: opportunityStatusCodeSchema,
|
|
522
|
+
name: statusNameSchema.optional(),
|
|
523
|
+
defaultName: z.string().trim().min(1).max(120),
|
|
524
|
+
kind: opportunityStatusKindSchema,
|
|
525
|
+
isInitial: z.boolean().optional(),
|
|
526
|
+
weight: z.number().int().min(0).max(100_000).optional(),
|
|
527
|
+
color: colorSchema.optional(),
|
|
528
|
+
});
|
|
529
|
+
/** `code` is immutable; strict, so a body naming it is refused. */
|
|
530
|
+
export const UpdateOpportunityStatusRequestSchema = CreateOpportunityStatusRequestSchema.omit({
|
|
531
|
+
code: true,
|
|
532
|
+
})
|
|
533
|
+
.partial()
|
|
534
|
+
.strict();
|
|
535
|
+
export const OpportunityTransitionEdgeSchema = z
|
|
536
|
+
.object({
|
|
537
|
+
fromStatusCode: opportunityStatusCodeSchema,
|
|
538
|
+
toStatusCode: opportunityStatusCodeSchema,
|
|
539
|
+
})
|
|
540
|
+
.refine((edge) => edge.fromStatusCode !== edge.toStatusCode, {
|
|
541
|
+
message: 'A transition must connect two different statuses',
|
|
542
|
+
});
|
|
543
|
+
export const SetOpportunityTransitionsRequestSchema = z.object({
|
|
544
|
+
add: z.array(OpportunityTransitionEdgeSchema).max(500).optional(),
|
|
545
|
+
remove: z.array(OpportunityTransitionEdgeSchema).max(500).optional(),
|
|
546
|
+
});
|
|
547
|
+
export const OrderStatusMappingSchema = z.object({
|
|
548
|
+
direction: orderStatusMappingDirectionSchema,
|
|
549
|
+
opportunityStatusCode: opportunityStatusCodeSchema,
|
|
550
|
+
/** An Order status code, by value — the Order workflow is the operator's. */
|
|
551
|
+
orderStatusCode: z.string().min(1).max(64),
|
|
552
|
+
/** Meaningful for `order_to_opportunity` only. */
|
|
553
|
+
requireAllOrders: z.boolean().optional(),
|
|
554
|
+
});
|
|
555
|
+
/** Replaces the whole set. */
|
|
556
|
+
export const SetOrderStatusMappingsRequestSchema = z.object({
|
|
557
|
+
mappings: z.array(OrderStatusMappingSchema).max(500),
|
|
558
|
+
});
|
|
559
|
+
export const SetValueCountingStatusesRequestSchema = z.object({
|
|
560
|
+
order: z.array(z.string().min(1).max(64)).max(200),
|
|
561
|
+
quoteRequest: z.array(quoteRequestStatusValueSchema).max(QUOTE_REQUEST_STATUS_VALUES.length),
|
|
562
|
+
});
|
|
563
|
+
export const OpportunityWorkflowStatusSchema = z.object({
|
|
564
|
+
code: z.string(),
|
|
565
|
+
name: z.record(z.string(), z.string()),
|
|
566
|
+
defaultName: z.string(),
|
|
567
|
+
kind: opportunityStatusKindSchema,
|
|
568
|
+
isInitial: z.boolean(),
|
|
569
|
+
weight: z.number().int(),
|
|
570
|
+
color: z.string(),
|
|
571
|
+
/** Opportunities currently in this status that the caller may see. */
|
|
572
|
+
inUseCount: z.number().int().nonnegative(),
|
|
573
|
+
});
|
|
574
|
+
export const OpportunityWorkflowSchema = z.object({
|
|
575
|
+
statuses: z.array(OpportunityWorkflowStatusSchema),
|
|
576
|
+
transitions: z.array(z.object({ fromStatusCode: z.string(), toStatusCode: z.string() })),
|
|
577
|
+
orderStatusMappings: z.array(z.object({
|
|
578
|
+
direction: orderStatusMappingDirectionSchema,
|
|
579
|
+
opportunityStatusCode: z.string(),
|
|
580
|
+
orderStatusCode: z.string(),
|
|
581
|
+
requireAllOrders: z.boolean(),
|
|
582
|
+
/** `false` once the Order status the mapping names no longer exists. */
|
|
583
|
+
orderStatusKnown: z.boolean(),
|
|
584
|
+
})),
|
|
585
|
+
valueCountingStatuses: z.object({
|
|
586
|
+
order: z.array(z.string()),
|
|
587
|
+
quoteRequest: z.array(z.string()),
|
|
588
|
+
}),
|
|
589
|
+
});
|
|
590
|
+
export const OpportunityWorkflowResponseSchema = dataEnvelope(OpportunityWorkflowSchema);
|
|
591
|
+
// ---------------------------------------------------------------------------
|
|
592
|
+
// §5 Assignment
|
|
593
|
+
// ---------------------------------------------------------------------------
|
|
594
|
+
export const AssignOpportunityRequestSchema = z.object({
|
|
595
|
+
adminUserId: z.string().uuid().nullable(),
|
|
596
|
+
});
|
|
597
|
+
// ---------------------------------------------------------------------------
|
|
598
|
+
// §6 Notes and messages
|
|
599
|
+
// ---------------------------------------------------------------------------
|
|
600
|
+
const commentBodySchema = z.string().min(1).max(10_000);
|
|
601
|
+
export const OpportunityCommentListQuerySchema = z.object({
|
|
602
|
+
kind: opportunityCommentKindSchema,
|
|
603
|
+
});
|
|
604
|
+
export const CreateOpportunityCommentRequestSchema = z.object({
|
|
605
|
+
kind: opportunityCommentKindSchema,
|
|
606
|
+
body: commentBodySchema,
|
|
607
|
+
});
|
|
608
|
+
/**
|
|
609
|
+
* `POST /opportunities/:id/messages/read` — the administrator asking has read
|
|
610
|
+
* the conversation up to and including this message. Named by the message and
|
|
611
|
+
* not by a time, so no clock of the browser's is part of it.
|
|
612
|
+
*/
|
|
613
|
+
export const MarkOpportunityMessagesReadRequestSchema = z.object({
|
|
614
|
+
throughMessageId: z.string().uuid(),
|
|
615
|
+
});
|
|
616
|
+
/** What is left unread for the administrator asking, after the marker moved. */
|
|
617
|
+
export const OpportunityUnreadMessagesSchema = z.object({
|
|
618
|
+
unreadMessageCount: z.number().int().nonnegative(),
|
|
619
|
+
});
|
|
620
|
+
export const UpdateOpportunityCommentRequestSchema = z.object({
|
|
621
|
+
body: commentBodySchema,
|
|
622
|
+
});
|
|
623
|
+
export const OpportunityCommentSchema = z.object({
|
|
624
|
+
id: z.string().uuid(),
|
|
625
|
+
kind: opportunityCommentKindSchema,
|
|
626
|
+
author: z.object({ id: z.string().uuid(), name: z.string() }),
|
|
627
|
+
body: z.string(),
|
|
628
|
+
references: z.array(OpportunityReferenceSchema),
|
|
629
|
+
editedAt: isoTimestampSchema.nullable(),
|
|
630
|
+
createdAt: isoTimestampSchema,
|
|
631
|
+
});
|
|
632
|
+
export const OpportunityCommentResponseSchema = dataEnvelope(OpportunityCommentSchema);
|
|
633
|
+
export const OpportunityUnreadMessagesResponseSchema = dataEnvelope(OpportunityUnreadMessagesSchema);
|
|
634
|
+
export const OpportunityCommentListResponseSchema = dataEnvelope(z.array(OpportunityCommentSchema));
|
|
635
|
+
// ---------------------------------------------------------------------------
|
|
636
|
+
// §7 Attachments
|
|
637
|
+
// ---------------------------------------------------------------------------
|
|
638
|
+
export const CreateOpportunityAttachmentRequestSchema = z.object({
|
|
639
|
+
assetId: z.string().uuid(),
|
|
640
|
+
});
|
|
641
|
+
export const OpportunityAttachmentSchema = z.object({
|
|
642
|
+
id: z.string().uuid(),
|
|
643
|
+
assetId: z.string().uuid(),
|
|
644
|
+
fileName: z.string(),
|
|
645
|
+
mimeType: z.string(),
|
|
646
|
+
sizeBytes: z.number().int().nonnegative(),
|
|
647
|
+
url: z.string().nullable(),
|
|
648
|
+
uploadedBy: z.object({ id: z.string().uuid(), name: z.string() }),
|
|
649
|
+
createdAt: isoTimestampSchema,
|
|
650
|
+
});
|
|
651
|
+
export const OpportunityAttachmentResponseSchema = dataEnvelope(OpportunityAttachmentSchema);
|
|
652
|
+
export const OpportunityAttachmentListResponseSchema = dataEnvelope(z.array(OpportunityAttachmentSchema));
|
|
653
|
+
/**
|
|
654
|
+
* §7a — the largest file `POST /opportunities/:id/attachments/upload` reads,
|
|
655
|
+
* in bytes (25 MB). The route holds the whole file in memory before the media
|
|
656
|
+
* library decides anything about it, so this is the bound on what one request
|
|
657
|
+
* may make the process allocate; what a file may otherwise *be* — its type, a
|
|
658
|
+
* smaller size limit — is the media library's upload policy, applied as it is
|
|
659
|
+
* for any other upload. The screen reads it to refuse a larger file before
|
|
660
|
+
* sending it. Above it: 413 `CRM_ATTACHMENT_TOO_LARGE`.
|
|
661
|
+
*/
|
|
662
|
+
export const OPPORTUNITY_ATTACHMENT_MAX_BYTES = 25 * 1024 * 1024;
|
|
663
|
+
// ---------------------------------------------------------------------------
|
|
664
|
+
// §8 Tags
|
|
665
|
+
// ---------------------------------------------------------------------------
|
|
666
|
+
const tagNameSchema = z.string().trim().min(1).max(64);
|
|
667
|
+
export const CreateOpportunityTagRequestSchema = z.object({
|
|
668
|
+
name: tagNameSchema,
|
|
669
|
+
color: colorSchema.optional(),
|
|
670
|
+
});
|
|
671
|
+
export const UpdateOpportunityTagRequestSchema = z.object({
|
|
672
|
+
name: tagNameSchema.optional(),
|
|
673
|
+
color: colorSchema.optional(),
|
|
674
|
+
});
|
|
675
|
+
/** Replaces the Opportunity's whole tag set. */
|
|
676
|
+
export const SetOpportunityTagsRequestSchema = z.object({
|
|
677
|
+
tagIds: z.array(z.string().uuid()).max(50),
|
|
678
|
+
});
|
|
679
|
+
export const OpportunityTagSchema = OpportunityTagRefSchema.extend({
|
|
680
|
+
/** Opportunities carrying the tag that the caller may see. */
|
|
681
|
+
usageCount: z.number().int().nonnegative(),
|
|
682
|
+
});
|
|
683
|
+
export const OpportunityTagResponseSchema = dataEnvelope(OpportunityTagSchema);
|
|
684
|
+
export const OpportunityTagListResponseSchema = dataEnvelope(z.array(OpportunityTagSchema));
|
|
685
|
+
// ---------------------------------------------------------------------------
|
|
686
|
+
// §10 Board
|
|
687
|
+
// ---------------------------------------------------------------------------
|
|
688
|
+
/** The list filters minus `statusCode` / `state` — the columns *are* the statuses. */
|
|
689
|
+
export const OpportunityBoardQuerySchema = z.object({
|
|
690
|
+
...opportunityFilterShape,
|
|
691
|
+
perColumn: z.coerce.number().int().positive().max(200).default(50),
|
|
692
|
+
});
|
|
693
|
+
export const OpportunityCurrencyTotalSchema = z.object({
|
|
694
|
+
currency: z.string(),
|
|
695
|
+
total: z.string(),
|
|
696
|
+
});
|
|
697
|
+
export const OpportunityBoardColumnSchema = z.object({
|
|
698
|
+
status: OpportunityStatusRefSchema,
|
|
699
|
+
count: z.number().int().nonnegative(),
|
|
700
|
+
valueTotals: z.array(OpportunityCurrencyTotalSchema),
|
|
701
|
+
items: z.array(OpportunitySummarySchema),
|
|
702
|
+
hasMore: z.boolean(),
|
|
703
|
+
});
|
|
704
|
+
export const OpportunityBoardSchema = z.object({
|
|
705
|
+
columns: z.array(OpportunityBoardColumnSchema),
|
|
706
|
+
/** §12c — the fields a card shows, in order; what `cardValues` and `fieldFilters` refer to. */
|
|
707
|
+
cardFields: z.array(OpportunityBoardCardFieldSchema),
|
|
708
|
+
});
|
|
709
|
+
export const OpportunityBoardResponseSchema = dataEnvelope(OpportunityBoardSchema);
|
|
710
|
+
// ---------------------------------------------------------------------------
|
|
711
|
+
// §10a Lookups — what the CRM screens' pickers choose from
|
|
712
|
+
// ---------------------------------------------------------------------------
|
|
713
|
+
//
|
|
714
|
+
// The Organization, Sales Channel, assignee and contact-person pickers of the
|
|
715
|
+
// CRM screens read from CRM's own endpoints, gated by CRM's own codes, and not
|
|
716
|
+
// from the admin lists of the modules that own those rows: a Sales Rep holding
|
|
717
|
+
// `crm:read` / `crm:write` holds neither `customers:read`, `sales_channels:read`
|
|
718
|
+
// nor `admin_users:manage`, and must not need them to fill in a form
|
|
719
|
+
// (`specs/143-crm-sales-opportunities/research.md` N-D4). Each answer is the
|
|
720
|
+
// minimum a picker shows — an id and a label.
|
|
721
|
+
const lookupLimitSchema = z.coerce.number().int().positive().max(50).default(20);
|
|
722
|
+
const lookupSearchSchema = z.string().trim().max(200).optional();
|
|
723
|
+
/** `id` asks for one Organization by id (the label of a preselection); `q` searches by name. */
|
|
724
|
+
export const OpportunityOrganizationLookupQuerySchema = z.object({
|
|
725
|
+
q: lookupSearchSchema,
|
|
726
|
+
id: z.string().uuid().optional(),
|
|
727
|
+
limit: lookupLimitSchema,
|
|
728
|
+
});
|
|
729
|
+
export const OpportunityOrganizationOptionSchema = z.object({
|
|
730
|
+
id: z.string().uuid(),
|
|
731
|
+
name: z.string(),
|
|
732
|
+
});
|
|
733
|
+
export const OpportunityOrganizationLookupResponseSchema = dataEnvelope(z.array(OpportunityOrganizationOptionSchema));
|
|
734
|
+
/** `name` is per language, as the channel stores it; the screen resolves it. */
|
|
735
|
+
export const OpportunitySalesChannelOptionSchema = z.object({
|
|
736
|
+
id: z.string().uuid(),
|
|
737
|
+
code: z.string(),
|
|
738
|
+
name: z.record(z.string(), z.string()),
|
|
739
|
+
active: z.boolean(),
|
|
740
|
+
systemDefault: z.boolean(),
|
|
741
|
+
/** The currencies the channel sells in — what an Opportunity's currency is chosen from. */
|
|
742
|
+
defaultCurrency: z.string(),
|
|
743
|
+
currencies: z.array(z.string()),
|
|
744
|
+
});
|
|
745
|
+
export const OpportunitySalesChannelLookupResponseSchema = dataEnvelope(z.array(OpportunitySalesChannelOptionSchema));
|
|
746
|
+
export const OpportunityAssigneeLookupQuerySchema = z.object({
|
|
747
|
+
q: lookupSearchSchema,
|
|
748
|
+
limit: lookupLimitSchema,
|
|
749
|
+
});
|
|
750
|
+
/** An administrator who may be assigned — active ones only, by name. */
|
|
751
|
+
export const OpportunityAssigneeOptionSchema = z.object({
|
|
752
|
+
id: z.string().uuid(),
|
|
753
|
+
name: z.string(),
|
|
754
|
+
});
|
|
755
|
+
export const OpportunityAssigneeLookupResponseSchema = dataEnvelope(z.array(OpportunityAssigneeOptionSchema));
|
|
756
|
+
/**
|
|
757
|
+
* Who may be mentioned in a text (User Story 18). With `organizationId` — the
|
|
758
|
+
* Opportunity's — only people who may see that Organization are offered.
|
|
759
|
+
*/
|
|
760
|
+
export const OpportunityMentionLookupQuerySchema = z.object({
|
|
761
|
+
q: lookupSearchSchema,
|
|
762
|
+
organizationId: z.string().uuid().optional(),
|
|
763
|
+
limit: lookupLimitSchema,
|
|
764
|
+
});
|
|
765
|
+
/** A person to mention: a name to choose by — no e-mail address, no role. */
|
|
766
|
+
export const OpportunityMentionOptionSchema = z.object({
|
|
767
|
+
id: z.string().uuid(),
|
|
768
|
+
name: z.string(),
|
|
769
|
+
});
|
|
770
|
+
export const OpportunityMentionLookupResponseSchema = dataEnvelope(z.array(OpportunityMentionOptionSchema));
|
|
771
|
+
export const OpportunityContactLookupQuerySchema = z.object({
|
|
772
|
+
organizationId: z.string().uuid(),
|
|
773
|
+
q: lookupSearchSchema,
|
|
774
|
+
limit: lookupLimitSchema,
|
|
775
|
+
});
|
|
776
|
+
/** A member of the Organization who may be the Opportunity's contact person. */
|
|
777
|
+
export const OpportunityContactOptionSchema = z.object({
|
|
778
|
+
id: z.string().uuid(),
|
|
779
|
+
name: z.string(),
|
|
780
|
+
email: z.string(),
|
|
781
|
+
});
|
|
782
|
+
export const OpportunityContactLookupResponseSchema = dataEnvelope(z.array(OpportunityContactOptionSchema));
|
|
783
|
+
/**
|
|
784
|
+
* The Quote Requests of one Organization that can still be linked — the open
|
|
785
|
+
* ones, plus the one whose number is typed in full. Gated by CRM's own code:
|
|
786
|
+
* the quote desk's list is behind `rfqs:handle`, the right to handle quotes,
|
|
787
|
+
* which linking one to an Opportunity does not need (research N-H2).
|
|
788
|
+
*/
|
|
789
|
+
export const OpportunityQuoteRequestLookupQuerySchema = z.object({
|
|
790
|
+
organizationId: z.string().uuid(),
|
|
791
|
+
q: lookupSearchSchema,
|
|
792
|
+
limit: lookupLimitSchema,
|
|
793
|
+
});
|
|
794
|
+
export const OpportunityQuoteRequestOptionSchema = z.object({
|
|
795
|
+
id: z.string().uuid(),
|
|
796
|
+
number: z.string(),
|
|
797
|
+
status: z.string(),
|
|
798
|
+
});
|
|
799
|
+
export const OpportunityQuoteRequestLookupResponseSchema = dataEnvelope(z.array(OpportunityQuoteRequestOptionSchema));
|
|
800
|
+
// ---------------------------------------------------------------------------
|
|
801
|
+
// §11 History
|
|
802
|
+
// ---------------------------------------------------------------------------
|
|
803
|
+
export const OpportunityHistoryQuerySchema = z.object({
|
|
804
|
+
limit: z.coerce.number().int().positive().max(200).default(50),
|
|
805
|
+
cursor: z.string().optional(),
|
|
806
|
+
});
|
|
807
|
+
export const OpportunityHistoryEntrySchema = z.object({
|
|
808
|
+
id: z.string(),
|
|
809
|
+
actedAt: isoTimestampSchema,
|
|
810
|
+
action: z.string(),
|
|
811
|
+
actor: z.object({
|
|
812
|
+
kind: z.string(),
|
|
813
|
+
id: z.string().nullable(),
|
|
814
|
+
name: z.string().nullable(),
|
|
815
|
+
}),
|
|
816
|
+
before: z.unknown().nullable(),
|
|
817
|
+
after: z.unknown().nullable(),
|
|
818
|
+
/**
|
|
819
|
+
* What the tokens in this entry's texts — a description as it was and as it
|
|
820
|
+
* is — name for this reader (§9), so the history shows names and not codes.
|
|
821
|
+
*/
|
|
822
|
+
references: z.array(OpportunityReferenceSchema),
|
|
823
|
+
});
|
|
824
|
+
/**
|
|
825
|
+
* `truncated` is beside `pagination` and not part of it: `hasMore` goes on
|
|
826
|
+
* meaning "there is a next page to ask for". It is `true` on the last page a
|
|
827
|
+
* history can serve when the Opportunity has earlier entries beyond it — the
|
|
828
|
+
* history reaches a fixed way back — and `false` on every other page.
|
|
829
|
+
*/
|
|
830
|
+
export const OpportunityHistoryResponseSchema = collectionEnvelope(OpportunityHistoryEntrySchema).extend({
|
|
831
|
+
truncated: z.boolean(),
|
|
832
|
+
});
|
|
833
|
+
// ---------------------------------------------------------------------------
|
|
834
|
+
// §12 Analytics
|
|
835
|
+
// ---------------------------------------------------------------------------
|
|
836
|
+
const analyticsRangeShape = {
|
|
837
|
+
from: calendarDateSchema,
|
|
838
|
+
to: calendarDateSchema,
|
|
839
|
+
salesChannelId: z.string().uuid().optional(),
|
|
840
|
+
assignedAdminUserId: z.string().uuid().optional(),
|
|
841
|
+
};
|
|
842
|
+
export const OpportunityAnalyticsQuerySchema = z.object(analyticsRangeShape);
|
|
843
|
+
export const OpportunityTimeInStatusQuerySchema = z.object({
|
|
844
|
+
...analyticsRangeShape,
|
|
845
|
+
statusCode: repeatable(opportunityStatusCodeSchema),
|
|
846
|
+
});
|
|
847
|
+
export const TopOpportunitiesQuerySchema = z.object({
|
|
848
|
+
...analyticsRangeShape,
|
|
849
|
+
limit: z.coerce.number().int().positive().max(100).default(10),
|
|
850
|
+
basis: z.enum(['created', 'closed']).default('created'),
|
|
851
|
+
});
|
|
852
|
+
export const OpportunityHandlingTimeSchema = z.object({
|
|
853
|
+
averageSeconds: z.number().nullable(),
|
|
854
|
+
closedCount: z.number().int().nonnegative(),
|
|
855
|
+
byOutcome: z.object({
|
|
856
|
+
won: z.object({ averageSeconds: z.number().nullable(), closedCount: z.number().int() }),
|
|
857
|
+
lost: z.object({ averageSeconds: z.number().nullable(), closedCount: z.number().int() }),
|
|
858
|
+
}),
|
|
859
|
+
});
|
|
860
|
+
export const OpportunityTimeInStatusRowSchema = z.object({
|
|
861
|
+
statusCode: z.string(),
|
|
862
|
+
averageSeconds: z.number().nullable(),
|
|
863
|
+
sampleCount: z.number().int().nonnegative(),
|
|
864
|
+
});
|
|
865
|
+
export const OpportunityRepEffectivenessRowSchema = z.object({
|
|
866
|
+
/** `YYYY-MM`. */
|
|
867
|
+
month: z.string(),
|
|
868
|
+
adminUser: z.object({ id: z.string().uuid(), name: z.string() }),
|
|
869
|
+
wonCount: z.number().int().nonnegative(),
|
|
870
|
+
wonValue: z.array(OpportunityCurrencyTotalSchema),
|
|
871
|
+
});
|
|
872
|
+
export const OpportunityAverageValueRowSchema = z.object({
|
|
873
|
+
currency: z.string(),
|
|
874
|
+
average: z.string(),
|
|
875
|
+
count: z.number().int().nonnegative(),
|
|
876
|
+
});
|
|
877
|
+
export const OpportunityHandlingTimeResponseSchema = dataEnvelope(OpportunityHandlingTimeSchema);
|
|
878
|
+
export const OpportunityTimeInStatusResponseSchema = dataEnvelope(z.array(OpportunityTimeInStatusRowSchema));
|
|
879
|
+
export const OpportunityRepEffectivenessResponseSchema = dataEnvelope(z.array(OpportunityRepEffectivenessRowSchema));
|
|
880
|
+
export const TopOpportunitiesResponseSchema = dataEnvelope(z.array(OpportunitySummarySchema));
|
|
881
|
+
export const OpportunityAverageValueResponseSchema = dataEnvelope(z.array(OpportunityAverageValueRowSchema));
|
|
882
|
+
// ---------------------------------------------------------------------------
|
|
883
|
+
// §12d Events on an Opportunity and the Calendar (US21, US22)
|
|
884
|
+
// ---------------------------------------------------------------------------
|
|
885
|
+
//
|
|
886
|
+
// "Event" here is an entry in a calendar — a meeting, a call, a deadline. The
|
|
887
|
+
// in-process events the module publishes are the next section's.
|
|
888
|
+
/**
|
|
889
|
+
* The longest an Event may be. An Event is one calendar day in its own zone,
|
|
890
|
+
* and the day a clock goes back is 25 hours long — so this is the bound that
|
|
891
|
+
* needs no zone data, and "one local day" is the service's to refuse.
|
|
892
|
+
*/
|
|
893
|
+
export const OPPORTUNITY_EVENT_MAX_SPAN_HOURS = 25;
|
|
894
|
+
/**
|
|
895
|
+
* The widest range a Calendar read may ask for: the six-week month grid (42
|
|
896
|
+
* days), a day each side for an all-day Event of a far zone, and one.
|
|
897
|
+
*/
|
|
898
|
+
export const CALENDAR_EVENTS_MAX_RANGE_DAYS = 45;
|
|
899
|
+
/** A Calendar read answers this many Events at most, and says when it cut. */
|
|
900
|
+
export const CALENDAR_EVENTS_MAX_RESULTS = 500;
|
|
901
|
+
const HOUR_MS = 60 * 60 * 1000;
|
|
902
|
+
const DAY_MS = 24 * HOUR_MS;
|
|
903
|
+
/**
|
|
904
|
+
* Why a well-formed Event is refused — `details.rule` of a 422
|
|
905
|
+
* `VALIDATION_FAILED`, beside `details.field`. The first is also refused by
|
|
906
|
+
* the schema when both instants arrive in one body (400); the service repeats
|
|
907
|
+
* it for an edit that names one of them.
|
|
908
|
+
*/
|
|
909
|
+
export const opportunityEventRuleSchema = z.enum([
|
|
910
|
+
'ends_before_start',
|
|
911
|
+
'spans_days',
|
|
912
|
+
'not_whole_day',
|
|
913
|
+
'unknown_time_zone',
|
|
914
|
+
'reminder_in_past',
|
|
915
|
+
]);
|
|
916
|
+
/**
|
|
917
|
+
* What became of an Event's reminder, folded for a reader: `paused` is
|
|
918
|
+
* `scheduled` on a closed Opportunity and is derived on read, and a reminder
|
|
919
|
+
* being sent right now is reported as `scheduled`.
|
|
920
|
+
*/
|
|
921
|
+
export const opportunityEventReminderStateSchema = z.enum([
|
|
922
|
+
'scheduled',
|
|
923
|
+
'paused',
|
|
924
|
+
'sent',
|
|
925
|
+
'missed',
|
|
926
|
+
'no_recipient',
|
|
927
|
+
'undeliverable',
|
|
928
|
+
'interrupted',
|
|
929
|
+
]);
|
|
930
|
+
export const opportunityEventReminderChannelSchema = z.enum(['bell', 'email']);
|
|
931
|
+
export const calendarScopeSchema = z.enum(['mine', 'all']);
|
|
932
|
+
/**
|
|
933
|
+
* An instant of an Event, of a reminder or of a Calendar range: one the
|
|
934
|
+
* database holds and every zone can date.
|
|
935
|
+
*
|
|
936
|
+
* `isoDateTimeSchema` accepts any four-digit year **as written**, and an offset
|
|
937
|
+
* carries `9999-12-31T22:00:00-14:00` into the year 10000 — which JavaScript
|
|
938
|
+
* serialises with a signed six-digit year and PostgreSQL refuses, so the
|
|
939
|
+
* request used to end in a 500 (research N-CALR4). The range is the years
|
|
940
|
+
* 0001 – 9999 in UTC **less two days at each end**: the local date of an
|
|
941
|
+
* instant in any zone, and the 25 hours the Calendar read looks back before
|
|
942
|
+
* its `from`, then stay inside four-digit years as well.
|
|
943
|
+
*/
|
|
944
|
+
const EVENT_INSTANT_MIN_MS = Date.parse('0001-01-03T00:00:00.000Z');
|
|
945
|
+
const EVENT_INSTANT_MAX_MS = Date.parse('9999-12-30T00:00:00.000Z');
|
|
946
|
+
const eventInstantSchema = isoDateTimeSchema
|
|
947
|
+
.refine((value) => {
|
|
948
|
+
const instant = Date.parse(value);
|
|
949
|
+
return instant >= EVENT_INSTANT_MIN_MS && instant < EVENT_INSTANT_MAX_MS;
|
|
950
|
+
}, 'The instant must lie between 0001-01-03 and 9999-12-30 (UTC)')
|
|
951
|
+
.describe('ISO-8601 datetime with offset, e.g. 2026-04-23T10:15:30.000Z');
|
|
952
|
+
const opportunityEventWriteShape = {
|
|
953
|
+
name: z.string().trim().min(1).max(200),
|
|
954
|
+
/** Plain text; reference tokens are not parsed. */
|
|
955
|
+
description: z.string().max(5000).nullable().optional(),
|
|
956
|
+
allDay: z.boolean(),
|
|
957
|
+
/** For an all-day Event, the local midnight that starts its date. */
|
|
958
|
+
startsAt: eventInstantSchema,
|
|
959
|
+
/** Exclusive. For an all-day Event, the next local midnight. */
|
|
960
|
+
endsAt: eventInstantSchema,
|
|
961
|
+
/**
|
|
962
|
+
* The IANA zone the times were chosen in —
|
|
963
|
+
* `Intl.DateTimeFormat().resolvedOptions().timeZone` in the browser. Whether
|
|
964
|
+
* the runtime knows the zone is the service's to say (`unknown_time_zone`).
|
|
965
|
+
*/
|
|
966
|
+
timeZone: z.string().min(1).max(64),
|
|
967
|
+
/** `null` or absent = no reminder. Must be later than now — the service's rule. */
|
|
968
|
+
remindAt: eventInstantSchema.nullable().optional(),
|
|
969
|
+
};
|
|
970
|
+
/**
|
|
971
|
+
* The two rules that need neither a clock nor zone data. They are judged only
|
|
972
|
+
* when both instants are present, which on a create is always and on an edit
|
|
973
|
+
* is when the body names both.
|
|
974
|
+
*/
|
|
975
|
+
function refineEventSpan(value, ctx) {
|
|
976
|
+
if (value.startsAt === undefined || value.endsAt === undefined)
|
|
977
|
+
return;
|
|
978
|
+
const span = Date.parse(value.endsAt) - Date.parse(value.startsAt);
|
|
979
|
+
if (span <= 0) {
|
|
980
|
+
ctx.addIssue({ code: 'custom', path: ['endsAt'], message: 'An Event ends after it starts' });
|
|
981
|
+
}
|
|
982
|
+
else if (span > OPPORTUNITY_EVENT_MAX_SPAN_HOURS * HOUR_MS) {
|
|
983
|
+
ctx.addIssue({
|
|
984
|
+
code: 'custom',
|
|
985
|
+
path: ['endsAt'],
|
|
986
|
+
message: `An Event is at most ${OPPORTUNITY_EVENT_MAX_SPAN_HOURS} hours long`,
|
|
987
|
+
});
|
|
988
|
+
}
|
|
989
|
+
}
|
|
990
|
+
export const CreateOpportunityEventRequestSchema = z
|
|
991
|
+
.object(opportunityEventWriteShape)
|
|
992
|
+
.superRefine(refineEventSpan);
|
|
993
|
+
/**
|
|
994
|
+
* Every member of the create, all optional; strict, so a body naming anything
|
|
995
|
+
* else is refused instead of ignored. The rules are applied by the service to
|
|
996
|
+
* the Event **as it would be after the change**; `remindAt: null` removes the
|
|
997
|
+
* reminder and a different `remindAt` arms it again.
|
|
998
|
+
*/
|
|
999
|
+
export const UpdateOpportunityEventRequestSchema = z
|
|
1000
|
+
.object(opportunityEventWriteShape)
|
|
1001
|
+
.partial()
|
|
1002
|
+
.strict()
|
|
1003
|
+
.superRefine(refineEventSpan);
|
|
1004
|
+
export const OpportunityEventReminderSchema = z
|
|
1005
|
+
.object({
|
|
1006
|
+
at: isoDateTimeSchema,
|
|
1007
|
+
state: opportunityEventReminderStateSchema,
|
|
1008
|
+
handledAt: isoDateTimeSchema.nullable(),
|
|
1009
|
+
channels: z.array(opportunityEventReminderChannelSchema),
|
|
1010
|
+
})
|
|
1011
|
+
.refine((reminder) => (reminder.state === 'sent') === reminder.channels.length > 0, {
|
|
1012
|
+
path: ['channels'],
|
|
1013
|
+
message: 'channels is non-empty exactly when the reminder was sent',
|
|
1014
|
+
});
|
|
1015
|
+
export const OpportunityEventSchema = z.object({
|
|
1016
|
+
id: z.string().uuid(),
|
|
1017
|
+
opportunityId: z.string().uuid(),
|
|
1018
|
+
name: z.string(),
|
|
1019
|
+
description: z.string().nullable(),
|
|
1020
|
+
allDay: z.boolean(),
|
|
1021
|
+
/** UTC instants ("Z"); `endsAt` is exclusive. */
|
|
1022
|
+
startsAt: isoDateTimeSchema,
|
|
1023
|
+
endsAt: isoDateTimeSchema,
|
|
1024
|
+
timeZone: z.string(),
|
|
1025
|
+
/**
|
|
1026
|
+
* The date of an all-day Event, computed by the server in `timeZone`; `null`
|
|
1027
|
+
* for a timed one. A calendar places an all-day Event by this, whatever the
|
|
1028
|
+
* reader's own zone.
|
|
1029
|
+
*/
|
|
1030
|
+
allDayDate: calendarDateSchema.nullable(),
|
|
1031
|
+
reminder: OpportunityEventReminderSchema.nullable(),
|
|
1032
|
+
createdBy: z.object({ id: z.string().uuid(), name: z.string() }).nullable(),
|
|
1033
|
+
createdAt: isoTimestampSchema,
|
|
1034
|
+
updatedAt: isoTimestampSchema,
|
|
1035
|
+
});
|
|
1036
|
+
export const OpportunityEventResponseSchema = dataEnvelope(OpportunityEventSchema);
|
|
1037
|
+
export const OpportunityEventListResponseSchema = dataEnvelope(z.array(OpportunityEventSchema));
|
|
1038
|
+
/**
|
|
1039
|
+
* `GET /calendar/events`. `from` is inclusive and `to` exclusive; an Event is
|
|
1040
|
+
* in the answer when it overlaps the range. `scope` absent = the caller's
|
|
1041
|
+
* default, and the server decides what is honoured: `all` asked by a caller
|
|
1042
|
+
* confined to some Organizations is answered as `mine`, not refused.
|
|
1043
|
+
*
|
|
1044
|
+
* Write the instants in UTC (`Date#toISOString`): a `+` of an offset in a
|
|
1045
|
+
* query string that is not percent-encoded arrives as a space.
|
|
1046
|
+
*/
|
|
1047
|
+
export const CalendarEventsQuerySchema = z
|
|
1048
|
+
.object({
|
|
1049
|
+
from: eventInstantSchema,
|
|
1050
|
+
to: eventInstantSchema,
|
|
1051
|
+
scope: calendarScopeSchema.optional(),
|
|
1052
|
+
})
|
|
1053
|
+
.superRefine((value, ctx) => {
|
|
1054
|
+
const span = Date.parse(value.to) - Date.parse(value.from);
|
|
1055
|
+
if (span <= 0) {
|
|
1056
|
+
ctx.addIssue({ code: 'custom', path: ['to'], message: 'The range ends after it starts' });
|
|
1057
|
+
}
|
|
1058
|
+
else if (span > CALENDAR_EVENTS_MAX_RANGE_DAYS * DAY_MS) {
|
|
1059
|
+
ctx.addIssue({
|
|
1060
|
+
code: 'custom',
|
|
1061
|
+
path: ['to'],
|
|
1062
|
+
message: `The range is at most ${CALENDAR_EVENTS_MAX_RANGE_DAYS} days`,
|
|
1063
|
+
});
|
|
1064
|
+
}
|
|
1065
|
+
});
|
|
1066
|
+
/** What a calendar draws and nothing more — deliberately no description. */
|
|
1067
|
+
export const CalendarEventSchema = z.object({
|
|
1068
|
+
id: z.string().uuid(),
|
|
1069
|
+
name: z.string(),
|
|
1070
|
+
allDay: z.boolean(),
|
|
1071
|
+
startsAt: isoDateTimeSchema,
|
|
1072
|
+
endsAt: isoDateTimeSchema,
|
|
1073
|
+
allDayDate: calendarDateSchema.nullable(),
|
|
1074
|
+
hasReminder: z.boolean(),
|
|
1075
|
+
opportunity: z.object({
|
|
1076
|
+
id: z.string().uuid(),
|
|
1077
|
+
number: z.string(),
|
|
1078
|
+
title: z.string(),
|
|
1079
|
+
assignee: z.object({ id: z.string().uuid(), name: z.string() }).nullable(),
|
|
1080
|
+
}),
|
|
1081
|
+
});
|
|
1082
|
+
/**
|
|
1083
|
+
* `scope` is the one applied and `scopes` the ones this caller may ask for;
|
|
1084
|
+
* `truncated` says more than `CALENDAR_EVENTS_MAX_RESULTS` Events matched and
|
|
1085
|
+
* the first by `startsAt`, then `id`, were returned.
|
|
1086
|
+
*/
|
|
1087
|
+
export const CalendarEventsMetaSchema = z.object({
|
|
1088
|
+
scope: calendarScopeSchema,
|
|
1089
|
+
scopes: z.array(calendarScopeSchema).min(1),
|
|
1090
|
+
truncated: z.boolean(),
|
|
1091
|
+
});
|
|
1092
|
+
export const CalendarEventsResponseSchema = z.object({
|
|
1093
|
+
data: z.array(CalendarEventSchema),
|
|
1094
|
+
meta: CalendarEventsMetaSchema,
|
|
1095
|
+
});
|
|
1096
|
+
/**
|
|
1097
|
+
* The concrete name of one of the four templated status events. Statuses are
|
|
1098
|
+
* configured at runtime, so the names are not known at compile time — this is
|
|
1099
|
+
* the one place the scheme is written, for the emitter and every subscriber.
|
|
1100
|
+
*/
|
|
1101
|
+
export function opportunityStatusEventName(kind, p) {
|
|
1102
|
+
switch (kind) {
|
|
1103
|
+
case 'fromToBefore':
|
|
1104
|
+
return `crm.opportunity.status.from_${p.from}_to_${p.to}.before`;
|
|
1105
|
+
case 'fromBefore':
|
|
1106
|
+
return `crm.opportunity.status.from_${p.from}.before`;
|
|
1107
|
+
case 'fromToAfter':
|
|
1108
|
+
return `crm.opportunity.status.from_${p.from}_to_${p.to}.after`;
|
|
1109
|
+
case 'toAfter':
|
|
1110
|
+
return `crm.opportunity.status.to_${p.to}.after`;
|
|
1111
|
+
}
|
|
1112
|
+
}
|
|
1113
|
+
/** The fixed event names CRM emits. */
|
|
1114
|
+
export const CRM_EVENTS = {
|
|
1115
|
+
STATUS_CHANGED: 'crm.opportunity.status_changed.v1',
|
|
1116
|
+
CREATED: 'crm.opportunity.created.v1',
|
|
1117
|
+
CLOSED: 'crm.opportunity.closed.v1',
|
|
1118
|
+
ASSIGNED: 'crm.opportunity.assigned.v1',
|
|
1119
|
+
DOCUMENT_LINKED: 'crm.opportunity.document_linked.v1',
|
|
1120
|
+
};
|
|
1121
|
+
// ---------------------------------------------------------------------------
|
|
1122
|
+
// Events offered to outbound webhooks (`contracts/events-and-ports.md` §6)
|
|
1123
|
+
// ---------------------------------------------------------------------------
|
|
1124
|
+
//
|
|
1125
|
+
// The webhook delivery bridge serialises an event whole, so for these three
|
|
1126
|
+
// **the event payload is the webhook payload** — a public, versioned contract.
|
|
1127
|
+
// Each has a strict schema, the payload type is inferred from it (one
|
|
1128
|
+
// definition), and a test holds every event the module emits to it. Adding a
|
|
1129
|
+
// field is a reviewed change here; removing or renaming one is a new `.v2`
|
|
1130
|
+
// event offered beside the old. No description, title, note or message is in
|
|
1131
|
+
// any of them: `reason` is the short text somebody typed for one transition.
|
|
1132
|
+
const webhookEventEnvelopeShape = {
|
|
1133
|
+
eventId: z.string().min(1),
|
|
1134
|
+
occurredAt: isoDateTimeSchema,
|
|
1135
|
+
};
|
|
1136
|
+
/** Payload of `crm.opportunity.status_changed.v1`. */
|
|
1137
|
+
export const OpportunityStatusChangedEventV1Schema = z
|
|
1138
|
+
.object({
|
|
1139
|
+
...webhookEventEnvelopeShape,
|
|
1140
|
+
opportunityId: z.string().uuid(),
|
|
1141
|
+
number: z.string().min(1),
|
|
1142
|
+
/** Always present — what lets a subscription bound to one Organization receive only its own events. */
|
|
1143
|
+
organizationId: z.string().uuid(),
|
|
1144
|
+
salesChannelId: z.string().uuid().nullable(),
|
|
1145
|
+
from: z.string().min(1),
|
|
1146
|
+
to: z.string().min(1),
|
|
1147
|
+
fromKind: opportunityStatusKindSchema,
|
|
1148
|
+
toKind: opportunityStatusKindSchema,
|
|
1149
|
+
actor: z
|
|
1150
|
+
.object({ kind: z.enum(['admin', 'system']), adminUserId: z.string().uuid().optional() })
|
|
1151
|
+
.strict(),
|
|
1152
|
+
cause: z.enum(['manual', 'order_status', 'system']),
|
|
1153
|
+
/** The Order whose status caused the move, when `cause` is `order_status`. */
|
|
1154
|
+
causeOrderId: z.string().uuid().optional(),
|
|
1155
|
+
reason: z.string().max(2000).nullable(),
|
|
1156
|
+
})
|
|
1157
|
+
.strict();
|
|
1158
|
+
/** Payload of `crm.opportunity.created.v1`. */
|
|
1159
|
+
export const OpportunityCreatedEventV1Schema = z
|
|
1160
|
+
.object({
|
|
1161
|
+
...webhookEventEnvelopeShape,
|
|
1162
|
+
opportunityId: z.string().uuid(),
|
|
1163
|
+
number: z.string().min(1),
|
|
1164
|
+
organizationId: z.string().uuid(),
|
|
1165
|
+
source: opportunitySourceSchema,
|
|
1166
|
+
})
|
|
1167
|
+
.strict();
|
|
1168
|
+
/**
|
|
1169
|
+
* Payload of `crm.opportunity.closed.v1` — one event for won and lost, told
|
|
1170
|
+
* apart by `outcome`.
|
|
1171
|
+
*/
|
|
1172
|
+
export const OpportunityClosedEventV1Schema = z
|
|
1173
|
+
.object({
|
|
1174
|
+
...webhookEventEnvelopeShape,
|
|
1175
|
+
opportunityId: z.string().uuid(),
|
|
1176
|
+
organizationId: z.string().uuid(),
|
|
1177
|
+
outcome: opportunityClosedKindSchema,
|
|
1178
|
+
/** The Opportunity's effective value when it closed; `null` when it has none. */
|
|
1179
|
+
value: z.string().nullable(),
|
|
1180
|
+
currency: currencyCodeSchema,
|
|
1181
|
+
})
|
|
1182
|
+
.strict();
|
|
1183
|
+
/** The event types CRM offers to outbound webhooks, in the order they are offered. */
|
|
1184
|
+
export const CRM_WEBHOOK_EVENT_TYPES = [
|
|
1185
|
+
CRM_EVENTS.STATUS_CHANGED,
|
|
1186
|
+
CRM_EVENTS.CREATED,
|
|
1187
|
+
CRM_EVENTS.CLOSED,
|
|
1188
|
+
];
|
|
1189
|
+
/** The strict schema of each offered event's payload, by event type. */
|
|
1190
|
+
export const CRM_WEBHOOK_EVENT_SCHEMAS = {
|
|
1191
|
+
[CRM_EVENTS.STATUS_CHANGED]: OpportunityStatusChangedEventV1Schema,
|
|
1192
|
+
[CRM_EVENTS.CREATED]: OpportunityCreatedEventV1Schema,
|
|
1193
|
+
[CRM_EVENTS.CLOSED]: OpportunityClosedEventV1Schema,
|
|
1194
|
+
};
|
|
1195
|
+
// ---------------------------------------------------------------------------
|
|
1196
|
+
// The guard registry (`contracts/events-and-ports.md` §3)
|
|
1197
|
+
// ---------------------------------------------------------------------------
|
|
1198
|
+
/** Thrown by a guard to refuse a transition; the message is what the Sales Rep reads. */
|
|
1199
|
+
export class OpportunityTransitionVetoError extends Error {
|
|
1200
|
+
from;
|
|
1201
|
+
to;
|
|
1202
|
+
constructor(message, from, to) {
|
|
1203
|
+
super(message);
|
|
1204
|
+
this.from = from;
|
|
1205
|
+
this.to = to;
|
|
1206
|
+
this.name = 'OpportunityTransitionVetoError';
|
|
1207
|
+
}
|
|
1208
|
+
}
|
|
1209
|
+
/** Why a requested transition did not happen. */
|
|
1210
|
+
export const OPPORTUNITY_TRANSITION_REFUSALS = [
|
|
1211
|
+
'not_found',
|
|
1212
|
+
'unknown_status',
|
|
1213
|
+
'not_permitted',
|
|
1214
|
+
'vetoed',
|
|
1215
|
+
];
|
|
1216
|
+
//# sourceMappingURL=crm.js.map
|