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

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 (173) hide show
  1. package/dist/{accounts-X4CKM3HL.js → accounts-GOCNY6WI.js} +17 -14
  2. package/dist/app-RPRZMLU5.js +43 -0
  3. package/dist/app-upload-YJVEKZC6.js +198 -0
  4. package/dist/{blocks-YWDHEBOK.js → blocks-DE4RRWPJ.js} +207 -25
  5. package/dist/{chunk-VY64DMQO.js → chunk-2B6YUYZV.js} +23576 -11674
  6. package/dist/{run-RT2HVWMK.js → chunk-2CCHB37H.js} +9 -146
  7. package/dist/{chunk-DU6OIFOU.js → chunk-3OGDWKJ3.js} +530 -434
  8. package/dist/chunk-5D7BDF4Y.js +141 -0
  9. package/dist/{chunk-WO6D3XP3.js → chunk-6CM3WZG5.js} +13 -2470
  10. package/dist/chunk-CIBJGB5H.js +962 -0
  11. package/dist/chunk-EPDTPGZJ.js +330 -0
  12. package/dist/{chunk-LLULPZAJ.js → chunk-HAYF4G5V.js} +66 -23
  13. package/dist/chunk-HCG6T53D.js +61904 -0
  14. package/dist/chunk-JX4IFWNT.js +330 -0
  15. package/dist/{chunk-A4NTSYWV.js → chunk-KFHKNXGH.js} +786 -386
  16. package/dist/chunk-KMFMD52Z.js +13276 -0
  17. package/dist/{chunk-E4WCYTCT.js → chunk-LX2TTLVY.js} +174 -55
  18. package/dist/{chunk-GYTEW66E.js → chunk-O3R4FS2J.js} +1 -1
  19. package/dist/{chunk-LJFLENFC.js → chunk-Q6Y45DY6.js} +25 -2
  20. package/dist/{chunk-Y7JZFSTQ.js → chunk-QJZGYJVV.js} +823 -44
  21. package/dist/{chunk-6VXHPKGG.js → chunk-QQ3YSL5F.js} +172 -16
  22. package/dist/chunk-RGKJKC5T.js +876 -0
  23. package/dist/{chunk-IFG4FRW5.js → chunk-RSEWEFAV.js} +12 -2
  24. package/dist/{chunk-2ABSVMGB.js → chunk-SMJZIK2O.js} +1 -1
  25. package/dist/{chunk-CP6BXI6F.js → chunk-U72NEGCT.js} +8818 -3829
  26. package/dist/{chunk-WC5LHBBA.js → chunk-Z4IKF23A.js} +11 -7
  27. package/dist/chunk-Z7OVQ6BC.js +713 -0
  28. package/dist/{chunk-6UWRT4VM.js → chunk-ZJSFX4RD.js} +175 -3
  29. package/dist/{cli-2DFENR62.js → cli-OKQHHSOE.js} +17 -23
  30. package/dist/{cli-YIOVSKOD.js → cli-VYSD2S4Z.js} +231 -82
  31. package/dist/cli.js +5 -5
  32. package/dist/{client-repo-PRU3VCQQ.js → client-repo-NNUCHQ2Y.js} +7 -5
  33. package/dist/create.js +5 -5
  34. package/dist/{fields-2NC7LSYE.js → fields-GTHE6TTS.js} +27 -3
  35. package/dist/gateway-DPPEQZT4.js +25 -0
  36. package/dist/grants-6JY4XZO7.js +27 -0
  37. package/dist/invoke-MRONRZ5Q.js +33 -0
  38. package/dist/moves-UAUCMWL5.js +36 -0
  39. package/dist/{order-PUWD65BC.js → order-RKLGT74L.js} +2 -2
  40. package/dist/{person-WIQQ7ITU.js → person-YOZTFV4Q.js} +11 -11
  41. package/dist/plan-on-sale-H4F26YIN.js +26 -0
  42. package/dist/platform/migrations/0610_waitlists.sql +54 -0
  43. package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
  44. package/dist/platform/migrations/0650_person_links.sql +90 -0
  45. package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
  46. package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
  47. package/dist/platform/migrations/0730_practitioners.sql +79 -0
  48. package/dist/platform/migrations/0750_routine_mail.sql +98 -0
  49. package/dist/platform/migrations/0770_clear_fixed_role_grants.sql +64 -0
  50. package/dist/platform/migrations/0810_recurrence_exceptions.sql +66 -0
  51. package/dist/platform/migrations/0811_staff_time.sql +109 -0
  52. package/dist/platform/migrations/0812_staff_offers.sql +112 -0
  53. package/dist/platform/migrations/0813_pay_periods.sql +241 -0
  54. package/dist/platform/migrations/0814_staff_feed.sql +47 -0
  55. package/dist/platform/migrations/0815_checklists.sql +237 -0
  56. package/dist/platform/migrations/0816_checklist_schedules.sql +121 -0
  57. package/dist/platform/migrations/0817_checklist_day_window.sql +35 -0
  58. package/dist/platform/migrations/0850_agreements.sql +271 -0
  59. package/dist/platform/migrations/0851_agreement_acceptances.sql +387 -0
  60. package/dist/platform/migrations/0853_agreement_enforcement.sql +58 -0
  61. package/dist/platform/migrations/0854_agreement_copy.sql +149 -0
  62. package/dist/platform/migrations/0855_agreement_retention.sql +279 -0
  63. package/dist/platform/migrations/0856_subscription_cooling_off.sql +159 -0
  64. package/dist/platform/migrations/0857_agreement_copy_guardian.sql +337 -0
  65. package/dist/platform/migrations/0858_agreement_desk.sql +175 -0
  66. package/dist/platform/migrations/0910_routine_messages.sql +99 -0
  67. package/dist/platform/migrations/0911_texts.sql +60 -0
  68. package/dist/platform/migrations/0913_contact_consent.sql +93 -0
  69. package/dist/platform/migrations/0916_contact_mailbox_index.sql +29 -0
  70. package/dist/platform/migrations/0930_stock_movements.sql +95 -0
  71. package/dist/platform/migrations/0931_stock_low.sql +25 -0
  72. package/dist/platform/migrations/0932_order_delivery.sql +78 -0
  73. package/dist/platform/migrations/0950_order_adjustments.sql +111 -0
  74. package/dist/platform/migrations/0951_order_price_guards.sql +33 -0
  75. package/dist/platform/migrations/0952_order_paid_another_way.sql +194 -0
  76. package/dist/platform/migrations/0953_discount_uses.sql +183 -0
  77. package/dist/platform/migrations/0955_folded_addresses.sql +92 -0
  78. package/dist/platform/migrations/0970_published_text.sql +59 -0
  79. package/dist/platform/migrations/0971_publish_acks.sql +68 -0
  80. package/dist/platform/migrations/0990_customer_email_change.sql +65 -0
  81. package/dist/platform/migrations/1010_intake_links.sql +148 -0
  82. package/dist/platform/migrations/1030_invoices.sql +747 -0
  83. package/dist/platform/migrations/1031_invoice_orders.sql +327 -0
  84. package/dist/platform/migrations/1050_inbox_conversations.sql +83 -0
  85. package/dist/platform/migrations/1090_staff_hours.sql +43 -0
  86. package/dist/platform/migrations/1091_staff_time_margins.sql +12 -0
  87. package/dist/platform/migrations/1092_client_guard.sql +26 -0
  88. package/dist/platform/migrations/1095_thing_time.sql +70 -0
  89. package/dist/platform/migrations/1130_devices.sql +162 -0
  90. package/dist/platform/migrations/1135_person_codes.sql +88 -0
  91. package/dist/platform/migrations/1150_finance_periods.sql +316 -0
  92. package/dist/platform/migrations/1151_payouts.sql +202 -0
  93. package/dist/platform/migrations/1153_finance_money_dates.sql +18 -0
  94. package/dist/platform/migrations/1170_journeys.sql +318 -0
  95. package/dist/platform/migrations/1171_person_birthday.sql +52 -0
  96. package/dist/platform/migrations/1175_person_signals.sql +29 -0
  97. package/dist/platform/migrations/1190_restricted_values.sql +25 -0
  98. package/dist/platform/migrations/1230_note_levels.sql +113 -0
  99. package/dist/platform/migrations/1231_person_carers.sql +33 -0
  100. package/dist/platform/migrations/1232_note_kinds.sql +122 -0
  101. package/dist/platform/migrations/1270_time_entries.sql +145 -0
  102. package/dist/platform/migrations/1271_leave.sql +249 -0
  103. package/dist/platform/migrations/1273_time_entry_reopened.sql +21 -0
  104. package/dist/platform/migrations/1330_accounting.sql +260 -0
  105. package/dist/platform/migrations/1350_customer_feed.sql +24 -0
  106. package/dist/platform/migrations/1390_locations.sql +77 -0
  107. package/dist/platform/migrations/1410_outside_copy.sql +213 -0
  108. package/dist/platform/migrations/1430_inbox_activities.sql +231 -0
  109. package/dist/platform/migrations/1450_wrong_guesses.sql +23 -0
  110. package/dist/platform/sdk/acknowledge.ts +100 -0
  111. package/dist/platform/sdk/agreements.ts +185 -0
  112. package/dist/platform/sdk/allowance.ts +98 -8
  113. package/dist/platform/sdk/automation-check.ts +120 -9
  114. package/dist/platform/sdk/automation.ts +78 -10
  115. package/dist/platform/sdk/behaviour.ts +26 -6
  116. package/dist/platform/sdk/calendar-entry.ts +258 -0
  117. package/dist/platform/sdk/capacity.ts +103 -2
  118. package/dist/platform/sdk/checklists.ts +118 -0
  119. package/dist/platform/sdk/contract.ts +514 -27
  120. package/dist/platform/sdk/discount.ts +408 -0
  121. package/dist/platform/sdk/document.ts +4 -2
  122. package/dist/platform/sdk/field-types.ts +5 -0
  123. package/dist/platform/sdk/formula/compile.ts +10 -0
  124. package/dist/platform/sdk/index.ts +17 -0
  125. package/dist/platform/sdk/intake.ts +380 -0
  126. package/dist/platform/sdk/journey-signals.ts +215 -0
  127. package/dist/platform/sdk/manifest.ts +1313 -66
  128. package/dist/platform/sdk/mine.ts +161 -0
  129. package/dist/platform/sdk/occupies.ts +192 -0
  130. package/dist/platform/sdk/questions.ts +681 -0
  131. package/dist/platform/sdk/recurring.ts +90 -9
  132. package/dist/platform/sdk/restricted-fields.ts +129 -0
  133. package/dist/platform/sdk/rich-text.ts +112 -0
  134. package/dist/platform/sdk/routine-mail.ts +1272 -0
  135. package/dist/platform/sdk/runtime.ts +25 -12
  136. package/dist/platform/sdk/screens.ts +91 -0
  137. package/dist/platform/sdk/sellable.ts +595 -1
  138. package/dist/platform/sdk/slug.ts +7 -2
  139. package/dist/platform/sdk/staffed.ts +474 -0
  140. package/dist/platform/sdk/states.ts +220 -64
  141. package/dist/platform/sdk/stock.ts +332 -0
  142. package/dist/platform/sdk/team.ts +83 -0
  143. package/dist/platform/sdk/testing.ts +70 -6
  144. package/dist/platform/sdk/worked-on.ts +134 -0
  145. package/dist/{products-2H5DR232.js → products-GCQLSZ3U.js} +2 -2
  146. package/dist/run-7ID64RA6.js +65 -0
  147. package/dist/run-FH7OGGTV.js +131 -0
  148. package/dist/run-OYZIAP6M.js +3363 -0
  149. package/dist/{run-Y7T4TVOL.js → run-QOFRRSZV.js} +41 -60
  150. package/dist/{run-PZUCSDDL.js → run-TJAEWR5U.js} +21 -51
  151. package/dist/{src-XTOD7EXW.js → src-52VERUPK.js} +312 -4
  152. package/dist/src-PHRELWN5.js +40 -0
  153. package/dist/visibility-SZCINPP4.js +58 -0
  154. package/package.json +2 -2
  155. package/dist/chunk-6GDEDOV7.js +0 -157
  156. package/dist/chunk-6UPUF4ML.js +0 -29998
  157. package/dist/chunk-7CQGMVDO.js +0 -63
  158. package/dist/chunk-GYSGVT6R.js +0 -284
  159. package/dist/chunk-JJHHNV46.js +0 -227
  160. package/dist/chunk-K6T42YCH.js +0 -704
  161. package/dist/chunk-M7A6FR2Z.js +0 -2586
  162. package/dist/chunk-O2UIZHND.js +0 -249
  163. package/dist/chunk-Q4N55M2Z.js +0 -552
  164. package/dist/chunk-QGGJ2G6Z.js +0 -349
  165. package/dist/chunk-R4W5XAUD.js +0 -837
  166. package/dist/chunk-TQFGGSA4.js +0 -748
  167. package/dist/chunk-YJJHF65I.js +0 -759
  168. package/dist/chunk-Z3RMMB6S.js +0 -668
  169. package/dist/grants-QXMKYMGB.js +0 -32
  170. package/dist/invoke-I3NNNXVL.js +0 -39
  171. package/dist/plan-on-sale-NB774CQL.js +0 -26
  172. package/dist/src-GYS6NBQB.js +0 -44
  173. package/dist/visibility-DLGHU4YN.js +0 -33
