@composable-os/cli 0.0.0-stage → 0.1.0-beta.11

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (184) hide show
  1. package/LICENSE +109 -0
  2. package/README.md +24 -2
  3. package/dist/accounts-UHYLCLEY.js +45 -0
  4. package/dist/blocks-5IFU25J6.js +233 -0
  5. package/dist/chunk-2ABSVMGB.js +13 -0
  6. package/dist/chunk-2IVEVPMY.js +669 -0
  7. package/dist/chunk-2TWV3SVB.js +349 -0
  8. package/dist/chunk-2XC5JLBO.js +1931 -0
  9. package/dist/chunk-324WJXNP.js +320 -0
  10. package/dist/chunk-5KSXSK7Y.js +47 -0
  11. package/dist/chunk-6ELZRNUU.js +116 -0
  12. package/dist/chunk-6UWRT4VM.js +220 -0
  13. package/dist/chunk-6WGFA2IV.js +643 -0
  14. package/dist/chunk-6XTU2MTP.js +11278 -0
  15. package/dist/chunk-7CQGMVDO.js +63 -0
  16. package/dist/chunk-7D4GKZOX.js +615 -0
  17. package/dist/chunk-7OGCMQXG.js +284 -0
  18. package/dist/chunk-DHS2CV2M.js +139 -0
  19. package/dist/chunk-DU6OIFOU.js +2358 -0
  20. package/dist/chunk-E4WCYTCT.js +347 -0
  21. package/dist/chunk-E64SG24J.js +88 -0
  22. package/dist/chunk-FJIZGS5Q.js +698 -0
  23. package/dist/chunk-GYTEW66E.js +50 -0
  24. package/dist/chunk-HDIOVFAZ.js +544 -0
  25. package/dist/chunk-K34UKWEI.js +298 -0
  26. package/dist/chunk-KGHA67HG.js +765 -0
  27. package/dist/chunk-LAAL4YGR.js +365 -0
  28. package/dist/chunk-LO6WGU5Y.js +26189 -0
  29. package/dist/chunk-MBIKVRAC.js +1425 -0
  30. package/dist/chunk-P6UWZ6QQ.js +426 -0
  31. package/dist/chunk-PDD2ETVF.js +1302 -0
  32. package/dist/chunk-UB4I2QKR.js +31575 -0
  33. package/dist/chunk-WHKJGF36.js +2418 -0
  34. package/dist/chunk-XIDLW3EP.js +15471 -0
  35. package/dist/chunk-YFTLIEWU.js +504 -0
  36. package/dist/chunk-YNUZRTPH.js +182 -0
  37. package/dist/chunk-ZAWES2UD.js +9364 -0
  38. package/dist/chunk-ZZFWMVJO.js +704 -0
  39. package/dist/cli-5UNY5G5L.js +136 -0
  40. package/dist/cli-UYZMVQMR.js +24534 -0
  41. package/dist/cli.js +25 -0
  42. package/dist/client-repo-SE4EKG6W.js +55 -0
  43. package/dist/create.js +25 -0
  44. package/dist/fields-FTWWMD7N.js +50 -0
  45. package/dist/grants-LOW6TSWD.js +32 -0
  46. package/dist/invoke-6KVT6WJI.js +41 -0
  47. package/dist/moves-E2HKYCTK.js +41 -0
  48. package/dist/order-U4KZLLSJ.js +19 -0
  49. package/dist/person-UHLVBVLR.js +67 -0
  50. package/dist/plan-on-sale-TJPFCNL7.js +26 -0
  51. package/dist/platform/migrations/0001_init.sql +59 -0
  52. package/dist/platform/migrations/0002_users_settings.sql +34 -0
  53. package/dist/platform/migrations/0003_people_organisations.sql +225 -0
  54. package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
  55. package/dist/platform/migrations/0005_views_audit.sql +79 -0
  56. package/dist/platform/migrations/0006_search.sql +223 -0
  57. package/dist/platform/migrations/0007_crm_views.sql +141 -0
  58. package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
  59. package/dist/platform/migrations/0010_approval_queue.sql +90 -0
  60. package/dist/platform/migrations/0011_connected_apps.sql +36 -0
  61. package/dist/platform/migrations/0020_extensions.sql +373 -0
  62. package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
  63. package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
  64. package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
  65. package/dist/platform/migrations/0061_audit_retention.sql +95 -0
  66. package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
  67. package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
  68. package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
  69. package/dist/platform/migrations/0065_storage_stats.sql +13 -0
  70. package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
  71. package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
  72. package/dist/platform/migrations/0100_stage_history.sql +54 -0
  73. package/dist/platform/migrations/0110_integrations.sql +103 -0
  74. package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
  75. package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
  76. package/dist/platform/migrations/0130_automations.sql +113 -0
  77. package/dist/platform/migrations/0131_notifications.sql +29 -0
  78. package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
  79. package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
  80. package/dist/platform/migrations/0160_releases.sql +41 -0
  81. package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
  82. package/dist/platform/migrations/0170_automation_connections.sql +32 -0
  83. package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
  84. package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
  85. package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
  86. package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
  87. package/dist/platform/migrations/0210_daily_digest.sql +33 -0
  88. package/dist/platform/migrations/0220_entitlements.sql +13 -0
  89. package/dist/platform/migrations/0221_support_grants.sql +33 -0
  90. package/dist/platform/migrations/0250_judge.sql +11 -0
  91. package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
  92. package/dist/platform/migrations/0252_judge_usage.sql +14 -0
  93. package/dist/platform/migrations/0255_summary_checks.sql +9 -0
  94. package/dist/platform/migrations/0256_outbound_check.sql +9 -0
  95. package/dist/platform/migrations/0260_ai_usage.sql +20 -0
  96. package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
  97. package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
  98. package/dist/platform/migrations/0320_duplicates.sql +41 -0
  99. package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
  100. package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
  101. package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
  102. package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
  103. package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
  104. package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
  105. package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
  106. package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
  107. package/dist/platform/migrations/0362_voice_usage.sql +17 -0
  108. package/dist/platform/migrations/0365_routines.sql +38 -0
  109. package/dist/platform/migrations/0370_approval_execution.sql +20 -0
  110. package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
  111. package/dist/platform/migrations/0380_rec_views.sql +94 -0
  112. package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
  113. package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
  114. package/dist/platform/migrations/0402_erase_requests.sql +34 -0
  115. package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
  116. package/dist/platform/migrations/0411_device_sessions.sql +33 -0
  117. package/dist/platform/migrations/0420_transition_history.sql +100 -0
  118. package/dist/platform/migrations/0421_orders.sql +134 -0
  119. package/dist/platform/migrations/0422_order_payments.sql +109 -0
  120. package/dist/platform/migrations/0440_capacity.sql +100 -0
  121. package/dist/platform/migrations/0441_capacity_views.sql +40 -0
  122. package/dist/platform/migrations/0450_order_grants.sql +21 -0
  123. package/dist/platform/migrations/0451_pack_roles.sql +18 -0
  124. package/dist/platform/migrations/0460_content.sql +59 -0
  125. package/dist/platform/migrations/0461_media.sql +52 -0
  126. package/dist/platform/migrations/0470_publish_versions.sql +36 -0
  127. package/dist/platform/migrations/0471_permission_grants.sql +18 -0
  128. package/dist/platform/migrations/0490_staff_invites.sql +40 -0
  129. package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
  130. package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
  131. package/dist/platform/migrations/0500_published_media_field.sql +25 -0
  132. package/dist/platform/migrations/0501_import_keys.sql +23 -0
  133. package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
  134. package/dist/platform/migrations/0516_order_tax.sql +63 -0
  135. package/dist/platform/migrations/0520_publish_requests.sql +20 -0
  136. package/dist/platform/migrations/0530_subscriptions.sql +173 -0
  137. package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
  138. package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
  139. package/dist/platform/migrations/0533_allowances.sql +262 -0
  140. package/dist/platform/migrations/0560_recurring.sql +75 -0
  141. package/dist/platform/migrations/0580_subscription_grants.sql +21 -0
  142. package/dist/platform/migrations/0581_once_per_person.sql +34 -0
  143. package/dist/platform/migrations/0600_tool_actions_ran_at_queue.sql +22 -0
  144. package/dist/platform/migrations/0610_waitlists.sql +54 -0
  145. package/dist/platform/migrations/0630_subscription_changes.sql +122 -0
  146. package/dist/platform/migrations/0650_person_links.sql +90 -0
  147. package/dist/platform/migrations/0670_unmoved_guard.sql +52 -0
  148. package/dist/platform/migrations/0690_sellable_refund_due.sql +98 -0
  149. package/dist/platform/sdk/allowance.ts +522 -0
  150. package/dist/platform/sdk/automation-check.ts +534 -0
  151. package/dist/platform/sdk/automation.ts +743 -0
  152. package/dist/platform/sdk/behaviour.ts +215 -0
  153. package/dist/platform/sdk/capacity.ts +303 -0
  154. package/dist/platform/sdk/contract.ts +909 -0
  155. package/dist/platform/sdk/document.ts +935 -0
  156. package/dist/platform/sdk/field-types.ts +111 -0
  157. package/dist/platform/sdk/formula/ast.ts +72 -0
  158. package/dist/platform/sdk/formula/compile.ts +454 -0
  159. package/dist/platform/sdk/formula/index.ts +4 -0
  160. package/dist/platform/sdk/formula/parser.ts +417 -0
  161. package/dist/platform/sdk/index.ts +36 -0
  162. package/dist/platform/sdk/manifest.ts +1785 -0
  163. package/dist/platform/sdk/media.ts +108 -0
  164. package/dist/platform/sdk/permissions.ts +60 -0
  165. package/dist/platform/sdk/recurring.ts +321 -0
  166. package/dist/platform/sdk/renamed.ts +63 -0
  167. package/dist/platform/sdk/rich-text-fixture.ts +68 -0
  168. package/dist/platform/sdk/rich-text.ts +221 -0
  169. package/dist/platform/sdk/runtime.ts +410 -0
  170. package/dist/platform/sdk/sellable.ts +1138 -0
  171. package/dist/platform/sdk/slug.ts +25 -0
  172. package/dist/platform/sdk/states.ts +598 -0
  173. package/dist/platform/sdk/testing.ts +847 -0
  174. package/dist/platform/sdk/unique.ts +81 -0
  175. package/dist/products-2H5DR232.js +11 -0
  176. package/dist/run-7P4RQALH.js +648 -0
  177. package/dist/run-PO3W5BFA.js +508 -0
  178. package/dist/run-ZCGFMEZF.js +309 -0
  179. package/dist/src-CRO35DYY.js +46 -0
  180. package/dist/src-I3IJ4NKC.js +354 -0
  181. package/dist/token-MOJUA2U6.js +70 -0
  182. package/dist/token-util-TENRN4V7.js +6 -0
  183. package/dist/visibility-TVXZ67FD.js +41 -0
  184. package/package.json +33 -4
