@composable-os/cli 0.1.0-beta.10 → 0.1.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (64) hide show
  1. package/dist/{accounts-X4CKM3HL.js → accounts-UHYLCLEY.js} +10 -11
  2. package/dist/{blocks-YWDHEBOK.js → blocks-5IFU25J6.js} +2 -2
  3. package/dist/chunk-2IVEVPMY.js +669 -0
  4. package/dist/{chunk-QGGJ2G6Z.js → chunk-2TWV3SVB.js} +3 -3
  5. package/dist/chunk-2XC5JLBO.js +1931 -0
  6. package/dist/chunk-324WJXNP.js +320 -0
  7. package/dist/chunk-6ELZRNUU.js +116 -0
  8. package/dist/{chunk-YJJHF65I.js → chunk-6WGFA2IV.js} +58 -174
  9. package/dist/{chunk-A4NTSYWV.js → chunk-6XTU2MTP.js} +196 -10
  10. package/dist/{chunk-Q4N55M2Z.js → chunk-7D4GKZOX.js} +66 -3
  11. package/dist/{chunk-GYSGVT6R.js → chunk-7OGCMQXG.js} +9 -9
  12. package/dist/chunk-DHS2CV2M.js +139 -0
  13. package/dist/{chunk-LJFLENFC.js → chunk-E64SG24J.js} +1 -1
  14. package/dist/{chunk-Z3RMMB6S.js → chunk-FJIZGS5Q.js} +45 -15
  15. package/dist/chunk-K34UKWEI.js +298 -0
  16. package/dist/{chunk-LLULPZAJ.js → chunk-LAAL4YGR.js} +4 -4
  17. package/dist/{chunk-CP6BXI6F.js → chunk-LO6WGU5Y.js} +1338 -974
  18. package/dist/{chunk-Y7JZFSTQ.js → chunk-MBIKVRAC.js} +6 -6
  19. package/dist/{chunk-WC5LHBBA.js → chunk-P6UWZ6QQ.js} +1 -1
  20. package/dist/{chunk-6VXHPKGG.js → chunk-PDD2ETVF.js} +8 -8
  21. package/dist/{chunk-6UPUF4ML.js → chunk-UB4I2QKR.js} +1957 -380
  22. package/dist/{chunk-M7A6FR2Z.js → chunk-WHKJGF36.js} +154 -322
  23. package/dist/{chunk-VY64DMQO.js → chunk-XIDLW3EP.js} +190 -21
  24. package/dist/{chunk-IFG4FRW5.js → chunk-YFTLIEWU.js} +1 -1
  25. package/dist/{chunk-JJHHNV46.js → chunk-YNUZRTPH.js} +5 -50
  26. package/dist/{chunk-WO6D3XP3.js → chunk-ZAWES2UD.js} +31 -18
  27. package/dist/{chunk-K6T42YCH.js → chunk-ZZFWMVJO.js} +5 -5
  28. package/dist/{cli-2DFENR62.js → cli-5UNY5G5L.js} +22 -20
  29. package/dist/{cli-YIOVSKOD.js → cli-UYZMVQMR.js} +16 -13
  30. package/dist/cli.js +1 -1
  31. package/dist/{client-repo-PRU3VCQQ.js → client-repo-SE4EKG6W.js} +2 -2
  32. package/dist/create.js +1 -1
  33. package/dist/{fields-2NC7LSYE.js → fields-FTWWMD7N.js} +3 -3
  34. package/dist/grants-LOW6TSWD.js +32 -0
  35. package/dist/invoke-6KVT6WJI.js +41 -0
  36. package/dist/moves-E2HKYCTK.js +41 -0
  37. package/dist/{order-PUWD65BC.js → order-U4KZLLSJ.js} +2 -2
  38. package/dist/{person-WIQQ7ITU.js → person-UHLVBVLR.js} +9 -10
  39. package/dist/plan-on-sale-TJPFCNL7.js +26 -0
  40. package/dist/platform/migrations/0610_waitlists.sql +54 -0
  41. package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
  42. package/dist/platform/migrations/0650_person_links.sql +90 -0
  43. package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
  44. package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
  45. package/dist/platform/sdk/capacity.ts +102 -0
  46. package/dist/platform/sdk/contract.ts +25 -0
  47. package/dist/platform/sdk/manifest.ts +77 -1
  48. package/dist/platform/sdk/sellable.ts +251 -1
  49. package/dist/platform/sdk/states.ts +163 -49
  50. package/dist/{run-RT2HVWMK.js → run-7P4RQALH.js} +2 -2
  51. package/dist/{run-PZUCSDDL.js → run-PO3W5BFA.js} +1 -1
  52. package/dist/{run-Y7T4TVOL.js → run-ZCGFMEZF.js} +2 -2
  53. package/dist/src-CRO35DYY.js +46 -0
  54. package/dist/{src-XTOD7EXW.js → src-I3IJ4NKC.js} +8 -2
  55. package/dist/{visibility-DLGHU4YN.js → visibility-TVXZ67FD.js} +12 -4
  56. package/package.json +2 -2
  57. package/dist/chunk-6GDEDOV7.js +0 -157
  58. package/dist/chunk-O2UIZHND.js +0 -249
  59. package/dist/chunk-R4W5XAUD.js +0 -837
  60. package/dist/chunk-TQFGGSA4.js +0 -748
  61. package/dist/grants-QXMKYMGB.js +0 -32
  62. package/dist/invoke-I3NNNXVL.js +0 -39
  63. package/dist/plan-on-sale-NB774CQL.js +0 -26
  64. package/dist/src-GYS6NBQB.js +0 -44
