@composable-os/pack-offers 0.0.0-stage → 0.1.0-beta.16

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/tools.js ADDED
@@ -0,0 +1,597 @@
1
+ // The Offers pack's staff tools (stage 34, step 5). They become operations x.offers.<tool>, run in
2
+ // the sandbox, and reach the host only through ctx.ops. None of them holds a rule: what an order is
3
+ // charged, who qualifies, the limits and the one answer to a buyer are all the host's (ADR 0693).
4
+ // A tool writes a discount's terms or moves it, and reports what the host answered.
5
+ //
6
+ // Who may do what:
7
+ // - anyone on the staff, the assistant included, reads discounts and drafts one (`draftDiscount`):
8
+ // a draft applies to nobody;
9
+ // - making one live, pausing it, ending it and changing its terms are a person's, with
10
+ // `offers:manage` (`personApproves`: the assistant may ask, and its call waits for a person);
11
+ // - single-use codes are made by a person at the screen (`generateCodes`, `humanOnly`): they are
12
+ // shown once, in that answer only, and kept as their hash (ADR 0699). An approved call shows its
13
+ // answer to nobody, so an assistant cannot ask for codes: it drafts the discount and says so.
14
+ import { CODE_MIN_LENGTH, codeHash, defineTool, foldCode, OpsCallError, randomCodes, z, } from "@composable-os/sdk";
15
+ export const DISCOUNT = "offers.discount";
16
+ export const CODE = "offers.code";
17
+ /** What a discount may cover: the objects the shipped packs sell, one at a time. */
18
+ export const SOLD_OBJECTS = [
19
+ { value: "bookings.booking", label: "Drop-in classes" },
20
+ { value: "ticketing.tickettype", label: "Event tickets" },
21
+ { value: "memberships.passtype", label: "Class passes" },
22
+ { value: "courses.course", label: "Courses" },
23
+ { value: "courses.bundle", label: "Course bundles" },
24
+ { value: "shop.variant", label: "Shop goods" },
25
+ ];
26
+ /** Who a discount is for, as the host's `discount.who` knows them (DISCOUNT_WHO in the SDK). */
27
+ export const DISCOUNT_WHO_OPTIONS = [
28
+ { value: "anyone", label: "Anyone, guests included" },
29
+ { value: "signed_in", label: "Signed-in customers" },
30
+ { value: "members", label: "Members (a live membership)" },
31
+ { value: "new_customers", label: "New customers" },
32
+ { value: "organisation", label: "People of an organisation" },
33
+ { value: "tag", label: "People with a tag" },
34
+ ];
35
+ export const DISCOUNT_STATES = [
36
+ { value: "draft", label: "Draft" },
37
+ { value: "active", label: "Live" },
38
+ { value: "paused", label: "Paused" },
39
+ { value: "ended", label: "Ended" },
40
+ ];
41
+ /** The most single-use codes one call makes, and how many are written per host call. */
42
+ export const BATCH_MAX = 500;
43
+ export const WRITE_CHUNK = 50;
44
+ /** The most codes one call of voidCodes switches off. */
45
+ export const VOID_MAX = 200;
46
+ const id = z.string().min(1).max(64);
47
+ const text = (value) => value === null || value === undefined || value === "" ? null : String(value);
48
+ const num = (value) => value === null || value === undefined || value === "" ? null : Number(value);
49
+ const many = (value) => {
50
+ if (Array.isArray(value))
51
+ return value.map(String);
52
+ if (typeof value === "string" && value.startsWith("[")) {
53
+ try {
54
+ const parsed = JSON.parse(value);
55
+ return Array.isArray(parsed) ? parsed.map(String) : [];
56
+ }
57
+ catch {
58
+ return [];
59
+ }
60
+ }
61
+ return value === null || value === undefined || value === "" ? [] : [String(value)];
62
+ };
63
+ const whoValues = DISCOUNT_WHO_OPTIONS.map((o) => o.value);
64
+ const soldValues = SOLD_OBJECTS.map((o) => o.value);
65
+ const day = z.string().regex(/^\d{4}-\d{2}-\d{2}$/, "a day, YYYY-MM-DD");
66
+ /** A discount's terms, as a tool takes them. Every bound is also the field's, kept by the host. */
67
+ const terms = {
68
+ note: z.string().max(2000).describe("Why it exists, for staff"),
69
+ kind: z
70
+ .enum(["percent", "amount", "price"])
71
+ .describe("percent: a percentage off; amount: money off the order; price: a set price each"),
72
+ percent: z.number().min(1).max(100).describe("For percent: 1 to 100"),
73
+ amount: z
74
+ .number()
75
+ .min(0)
76
+ .describe("For amount: the money off, in the currency's major unit; for price: what each costs"),
77
+ automatic: z
78
+ .boolean()
79
+ .describe("True: applies by itself with no code (a member's price, a customer rate)"),
80
+ code: z
81
+ .string()
82
+ .max(64)
83
+ .describe(`A shared promo code anyone may type, at least ${CODE_MIN_LENGTH} letters or digits ` +
84
+ "(the host keeps it in capitals without spaces and refuses one another discount has)"),
85
+ who: z.enum(whoValues).describe("Who it is for. Anything but anyone needs a signed-in buyer"),
86
+ organisations: z.array(id).max(50).describe("Organisation ids, for who = organisation"),
87
+ tag: z.string().max(80).describe("The tag, for who = tag"),
88
+ appliesTo: z
89
+ .array(z.enum(soldValues))
90
+ .max(SOLD_OBJECTS.length)
91
+ .describe("What it covers (drop-ins, tickets, passes, courses, goods). Empty: everything"),
92
+ from: day.describe("First day it applies (UTC)"),
93
+ until: day.describe("Last day it applies (UTC)"),
94
+ totalUses: z.number().int().min(1).describe("Most orders in total"),
95
+ perPerson: z.number().int().min(1).describe("Most orders per person"),
96
+ minSpend: z.number().min(0).describe("Least the covered lines must cost"),
97
+ };
98
+ const discountOut = z.object({
99
+ id: z.string(),
100
+ name: z.string().nullable(),
101
+ state: z.string().nullable(),
102
+ kind: z.string().nullable(),
103
+ percent: z.number().nullable(),
104
+ amount: z.number().nullable(),
105
+ automatic: z.boolean(),
106
+ code: z.string().nullable().describe("The shared promo code, if it has one"),
107
+ who: z.string().nullable(),
108
+ appliesTo: z.array(z.string()),
109
+ from: z.string().nullable(),
110
+ until: z.string().nullable(),
111
+ totalUses: z.number().nullable(),
112
+ perPerson: z.number().nullable(),
113
+ minSpend: z.number().nullable(),
114
+ });
115
+ function discountShape(row) {
116
+ const v = row.values;
117
+ return {
118
+ id: row.id,
119
+ name: text(v.name),
120
+ state: text(v.state),
121
+ kind: text(v.kind),
122
+ percent: num(v.percent),
123
+ amount: num(v.amount),
124
+ automatic: v.automatic === true || v.automatic === 1,
125
+ code: text(v.code),
126
+ who: text(v.who),
127
+ appliesTo: many(v.appliesTo),
128
+ from: text(v.from),
129
+ until: text(v.until),
130
+ totalUses: num(v.totalUses),
131
+ perPerson: num(v.perPerson),
132
+ minSpend: num(v.minSpend),
133
+ };
134
+ }
135
+ const getDiscount = (ctx, discountId) => ctx.ops.call("record.get", { object: DISCOUNT, id: discountId });
136
+ /** Who started the call, for the record (a staff caller's name). */
137
+ const callerName = (ctx) => ctx.caller && "name" in ctx.caller && typeof ctx.caller.name === "string"
138
+ ? ctx.caller.name
139
+ : null;
140
+ // --- Reading -------------------------------------------------------------------------------------
141
+ const listRow = discountOut.extend({
142
+ used: z.number().describe("Orders paid with it"),
143
+ held: z.number().describe("Unpaid orders holding a use of it"),
144
+ given: z.number().describe("Money it took off paid orders, in the currency's minor unit"),
145
+ });
146
+ export const DISCOUNTS_LIMIT = 100;
147
+ export const discounts = defineTool({
148
+ description: "The business's discounts (promo codes, members' prices and customer rates): their terms, " +
149
+ "state (draft, active = live, paused, ended), and how often each was used and what it took " +
150
+ "off paid orders (in minor units, cents). Use state to narrow it ('which codes are live?'). " +
151
+ "Never shows single-use codes (they are kept as their hash). Read-only.",
152
+ input: z.object({
153
+ state: z.enum(["draft", "active", "paused", "ended"]).optional(),
154
+ automatic: z.boolean().optional().describe("Only prices that apply by themselves, or not"),
155
+ }),
156
+ output: z.object({ discounts: z.array(listRow), truncated: z.boolean() }),
157
+ risk: "read",
158
+ async handler(input, ctx) {
159
+ const where = [];
160
+ const params = [];
161
+ if (input.state) {
162
+ where.push("d.state = ?");
163
+ params.push(input.state);
164
+ }
165
+ if (input.automatic !== undefined) {
166
+ where.push(input.automatic ? "d.automatic = 1" : "coalesce(d.automatic, 0) = 0");
167
+ }
168
+ const result = await ctx.ops.call("query.sql", {
169
+ sql: "SELECT d.id AS id, d.name AS name, d.state AS state, d.kind AS kind, " +
170
+ "d.percent AS percent, d.amount AS amount, d.automatic AS automatic, d.code AS code, " +
171
+ // `from` is a reserved word: its column is `from_`.
172
+ "d.who AS who, d.applies_to AS applies_to, d.from_ AS from_day, d.until AS until, " +
173
+ "d.total_uses AS total_uses, d.per_person AS per_person, d.min_spend AS min_spend, " +
174
+ "(SELECT count(*) FROM rec_discount_use u WHERE u.discount_id = d.id AND u.state = 'used') AS used, " +
175
+ "(SELECT count(*) FROM rec_discount_use u WHERE u.discount_id = d.id AND u.state = 'held') AS held, " +
176
+ "(SELECT coalesce(sum(u.amount), 0) FROM rec_discount_use u WHERE u.discount_id = d.id AND u.state = 'used') AS given " +
177
+ "FROM rec_x_offers_discount d" +
178
+ (where.length ? ` WHERE ${where.join(" AND ")}` : "") +
179
+ ` ORDER BY d.name ASC LIMIT ${DISCOUNTS_LIMIT + 1}`,
180
+ params,
181
+ });
182
+ const rows = result.rows.slice(0, DISCOUNTS_LIMIT);
183
+ return {
184
+ truncated: result.rows.length > DISCOUNTS_LIMIT,
185
+ discounts: rows.map((r) => ({
186
+ ...discountShape({
187
+ id: String(r.id),
188
+ title: text(r.name),
189
+ values: {
190
+ name: r.name,
191
+ state: r.state,
192
+ kind: r.kind,
193
+ percent: r.percent,
194
+ amount: r.amount,
195
+ automatic: r.automatic,
196
+ code: r.code,
197
+ who: r.who,
198
+ appliesTo: r.applies_to,
199
+ from: r.from_day,
200
+ until: r.until,
201
+ totalUses: r.total_uses,
202
+ perPerson: r.per_person,
203
+ minSpend: r.min_spend,
204
+ },
205
+ }),
206
+ used: Number(r.used ?? 0),
207
+ held: Number(r.held ?? 0),
208
+ given: Number(r.given ?? 0),
209
+ })),
210
+ };
211
+ },
212
+ });
213
+ const batchRow = z.object({
214
+ batch: z.string().nullable(),
215
+ made: z.number(),
216
+ working: z.number().describe("Codes not voided"),
217
+ used: z.number().describe("Codes used on at least one paid order"),
218
+ usesPerCode: z.number().nullable(),
219
+ madeBy: z.string().nullable(),
220
+ madeAt: z.string().nullable(),
221
+ });
222
+ export const codeBatches = defineTool({
223
+ description: "The batches of single-use codes made for one discount: how many were made, how many still " +
224
+ "work and how many were used, who made them and when. Never the codes themselves, which " +
225
+ "were shown once to the person who made them. Read-only.",
226
+ input: z.object({ discountId: id }),
227
+ output: z.object({ batches: z.array(batchRow) }),
228
+ risk: "read",
229
+ async handler(input, ctx) {
230
+ const result = await ctx.ops.call("query.sql", {
231
+ sql: "SELECT c.batch AS batch, count(*) AS made, " +
232
+ "sum(CASE WHEN c.active = 1 THEN 1 ELSE 0 END) AS working, " +
233
+ "sum(CASE WHEN EXISTS (SELECT 1 FROM rec_discount_use u WHERE u.code_id = c.id " +
234
+ "AND u.state = 'used') THEN 1 ELSE 0 END) AS used, " +
235
+ "max(c.uses) AS uses, max(c.made_by) AS made_by, min(c.created_at) AS made_at " +
236
+ "FROM rec_x_offers_code c WHERE c.discount = ? GROUP BY c.batch " +
237
+ "ORDER BY made_at DESC LIMIT 100",
238
+ params: [input.discountId],
239
+ });
240
+ return {
241
+ batches: result.rows.map((r) => ({
242
+ batch: text(r.batch),
243
+ made: Number(r.made ?? 0),
244
+ working: Number(r.working ?? 0),
245
+ used: Number(r.used ?? 0),
246
+ usesPerCode: num(r.uses),
247
+ madeBy: text(r.made_by),
248
+ madeAt: text(r.made_at),
249
+ })),
250
+ };
251
+ },
252
+ });
253
+ // --- Drafting and changing -----------------------------------------------------------------------
254
+ const opened = z.object({ object: z.string(), id: z.string() });
255
+ export const draftDiscount = defineTool({
256
+ description: "Draft a discount: a promo code for a campaign (code = a word such as JANUARY26), a member's " +
257
+ "price (automatic = true, who = members, kind = price or percent, appliesTo = what it " +
258
+ "covers), a customer rate (automatic, who = organisation with organisations) or a discount " +
259
+ "for single-use codes (no code; a person then makes a batch). It is made as a draft and " +
260
+ "applies to nobody until a person makes it live with activateDiscount. The host refuses a " +
261
+ "code shorter than 6 characters or one another discount has. Returns the draft.",
262
+ input: z.object({
263
+ name: z.string().trim().min(1).max(120),
264
+ kind: terms.kind,
265
+ percent: terms.percent.optional(),
266
+ amount: terms.amount.optional(),
267
+ automatic: terms.automatic.optional(),
268
+ code: terms.code.optional(),
269
+ who: terms.who.optional(),
270
+ organisations: terms.organisations.optional(),
271
+ tag: terms.tag.optional(),
272
+ appliesTo: terms.appliesTo.optional(),
273
+ from: terms.from.optional(),
274
+ until: terms.until.optional(),
275
+ totalUses: terms.totalUses.optional(),
276
+ perPerson: terms.perPerson.optional(),
277
+ minSpend: terms.minSpend.optional(),
278
+ note: terms.note.optional(),
279
+ }),
280
+ output: discountOut.extend({ open: opened }),
281
+ risk: "write",
282
+ permission: "offers:manage",
283
+ async handler(input, ctx) {
284
+ // Made in the initial state, draft: the host refuses any other for anyone but itself.
285
+ const { id: discountId } = await ctx.ops.call("record.create", {
286
+ object: DISCOUNT,
287
+ values: input,
288
+ });
289
+ const row = await getDiscount(ctx, discountId);
290
+ return { ...discountShape(row), open: { object: DISCOUNT, id: discountId } };
291
+ },
292
+ });
293
+ const nullable = (schema) => schema.nullable().optional();
294
+ export const changeDiscount = defineTool({
295
+ description: "Change a discount's terms: what is off, what it covers, who it is for, its dates, limits " +
296
+ "or its shared promo code (null clears one). Not its state: use activateDiscount, " +
297
+ "pauseDiscount or endDiscount. A change to a live discount changes what buyers are charged " +
298
+ "from the next order, so a person makes it: the assistant's call waits for a person. Orders " +
299
+ "already started keep the deal they were priced with. Returns the discount.",
300
+ input: z.object({
301
+ discountId: id,
302
+ name: z.string().trim().min(1).max(120).optional(),
303
+ kind: terms.kind.optional(),
304
+ percent: nullable(terms.percent),
305
+ amount: nullable(terms.amount),
306
+ automatic: terms.automatic.optional(),
307
+ code: nullable(terms.code),
308
+ who: terms.who.optional(),
309
+ organisations: nullable(terms.organisations),
310
+ tag: nullable(terms.tag),
311
+ appliesTo: nullable(terms.appliesTo),
312
+ from: nullable(terms.from),
313
+ until: nullable(terms.until),
314
+ totalUses: nullable(terms.totalUses),
315
+ perPerson: nullable(terms.perPerson),
316
+ minSpend: nullable(terms.minSpend),
317
+ note: nullable(terms.note),
318
+ }),
319
+ output: discountOut,
320
+ risk: "write",
321
+ permission: "offers:manage",
322
+ personApproves: true,
323
+ async handler(input, ctx) {
324
+ const { discountId, ...values } = input;
325
+ if (Object.keys(values).length === 0) {
326
+ throw new OpsCallError("invalid_input", "Say what to change", { field: "discountId" });
327
+ }
328
+ await ctx.ops.call("record.update", { object: DISCOUNT, id: discountId, values });
329
+ return discountShape(await getDiscount(ctx, discountId));
330
+ },
331
+ });
332
+ // --- Making live, pausing, ending ----------------------------------------------------------------
333
+ /** Moves a discount from its current state (ADR 0437: of two moves at once, one goes through). */
334
+ async function move(ctx, discountId, to) {
335
+ const row = await getDiscount(ctx, discountId);
336
+ const from = text(row.values.state);
337
+ if (from === to)
338
+ return discountShape(row);
339
+ // The host refuses a move the object does not declare (from ended, say), in its own words.
340
+ await ctx.ops.call("record.update", {
341
+ object: DISCOUNT,
342
+ id: discountId,
343
+ values: { state: to },
344
+ ...(from ? { from } : {}),
345
+ });
346
+ return discountShape(await getDiscount(ctx, discountId));
347
+ }
348
+ const moveInput = z.object({ discountId: id });
349
+ export const activateDiscount = defineTool({
350
+ description: "Make a draft or paused discount live: from now on the host applies it to every order it " +
351
+ "covers (by its code, or by itself for a member's price). A person's decision with " +
352
+ "offers:manage: the assistant may ask, and its call waits for a person to approve. Check " +
353
+ "the terms first with discounts. Returns the discount.",
354
+ input: moveInput,
355
+ output: discountOut,
356
+ risk: "write",
357
+ permission: "offers:manage",
358
+ personApproves: true,
359
+ recordAction: {
360
+ object: DISCOUNT,
361
+ label: "Make live",
362
+ idInput: "discountId",
363
+ confirm: "Make this discount live? The host applies it to orders from now on.",
364
+ hideWhen: { field: "state", values: ["active", "ended"] },
365
+ },
366
+ handler: (input, ctx) => move(ctx, input.discountId, "active"),
367
+ });
368
+ export const pauseDiscount = defineTool({
369
+ description: "Pause a live discount: it applies to no new order until it is made live again. Orders " +
370
+ "already started keep their deal. A person's decision with offers:manage (the assistant's " +
371
+ "call waits for a person). Returns the discount.",
372
+ input: moveInput,
373
+ output: discountOut,
374
+ risk: "write",
375
+ permission: "offers:manage",
376
+ personApproves: true,
377
+ recordAction: {
378
+ object: DISCOUNT,
379
+ label: "Pause",
380
+ idInput: "discountId",
381
+ confirm: "Pause this discount? New orders will not get it until it is live again.",
382
+ hideWhen: { field: "state", values: ["draft", "paused", "ended"] },
383
+ },
384
+ handler: (input, ctx) => move(ctx, input.discountId, "paused"),
385
+ });
386
+ export const endDiscount = defineTool({
387
+ description: "End a discount for good: it applies to no new order and cannot be made live again (draft " +
388
+ "a new one instead). Orders already started keep their deal; its codes stop working. A " +
389
+ "person's decision with offers:manage (the assistant's call waits for a person). Returns the " +
390
+ "discount.",
391
+ input: moveInput,
392
+ output: discountOut,
393
+ risk: "destructive",
394
+ permission: "offers:manage",
395
+ personApproves: true,
396
+ recordAction: {
397
+ object: DISCOUNT,
398
+ label: "End",
399
+ idInput: "discountId",
400
+ confirm: "End this discount for good? It cannot be made live again.",
401
+ hideWhen: { field: "state", values: ["ended"] },
402
+ },
403
+ handler: (input, ctx) => move(ctx, input.discountId, "ended"),
404
+ });
405
+ // --- Single-use codes ----------------------------------------------------------------------------
406
+ /** A batch's default name: when it was made. */
407
+ const batchName = (at) => `Batch ${at.toISOString().slice(0, 16).replace("T", " ")}`;
408
+ /** The codes among `codes` whose records exist (a write that failed after it committed). */
409
+ async function written(ctx, discountId, codes) {
410
+ const hashes = await Promise.all(codes.map((c) => codeHash(c)));
411
+ const page = await ctx.ops.call("record.list", {
412
+ object: CODE,
413
+ filter: {
414
+ and: [
415
+ { field: "discount", op: "eq", value: discountId },
416
+ { field: "word", op: "in", value: hashes },
417
+ ],
418
+ },
419
+ limit: WRITE_CHUNK,
420
+ fields: ["word"],
421
+ });
422
+ const found = new Set(page.items.map((r) => String(r.values.word)));
423
+ return codes.filter((_, i) => found.has(hashes[i]));
424
+ }
425
+ export const generateCodes = defineTool({
426
+ description: `Make a batch of up to ${BATCH_MAX} random single-use codes for a discount, each good for ` +
427
+ "usesPerCode orders (1 by default), and show them once, in this answer, to export or send. " +
428
+ "The host keeps only each code's hash, so they cannot be shown again: keep the list. A " +
429
+ "person only, with offers:manage, at the discount's page; the assistant cannot make codes. " +
430
+ "Not for an ended discount. The discount still applies only once it is live. If the batch " +
431
+ "stops part way, the answer says so and holds every code that was made.",
432
+ input: z.object({
433
+ discountId: id,
434
+ count: z.coerce.number().int().min(1).max(BATCH_MAX).default(50),
435
+ usesPerCode: z.coerce.number().int().min(1).max(1000).default(1),
436
+ batch: z.string().trim().min(1).max(60).optional().describe("A name for the batch"),
437
+ }),
438
+ output: z.object({
439
+ discountId: z.string(),
440
+ batch: z.string(),
441
+ made: z.number(),
442
+ complete: z.boolean().describe("False: the batch stopped part way; see problem"),
443
+ problem: z.string().nullable(),
444
+ codes: z.array(z.string()).describe("The codes, shown once: the host keeps only their hash"),
445
+ }),
446
+ risk: "bulk-write",
447
+ permission: "offers:manage",
448
+ humanOnly: true,
449
+ // Shown once: never in the audit log, an approval's stored result or a replayed reply (ADR 0628).
450
+ redactResult: ["codes"],
451
+ recordAction: {
452
+ object: DISCOUNT,
453
+ label: "Make single-use codes",
454
+ idInput: "discountId",
455
+ ask: {
456
+ input: "count",
457
+ label: "How many",
458
+ options: [
459
+ { value: "10", label: "10 codes" },
460
+ { value: "50", label: "50 codes" },
461
+ { value: "100", label: "100 codes" },
462
+ { value: "500", label: "500 codes" },
463
+ ],
464
+ },
465
+ hideWhen: { field: "state", values: ["ended"] },
466
+ },
467
+ async handler(input, ctx) {
468
+ // The discount is read first: an unknown id is refused before any code is made, and an ended
469
+ // one too (its codes would never work, and nobody would know why).
470
+ const discount = await getDiscount(ctx, input.discountId);
471
+ if (discount.values.state === "ended") {
472
+ throw new OpsCallError("invalid_input", "This discount has ended: its codes would never work. Draft a new discount for them.", { field: "discountId", reason: "ended" });
473
+ }
474
+ const batch = input.batch ?? batchName(new Date());
475
+ const madeBy = callerName(ctx);
476
+ const codes = randomCodes(input.count);
477
+ const made = [];
478
+ let problem = null;
479
+ // In chunks (record.createMany, all or none each), so a batch of hundreds stays within what
480
+ // one host call writes. A chunk refused because a code was taken (80 random bits: it does not
481
+ // happen, but a unique index says so) is made again once with new codes.
482
+ for (let start = 0; start < codes.length && problem === null; start += WRITE_CHUNK) {
483
+ let chunk = codes.slice(start, start + WRITE_CHUNK);
484
+ for (let attempt = 0;; attempt++) {
485
+ const records = await Promise.all(chunk.map(async (code, i) => ({
486
+ label: `${batch} #${String(start + i + 1).padStart(4, "0")}`,
487
+ discount: input.discountId,
488
+ batch,
489
+ word: await codeHash(code),
490
+ uses: input.usesPerCode,
491
+ active: true,
492
+ ...(madeBy ? { madeBy } : {}),
493
+ })));
494
+ try {
495
+ await ctx.ops.call("record.createMany", { object: CODE, records });
496
+ made.push(...chunk);
497
+ break;
498
+ }
499
+ catch (error) {
500
+ const taken = error instanceof OpsCallError &&
501
+ error.code === "conflict" &&
502
+ attempt === 0 &&
503
+ JSON.stringify(error.details ?? {}).includes("code_taken");
504
+ if (taken) {
505
+ chunk = randomCodes(chunk.length);
506
+ continue;
507
+ }
508
+ // A write can fail after the database kept it (a call that timed out on the way back):
509
+ // the codes it made are given to the person with the rest, never left unheld.
510
+ const kept = await written(ctx, input.discountId, chunk).catch(() => []);
511
+ made.push(...kept);
512
+ const why = error instanceof Error ? error.message : "the host refused it";
513
+ problem = `Stopped after ${made.length} codes: ${why}`;
514
+ break;
515
+ }
516
+ }
517
+ }
518
+ if (!made.length && problem) {
519
+ throw new OpsCallError("conflict", problem, { discountId: input.discountId });
520
+ }
521
+ return {
522
+ discountId: input.discountId,
523
+ batch,
524
+ made: made.length,
525
+ complete: problem === null,
526
+ problem,
527
+ codes: made,
528
+ };
529
+ },
530
+ });
531
+ /** Switches off the working codes of a discount matching `filters`: at most VOID_MAX a call. */
532
+ async function voidMatching(ctx, discountId, filters) {
533
+ const where = {
534
+ and: [
535
+ { field: "discount", op: "eq", value: discountId },
536
+ { field: "active", op: "eq", value: true },
537
+ ...filters,
538
+ ],
539
+ };
540
+ let voided = 0;
541
+ while (voided < VOID_MAX) {
542
+ const page = await ctx.ops.call("record.list", {
543
+ object: CODE,
544
+ filter: where,
545
+ limit: Math.min(200, VOID_MAX - voided),
546
+ fields: ["active"],
547
+ });
548
+ if (!page.items.length)
549
+ break;
550
+ for (const code of page.items) {
551
+ await ctx.ops.call("record.update", {
552
+ object: CODE,
553
+ id: code.id,
554
+ values: { active: false },
555
+ });
556
+ voided++;
557
+ }
558
+ }
559
+ const left = await ctx.ops.call("record.count", {
560
+ object: CODE,
561
+ filter: where,
562
+ });
563
+ return { voided, remaining: Number(left.count ?? 0) };
564
+ }
565
+ const voidOut = z.object({ voided: z.number(), remaining: z.number() });
566
+ export const voidBatch = defineTool({
567
+ description: `Stop a whole batch of single-use codes working, by its name; at most ${VOID_MAX} a call ` +
568
+ "(call again while remaining is more than 0). Orders already started keep their deal. A " +
569
+ "person's decision with offers:manage (the assistant's call waits for a person). Returns how " +
570
+ "many were voided.",
571
+ input: z.object({ discountId: id, batch: z.string().trim().min(1).max(60) }),
572
+ output: voidOut,
573
+ risk: "bulk-write",
574
+ permission: "offers:manage",
575
+ personApproves: true,
576
+ handler: (input, ctx) => voidMatching(ctx, input.discountId, [{ field: "batch", op: "eq", value: input.batch }]),
577
+ });
578
+ export const voidCodes = defineTool({
579
+ description: "Stop single-use codes working, typed as they were given out (a code that leaked). A person " +
580
+ "only, with offers:manage, at the screen: the codes are never kept, in the audit log or in a " +
581
+ "request waiting for approval, so the assistant cannot ask for this (it may ask to void the " +
582
+ "whole batch with voidBatch). Returns how many were voided.",
583
+ input: z.object({
584
+ discountId: id,
585
+ codes: z.array(z.string().max(64)).min(1).max(50).describe("Codes as typed"),
586
+ }),
587
+ output: voidOut,
588
+ risk: "bulk-write",
589
+ permission: "offers:manage",
590
+ humanOnly: true,
591
+ // The codes a person types are never kept in the audit log.
592
+ redact: ["codes"],
593
+ async handler(input, ctx) {
594
+ const hashes = await Promise.all(input.codes.map((c) => codeHash(foldCode(c))));
595
+ return voidMatching(ctx, input.discountId, [{ field: "word", op: "in", value: hashes }]);
596
+ },
597
+ });
package/package.json CHANGED
@@ -1,6 +1,33 @@
1
1
  {
2
2
  "name": "@composable-os/pack-offers",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.1.0-beta.16",
4
+ "license": "FSL-1.1-ALv2",
5
+ "type": "module",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/timoconnellaus/composable-os.git"
9
+ },
10
+ "homepage": "https://composableos.dev",
11
+ "publishConfig": {
12
+ "access": "public",
13
+ "provenance": true
14
+ },
15
+ "description": "Offers: money off, declared as discounts the host applies when it prices an order (stage 34 step 5, ADR 0699): promo codes, batches of single-use codes, members' prices and customer rates, with the limits staff set and a person making each one live. Bundled as source into cos-runner.",
16
+ "exports": {
17
+ ".": {
18
+ "types": "./dist/index.d.ts",
19
+ "default": "./dist/index.js"
20
+ }
21
+ },
22
+ "files": [
23
+ "dist"
24
+ ],
25
+ "composableOs": {
26
+ "optional": true,
27
+ "label": "Offers",
28
+ "description": "Promo codes for a campaign, single-use codes for a newsletter, and members' prices that apply by themselves, with dates, limits and a person making each one live."
29
+ },
30
+ "dependencies": {
31
+ "@composable-os/sdk": "0.1.0-beta.16"
32
+ }
33
+ }
package/README.md DELETED
@@ -1,3 +0,0 @@
1
- # Temporary Holding Version
2
-
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.