@@ -0,0 +1,669 @@
1
+ #!/usr/bin/env node
2
+ import {
3
+ changeOrder,
4
+ createOrder,
5
+ loadOrderRow
6
+ } from "./chunk-6WGFA2IV.js";
7
+ import {
8
+ createRecord,
9
+ updateRecord
10
+ } from "./chunk-WHKJGF36.js";
11
+ import {
12
+ onEveryRecordMove,
13
+ onRecordMove
14
+ } from "./chunk-324WJXNP.js";
15
+ import {
16
+ creatorFor,
17
+ normaliseCustomerEmail,
18
+ sameEmailPeople
19
+ } from "./chunk-7OGCMQXG.js";
20
+ import {
21
+ erasedAddresses
22
+ } from "./chunk-XIDLW3EP.js";
23
+ import {
24
+ loadOrderCurrency,
25
+ toMinorUnits
26
+ } from "./chunk-6ELZRNUU.js";
27
+ import {
28
+ notifyStatements
29
+ } from "./chunk-ZZFWMVJO.js";
30
+ import {
31
+ UNREADABLE,
32
+ assertCreateRules,
33
+ boundMoment,
34
+ guardStatement,
35
+ newId,
36
+ pathReader,
37
+ recordHostChange
38
+ } from "./chunk-2XC5JLBO.js";
39
+ import {
40
+ ConfigError,
41
+ ConflictError,
42
+ NotFoundError,
43
+ UnknownOperationError,
44
+ ValidationError,
45
+ isLiveDependant,
46
+ linkGuardStatement,
47
+ orgReader,
48
+ staffPrincipal,
49
+ viewColumnOf,
50
+ visibleSource
51
+ } from "./chunk-6XTU2MTP.js";
52
+ import {
53
+ getObject,
54
+ listObjects
55
+ } from "./chunk-YFTLIEWU.js";
56
+
57
+ // ../core/src/orders/guests.ts
58
+ var hex = (bytes) => [...new Uint8Array(bytes)].map((b) => b.toString(16).padStart(2, "0")).join("");
59
+ function newOrderToken() {
60
+ return hex(crypto.getRandomValues(new Uint8Array(32)).buffer);
61
+ }
62
+ var ORDER_TOKEN = /^[0-9a-f]{64}$/;
63
+ async function hashOrderToken(token) {
64
+ return hex(await crypto.subtle.digest("SHA-256", new TextEncoder().encode(token)));
65
+ }
66
+ async function orderForToken(db, id, token, now) {
67
+ if (!ORDER_TOKEN.test(token)) return null;
68
+ const hash = await hashOrderToken(token);
69
+ const row = await db.selectFrom("core_order").selectAll().where((eb) => eb.or([eb("access_hash", "=", hash), eb("email_link_hash", "=", hash)])).executeTakeFirst();
70
+ if (!row || row.id !== id) return null;
71
+ if (row.access_until !== null && row.access_until <= now) return null;
72
+ return row;
73
+ }
74
+ async function resolveBuyer(ctx, address) {
75
+ const email = normaliseCustomerEmail(address);
76
+ const refused = () => new ValidationError("That email address cannot be used", { field: "email" });
77
+ if (!email) throw refused();
78
+ if ((await erasedAddresses(ctx.db, [email])).size > 0) throw refused();
79
+ const matches = await sameEmailPeople(ctx.db, email);
80
+ if (matches.length === 1) return { email, personId: matches[0], created: false };
81
+ if (matches.length > 1) {
82
+ const plan = await notifyStatements(
83
+ ctx.db,
84
+ {
85
+ to: [{ role: "admin" }],
86
+ type: "system.message",
87
+ title: "An order was placed with an address several people have",
88
+ body: `${matches.length} people have ${email}. The order belongs to none of them yet: merge them, then set the order's person.`,
89
+ link: { kind: "record", object: "person", id: matches[0] },
90
+ dedupeKey: `order.several_people:${email}`,
91
+ source: { actor: "system" }
92
+ },
93
+ ctx.now
94
+ );
95
+ ctx.write(...plan.statements);
96
+ return { email, personId: null, created: false };
97
+ }
98
+ const creator = await creatorFor(ctx.db, email);
99
+ if (!creator) throw new ConfigError("There is no admin to create the buyer's Person for");
100
+ const { personCreate } = await import("./person-UHLVBVLR.js");
101
+ const asCreator = Object.create(ctx, {
102
+ user: { value: creator },
103
+ actor: { value: "automation" },
104
+ principal: { value: staffPrincipal(creator) },
105
+ // The Person is the host's to create for the order: not the guest's write.
106
+ recordChange: { value: (change) => recordHostChange(ctx, change) }
107
+ });
108
+ const input = personCreate.input.parse({ emails: [{ email, primary: true }] });
109
+ const person = await personCreate.handler(input, asCreator);
110
+ return { email, personId: person.id, created: true };
111
+ }
112
+
113
+ // ../core/src/orders/moves.ts
114
+ function movesOf(object) {
115
+ return object?.sellable?.moves;
116
+ }
117
+ var notForSale = () => new ValidationError("This cannot be bought", { rule: "not_for_sale" });
118
+ async function buyerSees(ctx, principal, target, id) {
119
+ try {
120
+ const row = await ctx.db.selectFrom(visibleSource({ principal }, target)).select("id").where("id", "=", id).executeTakeFirst();
121
+ return Boolean(row);
122
+ } catch {
123
+ return false;
124
+ }
125
+ }
126
+ function hostView(ctx) {
127
+ if (ctx.principal.kind === "staff") return ctx;
128
+ const caller = ctx.principal;
129
+ return Object.create(ctx, {
130
+ principal: { value: orgReader(ctx.db).principal },
131
+ onBehalfOf: { value: caller },
132
+ actor: { value: "automation" },
133
+ user: {
134
+ value: {
135
+ id: caller.kind === "customer" ? caller.customerId : "public",
136
+ email: "",
137
+ name: caller.kind,
138
+ role: "viewer"
139
+ }
140
+ },
141
+ recordChange: { value: (change) => recordHostChange(ctx, change) }
142
+ });
143
+ }
144
+ var DEFAULT_HOLD_PERCENT = 50;
145
+ async function startHeld(ctx, input) {
146
+ const object = getObject(input.object);
147
+ const moves = movesOf(object);
148
+ const states = object?.states;
149
+ const customer = object?.customer;
150
+ if (!object || !moves || !states || !customer || !object.sellable) throw notForSale();
151
+ const sellable = object.sellable;
152
+ const caller = ctx.principal;
153
+ if (caller.kind === "staff" && !ctx.extension) {
154
+ throw new UnknownOperationError("order.startHeld");
155
+ }
156
+ if (caller.kind === "public" && !moves.guest) throw notForSale();
157
+ const spender = object.allowance && object.allowance.kind === "spender" ? object.allowance : void 0;
158
+ const reserved = new Set(
159
+ [
160
+ states.field,
161
+ customer.field,
162
+ customer.guardians?.madeBy,
163
+ spender?.holder,
164
+ spender?.waived,
165
+ sellable.price,
166
+ moves.order
167
+ ].filter((f) => typeof f === "string")
168
+ );
169
+ const writable = new Set(customer.write);
170
+ for (const name of Object.keys(input.values)) {
171
+ if (reserved.has(name) || !writable.has(name)) {
172
+ throw new ValidationError(`${object.name}.${name} cannot be set here`, { field: name });
173
+ }
174
+ }
175
+ if (caller.kind !== "staff") {
176
+ for (const [name, value] of Object.entries(input.values)) {
177
+ const field = object.fields.find((f) => f.name === name);
178
+ const to = field?.fieldType === "relation" ? field.options?.to : void 0;
179
+ if (!to || value === null || value === void 0) continue;
180
+ const target = getObject(to);
181
+ if (!target || typeof value !== "string" || !await buyerSees(ctx, caller, target, value)) {
182
+ throw new NotFoundError(to, String(value));
183
+ }
184
+ }
185
+ }
186
+ let payer;
187
+ let email;
188
+ let token = null;
189
+ let created = false;
190
+ if (caller.kind === "customer") {
191
+ if (input.email !== void 0) {
192
+ throw new ValidationError("You are signed in: the order uses your account's address", {
193
+ field: "email"
194
+ });
195
+ }
196
+ const account = await ctx.db.selectFrom("core_customer").select("email").where("id", "=", caller.customerId).executeTakeFirst();
197
+ if (!account) throw new NotFoundError("customer", caller.customerId);
198
+ payer = caller.personId;
199
+ email = account.email;
200
+ } else if (caller.kind === "public") {
201
+ if (input.forPersonId !== void 0) throw new NotFoundError("person", input.forPersonId);
202
+ const address = input.email ? normaliseCustomerEmail(input.email) : null;
203
+ if (!input.email) {
204
+ throw new ValidationError("An order needs the buyer's email address", { field: "email" });
205
+ }
206
+ if (!address || (await erasedAddresses(ctx.db, [address])).size > 0) {
207
+ throw new ValidationError("That email address cannot be used", { field: "email" });
208
+ }
209
+ payer = null;
210
+ email = address;
211
+ token = newOrderToken();
212
+ } else {
213
+ if (!input.email) {
214
+ throw new ValidationError("An order needs the buyer's email address", { field: "email" });
215
+ }
216
+ const buyer = await resolveBuyer(ctx, input.email);
217
+ payer = buyer.personId;
218
+ email = buyer.email;
219
+ created = buyer.created;
220
+ }
221
+ let holder = payer;
222
+ if (input.forPersonId !== void 0 && input.forPersonId !== payer) {
223
+ const ok = caller.kind === "customer" ? customer.guardians?.write === true && await isLiveDependant(ctx.db, caller.personId, input.forPersonId) : caller.kind === "staff" ? Boolean(
224
+ await ctx.db.selectFrom("core_person").select("id").where("id", "=", input.forPersonId).where("deleted_at", "is", null).executeTakeFirst()
225
+ ) : false;
226
+ if (!ok) throw new NotFoundError("person", input.forPersonId);
227
+ holder = input.forPersonId;
228
+ }
229
+ if (!holder && caller.kind !== "public") {
230
+ throw new ValidationError("That address belongs to more than one person: name the person", {
231
+ rule: "buyer_unclear",
232
+ field: "email"
233
+ });
234
+ }
235
+ const currency = await loadOrderCurrency(ctx.db);
236
+ if (!currency) throw new ConfigError("No currency is set for orders yet, so nothing can be sold");
237
+ const orderId = newId("order");
238
+ const host = hostView(ctx);
239
+ const madeBy = customer.guardians?.madeBy;
240
+ const after = {
241
+ ...input.values,
242
+ ...holder ? { [customer.field]: holder } : {},
243
+ [states.field]: moves.held,
244
+ ...spender?.waived ? { [spender.waived]: true } : {},
245
+ ...madeBy && payer && caller.kind === "customer" ? { [madeBy]: payer } : {},
246
+ ...moves.order ? { [moves.order]: orderId } : {}
247
+ };
248
+ await assertCreateRules(host, object, after, caller.kind === "staff" ? "staff" : "customer");
249
+ const reader = pathReader(host, object, after);
250
+ let price = null;
251
+ if (moves.price?.field !== void 0) price = await reader.read(moves.price.field);
252
+ if (price === UNREADABLE) throw notForSale();
253
+ if ((price === null || price === "") && moves.price?.setting !== void 0) {
254
+ price = await reader.setting(moves.price.setting);
255
+ }
256
+ const unitPrice = toMinorUnits(typeof price === "string" ? Number(price) : price, currency);
257
+ if (unitPrice === null || unitPrice <= 0) {
258
+ throw new ValidationError("This has no price yet", { rule: "no_price" });
259
+ }
260
+ const titled = moves.title ? await reader.read(moves.title) : null;
261
+ const title = typeof titled === "string" && titled.trim() ? titled.trim() : object.label;
262
+ after[sellable.price] = typeof price === "string" ? Number(price) : price;
263
+ const recordId = await createRecord(host, object, after, {
264
+ by: "host",
265
+ seamSet: new Set(madeBy ? [madeBy] : []),
266
+ // A Person staff's address made in this same batch cannot be read yet; every reference was
267
+ // judged above.
268
+ ...created ? { checkReferences: false } : {}
269
+ });
270
+ if (caller.kind === "public" && moves.holdCap && object.claims) {
271
+ const on = after[object.claims.on];
272
+ const target = object.fields.find((f) => f.name === object.claims?.on)?.options?.to;
273
+ if (typeof on === "string" && target) {
274
+ const capacity = await ctx.db.selectFrom("core_capacity").select("places").where("object_type", "=", target).where("record_id", "=", on).executeTakeFirst();
275
+ const raw = await reader.setting(moves.holdCap.setting);
276
+ const percent = typeof raw === "number" && Number.isFinite(raw) && raw >= 0 ? raw : DEFAULT_HOLD_PERCENT;
277
+ const places = Number(capacity?.places ?? 0);
278
+ const cap = Math.max(1, Math.ceil(places * percent / 100));
279
+ const ownerField = customer.field;
280
+ const stateField = states.field;
281
+ const columnOf = (name) => {
282
+ const f = object.fields.find((x) => x.name === name);
283
+ return f ? viewColumnOf(f) : null;
284
+ };
285
+ const onColumn = columnOf(object.claims.on);
286
+ const ownerColumn = columnOf(ownerField);
287
+ const stateColumn = columnOf(stateField);
288
+ let members = 0;
289
+ if (onColumn && ownerColumn && stateColumn) {
290
+ const counted = await ctx.db.selectFrom(visibleSource(orgReader(ctx.db), object)).select(
291
+ (eb) => eb.fn.countAll().as("n")
292
+ ).where(onColumn, "=", on).where(stateColumn, "=", moves.held).where(ownerColumn, "is not", null).executeTakeFirst();
293
+ members = Number(counted?.n ?? 0);
294
+ }
295
+ ctx.write(guardStatement("held_cap", target, on, cap + members));
296
+ }
297
+ }
298
+ if (caller.kind === "customer" && holder && holder !== caller.personId) {
299
+ ctx.write(linkGuardStatement(caller.personId, holder));
300
+ }
301
+ const line = {
302
+ id: newId("orderLine"),
303
+ position: 0,
304
+ object: object.name,
305
+ recordId,
306
+ title,
307
+ quantity: 1,
308
+ unitPrice,
309
+ total: unitPrice,
310
+ deposit: null
311
+ };
312
+ const started = await createOrder(ctx, {
313
+ id: orderId,
314
+ priced: [line],
315
+ lines: [{ object: object.name, id: recordId, quantity: 1 }],
316
+ personId: payer,
317
+ email,
318
+ placedAs: caller.kind,
319
+ pay: "full",
320
+ accessHash: token ? await hashOrderToken(token) : null
321
+ });
322
+ return { row: started.row, lines: started.lines, recordId, token };
323
+ }
324
+ var movingNow = /* @__PURE__ */ new WeakMap();
325
+ async function whileMoving(ctx, id, run) {
326
+ const key = ctx.write;
327
+ let set = movingNow.get(key);
328
+ if (!set) {
329
+ set = /* @__PURE__ */ new Set();
330
+ movingNow.set(key, set);
331
+ }
332
+ set.add(id);
333
+ try {
334
+ return await run();
335
+ } finally {
336
+ set.delete(id);
337
+ }
338
+ }
339
+ var isMoving = (ctx, id) => movingNow.get(ctx.write)?.has(id) === true;
340
+ async function storedValues(ctx, object, id) {
341
+ const row = await ctx.db.selectFrom(visibleSource(orgReader(ctx.db), object)).selectAll().where("id", "=", id).executeTakeFirst();
342
+ if (!row) return null;
343
+ const values = {};
344
+ for (const field of object.fields) {
345
+ const column = viewColumnOf(field);
346
+ if (column && Object.hasOwn(row, column)) values[field.name] = row[column];
347
+ }
348
+ return values;
349
+ }
350
+ function oweRefund(ctx, orderId, object, recordId, entered, reason, payment) {
351
+ ctx.write(
352
+ ctx.db.insertInto("core_sellable_refund_due").values({
353
+ id: newId("refundDue"),
354
+ order_id: orderId,
355
+ object_type: object.name,
356
+ record_id: recordId,
357
+ ...payment ? { payment_ref: payment.paymentRef, amount: payment.amount } : {},
358
+ entered,
359
+ reason,
360
+ state: "due",
361
+ created_at: ctx.now,
362
+ updated_at: ctx.now
363
+ }).onConflict((oc) => oc.doNothing())
364
+ );
365
+ }
366
+ async function tellAdmins(ctx, orderId, title, body) {
367
+ const plan = await notifyStatements(
368
+ ctx.db,
369
+ {
370
+ to: [{ role: "admin" }],
371
+ type: "system.message",
372
+ title,
373
+ body,
374
+ link: { kind: "record", object: "order", id: orderId },
375
+ dedupeKey: `order.moves:${orderId}:${title}:${ctx.now}`,
376
+ source: { actor: "system" }
377
+ },
378
+ ctx.now
379
+ );
380
+ ctx.write(...plan.statements);
381
+ }
382
+ async function oweLateRefund(ctx, orderId, payment) {
383
+ if (!payment.paymentRef) return false;
384
+ const lines = await ctx.db.selectFrom("core_order_line").select(["object_type", "record_id"]).where("order_id", "=", orderId).execute();
385
+ const moved = lines.find((line) => movesOf(getObject(line.object_type)));
386
+ if (!moved) return false;
387
+ oweRefund(
388
+ ctx,
389
+ orderId,
390
+ { name: moved.object_type },
391
+ moved.record_id,
392
+ payment.orderState === "paid" ? "duplicate_payment" : "late",
393
+ payment.orderState === "paid" ? "Paid twice" : payment.orderState === "refunded" ? "Paid again after it was refunded" : "Paid after its place went back",
394
+ { paymentRef: payment.paymentRef, amount: payment.amount }
395
+ );
396
+ return true;
397
+ }
398
+ async function matchGuest(ctx, email) {
399
+ if ((await erasedAddresses(ctx.db, [email])).size > 0) return null;
400
+ const trashed = await ctx.db.selectFrom("core_person_emails as e").innerJoin("core_person as p", "p.id", "e.person_id").select("p.id").where("e.email", "=", email).where("p.deleted_at", "is not", null).executeTakeFirst();
401
+ if (trashed && (await sameEmailPeople(ctx.db, email)).length === 0) return null;
402
+ try {
403
+ return await resolveBuyer(ctx, email);
404
+ } catch (error) {
405
+ if (error instanceof ConfigError) return null;
406
+ throw error;
407
+ }
408
+ }
409
+ async function release(ctx, object, moves, orderId, recordId, why) {
410
+ const field = object.states?.field;
411
+ if (!field) return;
412
+ await whileMoving(
413
+ ctx,
414
+ recordId,
415
+ () => updateRecord(ctx, object, recordId, { [field]: moves.expired }, { by: "host" })
416
+ );
417
+ oweRefund(ctx, orderId, object, recordId, why, "Paid, and could not be given to anyone");
418
+ }
419
+ var UNSETTLED_SCAN = 1e3;
420
+ var UNSETTLED_RELEASES = 20;
421
+ async function unsettledGuests(db, limit = UNSETTLED_SCAN) {
422
+ const out = [];
423
+ for (const object of listObjects()) {
424
+ const moves = movesOf(object);
425
+ const states = object.states;
426
+ const ownerField = object.customer?.field;
427
+ if (!moves?.guest || !states || !ownerField) continue;
428
+ const column = (name) => {
429
+ const field = object.fields.find((f) => f.name === name);
430
+ return field ? viewColumnOf(field) : null;
431
+ };
432
+ const stateColumn = column(states.field);
433
+ const ownerColumn = column(ownerField);
434
+ if (!stateColumn || !ownerColumn) continue;
435
+ const rows = await db.selectFrom(visibleSource(orgReader(db), object, "r")).innerJoin(
436
+ "core_order_line as l",
437
+ (join) => join.onRef("l.record_id", "=", "r.id").on("l.object_type", "=", object.name)
438
+ ).innerJoin("core_order as o", "o.id", "l.order_id").select(["r.id as record_id", "o.id as order_id"]).where(`r.${stateColumn}`, "=", moves.held).where(`r.${ownerColumn}`, "is", null).where("o.state", "=", "paid").orderBy("o.paid_at").limit(limit - out.length).execute();
439
+ for (const row of rows) {
440
+ out.push({ object: object.name, recordId: row.record_id, orderId: row.order_id });
441
+ }
442
+ if (out.length >= limit) break;
443
+ }
444
+ return out;
445
+ }
446
+ async function releaseUnsettledGuest(ctx, objectName, recordId) {
447
+ const object = getObject(objectName);
448
+ const moves = movesOf(object);
449
+ const states = object?.states;
450
+ const ownerField = object?.customer?.field;
451
+ const until = states?.create?.window?.until;
452
+ if (!object || !moves?.guest || !states || !ownerField || until === void 0) return false;
453
+ const values = await storedValues(ctx, object, recordId);
454
+ if (!values || values[states.field] !== moves.held || values[ownerField]) return false;
455
+ const order = await orderOfRecord(ctx, object, recordId);
456
+ if (!order || order.state !== "paid" || order.person_id) return false;
457
+ const closes = await boundMoment(ctx, pathReader(ctx, object, values), until);
458
+ if (closes !== null && Date.parse(ctx.now) < closes) return false;
459
+ await release(ctx, object, moves, order.id, recordId, "unsettled");
460
+ await tellAdmins(
461
+ ctx,
462
+ order.id,
463
+ "A paid drop-in was released: nobody said whose it was",
464
+ `Order ${order.id} was paid with an address several People share, and its Person was not set before booking closed. Its place went back and its refund is waiting in Approvals.`
465
+ );
466
+ return true;
467
+ }
468
+ async function settle(ctx, object, moves, orderId, recordId, values, personId, made = false) {
469
+ const states = object.states;
470
+ const ownerField = object.customer?.field;
471
+ if (!states || !ownerField) return;
472
+ const owner = personId ?? values[ownerField] ?? null;
473
+ if (owner && !values[ownerField]) {
474
+ const clash = await liveTwin(ctx, object, recordId, { ...values, [ownerField]: owner });
475
+ if (clash) {
476
+ await whileMoving(
477
+ ctx,
478
+ recordId,
479
+ () => updateRecord(ctx, object, recordId, { [states.field]: moves.expired }, { by: "host" })
480
+ );
481
+ oweRefund(ctx, orderId, object, recordId, "duplicate", "They already had a place on it");
482
+ await tellAdmins(
483
+ ctx,
484
+ orderId,
485
+ "A paid drop-in was a second booking",
486
+ `Order ${orderId} paid for a place its buyer already had: it was not kept, and its refund is waiting in Approvals.`
487
+ );
488
+ return;
489
+ }
490
+ }
491
+ await whileMoving(
492
+ ctx,
493
+ recordId,
494
+ () => updateRecord(
495
+ ctx,
496
+ object,
497
+ recordId,
498
+ {
499
+ ...owner && !values[ownerField] ? { [ownerField]: owner } : {},
500
+ [states.field]: moves.paid
501
+ },
502
+ { by: "host", ...made ? { checkReferences: false } : {} }
503
+ )
504
+ );
505
+ }
506
+ async function liveTwin(ctx, object, id, values) {
507
+ const ownerField = object.customer?.field;
508
+ for (const rule of object.unique ?? []) {
509
+ if (!ownerField || !rule.fields.includes(ownerField)) continue;
510
+ const stateField = object.states?.field;
511
+ const columnOf = (name) => {
512
+ const field = object.fields.find((f) => f.name === name);
513
+ return field ? viewColumnOf(field) : null;
514
+ };
515
+ let q = ctx.db.selectFrom(visibleSource(orgReader(ctx.db), object)).select("id").where("id", "!=", id);
516
+ for (const name of rule.fields) {
517
+ const column = columnOf(name);
518
+ if (!column) return false;
519
+ q = q.where(column, "=", values[name] ?? null);
520
+ }
521
+ const stateColumn = stateField ? columnOf(stateField) : null;
522
+ if (stateColumn && rule.states?.length) q = q.where(stateColumn, "in", [...rule.states]);
523
+ if (await q.executeTakeFirst()) return true;
524
+ }
525
+ return false;
526
+ }
527
+ var orderMoves = async (outer, move) => {
528
+ const ctx = hostView(outer);
529
+ const from = move.from?.id ?? null;
530
+ const to = move.to.id;
531
+ const paid = to === "paid" || to === "part_paid";
532
+ if (!paid && to !== "expired" && to !== "cancelled") return;
533
+ const lines = await ctx.db.selectFrom("core_order_line").select(["object_type", "record_id", "title"]).where("order_id", "=", move.id).execute();
534
+ for (const line of lines) {
535
+ const object = getObject(line.object_type);
536
+ const moves = movesOf(object);
537
+ if (!object?.states || !moves) continue;
538
+ const field = object.states.field;
539
+ if (isMoving(ctx, line.record_id)) continue;
540
+ const values = await storedValues(ctx, object, line.record_id);
541
+ const state = values?.[field] ?? null;
542
+ if (paid) {
543
+ if (from === "expired") {
544
+ throw new ConflictError(
545
+ `What this order held (${line.title}) went back when it expired: refund the payment instead`,
546
+ { order: move.id, rule: "held_gone" }
547
+ );
548
+ }
549
+ if (state === moves.held && values) {
550
+ const ownerField = object.customer?.field;
551
+ let personId = null;
552
+ let made = false;
553
+ if (ownerField && !values[ownerField]) {
554
+ const order = move.after;
555
+ personId = order.personId ?? null;
556
+ if (!personId) {
557
+ const buyer = order.email ? await matchGuest(ctx, order.email) : null;
558
+ if (!buyer) {
559
+ await release(ctx, object, moves, move.id, line.record_id, "unmatched");
560
+ await tellAdmins(
561
+ ctx,
562
+ move.id,
563
+ "A paid drop-in could not be given to anyone",
564
+ `Order ${move.id} was paid, and its address cannot be matched to a Person on file (erased, in the Trash, or no admin to create one for). Its place went back and its refund is waiting in Approvals.`
565
+ );
566
+ continue;
567
+ }
568
+ personId = buyer.personId;
569
+ made = buyer.created;
570
+ if (personId) {
571
+ ctx.write(
572
+ ctx.db.updateTable("core_order").set({ person_id: personId }).where("id", "=", move.id).where("person_id", "is", null)
573
+ );
574
+ }
575
+ }
576
+ if (!personId) continue;
577
+ }
578
+ await settle(ctx, object, moves, move.id, line.record_id, values, personId, made);
579
+ continue;
580
+ }
581
+ oweRefund(
582
+ ctx,
583
+ move.id,
584
+ object,
585
+ line.record_id,
586
+ String(state ?? "gone"),
587
+ "Paid after it was released"
588
+ );
589
+ await tellAdmins(
590
+ ctx,
591
+ move.id,
592
+ "A payment arrived for something no longer held",
593
+ `Order ${move.id} was paid for "${line.title}", which was no longer held for it. Its refund is waiting in Approvals.`
594
+ );
595
+ continue;
596
+ }
597
+ if (from === "pending" && state === moves.held) {
598
+ await whileMoving(
599
+ ctx,
600
+ line.record_id,
601
+ () => updateRecord(ctx, object, line.record_id, { [field]: moves.expired }, { by: "host" })
602
+ );
603
+ }
604
+ }
605
+ };
606
+ async function movesFollowPerson(ctx, orderId, personId) {
607
+ const order = await loadOrderRow(ctx.db, orderId);
608
+ if (order.state !== "paid") return;
609
+ const lines = await ctx.db.selectFrom("core_order_line").select(["object_type", "record_id"]).where("order_id", "=", orderId).execute();
610
+ for (const line of lines) {
611
+ const object = getObject(line.object_type);
612
+ const moves = movesOf(object);
613
+ const ownerField = object?.customer?.field;
614
+ if (!object?.states || !moves || !ownerField) continue;
615
+ const values = await storedValues(ctx, object, line.record_id);
616
+ if (!values || values[object.states.field] !== moves.held || values[ownerField]) continue;
617
+ await settle(ctx, object, moves, orderId, line.record_id, values, personId);
618
+ }
619
+ }
620
+ async function orderOfRecord(ctx, object, id) {
621
+ const line = await ctx.db.selectFrom("core_order_line").select("order_id").where("object_type", "=", object.name).where("record_id", "=", id).executeTakeFirst();
622
+ return line ? loadOrderRow(ctx.db, line.order_id) : null;
623
+ }
624
+ var recordMoves = async (ctx, move) => {
625
+ const moves = movesOf(move.object);
626
+ if (!moves || !move.from) return;
627
+ if (isMoving(ctx, move.id)) return;
628
+ const from = move.from.id;
629
+ const to = move.to.id;
630
+ const leavesHeld = from === moves.held && to !== moves.paid;
631
+ const refunds = from !== moves.held && moves.refund.includes(to);
632
+ if (!leavesHeld && !refunds) return;
633
+ const order = await orderOfRecord(ctx, move.object, move.id);
634
+ if (!order) return;
635
+ const label = move.object.fields.find((f) => f.name === move.object.states?.field)?.options?.choices?.find((c) => c.value === to)?.label ?? to;
636
+ if (leavesHeld) {
637
+ if (order.state === "pending") {
638
+ await whileMoving(
639
+ ctx,
640
+ move.id,
641
+ () => changeOrder(ctx, order, "cancelled", { cancelled_at: ctx.now }, "host")
642
+ );
643
+ } else if (order.state === "paid") {
644
+ oweRefund(ctx, order.id, move.object, move.id, to, `${move.object.label}: ${label}`);
645
+ }
646
+ return;
647
+ }
648
+ if (order.state !== "paid") return;
649
+ oweRefund(ctx, order.id, move.object, move.id, to, `${move.object.label}: ${label}`);
650
+ };
651
+ onRecordMove("order", orderMoves);
652
+ onEveryRecordMove(recordMoves);
653
+
654
+ export {
655
+ newOrderToken,
656
+ ORDER_TOKEN,
657
+ hashOrderToken,
658
+ orderForToken,
659
+ resolveBuyer,
660
+ movesOf,
661
+ DEFAULT_HOLD_PERCENT,
662
+ startHeld,
663
+ oweLateRefund,
664
+ UNSETTLED_SCAN,
665
+ UNSETTLED_RELEASES,
666
+ unsettledGuests,
667
+ releaseUnsettledGuest,
668
+ movesFollowPerson
669
+ };