@@ -1,66 +1,58 @@
1
1
  #!/usr/bin/env node
2
2
  import {
3
3
  applyTransition,
4
- callerMover,
5
- onRecordMove,
6
- resolveStateRequest,
7
- transitionTimeline
8
- } from "./chunk-R4W5XAUD.js";
4
+ callerMover
5
+ } from "./chunk-324WJXNP.js";
9
6
  import {
10
7
  addDaysToDate,
11
8
  assignOwner,
12
9
  recordAssignment,
13
10
  setRecordWriter
14
- } from "./chunk-Z3RMMB6S.js";
15
- import {
16
- defineOperation,
17
- personsTool
18
- } from "./chunk-6GDEDOV7.js";
11
+ } from "./chunk-FJIZGS5Q.js";
19
12
  import {
20
- armSeriesStatement,
21
13
  boundOf,
22
- guardStatement,
23
14
  keyingChangeStatement,
24
- markEditedStatement,
25
- occurrenceStatement,
26
15
  periodOf,
27
16
  rekeyStatements,
28
17
  returnStatements,
29
- seriesVersion,
30
18
  spendStatements,
31
19
  termsSyncStatements
32
- } from "./chunk-JJHHNV46.js";
33
- import {
34
- addLocalDays,
35
- currencyDecimals,
36
- isoWeekday,
37
- localParts,
38
- parseLocalDate,
39
- parseLocalTime,
40
- wallClockOf,
41
- wallClockToInstant,
42
- wallClockToIso
43
- } from "./chunk-O2UIZHND.js";
20
+ } from "./chunk-YNUZRTPH.js";
44
21
  import {
45
22
  TRASH_RETENTION_DAYS,
46
23
  jsonList,
47
24
  listInputSchema,
48
- notifyStatements,
49
25
  pageSchema,
50
26
  restorableUntil,
51
27
  runListQuery
52
- } from "./chunk-K6T42YCH.js";
28
+ } from "./chunk-ZZFWMVJO.js";
53
29
  import {
54
- CompiledQuery,
30
+ WAITLIST_FOR,
31
+ armSeriesStatement,
55
32
  assertNoConfirmedClaims,
56
33
  assertNoLiveClaim,
57
34
  counterWrite,
35
+ defineOperation,
36
+ guardStatement,
37
+ isoWeekday,
58
38
  loadGeneralSettings,
59
- newId
60
- } from "./chunk-TQFGGSA4.js";
39
+ localParts,
40
+ markEditedStatement,
41
+ newId,
42
+ occurrenceStatement,
43
+ parseLocalDate,
44
+ parseLocalTime,
45
+ personsTool,
46
+ resolveStateRequest,
47
+ seriesVersion,
48
+ transitionTimeline,
49
+ wallClockOf,
50
+ wallClockToInstant
51
+ } from "./chunk-2XC5JLBO.js";
61
52
  import {
62
53
  ALLOWANCE_FIELDS,
63
54
  CAPACITY_FIELDS,
55
+ CompiledQuery,
64
56
  ConflictError,
65
57
  FIELD_TYPE_REGISTRY,
66
58
  ForbiddenError,
@@ -76,15 +68,15 @@ import {
76
68
  viewColumnOf,
77
69
  visibleSource,
78
70
  visibleTable
79
- } from "./chunk-A4NTSYWV.js";
71
+ } from "./chunk-6XTU2MTP.js";
80
72
  import {
81
73
  getObject,
82
74
  isCoreObject,
83
75
  listObjects
84
- } from "./chunk-IFG4FRW5.js";
76
+ } from "./chunk-YFTLIEWU.js";
85
77
  import {
86
78
  mediaObject
87
- } from "./chunk-Q4N55M2Z.js";
79
+ } from "./chunk-7D4GKZOX.js";
88
80
  import {
89
81
  SLUG_MAX,
90
82
  SLUG_RE,
@@ -92,9 +84,8 @@ import {
92
84
  documentRefs,
93
85
  external_exports,
94
86
  isDocumentType,
95
- moveOrigins,
96
87
  slugify
97
- } from "./chunk-CP6BXI6F.js";
88
+ } from "./chunk-LO6WGU5Y.js";
98
89
 