@@ -0,0 +1,330 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ addLocalDays,
4
+ createRecord,
5
+ currencyDecimals,
6
+ jsonList,
7
+ loadGeneralSettings,
8
+ localParts,
9
+ newId,
10
+ notifyStatements,
11
+ onRecordMove,
12
+ updateRecord,
13
+ viewRow,
14
+ wallClockToIso
15
+ } from "./chunk-KMFMD52Z.js";
16
+ import {
17
+ FIELD_TYPE_REGISTRY,
18
+ formulaFromStorage,
19
+ orgReader,
20
+ viewColumnOf,
21
+ visibleSource
22
+ } from "./chunk-KFHKNXGH.js";
23
+ import {
24
+ getObject,
25
+ listObjects
26
+ } from "./chunk-RSEWEFAV.js";
27
+ import {
28
+ moveOrigins
29
+ } from "./chunk-U72NEGCT.js";
30
+ import {
31
+ NotFoundError,
32
+ ValidationError
33
+ } from "./chunk-RGKJKC5T.js";
34
+
35
+ // ../core/src/orders/grants.ts
36
+ var CODE_ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
37
+ var GRANT_CODE_LENGTH = 26;
38
+ function newGrantCode() {
39
+ const bytes = crypto.getRandomValues(new Uint8Array(GRANT_CODE_LENGTH));
40
+ return Array.from(bytes, (b) => CODE_ALPHABET[b & 31]).join("");
41
+ }
42
+ function grantFieldValue(object, row, name) {
43
+ const field = object.fields.find((f) => f.name === name);
44
+ const column = field ? viewColumnOf(field) : null;
45
+ if (!field || !column || !row) return null;
46
+ const raw = row[column] ?? null;
47
+ if (field.fieldType === "formula") return formulaFromStorage(field.options?.resultType, raw);
48
+ const type = field.fieldType;
49
+ return type && FIELD_TYPE_REGISTRY[type] ? FIELD_TYPE_REGISTRY[type].fromStorage(raw) : raw;
50
+ }
51
+ function idsByObject(rows) {
52
+ const out = /* @__PURE__ */ new Map();
53
+ for (const row of rows) {
54
+ const ids = out.get(row.object_type);
55
+ if (ids) ids.push(row.record_id);
56
+ else out.set(row.object_type, [row.record_id]);
57
+ }
58
+ return out;
59
+ }
60
+ async function readGrantItem(ctx, item, id) {
61
+ return viewRow(ctx.db, visibleSource(orgReader(ctx.db), item), id);
62
+ }
63
+ async function validFrom(ctx, granted, valid, itemValue) {
64
+ const zone = (await loadGeneralSettings(ctx.db)).timezone || "UTC";
65
+ const typeOf = (field) => granted.fields.find((f) => f.name === field)?.fieldType;
66
+ const local = localParts(ctx.now, zone);
67
+ const out = {};
68
+ if (valid.from) out[valid.from] = typeOf(valid.from) === "date" ? local.date : ctx.now;
69
+ const raw = valid.days ? itemValue(valid.days.slice("item.".length)) : null;
70
+ const days = typeof raw === "number" && Number.isFinite(raw) && raw > 0 ? Math.floor(raw) : null;
71
+ if (valid.until && days) {
72
+ if (typeOf(valid.until) === "date") {
73
+ const d = addLocalDays(local, days - 1);
74
+ out[valid.until] = `${d.year}-${String(d.month).padStart(2, "0")}-${String(d.day).padStart(2, "0")}`;
75
+ } else {
76
+ out[valid.until] = wallClockToIso(
77
+ {
78
+ ...addLocalDays(local, days),
79
+ hour: local.hour,
80
+ minute: local.minute,
81
+ second: local.second
82
+ },
83
+ zone
84
+ );
85
+ }
86
+ }
87
+ return out;
88
+ }
89
+ async function handGrantValues(ctx, granted, values) {
90
+ const item = listObjects().find((o) => o.sellable?.grants?.object === granted.name);
91
+ const grants = item?.sellable?.grants;
92
+ if (!item || !grants) return values;
93
+ const sourceField = (source) => Object.entries(grants.set).find(([, s]) => s === source)?.[0];
94
+ const itemField = sourceField("item");
95
+ const itemId = itemField ? values[itemField] : void 0;
96
+ if (typeof itemId !== "string" || !itemId) {
97
+ throw new ValidationError(`${granted.label} given by hand names its ${item.label}`, {
98
+ field: itemField ?? null
99
+ });
100
+ }
101
+ const itemRow = await readGrantItem(ctx, item, itemId);
102
+ if (!itemRow) throw new NotFoundError(item.name, itemId);
103
+ const out = { ...values };
104
+ if (grants.valid) {
105
+ const valid = await validFrom(
106
+ ctx,
107
+ granted,
108
+ grants.valid,
109
+ (field) => grantFieldValue(item, itemRow, field)
110
+ );
111
+ for (const key of [grants.valid.from, grants.valid.until]) {
112
+ if (key) out[key] = valid[key] ?? null;
113
+ }
114
+ }
115
+ const once = item.sellable?.onePerPerson;
116
+ if (once && grantFieldValue(item, itemRow, once) === true) {
117
+ const personField = sourceField("order.person");
118
+ const personId = personField ? out[personField] : void 0;
119
+ if (typeof personId !== "string" || !personId) {
120
+ throw new ValidationError("This is one per person: name the person it is given to", {
121
+ rule: "once_per_person",
122
+ reason: "no_person"
123
+ });
124
+ }
125
+ 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();
126
+ if (had) {
127
+ throw new ValidationError(
128
+ 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",
129
+ { rule: "once_per_person", reason: had.state }
130
+ );
131
+ }
132
+ ctx.write(
133
+ ctx.db.insertInto("core_sellable_once").values({
134
+ id: newId("sellableOnce"),
135
+ person_id: personId,
136
+ object_type: item.name,
137
+ record_id: itemId,
138
+ order_id: null,
139
+ state: "used",
140
+ source: "by_hand",
141
+ // The person who called the tool, or the staff caller when platform code gives it.
142
+ given_by: ctx.extension?.tool?.startedBy ?? (ctx.principal.kind === "staff" ? ctx.principal.userId : null),
143
+ created_at: ctx.now,
144
+ updated_at: ctx.now
145
+ })
146
+ );
147
+ }
148
+ return out;
149
+ }
150
+ async function grant(ctx, orderId, order, from) {
151
+ const onceRows = await ctx.db.selectFrom("core_sellable_once").select(["object_type", "state"]).where("order_id", "=", orderId).execute();
152
+ 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");
153
+ 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();
154
+ const currency = typeof order.currency === "string" ? order.currency : "";
155
+ for (const line of lines) {
156
+ const item = getObject(line.object_type);
157
+ const grants = item?.sellable?.grants;
158
+ if (!item || !grants) continue;
159
+ if (lostOnce(item.name)) {
160
+ await tellStaffOnce(ctx, orderId, line.title);
161
+ continue;
162
+ }
163
+ const granted = getObject(grants.object);
164
+ if (!granted?.states) {
165
+ console.error(`sellable ${item.name}: granted object ${grants.object} has no states`);
166
+ continue;
167
+ }
168
+ const sources = Object.values(grants.set);
169
+ if (item.sellable?.delivery) {
170
+ const delivery = await ctx.db.selectFrom("core_order_delivery").select("kind").where("line_id", "=", line.id).executeTakeFirst();
171
+ if (!delivery || delivery.kind === "here") continue;
172
+ }
173
+ const itemRow = sources.some((s) => s.startsWith("item.")) || grants.valid?.days ? await readGrantItem(ctx, item, line.record_id) : void 0;
174
+ const valid = grants.valid ? await validFrom(
175
+ ctx,
176
+ granted,
177
+ grants.valid,
178
+ (field) => grantFieldValue(item, itemRow, field)
179
+ ) : {};
180
+ const from2 = (source) => {
181
+ if (source === "item") return line.record_id;
182
+ if (source.startsWith("item.")) return grantFieldValue(item, itemRow, source.slice(5));
183
+ if (source === "order") return orderId;
184
+ if (source === "order.person") return order.personId ?? null;
185
+ if (source === "order.email") return order.email ?? null;
186
+ if (source === "line") return line.id;
187
+ if (source === "line.title") return line.title;
188
+ if (source === "line.unitPrice") return line.unit_price / 10 ** currencyDecimals(currency);
189
+ return null;
190
+ };
191
+ for (let unit = 0; unit < line.quantity; unit += 1) {
192
+ let code = null;
193
+ const values = { ...valid };
194
+ for (const [target, source] of Object.entries(grants.set)) {
195
+ if (source === "code") {
196
+ code = newGrantCode();
197
+ values[target] = code;
198
+ } else {
199
+ values[target] = from2(source);
200
+ }
201
+ }
202
+ const copied = {};
203
+ const generated = [];
204
+ for (const [target, source] of Object.entries(grants.set)) {
205
+ if (source === "code") generated.push(target);
206
+ else if (source.startsWith("item.")) {
207
+ const field = source.slice(5);
208
+ copied[target] = [
209
+ { object: line.object_type, id: line.record_id, field, value: values[target] }
210
+ ];
211
+ } else if (source === "line.title" && item.titleField) {
212
+ copied[target] = [
213
+ {
214
+ object: line.object_type,
215
+ id: line.record_id,
216
+ field: item.titleField,
217
+ value: line.title
218
+ }
219
+ ];
220
+ }
221
+ }
222
+ const id = await createRecord(ctx, granted, values, {
223
+ by: "host",
224
+ checkReferences: false,
225
+ copied,
226
+ generated
227
+ });
228
+ ctx.write(
229
+ ctx.db.insertInto("core_order_grant").values({
230
+ object_type: granted.name,
231
+ record_id: id,
232
+ order_id: orderId,
233
+ line_id: line.id,
234
+ code,
235
+ created_at: ctx.now
236
+ })
237
+ );
238
+ }
239
+ }
240
+ }
241
+ function grantFor(object) {
242
+ for (const candidate of listObjects()) {
243
+ const grants = candidate.sellable?.grants;
244
+ if (grants?.object === object) return grants;
245
+ }
246
+ return void 0;
247
+ }
248
+ async function voidGrants(ctx, orderId) {
249
+ const rows = await ctx.db.selectFrom("core_order_grant").select(["object_type", "record_id"]).where("order_id", "=", orderId).execute();
250
+ if (!rows.length) return;
251
+ const byObject = idsByObject(rows);
252
+ for (const [name, ids] of byObject) {
253
+ const object = getObject(name);
254
+ const states = object?.states;
255
+ const voidState = grantFor(name)?.void;
256
+ const field = states ? object.fields.find((f) => f.name === states.field) : void 0;
257
+ const column = field ? viewColumnOf(field) : null;
258
+ if (!object || !states || !voidState || !column) continue;
259
+ const finals = new Set(states.moves.filter((m) => m.final).map((m) => m.to));
260
+ const current = await ctx.db.selectFrom(visibleSource(orgReader(ctx.db), object)).select(["id", column]).where("id", "in", jsonList(ids)).execute();
261
+ for (const row of current) {
262
+ const state = row[column];
263
+ if (typeof state !== "string" || state === voidState || finals.has(state)) continue;
264
+ const allowed = states.moves.some(
265
+ (m) => m.to === voidState && moveOrigins(m).includes(state) && m.by.includes("host")
266
+ );
267
+ if (!allowed) continue;
268
+ await updateRecord(
269
+ ctx,
270
+ object,
271
+ String(row.id),
272
+ { [states.field]: voidState },
273
+ { by: "host" }
274
+ );
275
+ }
276
+ }
277
+ }
278
+ async function grantsFollowPerson(ctx, orderId, personId) {
279
+ const rows = await ctx.db.selectFrom("core_order_grant").select(["object_type", "record_id"]).where("order_id", "=", orderId).execute();
280
+ const byObject = idsByObject(rows);
281
+ for (const [name, ids] of byObject) {
282
+ const object = getObject(name);
283
+ const set = grantFor(name)?.set ?? {};
284
+ const fields = Object.keys(set).filter((field) => set[field] === "order.person");
285
+ if (!object || !fields.length) continue;
286
+ const live = await ctx.db.selectFrom(visibleSource(orgReader(ctx.db), object)).select("id").where("id", "in", jsonList(ids)).execute();
287
+ const values = Object.fromEntries(fields.map((field) => [field, personId]));
288
+ for (const { id } of live) await updateRecord(ctx, object, String(id), values, { by: "host" });
289
+ }
290
+ }
291
+ async function tellStaffOnce(ctx, orderId, title) {
292
+ const plan = await notifyStatements(
293
+ ctx.db,
294
+ {
295
+ to: [{ role: "admin" }],
296
+ type: "system.message",
297
+ title: "A one-per-person purchase granted nothing",
298
+ 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.`,
299
+ link: { kind: "record", object: "order", id: orderId },
300
+ dedupeKey: `order.once_lost:${orderId}`,
301
+ source: { actor: "system" }
302
+ },
303
+ ctx.now
304
+ );
305
+ ctx.write(...plan.statements);
306
+ }
307
+ var orderGrants = async (ctx, move) => {
308
+ const from = move.from?.id ?? null;
309
+ const to = move.to.id;
310
+ if ((to === "paid" || to === "part_paid") && (from === "pending" || from === "expired")) {
311
+ if (from === "pending" && move.after.invoiceId) {
312
+ const before = await ctx.db.selectFrom("core_order_grant").select("order_id").where("order_id", "=", move.id).limit(1).executeTakeFirst();
313
+ if (before) return;
314
+ }
315
+ await grant(ctx, move.id, move.after, from);
316
+ return;
317
+ }
318
+ if (to === "refunded" || to === "cancelled") await voidGrants(ctx, move.id);
319
+ };
320
+ onRecordMove("order", orderGrants);
321
+
322
+ export {
323
+ GRANT_CODE_LENGTH,
324
+ newGrantCode,
325
+ grantFieldValue,
326
+ readGrantItem,
327
+ validFrom,
328
+ handGrantValues,
329
+ grantsFollowPerson
330
+ };