@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,759 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- applyTransition,
4
- callerOf,
5
- onRecordMove
6
- } from "./chunk-R4W5XAUD.js";
7
- import {
8
- recordHostChange
9
- } from "./chunk-6GDEDOV7.js";
10
- import {
11
- paymentsTarget
12
- } from "./chunk-LJFLENFC.js";
13
- import {
14
- currencyDecimals,
15
- loadOrderCurrency,
16
- loadOrderExpiryMinutes,
17
- loadReturnOrigins,
18
- toMinorUnits
19
- } from "./chunk-O2UIZHND.js";
20
- import {
21
- confirmStatements,
22
- newId,
23
- queueClaim,
24
- releaseStatements
25
- } from "./chunk-TQFGGSA4.js";
26
- import {
27
- ConfigError,
28
- ConflictError,
29
- NotFoundError,
30
- ValidationError,
31
- buyableSource,
32
- orgReader,
33
- refreshSchemaRegistry,
34
- scopeOf,
35
- sql,
36
- viewColumnOf,
37
- visibleSource
38
- } from "./chunk-A4NTSYWV.js";
39
- import {
40
- getObject,
41
- listObjects
42
- } from "./chunk-IFG4FRW5.js";
43
- import {
44
- orderObject
45
- } from "./chunk-Q4N55M2Z.js";
46
-
47
- // ../core/src/orders/holds.ts
48
- var ORDER_CLAIM_TYPE = "order";
49
- async function linesWithCapacity(ctx, orderId) {
50
- const lines = await ctx.db.selectFrom("core_order_line").select(["object_type", "record_id", "quantity"]).where("order_id", "=", orderId).orderBy("position").execute();
51
- return lines.filter((line) => getObject(line.object_type)?.capacity);
52
- }
53
- async function claimOrderPlaces(ctx, orderId, lines) {
54
- for (const line of lines) {
55
- if (!getObject(line.object)?.capacity) continue;
56
- await queueClaim(ctx, {
57
- object: line.object,
58
- record: line.recordId,
59
- quantity: line.quantity,
60
- for: { type: ORDER_CLAIM_TYPE, id: orderId }
61
- });
62
- }
63
- }
64
- var orderHolds = async (ctx, move) => {
65
- const from = move.from?.id ?? null;
66
- const to = move.to.id;
67
- const target = { for: { type: ORDER_CLAIM_TYPE, id: move.id } };
68
- if ((to === "paid" || to === "part_paid") && from === "expired") {
69
- const lines = await linesWithCapacity(ctx, move.id);
70
- await claimOrderPlaces(
71
- ctx,
72
- move.id,
73
- lines.map((l) => ({ object: l.object_type, recordId: l.record_id, quantity: l.quantity }))
74
- );
75
- ctx.write(...confirmStatements(target, ctx.now));
76
- return;
77
- }
78
- if ((to === "paid" || to === "part_paid") && from === "pending") {
79
- ctx.write(...confirmStatements(target, ctx.now));
80
- return;
81
- }
82
- if (to === "cancelled" || to === "expired") {
83
- ctx.write(...releaseStatements(target, ctx.now, { confirmed: from === "part_paid" }));
84
- return;
85
- }
86
- if (to === "refunded") {
87
- const lines = await linesWithCapacity(ctx, move.id);
88
- const keeps = (line) => getObject(line.object_type)?.capacity?.releaseOnRefund === false;
89
- if (!lines.some(keeps)) {
90
- ctx.write(...releaseStatements(target, ctx.now, { confirmed: true }));
91
- return;
92
- }
93
- const releasing = new Set(
94
- lines.filter((l) => !keeps(l)).map((l) => `${l.object_type}\0${l.record_id}`)
95
- );
96
- if (!releasing.size) return;
97
- const claims = await ctx.db.selectFrom("core_capacity_claim").select(["id", "object_type", "record_id"]).where("for_type", "=", ORDER_CLAIM_TYPE).where("for_id", "=", move.id).where("state", "=", "confirmed").execute();
98
- for (const claim of claims) {
99
- if (!releasing.has(`${claim.object_type}\0${claim.record_id}`)) continue;
100
- ctx.write(...releaseStatements({ claim: claim.id }, ctx.now, { confirmed: true }));
101
- }
102
- }
103
- };
104
- onRecordMove("order", orderHolds);
105
-
106
- // ../core/src/orders/once.ts
107
- async function holdOncePerPerson(ctx, orderId, lines, buyer) {
108
- if (!lines.length) return;
109
- const refuse = (reason, message, line) => {
110
- throw new ValidationError(message, { rule: "once_per_person", reason, line });
111
- };
112
- const objects = /* @__PURE__ */ new Set();
113
- for (const line of lines) {
114
- if (buyer.placedAs === "public") {
115
- refuse("sign_in", "Sign in to buy this: it is one per person", line.position);
116
- }
117
- if (!buyer.personId) {
118
- refuse(
119
- "no_person",
120
- "This is one per person, and the order is not for one person yet: its address belongs to several people here. Merge them, or start it for one of them",
121
- line.position
122
- );
123
- }
124
- if (line.quantity !== 1 || objects.has(line.object)) {
125
- refuse("one", "This is one per person: one on one order", line.position);
126
- }
127
- objects.add(line.object);
128
- }
129
- const personId = buyer.personId;
130
- const had = await ctx.db.selectFrom("core_sellable_once").select(["object_type", "state"]).where("person_id", "=", personId).where("object_type", "in", [...objects]).where("state", "in", ["held", "used"]).execute();
131
- for (const line of lines) {
132
- const row = had.find((h) => h.object_type === line.object);
133
- if (!row) continue;
134
- refuse(
135
- row.state === "used" ? "used" : "held",
136
- row.state === "used" ? "This is one per person, and it has been bought for this person already" : "This is one per person, and an order for it is waiting to be paid",
137
- line.position
138
- );
139
- }
140
- for (const line of lines) {
141
- ctx.write(
142
- ctx.db.insertInto("core_sellable_once").values({
143
- id: newId("sellableOnce"),
144
- person_id: personId,
145
- object_type: line.object,
146
- record_id: line.recordId,
147
- order_id: orderId,
148
- state: "held",
149
- created_at: ctx.now,
150
- updated_at: ctx.now
151
- })
152
- );
153
- }
154
- }
155
- var orderOnce = async (ctx, move) => {
156
- const from = move.from?.id ?? null;
157
- const to = move.to.id;
158
- if ((to === "paid" || to === "part_paid") && from === "pending") {
159
- ctx.write(
160
- ctx.db.updateTable("core_sellable_once").set({ state: "used", updated_at: ctx.now }).where("order_id", "=", move.id).where("state", "=", "held")
161
- );
162
- return;
163
- }
164
- if ((to === "paid" || to === "part_paid") && from === "expired") {
165
- const released = await ctx.db.selectFrom("core_sellable_once").select(["person_id", "object_type", "record_id"]).where("order_id", "=", move.id).where("state", "=", "released").execute();
166
- for (const row of released) {
167
- if (!getObject(row.object_type)?.sellable?.onePerPerson) continue;
168
- const since = await ctx.db.selectFrom("core_sellable_once").select("id").where("person_id", "=", row.person_id).where("object_type", "=", row.object_type).where("state", "in", ["held", "used"]).executeTakeFirst();
169
- if (since) {
170
- throw new ConflictError(
171
- "This late payment cannot be honoured: it is for something one per person, and the person has had theirs since the order expired. Refund the payment instead",
172
- { rule: "once_per_person", reason: "had_since", order: move.id }
173
- );
174
- }
175
- ctx.write(
176
- ctx.db.insertInto("core_sellable_once").values({
177
- id: newId("sellableOnce"),
178
- person_id: row.person_id,
179
- object_type: row.object_type,
180
- record_id: row.record_id,
181
- order_id: move.id,
182
- state: "used",
183
- created_at: ctx.now,
184
- updated_at: ctx.now
185
- })
186
- );
187
- }
188
- return;
189
- }
190
- if ((to === "expired" || to === "cancelled") && from === "pending") {
191
- ctx.write(
192
- ctx.db.updateTable("core_sellable_once").set({ state: "released", updated_at: ctx.now }).where("order_id", "=", move.id).where("state", "=", "held")
193
- );
194
- }
195
- };
196
- onRecordMove("order", orderOnce);
197
-
198
- // ../core/src/orders/sellable.ts
199
- var GRANTS_PER_ORDER_CEILING = 100;
200
- var GRANTS_PER_LINE_DEFAULT = 10;
201
- function lineLimit(sellable, recordMax) {
202
- const own = recordMax === null ? null : Math.max(Math.floor(recordMax), 0);
203
- if (!sellable.grants) return own;
204
- return Math.min(own ?? GRANTS_PER_LINE_DEFAULT, GRANTS_PER_ORDER_CEILING);
205
- }
206
- function sellableOf(object) {
207
- return object.sellable;
208
- }
209
- function sellableProblems(sellable, object) {
210
- const problems = [];
211
- const field = (name) => object.fields.find((f) => f.name === name);
212
- const numeric = (name, what) => {
213
- const f = field(name);
214
- if (!f?.column) problems.push(`${what} "${name}" is not a single-valued field`);
215
- else if (f.type !== "number") problems.push(`${what} "${name}" is not a number`);
216
- };
217
- const date = (name, what) => {
218
- const f = field(name);
219
- if (!f?.column || f.type !== "date" && f.type !== "datetime") {
220
- problems.push(`${what} "${name}" is not a date field`);
221
- }
222
- };
223
- numeric(sellable.price, "price");
224
- if (sellable.maxPerOrder) numeric(sellable.maxPerOrder, "maxPerOrder");
225
- if (sellable.saleWindow?.from) date(sellable.saleWindow.from, "saleWindow.from");
226
- if (sellable.saleWindow?.until) date(sellable.saleWindow.until, "saleWindow.until");
227
- if (sellable.deposit) {
228
- numeric(sellable.deposit.amount, "deposit.amount");
229
- date(sellable.deposit.balanceDue, "deposit.balanceDue");
230
- }
231
- if (sellable.recurring?.trialDays) numeric(sellable.recurring.trialDays, "recurring.trialDays");
232
- if (!object.titleField) problems.push("a sellable object needs a title field");
233
- return problems;
234
- }
235
-
236
- // ../core/src/orders/orders.ts
237
- var ORDER_MAX_LINES = 50;
238
- var ORDER_MAX_QUANTITY = 1e3;
239
- var ORDER_ACCESS_DAYS_AFTER_CLOSE = 30;
240
- var CLOSED = /* @__PURE__ */ new Set(["paid", "cancelled", "expired", "refunded"]);
241
- var order = () => getObject("order") ?? orderObject;
242
- function orderSnapshot(row) {
243
- return {
244
- personId: row.person_id,
245
- email: row.email,
246
- state: row.state,
247
- currency: row.currency,
248
- total: row.total,
249
- paid: row.paid,
250
- balance: row.total - row.paid,
251
- refunded: row.refunded,
252
- pay: row.pay,
253
- deposit: row.deposit,
254
- balanceDueAt: row.balance_due_at,
255
- expiresAt: row.expires_at,
256
- placedAs: row.placed_as,
257
- paidAt: row.paid_at,
258
- cancelledAt: row.cancelled_at,
259
- refundedAt: row.refunded_at,
260
- taxAmount: row.tax_amount,
261
- taxRefunded: row.tax_refunded,
262
- taxCountry: row.tax_country
263
- };
264
- }
265
- async function loadOrderRow(db, id) {
266
- const row = await db.selectFrom("core_order").selectAll().where("id", "=", id).executeTakeFirst();
267
- if (!row) throw new NotFoundError("order", id);
268
- return row;
269
- }
270
- function refuseLine(rule, line, message, extra) {
271
- throw new ValidationError(message, { rule, line, ...extra });
272
- }
273
- var column = (field) => field ? viewColumnOf(field) : null;
274
- function dueMoment(value) {
275
- if (typeof value !== "string" || value.trim() === "") return null;
276
- const text = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T23:59:59.999Z` : value;
277
- const at = new Date(text);
278
- return Number.isNaN(at.getTime()) ? null : at.toISOString();
279
- }
280
- function windowMoment(value, end) {
281
- if (typeof value !== "string" || value.trim() === "") return null;
282
- const text = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}${end === "start" ? "T00:00:00.000Z" : "T23:59:59.999Z"}` : value;
283
- const at = new Date(text);
284
- return Number.isNaN(at.getTime()) ? null : at.toISOString();
285
- }
286
- async function readable(db, principal, object, id) {
287
- let source;
288
- try {
289
- source = buyableSource({ principal }, object);
290
- } catch {
291
- return false;
292
- }
293
- const row = await db.selectFrom(source).select("id").where("id", "=", id).executeTakeFirst();
294
- return Boolean(row);
295
- }
296
- async function priceLines(db, lines, currency, now = (/* @__PURE__ */ new Date()).toISOString(), buyer, options = {}) {
297
- const reader = orgReader(db);
298
- const seen = /* @__PURE__ */ new Set();
299
- const priced2 = [];
300
- let granting = 0;
301
- for (const [index, line] of lines.entries()) {
302
- const key = `${line.object}\0${line.id}`;
303
- if (seen.has(key)) {
304
- refuseLine("duplicate_line", index, "The same item is on the order twice: use a quantity");
305
- }
306
- seen.add(key);
307
- const object = getObject(line.object);
308
- const sellable = object ? sellableOf(object) : void 0;
309
- if (!object || !sellable || sellableProblems(sellable, object).length) {
310
- refuseLine("not_for_sale", index, "This cannot be bought");
311
- }
312
- if (Boolean(sellable.recurring) !== Boolean(options.plans)) {
313
- refuseLine(
314
- "not_for_sale",
315
- index,
316
- sellable.recurring ? "This is a plan: subscribe to it instead" : "This is not a plan"
317
- );
318
- }
319
- const row = await db.selectFrom(visibleSource(reader, object)).selectAll().where("id", "=", line.id).executeTakeFirst();
320
- if (!row) refuseLine("not_for_sale", index, "This cannot be bought");
321
- if (buyer && buyer.kind !== "staff" && !await readable(db, buyer, object, line.id)) {
322
- refuseLine("not_for_sale", index, "This cannot be bought");
323
- }
324
- const field = (name) => object.fields.find((f) => f.name === name);
325
- const read = (name) => {
326
- const col = column(field(name));
327
- return col ? row[col] ?? null : null;
328
- };
329
- const pricedIn = sellable.currency ?? field(sellable.price)?.options?.currency;
330
- if (pricedIn && pricedIn.toUpperCase() !== currency) {
331
- refuseLine(
332
- "currency",
333
- index,
334
- `This is priced in ${pricedIn}, and orders are in ${currency}`,
335
- {
336
- currency: pricedIn
337
- }
338
- );
339
- }
340
- const unitPrice = toMinorUnits(read(sellable.price), currency);
341
- if (unitPrice === null) refuseLine("no_price", index, "This has no price yet");
342
- if (sellable.saleWindow) {
343
- const from = windowMoment(read(sellable.saleWindow.from ?? ""), "start");
344
- const until = windowMoment(read(sellable.saleWindow.until ?? ""), "end");
345
- if (from && now < from || until && now > until) {
346
- refuseLine(
347
- "sale_window",
348
- index,
349
- from && now < from ? "This is not on sale yet" : "This is no longer on sale",
350
- { from, until }
351
- );
352
- }
353
- }
354
- const own = sellable.maxPerOrder ? read(sellable.maxPerOrder) : null;
355
- const max = lineLimit(sellable, typeof own === "number" && Number.isFinite(own) ? own : null);
356
- if (max !== null && line.quantity > max) {
357
- refuseLine("max_per_order", index, `At most ${max} of this on one order`, {
358
- max,
359
- asked: line.quantity
360
- });
361
- }
362
- if (sellable.grants) {
363
- if (granting + line.quantity > GRANTS_PER_ORDER_CEILING) {
364
- refuseLine(
365
- "max_per_order",
366
- index,
367
- `At most ${GRANTS_PER_ORDER_CEILING} tickets or other grants on one order`,
368
- {
369
- max: GRANTS_PER_ORDER_CEILING - granting,
370
- asked: line.quantity,
371
- ceiling: GRANTS_PER_ORDER_CEILING
372
- }
373
- );
374
- }
375
- granting += line.quantity;
376
- }
377
- let deposit = null;
378
- if (sellable.deposit) {
379
- const amount = toMinorUnits(read(sellable.deposit.amount), currency);
380
- const balanceDueAt = dueMoment(read(sellable.deposit.balanceDue));
381
- if (amount !== null && amount > 0 && balanceDueAt) deposit = { amount, balanceDueAt };
382
- }
383
- const title = object.titleField ? read(object.titleField) : null;
384
- const trial = sellable.recurring?.trialDays ? read(sellable.recurring.trialDays) : null;
385
- const onceFlag = sellable.onePerPerson ? read(sellable.onePerPerson) : null;
386
- priced2.push({
387
- ...onceFlag === 1 || onceFlag === true ? { once: true } : {},
388
- ...sellable.recurring ? {
389
- recurring: {
390
- interval: sellable.recurring.interval,
391
- trialDays: typeof trial === "number" && Number.isInteger(trial) && trial > 0 ? trial : null
392
- }
393
- } : {},
394
- id: newId("orderLine"),
395
- position: index,
396
- object: object.name,
397
- recordId: line.id,
398
- title: title == null || title === "" ? object.label : String(title),
399
- quantity: line.quantity,
400
- unitPrice,
401
- total: unitPrice * line.quantity,
402
- deposit
403
- });
404
- }
405
- return priced2;
406
- }
407
- async function createOrder(ctx, input) {
408
- if (!input.lines.length) throw new ValidationError("An order needs at least one line");
409
- if (input.lines.length > ORDER_MAX_LINES) {
410
- throw new ValidationError(`An order has at most ${ORDER_MAX_LINES} lines`);
411
- }
412
- for (const [index, line] of input.lines.entries()) {
413
- if (!Number.isInteger(line.quantity) || line.quantity < 1 || line.quantity > ORDER_MAX_QUANTITY) {
414
- throw new ValidationError("A quantity is a whole number, at least 1", { line: index });
415
- }
416
- }
417
- const currency = await loadOrderCurrency(ctx.db);
418
- if (!currency) {
419
- throw new ConfigError("No currency is set for orders yet, so nothing can be sold");
420
- }
421
- const lines = await priceLines(ctx.db, input.lines, currency, ctx.now, callerOf(ctx));
422
- const total = lines.reduce((sum, line) => sum + line.total, 0);
423
- if (total <= 0) {
424
- throw new ValidationError("An order with nothing to pay cannot be started", { rule: "total" });
425
- }
426
- let deposit = null;
427
- let balanceDueAt = null;
428
- if (input.pay === "deposit") {
429
- for (const line of lines) {
430
- if (!line.deposit) {
431
- refuseLine("deposit_not_offered", line.position, "This cannot be paid by deposit");
432
- }
433
- }
434
- const offered = lines.map((line) => line.deposit);
435
- deposit = lines.reduce((sum, line, i) => sum + (offered[i]?.amount ?? 0) * line.quantity, 0);
436
- balanceDueAt = offered.map((d) => d.balanceDueAt).sort()[0];
437
- if (deposit >= total) {
438
- throw new ValidationError("The deposit is the whole price: pay in full", {
439
- rule: "deposit_not_offered"
440
- });
441
- }
442
- if (balanceDueAt <= ctx.now) {
443
- throw new ValidationError("The balance was due before today: pay in full", {
444
- rule: "deposit_not_offered"
445
- });
446
- }
447
- }
448
- const minutes = await loadOrderExpiryMinutes(ctx.db);
449
- const id = newId("order");
450
- const row = {
451
- id,
452
- person_id: input.personId,
453
- email: input.email,
454
- currency,
455
- total,
456
- paid: 0,
457
- state: "pending",
458
- pay: input.pay,
459
- deposit,
460
- balance_due_at: balanceDueAt,
461
- expires_at: new Date(Date.parse(ctx.now) + minutes * 6e4).toISOString(),
462
- placed_as: input.placedAs,
463
- provider: null,
464
- provider_ref: null,
465
- access_hash: input.accessHash ?? null,
466
- access_until: null,
467
- email_link_hash: null,
468
- refunded: 0,
469
- tax_amount: 0,
470
- tax_refunded: 0,
471
- tax_country: null,
472
- subscription_id: null,
473
- period_start: null,
474
- period_end: null,
475
- invoice_ref: null,
476
- period_flag: null,
477
- paid_at: null,
478
- cancelled_at: null,
479
- refunded_at: null,
480
- created_at: ctx.now,
481
- updated_at: ctx.now,
482
- version: 0
483
- };
484
- const outcome = await applyTransition(
485
- ctx,
486
- order(),
487
- id,
488
- null,
489
- { state: "pending" },
490
- { by: "host" }
491
- );
492
- await claimOrderPlaces(ctx, id, lines);
493
- ctx.write(
494
- ctx.db.insertInto("core_order").values(row),
495
- ...lines.map(
496
- (line) => ctx.db.insertInto("core_order_line").values({
497
- id: line.id,
498
- order_id: id,
499
- position: line.position,
500
- object_type: line.object,
501
- record_id: line.recordId,
502
- title: line.title,
503
- quantity: line.quantity,
504
- unit_price: line.unitPrice,
505
- line_total: line.total,
506
- created_at: ctx.now
507
- })
508
- ),
509
- ...outcome.history
510
- );
511
- await holdOncePerPerson(
512
- ctx,
513
- id,
514
- lines.filter((line) => line.once).map((line) => ({
515
- object: line.object,
516
- recordId: line.recordId,
517
- quantity: line.quantity,
518
- position: line.position
519
- })),
520
- { personId: input.personId, placedAs: input.placedAs }
521
- );
522
- recordHostChange(ctx, { object: "order", id, action: "create", after: orderSnapshot(row) });
523
- postOrderMove(ctx, row, null);
524
- return { row, lines };
525
- }
526
- async function changeOrder(ctx, row, to, change, by) {
527
- const before = orderSnapshot(row);
528
- const next = {
529
- ...row,
530
- ...change,
531
- state: to,
532
- updated_at: ctx.now,
533
- version: row.version + 1,
534
- // A guest's link outlives the order's closing by a while, then stops.
535
- access_until: CLOSED.has(to) ? new Date(Date.parse(ctx.now) + ORDER_ACCESS_DAYS_AFTER_CLOSE * 864e5).toISOString() : null
536
- };
537
- const outcome = await applyTransition(ctx, order(), row.id, before, orderSnapshot(next), { by });
538
- ctx.write(
539
- ctx.db.updateTable("core_order").set({
540
- ...change,
541
- state: to,
542
- updated_at: next.updated_at,
543
- version: next.version,
544
- access_until: next.access_until
545
- }).where("id", "=", row.id),
546
- ...outcome.history
547
- );
548
- recordHostChange(ctx, {
549
- object: "order",
550
- id: row.id,
551
- action: "update",
552
- before,
553
- after: orderSnapshot(next)
554
- });
555
- if (to !== row.state) postOrderMove(ctx, next, row.state);
556
- return next;
557
- }
558
- var MOVE_WORDS = {
559
- pending: "started",
560
- part_paid: "part paid",
561
- paid: "paid",
562
- cancelled: "cancelled",
563
- expired: "expired",
564
- refunded: "refunded"
565
- };
566
- function formatMoney(amount, currency) {
567
- const digits = currencyDecimals(currency);
568
- return `${(amount / 10 ** digits).toFixed(digits)} ${currency}`;
569
- }
570
- function postOrderMove(ctx, row, from) {
571
- if (!row.person_id) return;
572
- const money = row.state === "pending" ? formatMoney(row.total, row.currency) : row.state === "refunded" ? formatMoney(row.refunded, row.currency) : `${formatMoney(row.paid, row.currency)} of ${formatMoney(row.total, row.currency)}`;
573
- ctx.postActivity({
574
- subject: `Order ${MOVE_WORDS[row.state]}: ${money}`,
575
- payload: {
576
- kind: "order.moved",
577
- orderId: row.id,
578
- from,
579
- to: row.state,
580
- total: row.total,
581
- paid: row.paid,
582
- refunded: row.refunded,
583
- currency: row.currency
584
- },
585
- links: [{ object: "person", id: row.person_id }]
586
- });
587
- }
588
- function chargeFor(row, minPart, amount) {
589
- const refuse = (message, rule, extra) => {
590
- throw new ValidationError(message, { rule, order: row.id, ...extra });
591
- };
592
- if (row.state === "pending") {
593
- const due = row.pay === "deposit" ? row.deposit : row.total;
594
- if (amount !== void 0 && amount !== due) {
595
- refuse("The first payment on an order is not the buyer's to choose", "charge_amount", {
596
- due
597
- });
598
- }
599
- return {
600
- amount: due,
601
- currency: row.currency,
602
- kind: row.pay === "deposit" ? "deposit" : "full"
603
- };
604
- }
605
- if (row.state === "part_paid") {
606
- const balance = row.total - row.paid;
607
- const least = Math.min(minPart, balance);
608
- const wanted = amount ?? balance;
609
- if (!Number.isInteger(wanted) || wanted < least || wanted > balance) {
610
- refuse(`A payment towards this order is between ${least} and ${balance}`, "charge_amount", {
611
- least,
612
- balance
613
- });
614
- }
615
- return {
616
- amount: wanted,
617
- currency: row.currency,
618
- kind: wanted === balance ? "balance" : "part"
619
- };
620
- }
621
- return refuse("Nothing can be paid on this order", "charge_state", { state: row.state });
622
- }
623
- var OVERDUE_LIMIT = 200;
624
- function overdueOrders(db, now, limit = OVERDUE_LIMIT) {
625
- return db.selectFrom("core_order").selectAll().where("state", "=", "part_paid").where("balance_due_at", "<", now).orderBy("balance_due_at").limit(Math.min(Math.max(limit, 1), OVERDUE_LIMIT)).execute();
626
- }
627
- function requireState(row, states, what) {
628
- if (!states.includes(row.state)) {
629
- throw new ConflictError(`An order that is ${row.state} cannot be ${what}`, {
630
- order: row.id,
631
- state: row.state
632
- });
633
- }
634
- }
635
-
636
- // ../core/src/orders/subscription-setup.ts
637
- async function subscriptionSetup(db) {
638
- let target = null;
639
- try {
640
- target = await paymentsTarget(db);
641
- } catch (error) {
642
- if (!(error instanceof ConfigError)) throw error;
643
- }
644
- return {
645
- returnOrigins: [...await loadReturnOrigins(db)],
646
- currency: await loadOrderCurrency(db),
647
- target
648
- };
649
- }
650
- function setupComplete(setup) {
651
- return setup.returnOrigins.length > 0 && setup.currency !== null && setup.target !== null;
652
- }
653
-
654
- // ../core/src/customers/plan-on-sale.ts
655
- var PUBLIC = Object.freeze({ kind: "public" });
656
- var PLANS_LOOKED_AT = 50;
657
- var PLAN_ON_SALE_MEMO_MS = 6e4;
658
- var memo = null;
659
- function forgetPlanOnSale() {
660
- memo = null;
661
- }
662
- async function findPlanOnSale(db, now = (/* @__PURE__ */ new Date()).toISOString(), options = {}) {
663
- const at = Date.now();
664
- if (options.memo && memo && at - memo.at < PLAN_ON_SALE_MEMO_MS) return memo.value;
665
- let value;
666
- try {
667
- value = await compute(db, now);
668
- } catch (error) {
669
- value = { state: "unknown", reason: error instanceof Error ? error.message : String(error) };
670
- }
671
- memo = { at, value };
672
- return value;
673
- }
674
- async function hasPlanOnSale(db, now = (/* @__PURE__ */ new Date()).toISOString()) {
675
- return (await findPlanOnSale(db, now)).state === "on_sale";
676
- }
677
- async function compute(db, now) {
678
- const setup = await subscriptionSetup(db);
679
- if (!setupComplete(setup)) return { state: "none" };
680
- await refreshSchemaRegistry(db);
681
- let unanswered = false;
682
- for (const object of listObjects()) {
683
- const sellable = sellableOf(object);
684
- if (!sellable?.recurring || sellableProblems(sellable, object).length) continue;
685
- const scope = scopeOf(PUBLIC, object, false);
686
- if (scope.kind !== "public") continue;
687
- let source;
688
- try {
689
- source = buyableSource({ principal: PUBLIC }, object);
690
- } catch {
691
- continue;
692
- }
693
- const readable2 = new Set(scope.columns);
694
- const columnOf = (name) => {
695
- const field = name ? object.fields.find((f) => f.name === name) : void 0;
696
- const column2 = field ? viewColumnOf(field) : null;
697
- return column2 && readable2.has(column2) ? column2 : null;
698
- };
699
- let query = db.selectFrom(source).select("id");
700
- const price = columnOf(sellable.price);
701
- if (price) query = query.where(sql.ref(price), ">", 0);
702
- const day = now.slice(0, 10);
703
- const from = columnOf(sellable.saleWindow?.from);
704
- if (from) {
705
- query = query.where(
706
- (eb) => eb.or([eb(sql.ref(from), "is", null), eb(sql.ref(from), "<=", now)])
707
- );
708
- }
709
- const until = columnOf(sellable.saleWindow?.until);
710
- if (until) {
711
- query = query.where(
712
- (eb) => eb.or([eb(sql.ref(until), "is", null), eb(sql.ref(until), ">=", day)])
713
- );
714
- }
715
- const rows = await query.orderBy("id").limit(PLANS_LOOKED_AT + 1).execute();
716
- for (const { id } of rows.slice(0, PLANS_LOOKED_AT)) {
717
- const found = await priced(db, object, id, setup.currency, now);
718
- if (found) return { state: "on_sale", plan: found };
719
- }
720
- if (rows.length > PLANS_LOOKED_AT) unanswered = true;
721
- }
722
- return unanswered ? { state: "unknown", reason: `more than ${PLANS_LOOKED_AT} plans to look at` } : { state: "none" };
723
- }
724
- async function priced(db, object, id, currency, now) {
725
- try {
726
- const [line] = await priceLines(
727
- db,
728
- [{ object: object.name, id, quantity: 1 }],
729
- currency,
730
- now,
731
- PUBLIC,
732
- { plans: true }
733
- );
734
- return line?.recurring && line.unitPrice > 0 ? { object: object.name, id, title: line.title } : null;
735
- } catch (error) {
736
- if (error instanceof ValidationError) return null;
737
- throw error;
738
- }
739
- }
740
-
741
- export {
742
- ORDER_MAX_LINES,
743
- ORDER_MAX_QUANTITY,
744
- orderSnapshot,
745
- loadOrderRow,
746
- priceLines,
747
- createOrder,
748
- changeOrder,
749
- formatMoney,
750
- chargeFor,
751
- overdueOrders,
752
- requireState,
753
- subscriptionSetup,
754
- PLANS_LOOKED_AT,
755
- PLAN_ON_SALE_MEMO_MS,
756
- forgetPlanOnSale,
757
- findPlanOnSale,
758
- hasPlanOnSale
759
- };