99
90
  // ../core/src/allowance/records.ts
100
91
  var PERIODS = ["total", "week", "month"];
@@ -541,12 +532,18 @@ function giveBack(ctx, spender, open, by) {
541
532
  addPending(ctx, pendingKey(open.object, open.record, open.period, open.zone), -1);
542
533
  return returnStatements(spender, by, ctx.now);
543
534
  }
544
- async function spenderWrite(ctx, object, id, before, written, outcome, by) {
535
+ async function spenderWrite(ctx, object, id, before, written, outcome, by, options = {}) {
545
536
  const def = spenderOf(object);
546
537
  if (!def || !object.states) return NOTHING;
547
538
  const ref = { object: object.name, id };
548
539
  const after = { ...before ?? {}, ...written, ...outcome.values };
549
540
  const to = outcome.moved?.id;
541
+ if (def.movedFrom && to === def.movedFrom.state && !options.movedInto) {
542
+ throw new ValidationError(
543
+ `${object.label} is moved by making the new one in its place (naming it in ${def.movedFrom.field}), in one write`,
544
+ { rule: "allowance", reason: "move_needs_target", field: object.states.field }
545
+ );
546
+ }
550
547
  const entering = to !== void 0 && def.spendIn.includes(to);
551
548
  const returning = to !== void 0 && def.returnIn.includes(to);
552
549
  const { relations, ownAt } = sources(def);
@@ -581,12 +578,63 @@ async function spenderWrite(ctx, object, id, before, written, outcome, by) {
581
578
  );
582
579
  }
583
580
  }
584
- const spending = entering && !open && !isWaived(after);
581
+ const fromId = def.movedFrom && before === null ? after[def.movedFrom.field] : null;
582
+ const moving = def.movedFrom !== void 0 && typeof fromId === "string" && fromId !== "";
583
+ let sourceWaived = false;
584
+ const madeByField = object.customer?.guardians?.madeBy;
585
+ let sourceMadeBy;
586
+ const orderField = object.sellable?.moves?.order;
587
+ let sourceOrder = null;
588
+ if (def.movedFrom && moving) {
589
+ if (by === "customer") {
590
+ throw new ValidationError(
591
+ `Only staff move a ${object.label.toLowerCase()} to another; cancel it and make a new one`,
592
+ { rule: "allowance", field: def.movedFrom.field }
593
+ );
594
+ }
595
+ if (!entering) {
596
+ throw new ValidationError(
597
+ `A ${object.label.toLowerCase()} moved from another is made in a state that spends`,
598
+ { rule: "allowance", field: def.movedFrom.field }
599
+ );
600
+ }
601
+ const source = await readValues(ctx, object, fromId);
602
+ if (!source) throw new NotFoundError(object.name, fromId);
603
+ if (source[def.person] !== after[def.person]) {
604
+ throw new ValidationError(`A ${object.label.toLowerCase()} moves to the same person`, {
605
+ rule: "allowance",
606
+ field: def.movedFrom.field
607
+ });
608
+ }
609
+ sourceWaived = isWaived(source);
610
+ if (madeByField) sourceMadeBy = source[madeByField] ?? null;
611
+ if (orderField) sourceOrder = source[orderField] ?? null;
612
+ if (!sourceWaived && isWaived(after)) {
613
+ throw new ValidationError(
614
+ `Whether ${object.label.toLowerCase()} spends a use moves with it: it cannot change now`,
615
+ { rule: "allowance", reason: "waived_kept", field: def.waived ?? def.movedFrom.field }
616
+ );
617
+ }
618
+ }
619
+ const spending = entering && !open && !isWaived(after) && !sourceWaived;
585
620
  const respending = open !== null && !returning && repointed;
586
621
  const fill = before === null || entering || repointed;
