@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
@@ -1,2586 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- applyTransition,
4
- callerMover,
5
- onRecordMove,
6
- resolveStateRequest,
7
- transitionTimeline
8
- } from "./chunk-R4W5XAUD.js";
9
- import {
10
- addDaysToDate,
11
- assignOwner,
12
- recordAssignment,
13
- setRecordWriter
14
- } from "./chunk-Z3RMMB6S.js";
15
- import {
16
- defineOperation,
17
- personsTool
18
- } from "./chunk-6GDEDOV7.js";
19
- import {
20
- armSeriesStatement,
21
- boundOf,
22
- guardStatement,
23
- keyingChangeStatement,
24
- markEditedStatement,
25
- occurrenceStatement,
26
- periodOf,
27
- rekeyStatements,
28
- returnStatements,
29
- seriesVersion,
30
- spendStatements,
31
- 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";
44
- import {
45
- TRASH_RETENTION_DAYS,
46
- jsonList,
47
- listInputSchema,
48
- notifyStatements,
49
- pageSchema,
50
- restorableUntil,
51
- runListQuery
52
- } from "./chunk-K6T42YCH.js";
53
- import {
54
- CompiledQuery,
55
- assertNoConfirmedClaims,
56
- assertNoLiveClaim,
57
- counterWrite,
58
- loadGeneralSettings,
59
- newId
60
- } from "./chunk-TQFGGSA4.js";
61
- import {
62
- ALLOWANCE_FIELDS,
63
- CAPACITY_FIELDS,
64
- ConflictError,
65
- FIELD_TYPE_REGISTRY,
66
- ForbiddenError,
67
- NotFoundError,
68
- PUBLISHED_FIELDS,
69
- ValidationError,
70
- allowanceMessage,
71
- fieldStorage,
72
- formulaFromStorage,
73
- objectTableOf,
74
- orgReader,
75
- sql,
76
- viewColumnOf,
77
- visibleSource,
78
- visibleTable
79
- } from "./chunk-A4NTSYWV.js";
80
- import {
81
- getObject,
82
- isCoreObject,
83
- listObjects
84
- } from "./chunk-IFG4FRW5.js";
85
- import {
86
- mediaObject
87
- } from "./chunk-Q4N55M2Z.js";
88
- import {
89
- SLUG_MAX,
90
- SLUG_RE,
91
- WEEKDAYS,
92
- documentRefs,
93
- external_exports,
94
- isDocumentType,
95
- moveOrigins,
96
- slugify
97
- } from "./chunk-CP6BXI6F.js";
98
-
99
- // ../core/src/allowance/records.ts
100
- var PERIODS = ["total", "week", "month"];
101
- function holderOf(object) {
102
- return object.allowance?.kind === "holder" ? object.allowance : void 0;
103
- }
104
- function spenderOf(object) {
105
- return object.allowance?.kind === "spender" ? object.allowance : void 0;
106
- }
107
- function paysFor(spender, holderObject) {
108
- const def = spenderOf(spender);
109
- if (!def) return false;
110
- const ext = spender.name.split(".")[0];
111
- const holderExt = holderObject.split(".")[0];
112
- return holderExt === ext || def.paidBy.some((p) => p === holderObject || p === holderExt);
113
- }
114
- function payingObjects(spender) {
115
- return listObjects().filter(
116
- (o) => holderOf(o)?.spendsOn.some((s) => s.object === spender.name) && paysFor(spender, o.name)
117
- );
118
- }
119
- function hostFilled(object) {
120
- const def = spenderOf(object);
121
- if (!def) return /* @__PURE__ */ new Set();
122
- return new Set(
123
- [...Object.keys(def.copy), def.local.weekday, def.local.minute].filter(
124
- (f) => typeof f === "string"
125
- )
126
- );
127
- }
128
- var recordUpdate = null;
129
- function setAllowanceRecordUpdate(update) {
130
- recordUpdate = update;
131
- }
132
- function fieldValue(object, row, name) {
133
- const field = object.fields.find((f) => f.name === name);
134
- const column = field ? viewColumnOf(field) : null;
135
- if (!field || !column || !row) return null;
136
- const raw = row[column] ?? null;
137
- if (field.fieldType === "formula") return formulaFromStorage(field.options?.resultType, raw);
138
- const type = field.fieldType;
139
- return type && FIELD_TYPE_REGISTRY[type] ? FIELD_TYPE_REGISTRY[type].fromStorage(raw) : raw;
140
- }
141
- function rowValues(object, row) {
142
- return Object.fromEntries(object.fields.map((f) => [f.name, fieldValue(object, row, f.name)]));
143
- }
144
- async function readValues(ctx, object, id) {
145
- const { rows } = await ctx.db.executeQuery(
146
- CompiledQuery.raw(`SELECT * FROM ${object.source} WHERE id = ?`, [id])
147
- );
148
- return rows[0] ? rowValues(object, rows[0]) : void 0;
149
- }
150
- var zones = /* @__PURE__ */ new WeakMap();
151
- function orgZone(ctx) {
152
- let zone = zones.get(ctx);
153
- if (!zone) {
154
- zone = loadGeneralSettings(ctx.db).then((s) => s.timezone || "UTC");
155
- zones.set(ctx, zone);
156
- }
157
- return zone;
158
- }
159
- var present = (value) => value !== null && value !== void 0 && value !== "" && !(Array.isArray(value) && value.length === 0);
160
- var iso = (value) => {
161
- if (!present(value)) return null;
162
- const at = new Date(String(value));
163
- return Number.isNaN(at.getTime()) ? null : at.toISOString();
164
- };
165
- function holderStorage(object) {
166
- const def = holderOf(object);
167
- const table = objectTableOf(object.name);
168
- const column = (name) => {
169
- const storage = fieldStorage(object.name, name);
170
- if (!storage?.column || !storage.own) {
171
- throw new Error(`allowance: ${object.name}.${name} has no column of its own`);
172
- }
173
- return storage.column;
174
- };
175
- if (!table) throw new Error(`allowance: ${object.name} has no table`);
176
- const bound = (name) => name ? {
177
- column: column(name),
178
- date: object.fields.find((f) => f.name === name)?.fieldType === "date"
179
- } : void 0;
180
- return {
181
- object: object.name,
182
- table,
183
- person: column(def.person),
184
- uses: column(def.uses),
185
- per: "fixed" in def.per ? { fixed: def.per.fixed } : { column: column(def.per.field) },
186
- from: bound(def.from),
187
- until: bound(def.until),
188
- zone: def.zone ? column(def.zone) : void 0,
189
- live: def.live && object.states ? { column: column(object.states.field), states: def.live } : void 0,
190
- emptyIsUnlimited: def.emptyIsUnlimited
191
- };
192
- }
193
- function fromTermsRow(row) {
194
- return {
195
- object: row.object_type,
196
- record: row.record_id,
197
- personId: row.person_id,
198
- uses: row.uses,
199
- per: row.per,
200
- zone: row.zone,
201
- validFrom: row.valid_from,
202
- validUntil: row.valid_until,
203
- fromDate: row.from_date,
204
- untilDate: row.until_date,
205
- live: row.live === 1,
206
- trashed: row.trashed === 1,
207
- prevPer: row.prev_per,
208
- prevZone: row.prev_zone,
209
- appliesFrom: row.applies_from
210
- };
211
- }
212
- async function storedTerms(ctx, holder) {
213
- const row = await ctx.db.selectFrom("core_allowance").selectAll().where("object_type", "=", holder.object).where("record_id", "=", holder.id).executeTakeFirst();
214
- return row ? fromTermsRow(row) : null;
215
- }
216
- function keyingAt(terms, at) {
217
- if (terms.appliesFrom && at < terms.appliesFrom && terms.prevPer && terms.prevZone) {
218
- return { per: terms.prevPer, zone: terms.prevZone };
219
- }
220
- return { per: terms.per, zone: terms.zone };
221
- }
222
- async function holderWrite(ctx, object, id, before, after) {
223
- const def = holderOf(object);
224
- if (!def) return [];
225
- const rawUses = after[def.uses];
226
- if (present(rawUses)) {
227
- if (typeof rawUses !== "number" || !Number.isInteger(rawUses) || rawUses < 0) {
228
- throw new ValidationError(
229
- `${object.label}: uses must be a whole number from 0${def.emptyIsUnlimited ? ", or empty for unlimited" : ""}`,
230
- { rule: "allowance", field: def.uses }
231
- );
232
- }
233
- }
234
- const zone = await orgZone(ctx);
235
- const statements = termsSyncStatements(holderStorage(object), { id }, zone, ctx.now);
236
- if (before === null) return statements;
237
- const stored = await storedTerms(ctx, { object: object.name, id });
238
- if (!stored) return statements;
239
- const per = "fixed" in def.per ? def.per.fixed : PERIODS.includes(after[def.per.field]) ? after[def.per.field] : "total";
240
- const ownZone = def.zone ? after[def.zone] : null;
241
- const nextZone = typeof ownZone === "string" && ownZone ? ownZone : stored.zone;
242
- if (per === stored.per && nextZone === stored.zone) return statements;
243
- const current = keyingAt(stored, ctx.now);
244
- const appliesFrom = stored.appliesFrom && stored.appliesFrom > ctx.now ? stored.appliesFrom : current.per === "total" ? ctx.now : periodOf(ctx.now, current.per, current.zone).endsAt;
245
- const holder = { object: object.name, id };
246
- statements.push(keyingChangeStatement(holder, current, appliesFrom, ctx.now));
247
- const open = await ctx.db.selectFrom("core_allowance_use").select(["id", "period", "zone", "at"]).where("object_type", "=", object.name).where("record_id", "=", id).where("returned_at", "is", null).where("at", ">=", appliesFrom).execute();
248
- for (const use of open) {
249
- const to = periodOf(use.at, per, nextZone);
250
- if (to.key === use.period && nextZone === use.zone) continue;
251
- statements.push(
252
- ...rekeyStatements(
253
- { id: use.id, holder, period: use.period, zone: use.zone },
254
- { period: to, zone: nextZone },
255
- ctx.now
256
- )
257
- );
258
- }
259
- return statements;
260
- }
261
- function holderTerms(object) {
262
- const def = holderOf(object);
263
- if (!def) return /* @__PURE__ */ new Set();
264
- const out = /* @__PURE__ */ new Set([def.person, def.uses]);
265
- if ("field" in def.per) out.add(def.per.field);
266
- for (const f of [def.from, def.until, def.zone]) if (f) out.add(f);
267
- for (const target of def.spendsOn) {
268
- for (const clause of target.when) {
269
- for (const v of [clause.in, clause.atLeast, clause.below]) {
270
- if (typeof v === "string") out.add(v);
271
- }
272
- }
273
- }
274
- return out;
275
- }
276
- function assertHolderCreatable(object, by) {
277
- if (holderOf(object) && by === "customer") {
278
- throw new ForbiddenError(`A customer cannot create a ${object.label.toLowerCase()}`);
279
- }
280
- }
281
- async function holderTrash(ctx, object, id) {
282
- if (!holderOf(object)) return [];
283
- return termsSyncStatements(holderStorage(object), { id }, await orgZone(ctx), ctx.now);
284
- }
285
- async function openUse(ctx, spender) {
286
- const row = await ctx.db.selectFrom("core_allowance_use").select(["id", "object_type", "record_id", "period", "zone"]).where("spender_type", "=", spender.object).where("spender_id", "=", spender.id).where("returned_at", "is", null).executeTakeFirst();
287
- return row ? {
288
- id: row.id,
289
- object: row.object_type,
290
- record: row.record_id,
291
- period: row.period,
292
- zone: row.zone
293
- } : null;
294
- }
295
- async function assertSpenderDeletable(ctx, object, id) {
296
- const def = spenderOf(object);
297
- if (!def || !def.returnIn.length) return;
298
- if (await openUse(ctx, { object: object.name, id })) {
299
- throw new ValidationError(
300
- `${object.label} holds a use of an allowance: move it to a state that gives the use back before deleting it`,
301
- { rule: "allowance", object: object.name, record: id }
302
- );
303
- }
304
- }
305
- var pending = /* @__PURE__ */ new WeakMap();
306
- var pendingKey = (object, record, period, zone) => `${object}|${record}|${period}|${zone}`;
307
- function addPending(ctx, key, n) {
308
- const map = pending.get(ctx) ?? /* @__PURE__ */ new Map();
309
- pending.set(ctx, map);
310
- map.set(key, (map.get(key) ?? 0) + n);
311
- }
312
- var pendingOf = (ctx, key) => pending.get(ctx)?.get(key) ?? 0;
313
- function refusal(details) {
314
- return new ValidationError(allowanceMessage(details), { ...details });
315
- }
316
- async function holdersOf(ctx, spender, personId) {
317
- const objects = payingObjects(spender);
318
- if (!objects.length) return [];
319
- const rows = await ctx.db.selectFrom("core_allowance").selectAll().where("person_id", "=", personId).where(
320
- "object_type",
321
- "in",
322
- objects.map((o) => o.name)
323
- ).orderBy("object_type").orderBy("record_id").limit(200).execute();
324
- const out = [];
325
- for (const row of rows) {
326
- const object = objects.find((o) => o.name === row.object_type);
327
- const values = row.trashed ? {} : await readValues(ctx, object, row.record_id);
328
- if (!values) continue;
329
- out.push({
330
- object,
331
- def: holderOf(object),
332
- id: row.record_id,
333
- values,
334
- terms: fromTermsRow(row)
335
- });
336
- }
337
- return out;
338
- }
339
- function meets(clause, spender, holder) {
340
- const value = spender[clause.field];
341
- if (clause.in !== void 0) {
342
- const limit = typeof clause.in === "string" ? holder[clause.in] : clause.in;
343
- if (!present(limit)) return true;
344
- const allowed = (Array.isArray(limit) ? limit : [limit]).map(String);
345
- const given = Array.isArray(value) ? value.map(String) : present(value) ? [String(value)] : [];
346
- return given.some((v) => allowed.includes(v));
347
- }
348
- for (const [bound, test] of [
349
- ["atLeast", (v, b) => v >= b],
350
- ["below", (v, b) => v < b]
351
- ]) {
352
- const raw = clause[bound];
353
- if (raw === void 0) continue;
354
- const limit = typeof raw === "string" ? holder[raw] : raw;
355
- if (!present(limit)) return true;
356
- if (!present(value)) return false;
357
- return test(Number(value), Number(limit));
358
- }
359
- return true;
360
- }
361
- function cannotPay(candidate, spender, values, at) {
362
- const { terms } = candidate;
363
- if (!terms.live || terms.trashed) return "not_live";
364
- const atDate = localParts(at, terms.zone).date;
365
- if (terms.validFrom && at < terms.validFrom || terms.fromDate && atDate < terms.fromDate) {
366
- return "not_yet_valid";
367
- }
368
- if (terms.validUntil && at >= terms.validUntil || terms.untilDate && atDate > terms.untilDate) {
369
- return "ended";
370
- }
371
- const covers = candidate.def.spendsOn.filter((s) => s.object === spender.name).some((s) => s.when.every((clause) => meets(clause, values, candidate.values)));
372
- return covers ? null : "not_covered";
373
- }
374
- async function roomAt(ctx, candidate, at) {
375
- const keying = keyingAt(candidate.terms, at);
376
- const period = periodOf(at, keying.per, keying.zone);
377
- const row = await ctx.db.selectFrom("core_allowance_period").select(["used", "uses"]).where("object_type", "=", candidate.object.name).where("record_id", "=", candidate.id).where("period", "=", period.key).where("zone", "=", keying.zone).executeTakeFirst();
378
- const key = pendingKey(candidate.object.name, candidate.id, period.key, keying.zone);
379
- return {
380
- period,
381
- zone: keying.zone,
382
- used: (row?.used ?? 0) + pendingOf(ctx, key),
383
- uses: row ? row.uses : candidate.terms.uses
384
- };
385
- }
386
- var hasRoom = (room) => room.uses === null || room.used < room.uses;
387
- var END = "9999-12-31T23:59:59.999Z";
388
- function precedence(a, b) {
389
- const unlimited = Number(b.terms.uses === null) - Number(a.terms.uses === null);
390
- if (unlimited !== 0) return unlimited;
391
- if (a.lapse !== b.lapse) return a.lapse < b.lapse ? -1 : 1;
392
- if (a.object.name !== b.object.name) return a.object.name < b.object.name ? -1 : 1;
393
- return a.id < b.id ? -1 : a.id > b.id ? 1 : 0;
394
- }
395
- function lapseOf(candidate, at) {
396
- const { terms } = candidate;
397
- const until = terms.validUntil ?? (terms.untilDate ? boundOf(terms.untilDate, "until", "date", terms.zone) : null) ?? END;
398
- const keying = keyingAt(candidate.terms, at);
399
- if (keying.per === "total") return until;
400
- const end = periodOf(at, keying.per, keying.zone).endsAt;
401
- return end < until ? end : until;
402
- }
403
- async function readSpender(ctx, object, def, after, options) {
404
- const filled = {};
405
- const related = /* @__PURE__ */ new Map();
406
- const through = async (path, from) => {
407
- const [rel, target] = path.split(".");
408
- if (!rel || !target) return from[path];
409
- const id = from[rel];
410
- if (typeof id !== "string" || !id) return null;
411
- if (!related.has(rel)) {
412
- const override = options.overrides?.get(id);
413
- if (override) related.set(rel, override);
414
- else {
415
- const field = object.fields.find((f) => f.name === rel);
416
- const to = field?.options?.to ? getObject(field.options.to) : void 0;
417
- related.set(rel, to ? await readValues(ctx, to, id) : void 0);
418
- }
419
- }
420
- return related.get(rel)?.[target] ?? null;
421
- };
422
- for (const [target, source] of Object.entries(def.copy)) {
423
- filled[target] = await through(source, after) ?? null;
424
- }
425
- const merged = { ...after, ...filled };
426
- let at = ctx.now;
427
- if (def.at) {
428
- const value = def.at.includes(".") ? await through(def.at, merged) : merged[def.at];
429
- const instant = iso(value);
430
- if (!instant && options.needAt) {
431
- throw new ValidationError(
432
- `${object.label} needs its time (${def.at}) before it can spend a use`,
433
- { rule: "allowance", field: def.at.split(".")[0] }
434
- );
435
- }
436
- if (instant) at = instant;
437
- }
438
- if (def.local.weekday || def.local.minute) {
439
- const zoneValue = def.local.zone ? def.local.zone.includes(".") ? await through(def.local.zone, merged) : merged[def.local.zone] : null;
440
- const zone = typeof zoneValue === "string" && zoneValue ? zoneValue : await orgZone(ctx);
441
- const local = localParts(at, zone);
442
- if (def.local.weekday) filled[def.local.weekday] = local.weekday;
443
- if (def.local.minute) filled[def.local.minute] = local.minuteOfDay;
444
- }
445
- return { values: filled, at };
446
- }
447
- function sources(def) {
448
- const relations = [def.at, def.local.zone, ...Object.values(def.copy)].filter((p) => typeof p === "string" && p.includes(".")).map((p) => p.split(".")[0]);
449
- const ownAt = def.at && !def.at.includes(".") ? def.at : null;
450
- const ownZone = def.local.zone && !def.local.zone.includes(".") ? def.local.zone : null;
451
- return {
452
- relations: [...new Set(relations)],
453
- ownAt: ownAt ?? ownZone
454
- };
455
- }
456
- var NOTHING = Object.freeze({ values: {}, statements: [] });
457
- var changedIn = (written, before, field) => Object.hasOwn(written, field) && JSON.stringify(written[field] ?? null) !== JSON.stringify(before?.[field] ?? null);
458
- async function spendFor(ctx, object, spender, values, at, by, options) {
459
- const def = spenderOf(object);
460
- const person = values[def.person];
461
- if (typeof person !== "string" || !person) {
462
- throw new ValidationError(`${object.label} needs a person before it can spend a use`, {
463
- rule: "allowance",
464
- reason: "no_holder",
465
- field: def.person
466
- });
467
- }
468
- const alive = await ctx.db.selectFrom("core_person").select("id").where("id", "=", person).where("deleted_at", "is", null).executeTakeFirst();
469
- if (!alive) throw refusal({ rule: "allowance", reason: "not_live" });
470
- const candidates = await holdersOf(ctx, object, person);
471
- const judged = await Promise.all(
472
- candidates.map(async (c) => ({
473
- ...c,
474
- reason: cannotPay(c, object, values, at),
475
- room: await roomAt(ctx, c, at),
476
- lapse: lapseOf(c, at)
477
- }))
478
- );
479
- const full = (c) => refusal({
480
- rule: "allowance",
481
- reason: "no_uses_left",
482
- object: c.object.name,
483
- record: c.id,
484
- period: c.room.period.key,
485
- uses: c.room.uses ?? 0,
486
- used: c.room.used
487
- });
488
- let chosen;
489
- if (options.named) {
490
- chosen = judged.find((c) => c.id === options.named);
491
- if (!chosen) throw refusal({ rule: "allowance", reason: await notTheirs(ctx, options.named) });
492
- if (chosen.reason) {
493
- throw refusal({
494
- rule: "allowance",
495
- reason: chosen.reason,
496
- object: chosen.object.name,
497
- record: chosen.id
498
- });
499
- }
500
- if (!hasRoom(chosen.room)) throw full(chosen);
501
- } else {
502
- const ordered = judged.sort(precedence);
503
- const covering = ordered.filter((c) => c.reason === null);
504
- if (!covering.length) {
505
- const first = ordered[0];
506
- throw refusal(
507
- first?.reason ? { rule: "allowance", reason: first.reason, object: first.object.name, record: first.id } : { rule: "allowance", reason: "no_holder" }
508
- );
509
- }
510
- const preferred = covering.find((c) => c.id === options.prefer && hasRoom(c.room));
511
- chosen = preferred ?? covering.find((c) => hasRoom(c.room));
512
- if (!chosen) throw full(covering[0]);
513
- }
514
- const holder = { object: chosen.object.name, id: chosen.id };
515
- addPending(
516
- ctx,
517
- pendingKey(holder.object, holder.id, chosen.room.period.key, chosen.room.zone),
518
- 1
519
- );
520
- const { statements } = spendStatements(
521
- {
522
- holder,
523
- period: chosen.room.period,
524
- zone: chosen.room.zone,
525
- spender,
526
- personId: person,
527
- at,
528
- atDate: localParts(at, chosen.terms.zone).date,
529
- by,
530
- movedFrom: options.movedFrom ?? null
531
- },
532
- ctx.now
533
- );
534
- return { holder: chosen.id, statements };
535
- }
536
- async function notTheirs(ctx, id) {
537
- const row = await ctx.db.selectFrom("core_allowance").select("record_id").where("record_id", "=", id).executeTakeFirst();
538
- return row ? "not_theirs" : "no_holder";
539
- }
540
- function giveBack(ctx, spender, open, by) {
541
- addPending(ctx, pendingKey(open.object, open.record, open.period, open.zone), -1);
542
- return returnStatements(spender, by, ctx.now);
543
- }
544
- async function spenderWrite(ctx, object, id, before, written, outcome, by) {
545
- const def = spenderOf(object);
546
- if (!def || !object.states) return NOTHING;
547
- const ref = { object: object.name, id };
548
- const after = { ...before ?? {}, ...written, ...outcome.values };
549
- const to = outcome.moved?.id;
550
- const entering = to !== void 0 && def.spendIn.includes(to);
551
- const returning = to !== void 0 && def.returnIn.includes(to);
552
- const { relations, ownAt } = sources(def);
553
- const repointed = relations.some((rel) => changedIn(written, before, rel)) || ownAt !== null && changedIn(written, before, ownAt);
554
- const open = before === null ? null : await openUse(ctx, ref);
555
- const holderWritten = changedIn(written, before, def.holder);
556
- if (open && !returning) {
557
- if (holderWritten) {
558
- throw new ValidationError(
559
- `${object.label} has spent a use of ${String(before?.[def.holder])}: give it back before naming another`,
560
- { rule: "allowance", field: def.holder }
561
- );
562
- }
563
- if (changedIn(written, before, def.person)) {
564
- throw new ValidationError(
565
- `${object.label} has spent a use of its person's: give it back before changing whose it is`,
566
- { rule: "allowance", field: def.person }
567
- );
568
- }
569
- }
570
- const isWaived = (values2) => {
571
- const v = def.waived ? values2?.[def.waived] : void 0;
572
- return v === true || v === 1 || v === "1" || v === "true";
573
- };
574
- const state = object.states.field;
575
- if (def.waived && before !== null && isWaived(before) !== isWaived(after)) {
576
- const inSpend = (values2) => typeof values2[state] === "string" && def.spendIn.includes(values2[state]);
577
- if (open || inSpend(before) || inSpend(after)) {
578
- throw new ValidationError(
579
- `Whether ${object.label.toLowerCase()} spends a use is decided when it is made: it cannot change now`,
580
- { rule: "allowance", reason: "waived_kept", field: def.waived }
581
- );
582
- }
583
- }
584
- const spending = entering && !open && !isWaived(after);
585
- const respending = open !== null && !returning && repointed;
586
- const fill = before === null || entering || repointed;
587
- const read = fill ? await readSpender(ctx, object, def, after, { needAt: spending || respending }) : { values: {}, at: ctx.now };
588
- const values = { ...read.values };
589
- const statements = [];
590
- const spenderValues = { ...after, ...values };
591
- if (returning && open) statements.push(...giveBack(ctx, ref, open, by));
592
- const namedNow = holderWritten && present(written[def.holder]) ? String(written[def.holder]) : null;
593
- if (namedNow && !spending && !(open && returning)) {
594
- const person = spenderValues[def.person];
595
- const theirs = typeof person === "string" && (await holdersOf(ctx, object, person)).some((c) => c.id === namedNow);
596
- if (!theirs) throw refusal({ rule: "allowance", reason: await notTheirs(ctx, namedNow) });
597
- }
598
- if (respending && open) {
599
- statements.push(...giveBack(ctx, ref, open, by));
600
- const spent2 = await spendFor(ctx, object, ref, spenderValues, read.at, by, {
601
- prefer: open.record,
602
- movedFrom: open.id
603
- });
604
- statements.push(...spent2.statements);
605
- values[def.holder] = spent2.holder;
606
- return { values, statements };
607
- }
608
- if (!spending) return { values, statements };
609
- 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
- }
626
- movedFrom = await openUse(ctx, { object: object.name, id: fromId });
627
- 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 });
629
- }
630
- const stored = present(spenderValues[def.holder]) ? String(spenderValues[def.holder]) : null;
631
- const named = namedNow ?? (movedFrom ? movedFrom.record : stored);
632
- const spent = await spendFor(ctx, object, ref, spenderValues, read.at, by, {
633
- named,
634
- movedFrom: movedFrom?.id ?? null
635
- });
636
- statements.push(...spent.statements);
637
- values[def.holder] = spent.holder;
638
- return { values, statements };
639
- }
640
- async function followSpenders(ctx, object, id, after, changed, by) {
641
- const statements = [];
642
- for (const spender of listObjects()) {
643
- const def = spenderOf(spender);
644
- if (!def || !spender.states) continue;
645
- const paths = [def.at, def.local.zone, ...Object.values(def.copy)].filter(
646
- (p) => typeof p === "string" && p.includes(".")
647
- );
648
- const rels = /* @__PURE__ */ new Set();
649
- for (const path of paths) {
650
- const [rel, target] = path.split(".");
651
- const field = spender.fields.find((f) => f.name === rel);
652
- if (field?.options?.to === object.name && changed.includes(target)) rels.add(rel);
653
- }
654
- if (!rels.size) continue;
655
- for (const rel of rels) {
656
- const field = spender.fields.find((f) => f.name === rel);
657
- const column = field ? viewColumnOf(field) : null;
658
- if (!column) continue;
659
- const { rows } = await ctx.db.executeQuery(
660
- CompiledQuery.raw(
661
- `SELECT s.* FROM ${spender.source} s JOIN core_allowance_use u ON u.spender_type = ? AND u.spender_id = s.id AND u.returned_at IS NULL WHERE s.${column} = ? ORDER BY s.id LIMIT 500`,
662
- [spender.name, id]
663
- )
664
- );
665
- for (const row of rows) {
666
- const values = rowValues(spender, row);
667
- const ref = { object: spender.name, id: String(row.id) };
668
- const open = await openUse(ctx, ref);
669
- if (!open) continue;
670
- const read = await readSpender(ctx, spender, def, values, {
671
- needAt: true,
672
- overrides: /* @__PURE__ */ new Map([[id, after]])
673
- });
674
- statements.push(...giveBack(ctx, ref, open, by));
675
- let spent;
676
- try {
677
- spent = await spendFor(ctx, spender, ref, { ...values, ...read.values }, read.at, by, {
678
- prefer: open.record,
679
- movedFrom: open.id
680
- });
681
- } catch (error) {
682
- if (error instanceof ValidationError) {
683
- const details = error.details;
684
- throw new ValidationError(
685
- `${spender.label} ${ref.id} could not be paid for after this change (${error.message}): move or cancel it first`,
686
- { ...details, spender: ref.id }
687
- );
688
- }
689
- throw error;
690
- }
691
- statements.push(...spent.statements);
692
- const sets = [];
693
- const params = [];
694
- for (const [name, value] of Object.entries({
695
- ...read.values,
696
- [def.holder]: spent.holder
697
- })) {
698
- const storage = fieldStorage(spender.name, name);
699
- if (!storage?.column || !storage.own) continue;
700
- const type = FIELD_TYPE_REGISTRY[storage.type];
701
- sets.push(`${storage.column} = ?`);
702
- params.push(type.toStorage(value));
703
- }
704
- const table = objectTableOf(spender.name);
705
- if (sets.length && table) {
706
- statements.push(
707
- CompiledQuery.raw(
708
- `UPDATE ${table} SET ${sets.join(", ")}, updated_at = ? WHERE id = ?`,
709
- [...params, ctx.now, ref.id]
710
- )
711
- );
712
- }
713
- }
714
- }
715
- }
716
- return statements;
717
- }
718
-
719
- // ../core/src/records/follows.ts
720
- var FOLLOWERS_MAX = 500;
721
- function followersOf(object) {
722
- const out = [];
723
- for (const child of listObjects()) {
724
- const f = child.states?.follows;
725
- if (!f || !child.states) continue;
726
- const rel = child.fields.find((field) => field.name === f.relation);
727
- if (rel?.options?.to !== object) continue;
728
- out.push({
729
- object: child,
730
- relation: f.relation,
731
- stateField: child.states.field,
732
- when: f.when,
733
- from: f.from
734
- });
735
- }
736
- return out;
737
- }
738
- async function followerIds(ctx, follower, id, limit = FOLLOWERS_MAX + 1) {
739
- const rel = follower.object.fields.find((f) => f.name === follower.relation);
740
- const state = follower.object.fields.find((f) => f.name === follower.stateField);
741
- const relCol = rel ? viewColumnOf(rel) : null;
742
- const stateCol = state ? viewColumnOf(state) : null;
743
- if (!relCol || !stateCol) return [];
744
- const rows = await ctx.db.selectFrom(
745
- visibleSource(orgReader(ctx.db), getObject(follower.object.name) ?? follower.object)
746
- ).select("id").where(relCol, "=", id).where(stateCol, "in", [...follower.from]).orderBy("id").limit(limit).execute();
747
- return rows.map((row) => String(row.id));
748
- }
749
- async function followersOn(ctx, object, id) {
750
- let count = 0;
751
- for (const follower of followersOf(object)) {
752
- count += (await followerIds(ctx, follower, id)).length;
753
- }
754
- return count;
755
- }
756
-
757
- // ../core/src/records/slug.ts
758
- function slugFields(object) {
759
- return object.fields.filter(
760
- (f) => f.fieldType === "slug" && f.extension !== void 0 && f.extension === object.extension && fieldStorage(object.name, f.name)?.own === true
761
- );
762
- }
763
- var empty = (value) => value === void 0 || value === null || value === "";
764
- function columnOf(object, field) {
765
- const column = fieldStorage(object.name, field.name)?.column;
766
- if (!column) throw new Error(`${object.name}.${field.name} has no column`);
767
- return column;
768
- }
769
- async function holders(ctx, object, field, slug, except) {
770
- const column = columnOf(object, field);
771
- let query = ctx.db.selectFrom(visibleTable(ctx, object, "t")).select("t.id").where("t.deleted_at", "is", null).where(sql.ref(`t.${column}`), "=", slug);
772
- if (except) query = query.where("t.id", "<>", except);
773
- const rows = await query.limit(1).execute();
774
- return rows.map((r) => String(r.id));
775
- }
776
- async function freeSlug(ctx, object, field, base) {
777
- const column = columnOf(object, field);
778
- const rows = await ctx.db.selectFrom(visibleTable(ctx, object, "t")).select(sql.ref(`t.${column}`).as("slug")).where("t.deleted_at", "is", null).where(
779
- (eb) => eb.or([
780
- eb(sql.ref(`t.${column}`), "=", base),
781
- // `base` is letters, digits and hyphens: nothing LIKE treats as a wildcard.
782
- eb(sql.ref(`t.${column}`), "like", `${base}-%`)
783
- ])
784
- ).execute();
785
- const taken = new Set(rows.map((r) => String(r.slug)));
786
- if (!taken.has(base)) return base;
787
- for (let n = 2; n < 1e4; n += 1) {
788
- const candidate = `${base}-${n}`;
789
- if (!taken.has(candidate)) return candidate;
790
- }
791
- throw new ValidationError(`No free address for "${base}"`, { reason: "slug_taken" });
792
- }
793
- async function slugsForCreate(ctx, object, values) {
794
- const fields = slugFields(object);
795
- if (!fields.length) return values;
796
- const out = { ...values };
797
- for (const field of fields) {
798
- const given = out[field.name];
799
- if (empty(given)) {
800
- const title = object.titleField ? out[object.titleField] : void 0;
801
- const local = object.name.split(".").pop() ?? "record";
802
- const base = slugify(typeof title === "string" ? title : "") || slugify(local) || "record";
803
- out[field.name] = await freeSlug(ctx, object, field, base);
804
- continue;
805
- }
806
- await assertFree(ctx, object, field, given, null);
807
- }
808
- return out;
809
- }
810
- async function assertSlugsFree(ctx, object, id, values) {
811
- for (const field of slugFields(object)) {
812
- if (!Object.hasOwn(values, field.name) || empty(values[field.name])) continue;
813
- await assertFree(ctx, object, field, values[field.name], id);
814
- }
815
- }
816
- async function assertFree(ctx, object, field, value, except) {
817
- if (typeof value !== "string" || value.length > SLUG_MAX || !SLUG_RE.test(value)) return;
818
- if ((await holders(ctx, object, field, value, except)).length) {
819
- throw new ValidationError(
820
- `${object.name}.${field.name}: "${value}" is another ${object.label.toLowerCase()}'s address`,
821
- { field: field.name, reason: "slug_taken", slug: value }
822
- );
823
- }
824
- }
825
- async function assertRestorable(ctx, object, id) {
826
- for (const field of slugFields(object)) {
827
- const column = columnOf(object, field);
828
- const row = await ctx.db.selectFrom(visibleTable(ctx, object, "t")).select(sql.ref(`t.${column}`).as("slug")).where("t.id", "=", id).executeTakeFirst();
829
- const slug = row?.slug;
830
- if (typeof slug !== "string" || !slug) continue;
831
- const taken = await holders(ctx, object, field, slug, id);
832
- if (taken.length) {
833
- throw new ConflictError(
834
- `"${slug}" is now another ${object.label.toLowerCase()}'s address: change the ${field.label.toLowerCase()} of one of them, then restore this one`,
835
- { field: field.name, slug, reason: "slug_taken", heldBy: taken[0] }
836
- );
837
- }
838
- }
839
- }
840
- async function redirectWrites(ctx, object, id, before, after) {
841
- const field = object.publishable?.slug;
842
- if (!field) return [];
843
- const old = before?.[field];
844
- const now = after[field];
845
- if (before && old === now) return [];
846
- const writes = [];
847
- if (typeof now === "string" && now) {
848
- writes.push(
849
- CompiledQuery.raw("DELETE FROM core_slug_redirect WHERE object_type = ? AND slug = ?", [
850
- object.name,
851
- now
852
- ])
853
- );
854
- }
855
- if (typeof old === "string" && old && before && await everPublished(ctx, object.name, id)) {
856
- writes.push(
857
- CompiledQuery.raw(
858
- "INSERT INTO core_slug_redirect (object_type, slug, record_id, created_at) VALUES (?, ?, ?, ?) ON CONFLICT (object_type, slug) DO UPDATE SET record_id = excluded.record_id, created_at = excluded.created_at",
859
- [object.name, old, id, ctx.now]
860
- )
861
- );
862
- }
863
- return writes;
864
- }
865
- async function everPublished(ctx, object, id) {
866
- const row = await ctx.db.selectFrom("core_publish_version").select("version").where("object_type", "=", object).where("record_id", "=", id).limit(1).executeTakeFirst();
867
- return row !== void 0;
868
- }
869
-
870
- // ../core/src/records/unique.ts
871
- async function assertUnique(ctx, object, id, after) {
872
- const stateField = object.states?.field;
873
- for (const rule of object.unique ?? []) {
874
- const state = stateField ? after[stateField] : void 0;
875
- if (rule.states && !(typeof state === "string" && rule.states.includes(state))) continue;
876
- const fields = rule.fields.map((name) => object.fields.find((f) => f.name === name));
877
- const values = rule.fields.map((name) => after[name]);
878
- if (values.some((v) => v === null || v === void 0 || v === "")) continue;
879
- if (fields.some((f) => !f?.column)) continue;
880
- let query = ctx.db.selectFrom(visibleSource(ctx, object)).select("id").where("id", "!=", id);
881
- fields.forEach((field, i) => {
882
- const value = values[i];
883
- query = query.where(
884
- field?.column,
885
- "=",
886
- typeof value === "boolean" ? value ? 1 : 0 : value
887
- );
888
- });
889
- const stateColumn = stateField ? object.fields.find((f) => f.name === stateField)?.column : void 0;
890
- if (rule.states && stateColumn) query = query.where(stateColumn, "in", [...rule.states]);
891
- const existing = await query.limit(1).executeTakeFirst();
892
- if (!existing) continue;
893
- const labels = fields.map((f) => f?.label ?? "").join(" and ");
894
- throw new ConflictError(`There is already a ${object.label.toLowerCase()} for this ${labels}`, {
895
- rule: "unique",
896
- object: object.name,
897
- fields: [...rule.fields],
898
- existing: existing.id
899
- });
900
- }
901
- }
902
-
903
- // ../core/src/recurring/index.ts
904
- var RECURRING_MAX_PER_RUN = 25;
905
- var DAILY_RUN_MINUTE = 5;
906
- var writer = null;
907
- function setRecurringWriter(next) {
908
- writer = next;
909
- }
910
- function records() {
911
- if (!writer) throw new Error("recurring: the record operations are not loaded");
912
- return writer;
913
- }
914
- var text = (value) => typeof value === "string" && value.trim() !== "" ? value : null;
915
- function assertRuleValues(object, values) {
916
- const def = object.recurring;
917
- if (!def) return;
918
- const label = (name) => object.fields.find((f) => f.name === name)?.label ?? name;
919
- const refuse = (field, message) => {
920
- throw new ValidationError(`${object.label}: ${label(field)} ${message}`, {
921
- field,
922
- rule: "recurring_rule"
923
- });
924
- };
925
- const time = values[def.rule.time];
926
- if (text(time) !== null && parseLocalTime(time) === null) {
927
- refuse(def.rule.time, "must be a local time, HH:MM (00:00 to 23:59)");
928
- }
929
- if (def.rule.length) {
930
- const length = values[def.rule.length];
931
- if (length !== null && length !== void 0 && !(typeof length === "number" && Number.isInteger(length) && length >= 1 && length <= 1440)) {
932
- refuse(def.rule.length, "must be whole minutes, from 1 to 1440");
933
- }
934
- }
935
- const from = text(values[def.rule.from]);
936
- const until = def.rule.until ? text(values[def.rule.until]) : null;
937
- if (from && until && until < from)
938
- refuse(def.rule.until ?? def.rule.from, "is before the first date");
939
- }
940
- function ruleOf(def, values, defaultZone) {
941
- const days = values[def.rule.weekdays];
942
- const weekdays = new Set(
943
- (Array.isArray(days) ? days : []).map((d) => WEEKDAYS.indexOf(String(d)) + 1).filter((d) => d > 0)
944
- );
945
- const minutes = parseLocalTime(text(values[def.rule.time]) ?? "");
946
- const from = text(values[def.rule.from]);
947
- if (!weekdays.size || minutes === null || !from || !parseLocalDate(from)) return null;
948
- const lengthValue = def.rule.length ? values[def.rule.length] : null;
949
- const until = def.rule.until ? text(values[def.rule.until]) : null;
950
- return {
951
- weekdays,
952
- minutes,
953
- length: typeof lengthValue === "number" && lengthValue > 0 ? lengthValue : null,
954
- from,
955
- until: until && parseLocalDate(until) ? until : null,
956
- zone: text(def.rule.zone ? values[def.rule.zone] : null) ?? defaultZone
957
- };
958
- }
959
- function ruleIncludes(rule, date) {
960
- if (date < rule.from || rule.until !== null && date > rule.until) return false;
961
- return rule.weekdays.has(isoWeekday(date));
962
- }
963
- function occurrenceOn(rule, date) {
964
- const starts = wallClockToInstant(wallClockOf(date, rule.minutes), rule.zone);
965
- return { date, starts, ends: rule.length === null ? null : starts + rule.length * 6e4 };
966
- }
967
- function occurrencesBetween(rule, first, last) {
968
- const out = [];
969
- const start = first > rule.from ? first : rule.from;
970
- const end = rule.until !== null && rule.until < last ? rule.until : last;
971
- for (let date = start; date <= end; date = addDaysToDate(date, 1)) {
972
- if (rule.weekdays.has(isoWeekday(date))) out.push(occurrenceOn(rule, date));
973
- }
974
- return out;
975
- }
976
- function isEnded(def, values) {
977
- if (!def.ended) return false;
978
- const value = values[def.ended.field];
979
- return typeof value === "string" && def.ended.in.includes(value);
980
- }
981
- var iso2 = (ms) => new Date(ms).toISOString();
982
- function occurrenceValues(def, rule, occurrence, series) {
983
- const values = { [def.into.starts]: iso2(occurrence.starts) };
984
- if (def.into.ends) values[def.into.ends] = occurrence.ends === null ? null : iso2(occurrence.ends);
985
- if (def.into.zone) values[def.into.zone] = rule.zone;
986
- for (const [target, source] of Object.entries(def.copy)) values[target] = series[source] ?? null;
987
- return values;
988
- }
989
- function generatedOf(def) {
990
- const generated = getObject(def.generates);
991
- if (!generated) throw new Error(`recurring: ${def.generates} is not installed`);
992
- return generated;
993
- }
994
- async function closureRanges(ctx, def, first, last) {
995
- if (!def.closures) return [];
996
- const closure = getObject(def.closures.object);
997
- const fromCol = closure?.fields.find((f) => f.name === def.closures?.from)?.column;
998
- const untilCol = closure?.fields.find((f) => f.name === def.closures?.until)?.column;
999
- if (!closure || !fromCol || !untilCol) return [];
1000
- const rows = await ctx.db.selectFrom(visibleSource(ctx, closure)).select([`${fromCol} as from`, `${untilCol} as until`]).where(fromCol, "<=", last).where(untilCol, ">=", first).execute();
1001
- return rows.flatMap((r) => r.from && r.until ? [{ from: r.from, until: r.until }] : []);
1002
- }
1003
- async function horizonOf(ctx, def) {
1004
- const floor = def.horizonAtLeast;
1005
- if (!floor) return def.horizonDays;
1006
- const target = getObject(floor.object);
1007
- const column = target?.fields.find((f) => f.name === floor.field)?.column;
1008
- if (!target || !column) return def.horizonDays;
1009
- const row = await ctx.db.selectFrom(visibleSource(ctx, target)).select((eb) => eb.fn.max(column).as("days")).executeTakeFirst();
1010
- const days = Math.ceil(Number(row?.days ?? 0));
1011
- return Math.min(Math.max(def.horizonDays, Number.isFinite(days) ? days + 1 : 0), 366);
1012
- }
1013
- async function generateSeries(ctx, object, id, limit = RECURRING_MAX_PER_RUN) {
1014
- const def = object.recurring;
1015
- if (!def) throw new ValidationError(`${object.label} has no recurring schedule`);
1016
- const version = await seriesVersion(ctx.db, object.name, id);
1017
- ctx.write(guardStatement("series", object.name, id, version));
1018
- const now = Date.parse(ctx.now);
1019
- const { timezone } = await loadGeneralSettings(ctx.db);
1020
- const series = await records().load(ctx, object, id);
1021
- const zone = series ? ruleOf(def, series, timezone)?.zone ?? timezone : timezone;
1022
- const today = localParts(now, zone).date;
1023
- const nextDaily = iso2(
1024
- wallClockToInstant(wallClockOf(addDaysToDate(today, 1), DAILY_RUN_MINUTE), zone)
1025
- );
1026
- const rule = series && !isEnded(def, series) ? ruleOf(def, series, timezone) : null;
1027
- if (!series || !rule) {
1028
- ctx.write(armSeriesStatement(object.name, id, nextDaily, ctx.now));
1029
- return { made: 0, more: false };
1030
- }
1031
- const last = addDaysToDate(today, await horizonOf(ctx, def));
1032
- const generated = generatedOf(def);
1033
- const made = new Set(
1034
- (await ctx.db.selectFrom("core_recurrence_occurrence").select("local_date").where("series_object", "=", object.name).where("series_id", "=", id).where("local_date", ">=", today).execute()).map((r) => r.local_date)
1035
- );
1036
- const closures = await closureRanges(ctx, def, today, last);
1037
- const closed = (date) => closures.some((c) => c.from <= date && date <= c.until);
1038
- const due = occurrencesBetween(rule, today, last).filter(
1039
- (o) => o.starts > now && !made.has(o.date) && !closed(o.date)
1040
- );
1041
- const batch = due.slice(0, Math.max(0, limit));
1042
- for (const occurrence of batch) {
1043
- const values = {
1044
- ...occurrenceValues(def, rule, occurrence, series),
1045
- [def.link]: id
1046
- };
1047
- const record = await records().create(ctx, generated, values, { by: "host" });
1048
- ctx.write(
1049
- occurrenceStatement({
1050
- seriesObject: object.name,
1051
- seriesId: id,
1052
- date: occurrence.date,
1053
- object: generated.name,
1054
- record,
1055
- now: ctx.now
1056
- })
1057
- );
1058
- }
1059
- const more = due.length > batch.length;
1060
- ctx.write(armSeriesStatement(object.name, id, more ? ctx.now : nextDaily, ctx.now));
1061
- if (!more) {
1062
- ctx.write(
1063
- ctx.db.updateTable("core_recurrence_series").set({ generated_until: last }).where("object_type", "=", object.name).where("record_id", "=", id)
1064
- );
1065
- }
1066
- return { made: batch.length, more };
1067
- }
1068
- function seriesObjectsOf(object) {
1069
- return listObjects().filter((o) => o.recurring?.generates === object);
1070
- }
1071
- function closuresOf(object) {
1072
- return listObjects().flatMap(
1073
- (o) => o.recurring?.closures?.object === object ? [o.recurring] : []
1074
- );
1075
- }
1076
- function generatedRecordEdited(ctx, object, id, before, after, by) {
1077
- if (by === "host") return {};
1078
- const defs = seriesObjectsOf(object.name).map((o) => o.recurring);
1079
- if (!defs.length) return {};
1080
- const watched = new Set(object.states ? [object.states.field] : []);
1081
- for (const def of defs) {
1082
- for (const f of [def.into.starts, def.into.ends, def.into.zone, ...Object.keys(def.copy)]) {
1083
- if (f) watched.add(f);
1084
- }
1085
- }
1086
- const differs = [...watched].some(
1087
- (f) => JSON.stringify(before[f] ?? null) !== JSON.stringify(after[f] ?? null)
1088
- );
1089
- if (!differs) return {};
1090
- ctx.write(markEditedStatement(object.name, id, ctx.now));
1091
- const changed = defs.find((def) => def.into.changed)?.into.changed;
1092
- return changed && before[changed] !== true ? { [changed]: true } : {};
1093
- }
1094
- function seriesCreated(ctx, object, id) {
1095
- if (!object.recurring) return;
1096
- ctx.write(armSeriesStatement(object.name, id, ctx.now, ctx.now));
1097
- }
1098
- function cancellableFrom(object, cancel) {
1099
- return new Set(
1100
- (object.states?.moves ?? []).filter((m) => m.to === cancel && m.by.includes("host")).flatMap((m) => typeof m.from === "string" ? [m.from] : [...m.from])
1101
- );
1102
- }
1103
- function assertConfirmed(plans, confirm, what, how) {
1104
- if (!plans.length || confirm === plans.length) return;
1105
- throw new ConflictError(
1106
- `${plans.length} ${what} have places taken and would be moved or cancelled. Confirm with that count (${how}) to go ahead.`,
1107
- {
1108
- rule: "recurring_confirm",
1109
- count: plans.length,
1110
- // How many live records that follow them (bookings) the cancel moves with them (ADR 0507).
1111
- followers: plans.reduce((sum, p) => sum + (p.followers ?? 0), 0),
1112
- records: plans.map((p) => ({
1113
- id: p.id,
1114
- date: p.date,
1115
- action: p.action,
1116
- followers: p.followers ?? 0
1117
- }))
1118
- }
1119
- );
1120
- }
1121
- async function seriesChanged(ctx, object, id, before, after, options = {}) {
1122
- const def = object.recurring;
1123
- if (!def) return;
1124
- const watched = [
1125
- ...Object.values(def.rule),
1126
- ...Object.values(def.copy),
1127
- ...def.ended ? [def.ended.field] : []
1128
- ].filter((f) => typeof f === "string");
1129
- const changed = options.trashed || watched.some((f) => JSON.stringify(before[f] ?? null) !== JSON.stringify(after[f] ?? null));
1130
- const version = await seriesVersion(ctx.db, object.name, id);
1131
- ctx.write(guardStatement("series", object.name, id, version));
1132
- ctx.write(armSeriesStatement(object.name, id, ctx.now, ctx.now));
1133
- if (!changed) return;
1134
- const generated = generatedOf(def);
1135
- const { timezone } = await loadGeneralSettings(ctx.db);
1136
- const ended = options.trashed || isEnded(def, after);
1137
- const rule = ended ? null : ruleOf(def, after, timezone);
1138
- const now = Date.parse(ctx.now);
1139
- const zones2 = [ruleOf(def, before, timezone)?.zone ?? timezone, rule?.zone ?? timezone];
1140
- const today = zones2.map((z) => localParts(now, z).date).sort()[0];
1141
- const first = options.from && parseLocalDate(options.from) && options.from > today ? options.from : today;
1142
- const rows = await ctx.db.selectFrom("core_recurrence_occurrence").select(["local_date", "record_id", "edited_at"]).where("series_object", "=", object.name).where("series_id", "=", id).where("local_date", ">=", first).orderBy("local_date").execute();
1143
- const finals = new Set((generated.states?.moves ?? []).filter((m) => m.final).map((m) => m.to));
1144
- const stateField = generated.states?.field;
1145
- const plans = [];
1146
- for (const row of rows) {
1147
- if (row.edited_at && !ended) continue;
1148
- const record = await records().load(ctx, generated, row.record_id);
1149
- if (!record) continue;
1150
- const starts = Date.parse(String(record[def.into.starts] ?? ""));
1151
- if (!(starts > now)) continue;
1152
- const state = stateField && typeof record[stateField] === "string" ? record[stateField] : null;
1153
- if (state !== null && (state === def.cancel || finals.has(state))) continue;
1154
- const claimed = await claimedOn(ctx, generated, row.record_id);
1155
- const followers = await followersOn(ctx, generated.name, row.record_id);
1156
- if (!rule || !ruleIncludes(rule, row.local_date)) {
1157
- plans.push({
1158
- id: row.record_id,
1159
- date: row.local_date,
1160
- values: {},
1161
- // Places taken, or anything following it (a waiting booking): cancelled, never removed.
1162
- action: claimed > 0 || followers > 0 ? "cancel" : "remove",
1163
- claimed,
1164
- followers,
1165
- state
1166
- });
1167
- continue;
1168
- }
1169
- const wanted = occurrenceValues(def, rule, occurrenceOn(rule, row.local_date), after);
1170
- const values = Object.fromEntries(
1171
- Object.entries(wanted).filter(
1172
- ([f, v]) => JSON.stringify(record[f] ?? null) !== JSON.stringify(v ?? null)
1173
- )
1174
- );
1175
- const places = generated.capacity?.places;
1176
- if (places && typeof values[places] === "number" && values[places] < claimed) {
1177
- values[places] = claimed;
1178
- }
1179
- if (Object.keys(values).length) {
1180
- plans.push({
1181
- id: row.record_id,
1182
- date: row.local_date,
1183
- values,
1184
- action: "update",
1185
- claimed,
1186
- followers,
1187
- state
1188
- });
1189
- }
1190
- }
1191
- const cancellable = cancellableFrom(generated, def.cancel);
1192
- const stuck = plans.filter(
1193
- (p) => p.action === "cancel" && (!stateField || !cancellable.has(p.state ?? ""))
1194
- );
1195
- if (stuck.length) {
1196
- throw new ConflictError(
1197
- `${stuck.length} ${generated.plural?.toLowerCase() ?? "records"} with places taken are in a state the platform cannot cancel them from; change them by hand first.`,
1198
- {
1199
- rule: "recurring_cannot_cancel",
1200
- records: stuck.map((p) => ({ id: p.id, date: p.date, state: p.state }))
1201
- }
1202
- );
1203
- }
1204
- const timeFields = [def.into.starts, def.into.ends, def.into.zone].filter(Boolean);
1205
- assertConfirmed(
1206
- plans.filter(
1207
- (p) => (p.claimed > 0 || p.followers > 0) && (p.action === "cancel" || timeFields.some((f) => Object.hasOwn(p.values, f)))
1208
- ),
1209
- options.confirm,
1210
- `of this ${object.label.toLowerCase()}'s ${generated.plural?.toLowerCase() ?? "records"}`,
1211
- options.trashed ? "end the series with recurring.change first" : "recurring.change"
1212
- );
1213
- for (const plan of plans) {
1214
- if (generated.capacity) {
1215
- ctx.write(guardStatement("claimed", generated.name, plan.id, plan.claimed));
1216
- }
1217
- if (plan.action === "update") {
1218
- await records().update(ctx, generated, plan.id, plan.values, { by: "host" });
1219
- } else if (plan.action === "cancel" && stateField) {
1220
- await records().update(ctx, generated, plan.id, { [stateField]: def.cancel }, { by: "host" });
1221
- } else {
1222
- await records().remove(ctx, generated, plan.id);
1223
- ctx.write(
1224
- ctx.db.deleteFrom("core_recurrence_occurrence").where("object_type", "=", generated.name).where("record_id", "=", plan.id)
1225
- );
1226
- }
1227
- }
1228
- }
1229
- async function claimedOn(ctx, object, id) {
1230
- if (!object.capacity) return 0;
1231
- const row = await ctx.db.selectFrom("core_capacity").select(["held", "taken"]).where("object_type", "=", object.name).where("record_id", "=", id).executeTakeFirst();
1232
- return row ? row.held + row.taken : 0;
1233
- }
1234
- function rangeOf(closure, values) {
1235
- if (!values) return null;
1236
- const from = text(values[closure.from]);
1237
- const until = text(values[closure.until]);
1238
- if (!from || !until || !parseLocalDate(from) || !parseLocalDate(until) || until < from) {
1239
- return null;
1240
- }
1241
- return { from, until };
1242
- }
1243
- async function closureWritten(ctx, object, before, after, confirm) {
1244
- const defs = closuresOf(object.name);
1245
- if (!defs.length) return;
1246
- const { timezone } = await loadGeneralSettings(ctx.db);
1247
- const seen = /* @__PURE__ */ new Set();
1248
- const targets = [];
1249
- for (const def of defs) {
1250
- const closure = def.closures;
1251
- if (!closure || seen.has(def.generates)) continue;
1252
- seen.add(def.generates);
1253
- const range = rangeOf(closure, after);
1254
- const old = rangeOf(closure, before);
1255
- if (!range || old && old.from === range.from && old.until === range.until) continue;
1256
- const generated = generatedOf(def);
1257
- const startsCol = generated.fields.find((f) => f.name === def.into.starts)?.column;
1258
- const stateField = generated.states?.field;
1259
- const stateCol = generated.fields.find((f) => f.name === stateField)?.column;
1260
- if (!startsCol || !stateField || !stateCol) continue;
1261
- const zoneCol = def.into.zone ? generated.fields.find((f) => f.name === def.into.zone)?.column : void 0;
1262
- const movable = [...cancellableFrom(generated, def.cancel)];
1263
- if (!movable.length) continue;
1264
- const now = Date.parse(ctx.now);
1265
- const rows = await ctx.db.selectFrom(visibleSource(ctx, generated)).select(["id", `${startsCol} as starts`, ...zoneCol ? [`${zoneCol} as zone`] : []]).where(startsCol, ">=", addDaysToDate(range.from, -2)).where(startsCol, "<", addDaysToDate(range.until, 3)).where(stateCol, "in", movable).execute();
1266
- for (const row of rows) {
1267
- const starts = Date.parse(row.starts ?? "");
1268
- if (!(starts > now)) continue;
1269
- const date = localParts(starts, row.zone || timezone).date;
1270
- if (date < range.from || date > range.until) continue;
1271
- if (old && date >= old.from && date <= old.until) continue;
1272
- const claimed = await claimedOn(ctx, generated, row.id);
1273
- const followers = await followersOn(ctx, generated.name, row.id);
1274
- targets.push({
1275
- generated,
1276
- stateField,
1277
- cancel: def.cancel,
1278
- id: row.id,
1279
- date,
1280
- claimed,
1281
- followers
1282
- });
1283
- }
1284
- }
1285
- assertConfirmed(
1286
- targets.filter((t) => t.claimed > 0 || t.followers > 0).map((t) => ({
1287
- id: t.id,
1288
- date: t.date,
1289
- action: "cancel",
1290
- claimed: t.claimed,
1291
- followers: t.followers
1292
- })),
1293
- confirm,
1294
- "of the records this closure covers",
1295
- "recurring.close"
1296
- );
1297
- for (const t of targets) {
1298
- if (t.generated.capacity)
1299
- ctx.write(guardStatement("claimed", t.generated.name, t.id, t.claimed));
1300
- await records().update(ctx, t.generated, t.id, { [t.stateField]: t.cancel }, { by: "host" });
1301
- }
1302
- }
1303
- function requireSeriesObject(name) {
1304
- const object = getObject(name);
1305
- if (!object?.recurring) {
1306
- throw new ValidationError(`${name} has no recurring schedule`, { field: "object" });
1307
- }
1308
- return object;
1309
- }
1310
- function requireClosureObject(name) {
1311
- const object = getObject(name);
1312
- if (!object || !closuresOf(name).length) {
1313
- throw new ValidationError(`${name} is not the closures of a recurring schedule`, {
1314
- field: "object"
1315
- });
1316
- }
1317
- return object;
1318
- }
1319
-
1320
- // ../core/src/operations/record.ts
1321
- var objectName = external_exports.string().min(1).max(80).regex(/^[a-z][a-z0-9]*(\.[a-z][a-z0-9]*)?$/).describe("Object: an extension object (`<extension>.<object>`) or a core object");
1322
- var recordId = external_exports.string().min(1).max(64).describe("Record id");
1323
- var valuesSchema = external_exports.record(external_exports.string().max(80), external_exports.unknown()).describe("Field values by registry field name (see schema.objects)");
1324
- var recordSchema = external_exports.object({
1325
- object: external_exports.string(),
1326
- id: external_exports.string(),
1327
- title: external_exports.string().nullable(),
1328
- values: external_exports.record(external_exports.string(), external_exports.unknown()),
1329
- createdAt: external_exports.string().nullable(),
1330
- updatedAt: external_exports.string().nullable()
1331
- });
1332
- function requireObject(name) {
1333
- const object = getObject(name);
1334
- if (!object) throw new ValidationError(`Unknown object "${name}"`, { object: name });
1335
- return object;
1336
- }
1337
- function requireExtensionObject(name) {
1338
- const object = requireObject(name);
1339
- if (isCoreObject(name) || !object.extension || !object.titleField) {
1340
- throw new ValidationError(
1341
- `${name} is a core object; use its own operations (e.g. ${name}.create)`,
1342
- { object: name }
1343
- );
1344
- }
1345
- return object;
1346
- }
1347
- function extensionFields(object) {
1348
- return object.fields.filter((f) => f.extension);
1349
- }
1350
- function manifestOf(field) {
1351
- return {
1352
- type: field.fieldType,
1353
- label: field.label,
1354
- ...field.options?.choices ? { options: [...field.options.choices] } : {},
1355
- ...field.options?.to ? { to: field.options.to } : {},
1356
- ...field.options?.many !== void 0 ? { many: field.options.many } : {},
1357
- ...field.options?.min !== void 0 ? { min: field.options.min } : {},
1358
- ...field.options?.max !== void 0 ? { max: field.options.max } : {},
1359
- ...field.options?.step !== void 0 ? { step: field.options.step } : {},
1360
- ...field.options?.document ? {
1361
- schema: field.options.document.schema,
1362
- ...field.options.document.maxBytes !== void 0 ? { maxBytes: field.options.document.maxBytes } : {}
1363
- } : {}
1364
- };
1365
- }
1366
- function fromRow(object, row) {
1367
- const values = {};
1368
- for (const field of extensionFields(object)) {
1369
- const type = field.fieldType;
1370
- const column = viewColumnOf(field);
1371
- const rawValue = column ? row[column] : null;
1372
- values[field.name] = type === "formula" ? formulaFromStorage(field.options?.resultType, rawValue) : FIELD_TYPE_REGISTRY[type].fromStorage(rawValue ?? null);
1373
- }
1374
- if (object.capacity) {
1375
- for (const field of CAPACITY_FIELDS) {
1376
- const raw = field.column ? row[field.column] : null;
1377
- values[field.name] = raw === void 0 || raw === null ? null : Number(raw);
1378
- }
1379
- }
1380
- if (object.allowance?.kind === "holder") {
1381
- for (const field of ALLOWANCE_FIELDS) {
1382
- const raw = field.column ? row[field.column] : null;
1383
- values[field.name] = raw === void 0 || raw === null ? null : Number(raw);
1384
- }
1385
- }
1386
- if (object.publishable) {
1387
- for (const field of PUBLISHED_FIELDS) {
1388
- const raw = field.column ? row[field.column] : null;
1389
- values[field.name] = raw === void 0 || raw === null ? null : field.type === "number" ? Number(raw) : raw;
1390
- }
1391
- }
1392
- const titleColumn = object.titleField ? object.fields.find((f) => f.name === object.titleField)?.column : void 0;
1393
- const titleValue = titleColumn ? row[titleColumn] : row.name ?? row.display_name ?? row.title;
1394
- return {
1395
- object: object.name,
1396
- id: String(row.id),
1397
- title: titleValue == null ? null : String(titleValue),
1398
- values,
1399
- createdAt: row.created_at ?? null,
1400
- updatedAt: row.updated_at ?? null
1401
- };
1402
- }
1403
- async function loadRecord(reader, object, id) {
1404
- const row = await reader.db.selectFrom(visibleSource(reader, object)).selectAll().where("id", "=", id).executeTakeFirst();
1405
- return row ? fromRow(object, row) : null;
1406
- }
1407
- async function prepareValues(ctx, object, values, mode, options = {}) {
1408
- const prepared = [];
1409
- for (const [name, value] of Object.entries(values)) {
1410
- const field = object.fields.find((f) => f.name === name);
1411
- if (!field) {
1412
- throw new ValidationError(`Unknown field "${name}" on ${object.name}`, {
1413
- field: name,
1414
- allowed: extensionFields(object).filter((f) => !f.readOnly).map((f) => f.name)
1415
- });
1416
- }
1417
- if (!field.extension) {
1418
- throw new ValidationError(
1419
- `${object.name}.${name} is a core field; change it with ${object.name}.update`,
1420
- { field: name }
1421
- );
1422
- }
1423
- const term = holderTerms(object).has(name);
1424
- 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";
1426
- if (!hostCode && hostFilled(object).has(name)) {
1427
- throw new ValidationError(`${object.name}.${name} is set by the host and cannot be written`, {
1428
- field: name
1429
- });
1430
- }
1431
- if (field.readOnly && !ownCode && !hostCode) {
1432
- throw new ValidationError(
1433
- field.fieldType === "formula" ? `${object.name}.${name} is computed and cannot be set` : `${object.name}.${name} is set automatically and cannot be written`,
1434
- { field: name }
1435
- );
1436
- }
1437
- const storage = fieldStorage(object.name, name);
1438
- if (!storage?.column) throw new ValidationError(`${object.name}.${name} cannot be written`);
1439
- const spec = FIELD_TYPE_REGISTRY[storage.type];
1440
- const parsed = spec.schema(manifestOf(field)).safeParse(value);
1441
- if (!parsed.success) {
1442
- const first = [
1443
- "document",
1444
- "richText",
1445
- "image",
1446
- "video",
1447
- "slug",
1448
- "number",
1449
- "currency",
1450
- "percent"
1451
- ].includes(storage.type) ? parsed.error.issues[0] : void 0;
1452
- const where = first ? `: ${[name, ...first.path.map(String)].join(".")}: ${first.message}` : "";
1453
- throw new ValidationError(`Invalid value for ${object.name}.${name}${where}`, {
1454
- field: name,
1455
- issues: parsed.error.issues
1456
- });
1457
- }
1458
- if (field.required && (parsed.data === null || parsed.data === "")) {
1459
- throw new ValidationError(`${object.name}.${name} is required`, { field: name });
1460
- }
1461
- prepared.push({
1462
- field,
1463
- value: parsed.data,
1464
- stored: spec.toStorage(parsed.data),
1465
- table: storage.table,
1466
- column: storage.column,
1467
- own: storage.own
1468
- });
1469
- }
1470
- if (mode === "create") {
1471
- for (const field of extensionFields(object)) {
1472
- if (field.required && !prepared.some((p) => p.field.name === field.name)) {
1473
- const storage = fieldStorage(object.name, field.name);
1474
- if (storage?.own) {
1475
- throw new ValidationError(`${object.name}.${field.name} is required`, {
1476
- field: field.name
1477
- });
1478
- }
1479
- }
1480
- }
1481
- }
1482
- if (options.checkReferences !== false) await assertReferences(ctx, prepared);
1483
- return prepared;
1484
- }
1485
- async function checkRecordValues(ctx, object, values, mode, options = {}) {
1486
- const prepared = await prepareValues(ctx, object, values, mode, options);
1487
- return Object.fromEntries(
1488
- prepared.map((p) => {
1489
- const type = fieldStorage(object.name, p.field.name)?.type ?? "text";
1490
- return [p.field.name, FIELD_TYPE_REGISTRY[type].fromStorage(p.stored)];
1491
- })
1492
- );
1493
- }
1494
- function hostValues(object, values) {
1495
- return Object.entries(values).map(([name, value]) => {
1496
- const field = object.fields.find((f) => f.name === name);
1497
- const storage = fieldStorage(object.name, name);
1498
- if (!field || !storage?.column) throw new Error(`${object.name}.${name} cannot be set`);
1499
- const spec = FIELD_TYPE_REGISTRY[storage.type];
1500
- const parsed = spec.schema(manifestOf(field)).parse(value);
1501
- return {
1502
- field,
1503
- value: parsed,
1504
- stored: spec.toStorage(parsed),
1505
- table: storage.table,
1506
- column: storage.column,
1507
- own: storage.own
1508
- };
1509
- });
1510
- }
1511
- function withHostValues(prepared, outcome, object) {
1512
- const extra = hostValues(object, outcome.values);
1513
- return [...prepared.filter((p) => !Object.hasOwn(outcome.values, p.field.name)), ...extra];
1514
- }
1515
- function withValues(outcome, values) {
1516
- return Object.keys(values).length ? { ...outcome, values: { ...outcome.values, ...values } } : outcome;
1517
- }
1518
- var valuesOf = (prepared) => Object.fromEntries(prepared.map((p) => [p.field.name, p.value]));
1519
- function assertChoiceRequirements(object, prepared, values) {
1520
- for (const p of prepared) {
1521
- const choice = p.field.options?.choices?.find((c) => c.value === p.value);
1522
- if (!choice?.requires?.length) continue;
1523
- const prefix = p.field.name.includes(".") ? `${p.field.name.split(".")[0]}.` : "";
1524
- const missing = choice.requires.map((name) => object.fields.find((f) => f.name === name || f.name === `${prefix}${name}`)).filter((f) => Boolean(f)).filter((f) => {
1525
- const value = values[f.name];
1526
- return value === null || value === void 0 || value === "" || Array.isArray(value) && value.length === 0;
1527
- });
1528
- const first = missing[0];
1529
- if (first) {
1530
- throw new ValidationError(
1531
- `${p.field.label} \u201C${choice.label}\u201D needs ${missing.map((f) => f.label).join(", ")}`,
1532
- {
1533
- field: first.name,
1534
- fields: missing.map((f) => f.name),
1535
- reason: "required_by_choice",
1536
- choiceField: p.field.name,
1537
- choice: choice.value
1538
- }
1539
- );
1540
- }
1541
- }
1542
- }
1543
- async function assertReferences(ctx, prepared) {
1544
- for (const p of prepared) {
1545
- if (p.value == null) continue;
1546
- if (isDocumentType(p.field.fieldType)) {
1547
- await assertDocumentRefs(ctx, p.field, p.value);
1548
- continue;
1549
- }
1550
- const ids = Array.isArray(p.value) ? p.value : [String(p.value)];
1551
- if (!ids.length) continue;
1552
- if (p.field.fieldType === "user") {
1553
- const found = await ctx.db.selectFrom("core_user").select("id").where("id", "in", jsonList(ids)).where("kind", "=", "human").execute();
1554
- if (found.length !== new Set(ids).size) {
1555
- throw new ValidationError(`${p.field.name}: no such user`, { field: p.field.name });
1556
- }
1557
- continue;
1558
- }
1559
- if (p.field.fieldType === "relation" && p.field.options?.to) {
1560
- const target = getObject(p.field.options.to);
1561
- if (!target) throw new ValidationError(`${p.field.name}: unknown target object`);
1562
- const found = await ctx.db.selectFrom(visibleSource(ctx, target)).select("id").where("id", "in", jsonList(ids)).execute();
1563
- const have = new Set(found.map((r) => String(r.id)));
1564
- const missing = [...new Set(ids)].filter((id) => !have.has(id));
1565
- if (missing.length) {
1566
- throw new ValidationError(
1567
- `${p.field.name}: no live ${target.name} with id ${missing.join(", ")}`,
1568
- {
1569
- field: p.field.name,
1570
- missing
1571
- }
1572
- );
1573
- }
1574
- }
1575
- }
1576
- }
1577
- async function assertDocumentRefs(ctx, field, value) {
1578
- const schema = field.options?.document?.schema;
1579
- if (!schema) return;
1580
- const refs = documentRefs(schema, value);
1581
- const byObject = /* @__PURE__ */ new Map();
1582
- for (const ref of refs) byObject.set(ref.to, [...byObject.get(ref.to) ?? [], ref]);
1583
- for (const [to, list] of byObject) {
1584
- const target = getObject(to);
1585
- if (!target) throw new ValidationError(`${field.name}: unknown object ${to}`);
1586
- const ids = [...new Set(list.map((r) => r.id))];
1587
- const found = await ctx.db.selectFrom(visibleSource(ctx, target)).select("id").where("id", "in", jsonList(ids)).execute();
1588
- const have = new Set(found.map((r) => String(r.id)));
1589
- const missing = list.find((r) => !have.has(r.id));
1590
- if (missing) {
1591
- const where = [field.name, ...missing.path.map(String)].join(".");
1592
- throw new ValidationError(`${where}: no live ${to} with id ${missing.id}`, {
1593
- field: field.name,
1594
- path: missing.path,
1595
- missing: ids.filter((id) => !have.has(id))
1596
- });
1597
- }
1598
- if (to === "media") await assertMediaKinds(ctx, field, list);
1599
- }
1600
- }
1601
- async function assertMediaKinds(ctx, field, refs) {
1602
- const typed = refs.filter((r) => r.media);
1603
- if (!typed.length) return;
1604
- const rows = await ctx.db.selectFrom(visibleSource(ctx, mediaObject)).select(["id", "kind", "state"]).where("id", "in", jsonList([...new Set(typed.map((r) => r.id))])).execute();
1605
- const byId = new Map(rows.map((r) => [String(r.id), r]));
1606
- for (const ref of typed) {
1607
- const row = byId.get(ref.id);
1608
- const where = [field.name, ...ref.path.map(String)].join(".");
1609
- if (!row || row.kind !== ref.media) {
1610
- throw new ValidationError(`${where}: ${ref.id} is not a ${ref.media}`, {
1611
- field: field.name,
1612
- path: ref.path,
1613
- reason: "media_kind",
1614
- expected: ref.media
1615
- });
1616
- }
1617
- if (ref.media === "video" && row.state !== "ready") {
1618
- throw new ValidationError(`${where}: the video ${ref.id} is not ready yet`, {
1619
- field: field.name,
1620
- path: ref.path,
1621
- reason: "video_not_ready",
1622
- state: row.state
1623
- });
1624
- }
1625
- }
1626
- }
1627
- function sideWrites(id, prepared) {
1628
- const byTable = /* @__PURE__ */ new Map();
1629
- for (const p of prepared.filter((x) => !x.own)) {
1630
- byTable.set(p.table, [...byTable.get(p.table) ?? [], p]);
1631
- }
1632
- return [...byTable].map(([table, values]) => {
1633
- const columns = values.map((v) => v.column);
1634
- return CompiledQuery.raw(
1635
- `INSERT INTO ${table} (id, ${columns.join(", ")}) VALUES (?, ${columns.map(() => "?").join(", ")}) ON CONFLICT (id) DO UPDATE SET ${columns.map((c) => `${c} = excluded.${c}`).join(", ")}`,
1636
- [id, ...values.map((v) => v.stored)]
1637
- );
1638
- });
1639
- }
1640
- function searchDoc(object, id, title) {
1641
- return [
1642
- CompiledQuery.raw("DELETE FROM core_search_docs WHERE object_type = ? AND record_id = ?", [
1643
- object,
1644
- id
1645
- ]),
1646
- CompiledQuery.raw(
1647
- "INSERT INTO core_search_docs (object_type, record_id, title, body) VALUES (?, ?, ?, '')",
1648
- [object, id, title ?? ""]
1649
- )
1650
- ];
1651
- }
1652
- function snapshot(record) {
1653
- return { ...record.values };
1654
- }
1655
- var recordCreate = defineOperation({
1656
- name: "record.create",
1657
- description: "Create a record of an extension object (`<extension>.<object>`, see schema.objects) with field values by name. Formula fields are computed and cannot be set; relation fields take record ids (an array when the field holds many). Returns the stored record. Core objects (person, organisation, \u2026) use their own create operations.",
1658
- input: external_exports.object({ object: objectName, values: valuesSchema.default({}) }),
1659
- output: recordSchema,
1660
- permission: "records:write",
1661
- risk: "write",
1662
- async handler(input, ctx) {
1663
- const object = requireExtensionObject(input.object);
1664
- const id = await createRecord(ctx, object, input.values);
1665
- return ctx.afterCommit(async () => await loadRecord(ctx, object, id));
1666
- }
1667
- });
1668
- async function createRecord(ctx, object, values, options = {}) {
1669
- const requester = options.by ?? (object.states?.requests ? callerMover(ctx) : void 0);
1670
- 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;
1672
- const withDefaults = await slugsForCreate(ctx, object, await applyDefaults(ctx, object, handed));
1673
- let prepared = await prepareValues(ctx, object, withDefaults, "create", options);
1674
- assertOneOf(object, valuesOf(prepared));
1675
- assertRuleValues(object, valuesOf(prepared));
1676
- const ownerField = object.ownerField;
1677
- const assignment = ownerField && (withDefaults[ownerField] === void 0 || withDefaults[ownerField] === null) ? await assignOwner(ctx, object, { get: (field) => valuesOf(prepared)[field] ?? null }) : null;
1678
- if (ownerField && assignment?.ownerId) {
1679
- prepared = [
1680
- ...prepared.filter((p) => p.field.name !== ownerField),
1681
- ...hostValues(object, { [ownerField]: assignment.ownerId })
1682
- ];
1683
- }
1684
- assertChoiceRequirements(object, prepared, valuesOf(prepared));
1685
- const table = objectTableOf(object.name);
1686
- const id = newId("record");
1687
- const by = options.by ?? callerMover(ctx);
1688
- assertHolderCreatable(object, by);
1689
- const outcome = await applyTransition(ctx, object, id, null, valuesOf(prepared), {
1690
- by,
1691
- cache: options.cache
1692
- });
1693
- const spent = await spenderWrite(ctx, object, id, null, valuesOf(prepared), outcome, by);
1694
- prepared = withHostValues(prepared, withValues(outcome, spent.values), object);
1695
- await assertUnique(ctx, object, id, valuesOf(prepared));
1696
- const own = prepared.filter((p) => p.own);
1697
- const columns = ["id", "created_at", "updated_at", "created_by", ...own.map((p) => p.column)];
1698
- ctx.write(
1699
- CompiledQuery.raw(
1700
- `INSERT INTO ${table} (${columns.join(", ")}) VALUES (${columns.map(() => "?").join(", ")})`,
1701
- [id, ctx.now, ctx.now, ctx.user.id, ...own.map((p) => p.stored)]
1702
- ),
1703
- ...sideWrites(id, prepared),
1704
- ...outcome.history
1705
- );
1706
- const counter = await counterWrite(ctx, object, id, valuesOf(prepared), "create");
1707
- if (counter) ctx.write(counter);
1708
- ctx.write(...await holderWrite(ctx, object, id, null, valuesOf(prepared)));
1709
- ctx.write(...spent.statements);
1710
- const title = prepared.find((p) => p.field.name === object.titleField)?.value;
1711
- ctx.write(...searchDoc(object.name, id, title == null ? null : String(title)));
1712
- ctx.write(...await redirectWrites(ctx, object, id, null, valuesOf(prepared)));
1713
- seriesCreated(ctx, object, id);
1714
- await closureWritten(ctx, object, null, valuesOf(prepared), options.recurringConfirm);
1715
- const assigned = assignment ? recordAssignment(ctx, object, id, assignment, {
1716
- timeline: options.assignmentTimeline !== false
1717
- }) : void 0;
1718
- ctx.recordChange({
1719
- object: object.name,
1720
- id,
1721
- action: "create",
1722
- after: valuesOf(prepared),
1723
- assignment: assigned
1724
- });
1725
- return id;
1726
- }
1727
- async function applyDefaults(ctx, object, values) {
1728
- const named = await withZoneDefaults(ctx, object, await withDefaultTitle(ctx, object, values));
1729
- const fields = object.fields.filter(
1730
- (f) => f.extension === object.extension && (f.options?.default !== void 0 || f.options?.defaultSetting) && (named[f.name] === void 0 || named[f.name] === null)
1731
- );
1732
- if (!fields.length || !object.extension) return named;
1733
- let settings = {};
1734
- if (fields.some((f) => f.options?.defaultSetting)) {
1735
- const row = await ctx.db.selectFrom("core_extension_settings").select("value").where("extension_id", "=", object.extension).executeTakeFirst();
1736
- settings = row ? JSON.parse(row.value) : {};
1737
- }
1738
- const out = { ...named };
1739
- for (const field of fields) {
1740
- const setting = field.options?.defaultSetting ? settings[field.options.defaultSetting] : null;
1741
- const value = setting ?? field.options?.default;
1742
- if (value !== void 0 && value !== null) out[field.name] = value;
1743
- }
1744
- return out;
1745
- }
1746
- async function withZoneDefaults(ctx, object, values) {
1747
- const empty2 = object.fields.filter(
1748
- (f) => f.fieldType === "timezone" && f.options?.default === void 0 && !f.options?.defaultSetting && (values[f.name] === void 0 || values[f.name] === null || values[f.name] === "")
1749
- );
1750
- if (!empty2.length) return values;
1751
- const { timezone } = await loadGeneralSettings(ctx.db);
1752
- return { ...values, ...Object.fromEntries(empty2.map((f) => [f.name, timezone])) };
1753
- }
1754
- async function withDefaultTitle(ctx, object, values) {
1755
- const { titleDefault, titleField } = object;
1756
- if (!titleDefault || !titleField) return values;
1757
- const given = values[titleField];
1758
- if (given !== void 0 && given !== null && given !== "") return values;
1759
- for (const name of titleDefault.from) {
1760
- const to = object.fields.find((f) => f.name === name)?.options?.to;
1761
- const title = await titleOf(ctx, to, values[name]);
1762
- if (title) return { ...values, [titleField]: `${title}${titleDefault.suffix ?? ""}` };
1763
- }
1764
- return values;
1765
- }
1766
- function assertOneOf(object, values) {
1767
- for (const group of object.requireOneOf ?? []) {
1768
- const filled = group.some((name) => {
1769
- const value = values[name];
1770
- return value !== null && value !== void 0 && value !== "";
1771
- });
1772
- if (filled) continue;
1773
- const labels = group.map((name) => object.fields.find((f) => f.name === name)?.label ?? name);
1774
- throw new ValidationError(
1775
- `${object.label} needs ${labels.slice(0, -1).join(", ")} or ${labels.at(-1)}`,
1776
- { field: group[0], fields: [...group], reason: "require_one_of" }
1777
- );
1778
- }
1779
- }
1780
- async function titleOf(ctx, to, id) {
1781
- if (typeof id !== "string" || !to) return null;
1782
- const target = getObject(to);
1783
- const column = target?.titleField ? target.fields.find((f) => f.name === target.titleField)?.column : target?.name === "organisation" ? "name" : target?.name === "person" ? "display_name" : void 0;
1784
- if (!target || !column) return null;
1785
- const row = await sql`
1786
- SELECT ${sql.ref(column)} AS title FROM ${visibleSource(ctx, target)} WHERE id = ${id}
1787
- `.execute(ctx.db);
1788
- return row.rows[0]?.title ?? null;
1789
- }
1790
- async function timelineFor(ctx, object, id, before, after, outcome) {
1791
- const move = transitionTimeline(outcome);
1792
- const tracked = object.fields.filter(
1793
- (f) => f.track === "timeline" && JSON.stringify(before[f.name] ?? null) !== JSON.stringify(after[f.name] ?? null)
1794
- );
1795
- if (!tracked.length) return void 0;
1796
- const links = [{ object: object.name, id }];
1797
- for (const name of object.timelineLinks ?? []) {
1798
- const to = object.fields.find((f) => f.name === name)?.options?.to;
1799
- const value = after[name];
1800
- if (to && typeof value === "string") links.push({ object: to, id: value });
1801
- }
1802
- const labels = {};
1803
- for (const field of tracked) {
1804
- if (move && field.name === move.field) {
1805
- labels[field.name] = move.labels;
1806
- continue;
1807
- }
1808
- if (field.fieldType !== "relation" || field.options?.many) continue;
1809
- labels[field.name] = {
1810
- before: await titleOf(ctx, field.options?.to, before[field.name]),
1811
- after: await titleOf(ctx, field.options?.to, after[field.name])
1812
- };
1813
- }
1814
- return {
1815
- ...move ? { subject: move.subject } : {},
1816
- links,
1817
- labels
1818
- };
1819
- }
1820
- var recordGet = defineOperation({
1821
- name: "record.get",
1822
- description: "Get one record by object and id. For extension objects returns every field; for core objects returns only the values of extension fields (use person.get etc. for core fields). Read-only.",
1823
- input: external_exports.object({ object: objectName, id: recordId }),
1824
- output: recordSchema,
1825
- permission: "records:read",
1826
- risk: "read",
1827
- mcp: { idempotent: true },
1828
- async handler(input, ctx) {
1829
- const object = requireObject(input.object);
1830
- const record = await loadRecord(ctx, object, input.id);
1831
- if (!record) throw new NotFoundError(input.object, input.id);
1832
- return record;
1833
- }
1834
- });
1835
- async function updateRecord(ctx, object, id, values, options = {}) {
1836
- const before = await loadRecord(ctx, object, id);
1837
- if (!before) throw new NotFoundError(object.name, id);
1838
- const by = options.by ?? callerMover(ctx);
1839
- const asked = await resolveStateRequest(ctx, object, before.values, values, by);
1840
- if (options.from !== void 0) assertMovesFrom(object, before.values, asked, options.from);
1841
- let prepared = await prepareValues(ctx, object, asked, "update", options);
1842
- if (!prepared.length) return false;
1843
- assertRuleValues(object, { ...before.values, ...valuesOf(prepared) });
1844
- await assertSlugsFree(ctx, object, id, valuesOf(prepared));
1845
- assertChoiceRequirements(object, prepared, {
1846
- ...before.values,
1847
- ...Object.fromEntries(prepared.map((p) => [p.field.name, p.value]))
1848
- });
1849
- assertOneOf(object, {
1850
- ...before.values,
1851
- ...Object.fromEntries(prepared.map((p) => [p.field.name, p.value]))
1852
- });
1853
- const outcome = await applyTransition(ctx, object, id, before.values, valuesOf(prepared), {
1854
- by
1855
- });
1856
- const spent = await spenderWrite(ctx, object, id, before.values, valuesOf(prepared), outcome, by);
1857
- prepared = withHostValues(prepared, withValues(outcome, spent.values), object);
1858
- const edited = generatedRecordEdited(
1859
- ctx,
1860
- object,
1861
- id,
1862
- before.values,
1863
- { ...before.values, ...valuesOf(prepared) },
1864
- by
1865
- );
1866
- if (Object.keys(edited).length) {
1867
- prepared = [
1868
- ...prepared.filter((p) => !Object.hasOwn(edited, p.field.name)),
1869
- ...hostValues(object, edited)
1870
- ];
1871
- }
1872
- if (object.unique)
1873
- await assertUnique(ctx, object, id, { ...before.values, ...valuesOf(prepared) });
1874
- const own = prepared.filter((p) => p.own);
1875
- if (own.length || !isCoreObject(object.name)) {
1876
- const table = objectTableOf(object.name);
1877
- if (table) {
1878
- ctx.write(
1879
- CompiledQuery.raw(
1880
- `UPDATE ${table} SET ${[...own.map((p) => `${p.column} = ?`), "updated_at = ?", "updated_by = ?"].join(", ")} WHERE id = ? AND deleted_at IS NULL`,
1881
- [...own.map((p) => p.stored), ctx.now, ctx.user.id, id]
1882
- )
1883
- );
1884
- }
1885
- }
1886
- ctx.write(...sideWrites(id, prepared), ...outcome.history);
1887
- const after = {
1888
- ...before.values,
1889
- ...Object.fromEntries(prepared.map((p) => [p.field.name, p.value]))
1890
- };
1891
- const counter = await counterWrite(
1892
- ctx,
1893
- object,
1894
- id,
1895
- after,
1896
- prepared.map((p) => p.field.name)
1897
- );
1898
- if (counter) ctx.write(counter);
1899
- ctx.write(...await holderWrite(ctx, object, id, before.values, after));
1900
- ctx.write(...spent.statements);
1901
- ctx.write(
1902
- ...await followSpenders(
1903
- ctx,
1904
- object,
1905
- id,
1906
- after,
1907
- prepared.map((p) => p.field.name),
1908
- by
1909
- )
1910
- );
1911
- await moveFollowers(ctx, object, id, outcome.moved?.id);
1912
- await seriesChanged(ctx, object, id, before.values, after, {
1913
- confirm: options.recurringConfirm,
1914
- from: options.recurringFrom
1915
- });
1916
- await closureWritten(ctx, object, before.values, after, options.recurringConfirm);
1917
- ctx.write(...await redirectWrites(ctx, object, id, before.values, after));
1918
- const timeline = await timelineFor(ctx, object, id, before.values, after, outcome);
1919
- if (object.titleField && prepared.some((p) => p.field.name === object.titleField)) {
1920
- const title = after[object.titleField];
1921
- ctx.write(...searchDoc(object.name, id, title == null ? null : String(title)));
1922
- }
1923
- ctx.recordChange({
1924
- object: object.name,
1925
- id,
1926
- action: "update",
1927
- before: snapshot(before),
1928
- after,
1929
- ...timeline ? { timeline } : {}
1930
- });
1931
- return true;
1932
- }
1933
- async function moveFollowers(ctx, object, id, to) {
1934
- 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;
1938
- const ids = await followerIds(ctx, follower, id);
1939
- if (ids.length > FOLLOWERS_MAX) {
1940
- throw new ConflictError(
1941
- `${object.label} has more than ${FOLLOWERS_MAX} ${(follower.object.plural ?? "records").toLowerCase()} to move with it`,
1942
- { rule: "follows_too_many", object: follower.object.name }
1943
- );
1944
- }
1945
- for (const child of ids) {
1946
- await updateRecord(
1947
- ctx,
1948
- follower.object,
1949
- child,
1950
- { [follower.stateField]: target },
1951
- {
1952
- by: "host"
1953
- }
1954
- );
1955
- }
1956
- }
1957
- }
1958
- function assertMovesFrom(object, stored, values, from) {
1959
- const field = object.states?.field ?? object.stages?.field;
1960
- if (!field) {
1961
- throw new ValidationError(`${object.label} has no states or stages, so "from" means nothing`, {
1962
- field: "from"
1963
- });
1964
- }
1965
- const label = object.fields.find((f) => f.name === field)?.label ?? field;
1966
- const to = values[field];
1967
- if (to === void 0 || to === null || String(to) === from) {
1968
- throw new ValidationError(`With "from", the write must move ${label} to another value`, {
1969
- field
1970
- });
1971
- }
1972
- const current = stored[field] ?? null;
1973
- if (current === null || String(current) !== from) {
1974
- throw new ConflictError(
1975
- `${object.label} is no longer ${from}: its ${label.toLowerCase()} is ${String(current ?? "empty")}. Nothing was changed.`,
1976
- { reason: "not_in_position", field, from, current }
1977
- );
1978
- }
1979
- }
1980
- setRecordWriter({ create: createRecord, update: updateRecord });
1981
- setAllowanceRecordUpdate(updateRecord);
1982
- async function trashRecordAsHost(ctx, object, id) {
1983
- const before = await loadRecord(ctx, object, id);
1984
- if (!before) return;
1985
- if (await claimedOn(ctx, object, id) > 0) {
1986
- throw new ConflictError(`${object.label} has places taken and cannot be removed`, {
1987
- rule: "capacity",
1988
- object: object.name,
1989
- record: id
1990
- });
1991
- }
1992
- await assertNoLiveClaim(ctx, object, id);
1993
- if (object.capacity) ctx.write(guardStatement("claimed", object.name, id, 0));
1994
- if (object.claims) ctx.write(guardStatement("claimant", object.name, id, 0));
1995
- const table = objectTableOf(object.name);
1996
- ctx.write(
1997
- CompiledQuery.raw(`UPDATE ${table} SET deleted_at = ?, deleted_by = ? WHERE id = ?`, [
1998
- ctx.now,
1999
- ctx.user.id,
2000
- id
2001
- ]),
2002
- CompiledQuery.raw("DELETE FROM core_search_docs WHERE object_type = ? AND record_id = ?", [
2003
- object.name,
2004
- id
2005
- ])
2006
- );
2007
- ctx.recordChange({ object: object.name, id, action: "delete", before: snapshot(before) });
2008
- }
2009
- setRecurringWriter({
2010
- load: async (ctx, object, id) => (await loadRecord(ctx, object, id))?.values ?? null,
2011
- create: (ctx, object, values, options) => createRecord(ctx, object, values, options),
2012
- update: (ctx, object, id, values, options) => updateRecord(ctx, object, id, values, options),
2013
- remove: trashRecordAsHost
2014
- });
2015
- var recordUpdate2 = defineOperation({
2016
- name: "record.update",
2017
- description: "Update field values of a record. On extension objects any writable field; on core objects only extension fields (named `<extension>.<field>`). Pass null to clear a value. Changes are recorded in the record's history; fields tracked on the timeline post a system activity. Returns the stored record.",
2018
- input: external_exports.object({
2019
- object: objectName,
2020
- id: recordId,
2021
- values: valuesSchema,
2022
- from: external_exports.string().min(1).max(64).optional().describe(
2023
- "Only move the record if it is still in this state (or stage id), and move it out of it: for a write two people may make at once, such as checking a ticket in. Refused as a conflict (reason not_in_position or moved_meanwhile) when the record has left it."
2024
- )
2025
- }),
2026
- output: recordSchema,
2027
- permission: "records:write",
2028
- risk: "write",
2029
- async handler(input, ctx) {
2030
- const object = requireObject(input.object);
2031
- await updateRecord(ctx, object, input.id, input.values, { from: input.from });
2032
- return ctx.afterCommit(async () => await loadRecord(ctx, object, input.id));
2033
- }
2034
- });
2035
- function isGranted(object) {
2036
- return listObjects().some((o) => o.sellable?.grants?.object === object.name);
2037
- }
2038
- async function grantedBy(ctx, object, id) {
2039
- const [order, subscription] = await Promise.all([
2040
- ctx.db.selectFrom("core_order_grant").select("record_id").where("object_type", "=", object).where("record_id", "=", id).executeTakeFirst(),
2041
- ctx.db.selectFrom("core_subscription_grant").select("record_id").where("object_type", "=", object).where("record_id", "=", id).executeTakeFirst()
2042
- ]);
2043
- return Boolean(order ?? subscription);
2044
- }
2045
- async function assertHolderTrashRule(ctx, object, id, state, restoring) {
2046
- const def = object.allowance;
2047
- if (def?.kind !== "holder" || !object.states) return;
2048
- const finals = new Set(object.states.moves.filter((m) => m.final).map((m) => m.to));
2049
- const final = typeof state === "string" && finals.has(state);
2050
- const live = typeof state === "string" && (def.live ?? []).includes(state);
2051
- const granted = !final && await grantedBy(ctx, object.name, id);
2052
- if (!restoring && (live || granted)) {
2053
- throw new ValidationError(
2054
- `${object.label} can still be spent or is kept by what granted it: void or end it before deleting it`,
2055
- { rule: "allowance", reason: "holder_live", object: object.name, record: id }
2056
- );
2057
- }
2058
- if (restoring && granted) {
2059
- throw new ValidationError(
2060
- `${object.label} was granted and is not ended or void: what granted it decides its state, so it is not restored`,
2061
- { rule: "allowance", reason: "holder_granted", object: object.name, record: id }
2062
- );
2063
- }
2064
- }
2065
- var recordDelete = defineOperation({
2066
- name: "record.delete",
2067
- description: `Move a record of an extension object to Trash (soft delete). It can be restored with record.restore for ${TRASH_RETENTION_DAYS} days. Returns the id and the restore deadline.`,
2068
- input: external_exports.object({ object: objectName, id: recordId }),
2069
- output: external_exports.object({ id: external_exports.string(), restorableUntil: external_exports.string() }),
2070
- permission: "records:write",
2071
- risk: "destructive",
2072
- async handler(input, ctx) {
2073
- const object = requireExtensionObject(input.object);
2074
- const before = await loadRecord(ctx, object, input.id);
2075
- if (!before) throw new NotFoundError(input.object, input.id);
2076
- await assertNoConfirmedClaims(ctx, object, input.id);
2077
- await assertSpenderDeletable(ctx, object, input.id);
2078
- if (object.states) {
2079
- await assertHolderTrashRule(ctx, object, input.id, before.values[object.states.field], false);
2080
- }
2081
- await assertNoLiveClaim(ctx, object, input.id);
2082
- await seriesChanged(ctx, object, input.id, before.values, before.values, { trashed: true });
2083
- if (object.claims) ctx.write(guardStatement("claimant", object.name, input.id, 0));
2084
- const table = objectTableOf(object.name);
2085
- ctx.write(
2086
- CompiledQuery.raw(`UPDATE ${table} SET deleted_at = ?, deleted_by = ? WHERE id = ?`, [
2087
- ctx.now,
2088
- ctx.user.id,
2089
- input.id
2090
- ]),
2091
- CompiledQuery.raw("DELETE FROM core_search_docs WHERE object_type = ? AND record_id = ?", [
2092
- object.name,
2093
- input.id
2094
- ]),
2095
- ...await holderTrash(ctx, object, input.id)
2096
- );
2097
- ctx.recordChange({
2098
- object: object.name,
2099
- id: input.id,
2100
- action: "delete",
2101
- before: snapshot(before)
2102
- });
2103
- return { id: input.id, restorableUntil: restorableUntil(ctx.now) };
2104
- }
2105
- });
2106
- var recordRestore = defineOperation({
2107
- name: "record.restore",
2108
- description: "Restore a record of an extension object from Trash (within 30 days of its deletion). Returns the restored record.",
2109
- input: external_exports.object({ object: objectName, id: recordId }),
2110
- output: recordSchema,
2111
- permission: "records:write",
2112
- risk: "write",
2113
- async handler(input, ctx) {
2114
- const object = requireExtensionObject(input.object);
2115
- const table = objectTableOf(object.name);
2116
- const row = await sql`
2117
- SELECT deleted_at FROM ${visibleTable(ctx, object)} WHERE id = ${input.id}
2118
- `.execute(ctx.db);
2119
- const deletedAt = row.rows[0]?.deleted_at;
2120
- if (deletedAt === void 0) throw new NotFoundError(input.object, input.id);
2121
- if (deletedAt === null) throw new ValidationError(`${input.id} is not in Trash`);
2122
- await assertRestorable(ctx, object, input.id);
2123
- const stateColumn = object.states ? fieldStorage(object.name, object.states.field)?.column : void 0;
2124
- if (stateColumn) {
2125
- const stored = await sql`
2126
- SELECT * FROM ${visibleTable(ctx, object)} WHERE id = ${input.id}
2127
- `.execute(ctx.db);
2128
- await assertHolderTrashRule(ctx, object, input.id, stored.rows[0]?.[stateColumn], true);
2129
- }
2130
- ctx.write(
2131
- CompiledQuery.raw(`UPDATE ${table} SET deleted_at = NULL, deleted_by = NULL WHERE id = ?`, [
2132
- input.id
2133
- ]),
2134
- ...await holderTrash(ctx, object, input.id)
2135
- );
2136
- ctx.recordChange({ object: object.name, id: input.id, action: "restore", diff: {} });
2137
- seriesCreated(ctx, object, input.id);
2138
- return ctx.afterCommit(async () => {
2139
- const record = await loadRecord(ctx, object, input.id);
2140
- await ctx.db.insertInto("core_search_docs").values({
2141
- object_type: object.name,
2142
- record_id: input.id,
2143
- title: record.title ?? "",
2144
- body: ""
2145
- }).onConflict((oc) => oc.columns(["object_type", "record_id"]).doNothing()).execute();
2146
- return record;
2147
- });
2148
- }
2149
- });
2150
- var recordList = defineOperation({
2151
- name: "record.list",
2152
- description: "List records of an extension object (or a core object's extension fields) with the same filter JSON, sort and cursor as other list operations. Every field in schema.objects is filterable, including formula fields; multi-valued fields match any value. Read-only.",
2153
- input: listInputSchema.extend({ object: objectName }),
2154
- output: pageSchema(recordSchema),
2155
- permission: "records:read",
2156
- risk: "read",
2157
- mcp: { idempotent: true },
2158
- async handler(input, ctx) {
2159
- const object = requireObject(input.object);
2160
- const page = await runListQuery(ctx, object, input);
2161
- const items = page.rows.map((row) => {
2162
- const record = fromRow(object, row);
2163
- if (input.fields) {
2164
- record.values = Object.fromEntries(
2165
- Object.entries(record.values).filter(([key]) => input.fields?.includes(key))
2166
- );
2167
- for (const name of input.fields) {
2168
- const field = object.fields.find((f) => f.name === name);
2169
- if (field && !field.extension && field.column && !(name in record.values)) {
2170
- record.values[name] = row[field.column] ?? null;
2171
- }
2172
- }
2173
- }
2174
- return record;
2175
- });
2176
- return { items, nextCursor: page.nextCursor };
2177
- }
2178
- });
2179
- var fieldInfoSchema = external_exports.object({
2180
- name: external_exports.string(),
2181
- label: external_exports.string(),
2182
- type: external_exports.string(),
2183
- fieldType: external_exports.string().nullable(),
2184
- enumValues: external_exports.array(external_exports.string()).nullable(),
2185
- multi: external_exports.boolean(),
2186
- filterable: external_exports.boolean(),
2187
- sortable: external_exports.boolean(),
2188
- readOnly: external_exports.boolean(),
2189
- required: external_exports.boolean(),
2190
- track: external_exports.boolean(),
2191
- extension: external_exports.string().nullable(),
2192
- description: external_exports.string().nullable(),
2193
- options: external_exports.record(external_exports.string(), external_exports.unknown()).nullable()
2194
- });
2195
- var objectInfoSchema = external_exports.object({
2196
- name: external_exports.string(),
2197
- label: external_exports.string(),
2198
- plural: external_exports.string().nullable(),
2199
- icon: external_exports.string().nullable(),
2200
- titleField: external_exports.string().nullable(),
2201
- extension: external_exports.string().nullable(),
2202
- description: external_exports.string().nullable(),
2203
- /** The rec_* view, for query.sql. */
2204
- view: external_exports.string(),
2205
- fields: external_exports.array(fieldInfoSchema),
2206
- /** Where the UI lists it: main navigation, Settings, or nowhere (ADR 0100). */
2207
- navigation: external_exports.enum(["main", "settings", "none"]),
2208
- /** The stage behaviour, when it has one (ADR 0100). */
2209
- stages: external_exports.record(external_exports.string(), external_exports.unknown()).nullable(),
2210
- /** The capacity behaviour, when it has one (ADR 0430). */
2211
- capacity: external_exports.object({
2212
- places: external_exports.string(),
2213
- pool: external_exports.object({ field: external_exports.string(), object: external_exports.string() }).nullable(),
2214
- show: external_exports.enum(["exact", "low", "availability"]),
2215
- lowAt: external_exports.number().nullable(),
2216
- releaseOnRefund: external_exports.boolean()
2217
- }).nullable(),
2218
- /** The sellable behaviour, when it has one (ADR 0435): its price, rules and what it grants. */
2219
- sellable: external_exports.record(external_exports.string(), external_exports.unknown()).nullable(),
2220
- /** The state machine, when it has one (ADR 0425). */
2221
- states: external_exports.record(external_exports.string(), external_exports.unknown()).nullable(),
2222
- /**
2223
- * Versions of its content (ADRs 0446, 0441), when it has them: the content fields, its slug
2224
- * field and date field, and whether the public reads it (ADR 0442: then it has previews).
2225
- */
2226
- publishable: external_exports.object({
2227
- content: external_exports.array(external_exports.string()),
2228
- slug: external_exports.string().nullable(),
2229
- date: external_exports.string().nullable(),
2230
- public: external_exports.boolean()
2231
- }).nullable(),
2232
- timelineLinks: external_exports.array(external_exports.string()),
2233
- /** The owner field assignment rules set (ADR 0246), when the object has one. */
2234
- ownerField: external_exports.string().nullable(),
2235
- /** Sidebar order among extension objects (lower first). */
2236
- navigationOrder: external_exports.number(),
2237
- /** The relations an untitled record is named after (ADR 0246), when it has any. */
2238
- titleDefaultFrom: external_exports.array(external_exports.string())
2239
- });
2240
- function objectInfo(object) {
2241
- return {
2242
- name: object.name,
2243
- label: object.label,
2244
- plural: object.plural ?? null,
2245
- icon: object.icon ?? null,
2246
- titleField: object.titleField ?? null,
2247
- extension: object.extension ?? null,
2248
- description: object.description ?? null,
2249
- view: object.source,
2250
- navigation: object.navigation ?? "main",
2251
- stages: object.stages ? { ...object.stages } : null,
2252
- capacity: object.capacity ? {
2253
- places: object.capacity.places,
2254
- pool: object.capacity.pool ? { ...object.capacity.pool } : null,
2255
- show: object.capacity.show,
2256
- lowAt: object.capacity.lowAt ?? null,
2257
- releaseOnRefund: object.capacity.releaseOnRefund
2258
- } : null,
2259
- sellable: object.sellable ? { ...object.sellable } : null,
2260
- states: object.states ? { ...object.states } : null,
2261
- publishable: object.publishable ? {
2262
- content: [...object.publishable.content],
2263
- slug: object.publishable.slug ?? null,
2264
- date: object.publishable.date ?? null,
2265
- public: Boolean(object.public)
2266
- } : null,
2267
- timelineLinks: [...object.timelineLinks ?? []],
2268
- ownerField: object.ownerField ?? null,
2269
- navigationOrder: object.navigationOrder ?? 100,
2270
- titleDefaultFrom: [...object.titleDefault?.from ?? []],
2271
- fields: object.fields.map((f) => ({
2272
- name: f.name,
2273
- label: f.label,
2274
- type: f.type,
2275
- fieldType: f.fieldType ?? null,
2276
- enumValues: f.enumValues ? [...f.enumValues] : null,
2277
- multi: Boolean(f.related),
2278
- filterable: f.filterable,
2279
- sortable: f.sortable,
2280
- readOnly: Boolean(f.readOnly),
2281
- required: Boolean(f.required),
2282
- track: f.track === "timeline",
2283
- extension: f.extension ?? null,
2284
- description: f.description ?? null,
2285
- options: f.options ? { ...f.options } : null
2286
- }))
2287
- };
2288
- }
2289
- var schemaObjects = defineOperation({
2290
- name: "schema.objects",
2291
- description: "List every object in the field registry (core objects and extension objects) with their fields: name, label, type, filterability, sortability, whether computed, and type options (select choices, relation target, formula expression). Use it before record.* and list filters. Read-only.",
2292
- input: external_exports.object({ object: objectName.optional() }),
2293
- output: external_exports.object({ objects: external_exports.array(objectInfoSchema) }),
2294
- permission: "records:read",
2295
- risk: "read",
2296
- mcp: { idempotent: true },
2297
- async handler(input) {
2298
- const objects = input.object ? [requireObject(input.object)] : listObjects();
2299
- return { objects: objects.map(objectInfo) };
2300
- }
2301
- });
2302
- var recordOperations = [
2303
- recordCreate,
2304
- recordGet,
2305
- recordUpdate2,
2306
- recordDelete,
2307
- recordRestore,
2308
- recordList,
2309
- schemaObjects
2310
- ];
2311
-
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
- export {
2564
- holderOf,
2565
- storedTerms,
2566
- keyingAt,
2567
- slugsForCreate,
2568
- RECURRING_MAX_PER_RUN,
2569
- generateSeries,
2570
- requireSeriesObject,
2571
- requireClosureObject,
2572
- GRANT_CODE_LENGTH,
2573
- newGrantCode,
2574
- grantFieldValue,
2575
- readGrantItem,
2576
- validFrom,
2577
- handGrantValues,
2578
- grantsFollowPerson,
2579
- recordSchema,
2580
- requireExtensionObject,
2581
- loadRecord,
2582
- checkRecordValues,
2583
- createRecord,
2584
- updateRecord,
2585
- recordOperations
2586
- };