587
622
  const read = fill ? await readSpender(ctx, object, def, after, { needAt: spending || respending }) : { values: {}, at: ctx.now };
588
- const values = { ...read.values };
623
+ const values = {
624
+ ...read.values,
625
+ ...sourceWaived && def.waived ? { [def.waived]: true } : {},
626
+ ...madeByField && moving ? { [madeByField]: sourceMadeBy ?? null } : {},
627
+ ...orderField && moving && sourceOrder ? { [orderField]: sourceOrder } : {}
628
+ };
589
629
  const statements = [];
630
+ if (object.sellable?.moves && moving) {
631
+ statements.push(
632
+ CompiledQuery.raw(
633
+ "UPDATE core_order_line SET record_id = ? WHERE object_type = ? AND record_id = ?",
634
+ [id, object.name, fromId]
635
+ )
636
+ );
637
+ }
590
638
  const spenderValues = { ...after, ...values };
591
639
  if (returning && open) statements.push(...giveBack(ctx, ref, open, by));
592
640
  const namedNow = holderWritten && present(written[def.holder]) ? String(written[def.holder]) : null;
@@ -605,28 +653,19 @@ async function spenderWrite(ctx, object, id, before, written, outcome, by) {
605
653
  values[def.holder] = spent2.holder;
606
654
  return { values, statements };
607
655
  }
608
- if (!spending) return { values, statements };
609
656
  let movedFrom = null;
610
- const fromId = def.movedFrom && before === null ? after[def.movedFrom.field] : null;
611
- if (def.movedFrom && typeof fromId === "string" && fromId) {
612
- if (by === "customer") {
613
- throw new ValidationError(
614
- `Only staff move a ${object.label.toLowerCase()} to another; cancel it and make a new one`,
615
- { rule: "allowance", field: def.movedFrom.field }
616
- );
617
- }
618
- const source = await readValues(ctx, object, fromId);
619
- if (!source) throw new NotFoundError(object.name, fromId);
620
- if (source[def.person] !== spenderValues[def.person]) {
621
- throw new ValidationError(`A ${object.label.toLowerCase()} moves to the same person`, {
622
- rule: "allowance",
623
- field: def.movedFrom.field
624
- });
625
- }
657
+ if (def.movedFrom && moving) {
626
658
  movedFrom = await openUse(ctx, { object: object.name, id: fromId });
627
659
  if (!recordUpdate) throw new Error("allowance: the record writer is not set");
628
- await recordUpdate(ctx, object, fromId, { [object.states.field]: def.movedFrom.state }, { by });
660
+ await recordUpdate(
661
+ ctx,
662
+ object,
663
+ fromId,
664
+ { [object.states.field]: def.movedFrom.state },
665
+ { by, movedInto: id }
666
+ );
629
667
  }
668
+ if (!spending) return { values, statements };
630
669
  const stored = present(spenderValues[def.holder]) ? String(spenderValues[def.holder]) : null;
631
670
  const named = namedNow ?? (movedFrom ? movedFrom.record : stored);
632
671
  const spent = await spendFor(ctx, object, ref, spenderValues, read.at, by, {
@@ -1422,7 +1461,19 @@ async function prepareValues(ctx, object, values, mode, options = {}) {
1422
1461
  }
1423
1462
  const term = holderTerms(object).has(name);
1424
1463
  const ownCode = field.fieldType !== "formula" && field.extension !== void 0 && ctx.extension?.id === field.extension && (!term || personsTool(ctx, field.extension) !== null);
1425
- const hostCode = field.fieldType !== "formula" && options.by === "host";
1464
+ if (name === object.customer?.guardians?.madeBy) {
1465
+ if (mode === "create" && options.seamSet?.has(name)) {
1466
+ } else {
1467
+ throw new ValidationError(
1468
+ `${object.name}.${name} is set by the host and cannot be written`,
1469
+ {
1470
+ field: name
1471
+ }
1472
+ );
1473
+ }
1474
+ }
1475
+ const seamCode = options.seamSet?.has(name) === true;
1476
+ const hostCode = field.fieldType !== "formula" && (options.by === "host" || seamCode);
1426
1477
  if (!hostCode && hostFilled(object).has(name)) {
1427
1478
  throw new ValidationError(`${object.name}.${name} is set by the host and cannot be written`, {
1428
1479
  field: name
@@ -1668,7 +1719,7 @@ var recordCreate = defineOperation({
1668
1719
  async function createRecord(ctx, object, values, options = {}) {
1669
1720
  const requester = options.by ?? (object.states?.requests ? callerMover(ctx) : void 0);
1670
1721
  const asked = requester ? await resolveStateRequest(ctx, object, null, values, requester) : values;
1671
- const handed = options.by !== "host" && personsTool(ctx, object.extension) !== null && isGranted(object) ? await (await import("./grants-QXMKYMGB.js")).handGrantValues(ctx, object, asked) : asked;
1722
+ const handed = options.by !== "host" && personsTool(ctx, object.extension) !== null && isGranted(object) ? await (await import("./grants-LOW6TSWD.js")).handGrantValues(ctx, object, asked) : asked;
1672
1723
  const withDefaults = await slugsForCreate(ctx, object, await applyDefaults(ctx, object, handed));
1673
1724
  let prepared = await prepareValues(ctx, object, withDefaults, "create", options);
1674
1725
  assertOneOf(object, valuesOf(prepared));
@@ -1853,7 +1904,18 @@ async function updateRecord(ctx, object, id, values, options = {}) {
1853
1904
  const outcome = await applyTransition(ctx, object, id, before.values, valuesOf(prepared), {
1854
1905
  by
1855
1906
  });
1856
- const spent = await spenderWrite(ctx, object, id, before.values, valuesOf(prepared), outcome, by);
1907
+ const spent = await spenderWrite(
1908
+ ctx,
1909
+ object,
1910
+ id,
1911
+ before.values,
1912
+ valuesOf(prepared),
1913
+ outcome,
1914
+ by,
1915
+ {
1916
+ movedInto: options.movedInto
1917
+ }
1918
+ );
1857
1919
  prepared = withHostValues(prepared, withValues(outcome, spent.values), object);
1858
1920
  const edited = generatedRecordEdited(
1859
1921
  ctx,
@@ -1932,9 +1994,12 @@ async function updateRecord(ctx, object, id, values, options = {}) {
1932
1994
  }
1933
1995
  async function moveFollowers(ctx, object, id, to) {
1934
1996
  if (!to) return;
1935
- for (const follower of followersOf(object.name)) {
1936
- const target = Object.hasOwn(follower.when, to) ? follower.when[to] : void 0;
1937
- if (!target) continue;
1997
+ const following = followersOf(object.name).filter((f) => Object.hasOwn(f.when, to));
1998
+ if (!following.length) return;
1999
+ const claims = object.capacity && !ctx.simulation ? await ctx.db.selectFrom("core_capacity_claim").select(["id", "for_type", "for_id", "quantity"]).where("object_type", "=", object.name).where("record_id", "=", id).where("state", "in", ["held", "confirmed"]).execute() : null;
2000
+ const givenBack = /* @__PURE__ */ new Set();
2001
+ for (const follower of following) {
2002
+ const target = follower.when[to];
1938
2003
  const ids = await followerIds(ctx, follower, id);
1939
2004
  if (ids.length > FOLLOWERS_MAX) {
1940
2005
  throw new ConflictError(
@@ -1942,6 +2007,27 @@ async function moveFollowers(ctx, object, id, to) {
1942
2007
  { rule: "follows_too_many", object: follower.object.name }
1943
2008
  );
1944
2009
  }
2010
+ const fc = follower.object.claims;
2011
+ if (claims && fc?.object === object.name && fc.on === follower.relation) {
2012
+ const keeps = fc.held.includes(target) || fc.confirmed.includes(target);
2013
+ const moving = new Set(ids);
2014
+ if (!keeps) {
2015
+ for (const c of claims) {
2016
+ if (c.for_type === follower.object.name && moving.has(c.for_id)) givenBack.add(c.id);
2017
+ }
2018
+ }
2019
+ const waiting = fc.waitlist?.state;
2020
+ if (waiting && follower.from.includes(waiting) && ids.length) {
2021
+ const waiters = await followerIds(ctx, { ...follower, from: [waiting] }, id);
2022
+ if (waiters.length) {
2023
+ for (const c of claims) {
2024
+ if (c.for_type === WAITLIST_FOR && c.for_id === follower.object.name) {
2025
+ givenBack.add(c.id);
2026
+ }
2027
+ }
2028
+ }
2029
+ }
2030
+ }
1945
2031
  for (const child of ids) {
1946
2032
  await updateRecord(
1947
2033
  ctx,
@@ -1954,6 +2040,10 @@ async function moveFollowers(ctx, object, id, to) {
1954
2040
  );
1955
2041
  }
1956
2042
  }
2043
+ if (claims) {
2044
+ const expected = claims.filter((c) => !givenBack.has(c.id)).reduce((sum, c) => sum + Number(c.quantity), 0);
2045
+ ctx.write(guardStatement("claimed", object.name, id, expected));
2046
+ }
1957
2047
  }
1958
2048
  function assertMovesFrom(object, stored, values, from) {
1959
2049
  const field = object.states?.field ?? object.stages?.field;
@@ -2309,257 +2399,6 @@ var recordOperations = [
2309
2399
  schemaObjects
2310
2400
  ];
2311
2401
 
2312
- // ../core/src/orders/grants.ts
2313
- var CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
2314
- var GRANT_CODE_LENGTH = 26;
2315
- function newGrantCode() {
2316
- const bytes = crypto.getRandomValues(new Uint8Array(GRANT_CODE_LENGTH));
2317
- return Array.from(bytes, (b) => CODE_ALPHABET[b & 31]).join("");
2318
- }
2319
- function grantFieldValue(object, row, name) {
2320
- const field = object.fields.find((f) => f.name === name);
2321
- const column = field ? viewColumnOf(field) : null;
2322
- if (!field || !column || !row) return null;
2323
- const raw = row[column] ?? null;
2324
- if (field.fieldType === "formula") return formulaFromStorage(field.options?.resultType, raw);
2325
- const type = field.fieldType;
2326
- return type && FIELD_TYPE_REGISTRY[type] ? FIELD_TYPE_REGISTRY[type].fromStorage(raw) : raw;
2327
- }
2328
- async function readGrantItem(ctx, item, id) {
2329
- return await ctx.db.selectFrom(visibleSource(orgReader(ctx.db), item)).selectAll().where("id", "=", id).executeTakeFirst();
2330
- }
2331
- async function validFrom(ctx, granted, valid, itemValue) {
2332
- const zone = (await loadGeneralSettings(ctx.db)).timezone || "UTC";
2333
- const typeOf = (field) => granted.fields.find((f) => f.name === field)?.fieldType;
2334
- const local = localParts(ctx.now, zone);
2335
- const out = {};
2336
- if (valid.from) out[valid.from] = typeOf(valid.from) === "date" ? local.date : ctx.now;
2337
- const raw = valid.days ? itemValue(valid.days.slice("item.".length)) : null;
2338
- const days = typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : null;
2339
- if (valid.until && days) {
2340
- if (typeOf(valid.until) === "date") {
2341
- const d = addLocalDays(local, days - 1);
2342
- out[valid.until] = `${d.year}-${String(d.month).padStart(2, "0")}-${String(d.day).padStart(2, "0")}`;
2343
- } else {
2344
- out[valid.until] = wallClockToIso(
2345
- {
2346
- ...addLocalDays(local, days),
2347
- hour: local.hour,
2348
- minute: local.minute,
2349
- second: local.second
2350
- },
2351
- zone
2352
- );
2353
- }
2354
- }
2355
- return out;
2356
- }
2357
- async function handGrantValues(ctx, granted, values) {
2358
- const item = listObjects().find((o) => o.sellable?.grants?.object === granted.name);
2359
- const grants = item?.sellable?.grants;
2360
- if (!item || !grants) return values;
2361
- const sourceField = (source) => Object.entries(grants.set).find(([, s]) => s === source)?.[0];
2362
- const itemField = sourceField("item");
2363
- const itemId = itemField ? values[itemField] : void 0;
2364
- if (typeof itemId !== "string" || !itemId) {
2365
- throw new ValidationError(`${granted.label} given by hand names its ${item.label}`, {
2366
- field: itemField ?? null
2367
- });
2368
- }
2369
- const itemRow = await readGrantItem(ctx, item, itemId);
2370
- if (!itemRow) throw new NotFoundError(item.name, itemId);
2371
- const out = { ...values };
2372
- if (grants.valid) {
2373
- const valid = await validFrom(
2374
- ctx,
2375
- granted,
2376
- grants.valid,
2377
- (field) => grantFieldValue(item, itemRow, field)
2378
- );
2379
- for (const key of [grants.valid.from, grants.valid.until]) {
2380
- if (key) out[key] = valid[key] ?? null;
2381
- }
2382
- }
2383
- const once = item.sellable?.onePerPerson;
2384
- if (once && grantFieldValue(item, itemRow, once) === true) {
2385
- const personField = sourceField("order.person");
2386
- const personId = personField ? out[personField] : void 0;
2387
- if (typeof personId !== "string" || !personId) {
2388
- throw new ValidationError("This is one per person: name the person it is given to", {
2389
- rule: "once_per_person",
2390
- reason: "no_person"
2391
- });
2392
- }
2393
- const had = await ctx.db.selectFrom("core_sellable_once").select("state").where("person_id", "=", personId).where("object_type", "=", item.name).where("state", "in", ["held", "used"]).executeTakeFirst();
2394
- if (had) {
2395
- throw new ValidationError(
2396
- had.state === "used" ? "This is one per person, and this person has had theirs" : "This is one per person, and an order for this person's is waiting to be paid",
2397
- { rule: "once_per_person", reason: had.state }
2398
- );
2399
- }
2400
- ctx.write(
2401
- ctx.db.insertInto("core_sellable_once").values({
2402
- id: newId("sellableOnce"),
2403
- person_id: personId,
2404
- object_type: item.name,
2405
- record_id: itemId,
2406
- order_id: null,
2407
- state: "used",
2408
- source: "by_hand",
2409
- // The person who called the tool, or the staff caller when platform code gives it.
2410
- given_by: ctx.extension?.tool?.startedBy ?? (ctx.principal.kind === "staff" ? ctx.principal.userId : null),
2411
- created_at: ctx.now,
2412
- updated_at: ctx.now
2413
- })
2414
- );
2415
- }
2416
- return out;
2417
- }
2418
- async function grant(ctx, orderId, order, from) {
2419
- const onceRows = await ctx.db.selectFrom("core_sellable_once").select(["object_type", "state"]).where("order_id", "=", orderId).execute();
2420
- const lostOnce = (object) => from === "pending" && onceRows.some((r) => r.object_type === object && r.state === "released") && !onceRows.some((r) => r.object_type === object && r.state !== "released");
2421
- const lines = await ctx.db.selectFrom("core_order_line").select(["id", "object_type", "record_id", "title", "quantity", "unit_price"]).where("order_id", "=", orderId).orderBy("position").execute();
2422
- const currency = typeof order.currency === "string" ? order.currency : "";
2423
- for (const line of lines) {
2424
- const item = getObject(line.object_type);
2425
- const grants = item?.sellable?.grants;
2426
- if (!item || !grants) continue;
2427
- if (lostOnce(item.name)) {
2428
- await tellStaffOnce(ctx, orderId, line.title);
2429
- continue;
2430
- }
2431
- const granted = getObject(grants.object);
2432
- if (!granted?.states) {
2433
- console.error(`sellable ${item.name}: granted object ${grants.object} has no states`);
2434
- continue;
2435
- }
2436
- const sources2 = Object.values(grants.set);
2437
- const itemRow = sources2.some((s) => s.startsWith("item.")) || grants.valid?.days ? await readGrantItem(ctx, item, line.record_id) : void 0;
2438
- const valid = grants.valid ? await validFrom(
2439
- ctx,
2440
- granted,
2441
- grants.valid,
2442
- (field) => grantFieldValue(item, itemRow, field)
2443
- ) : {};
2444
- const from2 = (source) => {
2445
- if (source === "item") return line.record_id;
2446
- if (source.startsWith("item.")) return grantFieldValue(item, itemRow, source.slice(5));
2447
- if (source === "order") return orderId;
2448
- if (source === "order.person") return order.personId ?? null;
2449
- if (source === "order.email") return order.email ?? null;
2450
- if (source === "line") return line.id;
2451
- if (source === "line.title") return line.title;
2452
- if (source === "line.unitPrice") return line.unit_price / 10 ** currencyDecimals(currency);
2453
- return null;
2454
- };
2455
- for (let unit = 0; unit < line.quantity; unit += 1) {
2456
- let code = null;
2457
- const values = { ...valid };
2458
- for (const [target, source] of Object.entries(grants.set)) {
2459
- if (source === "code") {
2460
- code = newGrantCode();
2461
- values[target] = code;
2462
- } else {
2463
- values[target] = from2(source);
2464
- }
2465
- }
2466
- const id = await createRecord(ctx, granted, values, { by: "host", checkReferences: false });
2467
- ctx.write(
2468
- ctx.db.insertInto("core_order_grant").values({
2469
- object_type: granted.name,
2470
- record_id: id,
2471
- order_id: orderId,
2472
- line_id: line.id,
2473
- code,
2474
- created_at: ctx.now
2475
- })
2476
- );
2477
- }
2478
- }
2479
- }
2480
- function grantFor(object) {
2481
- for (const candidate of listObjects()) {
2482
- const grants = candidate.sellable?.grants;
2483
- if (grants?.object === object) return grants;
2484
- }
2485
- return void 0;
2486
- }
2487
- async function voidGrants(ctx, orderId) {
2488
- const rows = await ctx.db.selectFrom("core_order_grant").select(["object_type", "record_id"]).where("order_id", "=", orderId).execute();
2489
- if (!rows.length) return;
2490
- const byObject = /* @__PURE__ */ new Map();
2491
- for (const row of rows) {
2492
- byObject.set(row.object_type, [...byObject.get(row.object_type) ?? [], row.record_id]);
2493
- }
2494
- for (const [name, ids] of byObject) {
2495
- const object = getObject(name);
2496
- const states = object?.states;
2497
- const voidState = grantFor(name)?.void;
2498
- const field = states ? object.fields.find((f) => f.name === states.field) : void 0;
2499
- const column = field ? viewColumnOf(field) : null;
2500
- if (!object || !states || !voidState || !column) continue;
2501
- const finals = new Set(states.moves.filter((m) => m.final).map((m) => m.to));
2502
- const current = await ctx.db.selectFrom(visibleSource(orgReader(ctx.db), object)).select(["id", column]).where("id", "in", ids).execute();
2503
- for (const row of current) {
2504
- const state = row[column];
2505
- if (typeof state !== "string" || state === voidState || finals.has(state)) continue;
2506
- const allowed = states.moves.some(
2507
- (m) => m.to === voidState && moveOrigins(m).includes(state) && m.by.includes("host")
2508
- );
2509
- if (!allowed) continue;
2510
- await updateRecord(
2511
- ctx,
2512
- object,
2513
- String(row.id),
2514
- { [states.field]: voidState },
2515
- { by: "host" }
2516
- );
2517
- }
2518
- }
2519
- }
2520
- async function grantsFollowPerson(ctx, orderId, personId) {
2521
- const rows = await ctx.db.selectFrom("core_order_grant").select(["object_type", "record_id"]).where("order_id", "=", orderId).execute();
2522
- const byObject = /* @__PURE__ */ new Map();
2523
- for (const row of rows) {
2524
- byObject.set(row.object_type, [...byObject.get(row.object_type) ?? [], row.record_id]);
2525
- }
2526
- for (const [name, ids] of byObject) {
2527
- const object = getObject(name);
2528
- const set = grantFor(name)?.set ?? {};
2529
- const fields = Object.keys(set).filter((field) => set[field] === "order.person");
2530
- if (!object || !fields.length) continue;
2531
- const live = await ctx.db.selectFrom(visibleSource(orgReader(ctx.db), object)).select("id").where("id", "in", ids).execute();
2532
- const values = Object.fromEntries(fields.map((field) => [field, personId]));
2533
- for (const { id } of live) await updateRecord(ctx, object, id, values, { by: "host" });
2534
- }
2535
- }
2536
- async function tellStaffOnce(ctx, orderId, title) {
2537
- const plan = await notifyStatements(
2538
- ctx.db,
2539
- {
2540
- to: [{ role: "admin" }],
2541
- type: "system.message",
2542
- title: "A one-per-person purchase granted nothing",
2543
- body: `Order ${orderId} was paid for "${title}", which is one per person, and its person (merged with another since it was started) has had theirs. Nothing was granted for it: refund it.`,
2544
- link: { kind: "record", object: "order", id: orderId },
2545
- dedupeKey: `order.once_lost:${orderId}`,
2546
- source: { actor: "system" }
2547
- },
2548
- ctx.now
2549
- );
2550
- ctx.write(...plan.statements);
2551
- }
2552
- var orderGrants = async (ctx, move) => {
2553
- const from = move.from?.id ?? null;
2554
- const to = move.to.id;
2555
- if ((to === "paid" || to === "part_paid") && (from === "pending" || from === "expired")) {
2556
- await grant(ctx, move.id, move.after, from);
2557
- return;
2558
- }
2559
- if (to === "refunded" || to === "cancelled") await voidGrants(ctx, move.id);
2560
- };
2561
- onRecordMove("order", orderGrants);
2562
-
2563
2402
  export {
2564
2403
  holderOf,
2565
2404
  storedTerms,
@@ -2569,13 +2408,6 @@ export {
2569
2408
  generateSeries,
2570
2409
  requireSeriesObject,
2571
2410
  requireClosureObject,
2572
- GRANT_CODE_LENGTH,
2573
- newGrantCode,
2574
- grantFieldValue,
2575
- readGrantItem,
2576
- validFrom,
2577
- handGrantValues,
2578
- grantsFollowPerson,
2579
2411
  recordSchema,
2580
2412
  requireExtensionObject,
2581
2413
  loadRecord,