@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,837 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- personsTool
4
- } from "./chunk-6GDEDOV7.js";
5
- import {
6
- localDaysBefore
7
- } from "./chunk-O2UIZHND.js";
8
- import {
9
- CompiledQuery,
10
- assertClaimRelationKept,
11
- claimantMove,
12
- loadGeneralSettings,
13
- newId
14
- } from "./chunk-TQFGGSA4.js";
15
- import {
16
- FIELD_TYPE_REGISTRY,
17
- ForbiddenError,
18
- ValidationError,
19
- registryFieldName,
20
- sql,
21
- viewColumnOf,
22
- visibleSource
23
- } from "./chunk-A4NTSYWV.js";
24
- import {
25
- getObject
26
- } from "./chunk-IFG4FRW5.js";
27
- import {
28
- moveOrigins
29
- } from "./chunk-CP6BXI6F.js";
30
-
31
- // ../core/src/records/transitions.ts
32
- function callerOf(ctx) {
33
- return ctx.onBehalfOf ?? ctx.principal;
34
- }
35
- function enteredBy(ctx) {
36
- return callerOf(ctx).kind === "staff" ? ctx.user.id : null;
37
- }
38
- var ALL_MOVERS = ["staff", "customer", "host"];
39
- var TransitionRuleError = class extends ValidationError {
40
- name = "TransitionRuleError";
41
- };
42
- var NO_TRANSITION = {
43
- values: {},
44
- history: [],
45
- moved: null,
46
- left: null,
47
- field: null
48
- };
49
- function isEmptyValue(value) {
50
- return value === null || value === void 0 || typeof value === "string" && value.trim() === "" || Array.isArray(value) && value.length === 0;
51
- }
52
- function ruleBase(write, rule, fields) {
53
- return {
54
- rule,
55
- object: write.object.name,
56
- field: fields[0],
57
- fields,
58
- labels: fields.map(write.labelOf)
59
- };
60
- }
61
- async function runTransition(lifecycle, ctx, object, id, before, written, by) {
62
- const values = {};
63
- const after = { ...before ?? {}, ...written };
64
- const has = (field) => Object.hasOwn(written, field);
65
- const write = {
66
- ctx,
67
- object,
68
- id,
69
- before,
70
- written,
71
- after,
72
- by,
73
- has,
74
- changed: (field) => has(field) && JSON.stringify(written[field] ?? null) !== JSON.stringify(before?.[field] ?? null),
75
- set: (field, value) => {
76
- if (!field) return;
77
- values[field] = value;
78
- after[field] = value;
79
- },
80
- labelOf: (field) => object.fields.find((f) => f.name === field)?.label ?? field
81
- };
82
- const placement = await lifecycle.place(write);
83
- if (!placement) return NO_TRANSITION;
84
- const { to } = placement;
85
- const moved = to.id !== placement.fromId;
86
- if (moved && !placement.by.includes(by)) {
87
- throw lifecycle.refusal(
88
- write,
89
- {
90
- rule: "move_not_permitted",
91
- message: notPermittedMessage(object, to, placement.by),
92
- fields: [lifecycle.field]
93
- },
94
- placement
95
- );
96
- }
97
- lifecycle.follow?.(write, placement, moved);
98
- const required = [...new Set(placement.requires)].filter(
99
- (field) => object.fields.some((f) => f.name === field)
100
- );
101
- const checked = moved || before === null ? required : required.filter(write.changed);
102
- const missing = checked.filter((field) => isEmptyValue(after[field]));
103
- if (missing.length) {
104
- throw lifecycle.refusal(
105
- write,
106
- {
107
- rule: "required_fields",
108
- message: `${to.title} needs ${missing.map(write.labelOf).join(", ")}`,
109
- fields: missing
110
- },
111
- placement
112
- );
113
- }
114
- const history = [];
115
- if (moved) {
116
- if (before !== null) {
117
- const column2 = object.fields.find((f) => f.name === lifecycle.field)?.column;
118
- if (!column2) {
119
- throw new ValidationError(`${object.label} has no column for ${lifecycle.field}`);
120
- }
121
- ctx.write(
122
- CompiledQuery.raw(
123
- `UPDATE core_transition_history SET left_at = ? WHERE object_type = ? AND record_id = ? AND left_at IS NULL AND EXISTS (SELECT 1 FROM ${object.source} WHERE id = ? AND ${column2} IS ?)`,
124
- [ctx.now, object.name, id, id, storedPosition(before[lifecycle.field])]
125
- )
126
- );
127
- }
128
- history.push(
129
- CompiledQuery.raw(
130
- "INSERT INTO core_transition_history (id, object_type, record_id, form, position_id, group_id, position_type, entered_at, left_at, entered_by, entered_as) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)",
131
- [
132
- newId("stageHistory"),
133
- object.name,
134
- id,
135
- lifecycle.form,
136
- to.id,
137
- placement.group(),
138
- to.type,
139
- ctx.now,
140
- enteredBy(ctx),
141
- by
142
- ]
143
- )
144
- );
145
- }
146
- return {
147
- values,
148
- history,
149
- moved: moved ? to : null,
150
- left: moved ? placement.from : null,
151
- field: lifecycle.field
152
- };
153
- }
154
- function storedPosition(value) {
155
- if (value === null || value === void 0) return null;
156
- if (typeof value === "object" && value && "id" in value)
157
- return String(value.id);
158
- return String(value);
159
- }
160
- function notPermittedMessage(object, to, by) {
161
- if (by.length === 1 && by[0] === "host") {
162
- return `${object.label} becomes ${to.title} when the platform confirms it; it cannot be set`;
163
- }
164
- const who = by.map((mover) => mover === "host" ? "the platform" : mover).join(" or ");
165
- return `Only ${who} can move ${object.label.toLowerCase()} to ${to.title}`;
166
- }
167
- function transitionTimeline(outcome) {
168
- if (!outcome.moved || !outcome.field) return void 0;
169
- return {
170
- subject: `Moved to ${outcome.moved.title}`,
171
- field: outcome.field,
172
- labels: { before: outcome.left?.title ?? null, after: outcome.moved.title }
173
- };
174
- }
175
-
176
- // ../core/src/records/stages.ts
177
- var StageRuleError = class extends TransitionRuleError {
178
- name = "StageRuleError";
179
- constructor(message, details) {
180
- super(message, details);
181
- }
182
- };
183
- function column(object, field) {
184
- const definition = object.fields.find((f) => f.name === field);
185
- return definition ? viewColumnOf(definition) : null;
186
- }
187
- function readValue(field, raw) {
188
- if (!field?.fieldType) return raw ?? null;
189
- const type = field.fieldType;
190
- return FIELD_TYPE_REGISTRY[type]?.fromStorage(raw ?? null) ?? raw ?? null;
191
- }
192
- function stageObjectOf(object, stages) {
193
- const to = object.fields.find((f) => f.name === stages.field)?.options?.to;
194
- const target = to ? getObject(to) : void 0;
195
- if (!target) throw new ValidationError(`${object.name}: its stage object is not installed`);
196
- return target;
197
- }
198
- async function loadStages(ctx, stageObject, stages, ids, cache = /* @__PURE__ */ new Map()) {
199
- const out = /* @__PURE__ */ new Map();
200
- const missing = [...new Set(ids)].filter((id) => {
201
- const hit = cache.get(id);
202
- if (hit) out.set(id, hit);
203
- return !cache.has(id);
204
- });
205
- if (missing.length) {
206
- const fieldOf = (name) => name ? stageObject.fields.find((f) => f.name === name) : void 0;
207
- const rows = await sql`
208
- SELECT * FROM ${visibleSource(ctx, stageObject)}
209
- WHERE id IN (SELECT value FROM json_each(${JSON.stringify(missing)}))
210
- `.execute(ctx.db);
211
- const titleColumn = stageObject.titleField ? column(stageObject, stageObject.titleField) : null;
212
- const get = (row, name) => {
213
- const field = fieldOf(name);
214
- const col = field ? viewColumnOf(field) : null;
215
- return col ? readValue(field, row[col]) : null;
216
- };
217
- for (const row of rows.rows) {
218
- const type = get(row, stages.stage.type);
219
- const required = get(row, stages.stage.requiredFields);
220
- const order = get(row, stages.stage.order);
221
- const probability = get(row, stages.stage.probability);
222
- const group = get(row, stages.stage.group);
223
- const info = {
224
- id: String(row.id),
225
- title: titleColumn ? String(row[titleColumn] ?? row.id) : String(row.id),
226
- type: type === "won" || type === "lost" ? type : "open",
227
- order: typeof order === "number" ? order : null,
228
- requiredFields: Array.isArray(required) ? required.map(String) : [],
229
- probability: typeof probability === "number" ? probability : null,
230
- group: typeof group === "string" ? group : null
231
- };
232
- cache.set(info.id, info);
233
- out.set(info.id, info);
234
- }
235
- for (const id of missing) if (!out.has(id)) cache.set(id, null);
236
- }
237
- return out;
238
- }
239
- async function firstStage(ctx, stageObject, stages, group) {
240
- const order = column(stageObject, stages.stage.order);
241
- const groupColumn = stages.stage.group ? column(stageObject, stages.stage.group) : null;
242
- if (!order) return null;
243
- const where = groupColumn ? sql`WHERE ${sql.ref(groupColumn)} = ${group}` : sql``;
244
- const row = await sql`
245
- SELECT id FROM ${visibleSource(ctx, stageObject)} ${where}
246
- ORDER BY ${sql.ref(order)} IS NULL, ${sql.ref(order)}, id LIMIT 1
247
- `.execute(ctx.db);
248
- return row.rows[0]?.id ?? null;
249
- }
250
- async function defaultGroup(ctx, object, stages, group) {
251
- const setting = stages.defaultGroupSetting;
252
- const ext = object.extension;
253
- const to = object.fields.find((f) => f.name === group)?.options?.to;
254
- const groupObject = to ? getObject(to) : void 0;
255
- if (!setting || !ext || !groupObject?.titleField) return null;
256
- const [stored, installed] = await Promise.all([
257
- ctx.db.selectFrom("core_extension_settings").select("value").where("extension_id", "=", ext).executeTakeFirst(),
258
- ctx.db.selectFrom("core_extensions").select("manifest").where("id", "=", ext).executeTakeFirst()
259
- ]);
260
- const value = (stored ? JSON.parse(stored.value)[setting] : void 0) ?? (installed ? JSON.parse(installed.manifest).settings?.[setting]?.default : void 0);
261
- if (typeof value !== "string" || !value.trim()) return null;
262
- const title = column(groupObject, groupObject.titleField);
263
- if (!title) return null;
264
- const row = await sql`
265
- SELECT id FROM ${visibleSource(ctx, groupObject)}
266
- WHERE id = ${value.trim()} OR lower(${sql.ref(title)}) = ${value.trim().toLowerCase()}
267
- ORDER BY id = ${value.trim()} DESC, id LIMIT 1
268
- `.execute(ctx.db);
269
- return row.rows[0]?.id ?? null;
270
- }
271
- var STAGE_MOVERS = ["staff", "host"];
272
- var stageRef = (stage) => ({ id: stage.id, title: stage.title, type: stage.type });
273
- function stagesLifecycle(object, stages, cache = /* @__PURE__ */ new Map()) {
274
- const group = stages.group;
275
- const refuse = (write, rule, message, fields, stage, by) => new StageRuleError(message, {
276
- ...ruleBase(write, rule, fields),
277
- rule,
278
- stage: stage ? stageRef(stage) : null,
279
- ...by ? { by: [...by] } : {}
280
- });
281
- return {
282
- form: "stages",
283
- field: stages.field,
284
- async place(write) {
285
- const { ctx, before, written, after, has, set, labelOf } = write;
286
- const stageObject = stageObjectOf(object, stages);
287
- const beforeStage = before?.[stages.field] ?? null;
288
- let stageId = after[stages.field] ?? null;
289
- const groupChanged = Boolean(
290
- group && has(group) && written[group] !== (before?.[group] ?? null)
291
- );
292
- const stageWritten = has(stages.field);
293
- if (!stageWritten && (before === null || groupChanged) || stageWritten && stageId === null) {
294
- if (stageWritten && stageId === null && before !== null) {
295
- throw refuse(
296
- write,
297
- "no_stage",
298
- `${object.label} must be in a stage`,
299
- [stages.field],
300
- null
301
- );
302
- }
303
- let groupId = group ? after[group] ?? null : null;
304
- if (group && !groupId && before === null && stages.defaultGroupSetting) {
305
- groupId = await defaultGroup(ctx, object, stages, group);
306
- if (groupId) set(group, groupId);
307
- }
308
- if (!group || groupId) {
309
- stageId = await firstStage(ctx, stageObject, stages, groupId);
310
- if (stageId) set(stages.field, stageId);
311
- }
312
- }
313
- if (!stageId) {
314
- if (before === null && !group) return null;
315
- throw refuse(
316
- write,
317
- "no_stage",
318
- group ? `Choose a ${labelOf(group).toLowerCase()} with at least one stage, or a stage` : `${object.label} needs a stage`,
319
- [group ?? stages.field],
320
- null
321
- );
322
- }
323
- const loaded = await loadStages(
324
- ctx,
325
- stageObject,
326
- stages,
327
- beforeStage ? [stageId, beforeStage] : [stageId],
328
- cache
329
- );
330
- const stage = loaded.get(stageId);
331
- if (!stage) {
332
- throw new ValidationError(`${labelOf(stages.field)}: no live stage with id ${stageId}`, {
333
- field: stages.field
334
- });
335
- }
336
- if (group && stage.group) {
337
- const groupId = after[group] ?? null;
338
- if (groupId === null) set(group, stage.group);
339
- else if (groupId !== stage.group) {
340
- throw refuse(
341
- write,
342
- "stage_not_in_group",
343
- `${stage.title} is not a stage of this ${labelOf(group).toLowerCase()}`,
344
- [stages.field],
345
- stage
346
- );
347
- }
348
- }
349
- const left = beforeStage ? loaded.get(beforeStage) ?? null : null;
350
- return {
351
- stage,
352
- fromId: beforeStage,
353
- from: left ? stageRef(left) : null,
354
- to: stageRef(stage),
355
- by: STAGE_MOVERS,
356
- requires: [...stage.requiredFields, ...stages.requiredByType?.[stage.type] ?? []],
357
- group: () => group ? after[group] ?? null : stage.group
358
- };
359
- },
360
- follow(write, { stage }, moved) {
361
- const { ctx, before, written, after, changed, set } = write;
362
- if (stages.status && (moved || after[stages.status] !== stage.type)) {
363
- set(stages.status, stage.type);
364
- }
365
- if (stages.closedDate && moved) {
366
- const field = object.fields.find((f) => f.name === stages.closedDate);
367
- const now = field?.fieldType === "datetime" ? ctx.now : ctx.now.slice(0, 10);
368
- set(stages.closedDate, stage.type === "open" ? null : now);
369
- }
370
- if (stages.probability) {
371
- const { field, overridden } = stages.probability;
372
- let isOverridden = before?.[overridden] === true;
373
- if (changed(overridden) && written[overridden] !== true) isOverridden = false;
374
- else if (changed(field)) {
375
- isOverridden = written[field] !== null && written[field] !== void 0;
376
- } else if (changed(overridden)) isOverridden = true;
377
- if (after[overridden] !== isOverridden) set(overridden, isOverridden);
378
- if (!isOverridden && after[field] !== stage.probability) set(field, stage.probability);
379
- }
380
- },
381
- refusal(write, refusal, placement) {
382
- return refuse(
383
- write,
384
- `stage_${refusal.rule}`,
385
- refusal.message,
386
- refusal.fields,
387
- placement.stage,
388
- refusal.rule === "move_not_permitted" ? placement.by : void 0
389
- );
390
- }
391
- };
392
- }
393
-
394
- // ../core/src/records/windows.ts
395
- function pathReader(ctx, object, after) {
396
- const ext = object.extension;
397
- const records = /* @__PURE__ */ new Map();
398
- const load = (target, id) => {
399
- const key = `${target.name}:${id}`;
400
- const cached = records.get(key);
401
- if (cached) return cached;
402
- const promise = (async () => {
403
- const stored = await ctx.db.selectFrom(visibleSource(ctx, target)).selectAll().where("id", "=", id).executeTakeFirst();
404
- if (!stored) return null;
405
- const values = {};
406
- for (const field of target.fields) {
407
- if (field.column && Object.hasOwn(stored, field.column)) {
408
- values[field.name] = stored[field.column];
409
- }
410
- }
411
- return values;
412
- })();
413
- records.set(key, promise);
414
- return promise;
415
- };
416
- const nameOn = (on, local) => ext ? registryFieldName(ext, on.name, local) : local;
417
- let settings;
418
- const loadSettings = () => {
419
- settings ??= (async () => {
420
- if (!ext) return {};
421
- const [stored, declared] = await Promise.all([
422
- ctx.db.selectFrom("core_extension_settings").select("value").where("extension_id", "=", ext).executeTakeFirst(),
423
- ctx.db.selectFrom("core_extensions").select("manifest").where("id", "=", ext).executeTakeFirst()
424
- ]);
425
- const defaults = Object.fromEntries(
426
- Object.entries(
427
- (declared ? JSON.parse(declared.manifest) : {}).settings ?? {}
428
- ).map(([name, s]) => [name, s.default ?? null])
429
- );
430
- return {
431
- ...defaults,
432
- ...stored ? JSON.parse(stored.value) : {}
433
- };
434
- })();
435
- return settings;
436
- };
437
- return {
438
- async read(path) {
439
- const parts = path.split(".");
440
- let values = after;
441
- let on = object;
442
- for (const [i, part] of parts.entries()) {
443
- if (!values) return null;
444
- const name = i === 0 ? part : nameOn(on, part);
445
- const value = values[name] ?? null;
446
- if (i === parts.length - 1) return value;
447
- const to = on.fields.find((f) => f.name === name)?.options?.to;
448
- const target = to ? getObject(to) : void 0;
449
- if (typeof value !== "string" || !value || !target) return null;
450
- values = await load(target, value);
451
- if (!values) return UNREADABLE;
452
- on = target;
453
- }
454
- return null;
455
- },
456
- async setting(name) {
457
- return (await loadSettings())[name] ?? null;
458
- }
459
- };
460
- }
461
- var UNREADABLE = /* @__PURE__ */ Symbol("unreadable");
462
- function asNumber(value) {
463
- if (typeof value === "number" && Number.isFinite(value)) return value;
464
- if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) {
465
- return Number(value);
466
- }
467
- return null;
468
- }
469
- async function boundMoment(ctx, reader, bound) {
470
- const b = typeof bound === "string" ? { at: bound } : bound;
471
- const at = await reader.read(b.at);
472
- const instant = typeof at === "string" ? Date.parse(at) : Number.NaN;
473
- if (Number.isNaN(instant)) return null;
474
- const part = async (value) => {
475
- if (value === void 0) return 0;
476
- if (typeof value === "number") return value;
477
- if (typeof value === "string") return asNumber(await reader.read(value));
478
- const raw = value.field === void 0 ? null : await reader.read(value.field);
479
- if (raw === UNREADABLE) return null;
480
- const own = asNumber(raw);
481
- if (own !== null || value.setting === void 0) return own;
482
- return asNumber(await reader.setting(value.setting));
483
- };
484
- const days = await part(b.daysBefore);
485
- const minutes = await part(b.minutesBefore);
486
- if (days === null || minutes === null) return null;
487
- let moment = instant;
488
- if (days !== 0) {
489
- const zoneValue = b.zone ? await reader.read(b.zone) : null;
490
- if (zoneValue === UNREADABLE) return null;
491
- const zone = typeof zoneValue === "string" && zoneValue ? zoneValue : (await loadGeneralSettings(ctx.db)).timezone;
492
- moment = localDaysBefore(instant, Math.trunc(days), zone);
493
- }
494
- return moment - Math.round(minutes * 6e4);
495
- }
496
- async function windowRefusal(ctx, reader, window, what) {
497
- if (!window) return null;
498
- const now = Date.parse(ctx.now);
499
- const from = window.from === void 0 ? void 0 : await boundMoment(ctx, reader, window.from);
500
- const until = window.until === void 0 ? void 0 : await boundMoment(ctx, reader, window.until);
501
- if (from === null || until === null) {
502
- return {
503
- rule: "window_unknown",
504
- message: `${what} cannot be done now: when it is allowed cannot be worked out`
505
- };
506
- }
507
- const iso = (ms) => new Date(ms).toISOString();
508
- const times = {
509
- ...from !== void 0 ? { opensAt: iso(from) } : {},
510
- ...until !== void 0 ? { closesAt: iso(until) } : {}
511
- };
512
- if (from !== void 0 && now < from) {
513
- return { rule: "window_not_open", message: `${what} opens at ${iso(from)}`, ...times };
514
- }
515
- if (until !== void 0 && now >= until) {
516
- return { rule: "window_closed", message: `${what} closed at ${iso(until)}`, ...times };
517
- }
518
- return null;
519
- }
520
- async function staffOnlySet(reader, paths) {
521
- for (const path of paths === void 0 ? [] : typeof paths === "string" ? [paths] : paths) {
522
- const value = await reader.read(path);
523
- if (value === UNREADABLE) return true;
524
- if (value === true || value === 1 || value === "1" || value === "true") return true;
525
- }
526
- return false;
527
- }
528
- function staffOnlyMessage(what) {
529
- return `${what} is made by staff only`;
530
- }
531
-
532
- // ../core/src/records/states.ts
533
- var StateRuleError = class extends TransitionRuleError {
534
- name = "StateRuleError";
535
- constructor(message, details) {
536
- super(message, details);
537
- }
538
- };
539
- var ref = (position) => position ? { id: position.id, title: position.title, final: position.type === "final" } : null;
540
- function statesLifecycle(object, states) {
541
- const field = states.field;
542
- const choices = object.fields.find((f) => f.name === field)?.options?.choices ?? [];
543
- const finals = new Set(states.moves.filter((move) => move.final).map((move) => move.to));
544
- const position = (value) => ({
545
- id: value,
546
- title: choices.find((choice) => choice.value === value)?.label ?? value,
547
- type: finals.has(value) ? "final" : "open"
548
- });
549
- const moveBetween = (from, to) => states.moves.find((move) => move.to === to && moveOrigins(move).includes(from));
550
- const reachable = (from) => [
551
- ...new Set(
552
- states.moves.filter((move) => moveOrigins(move).includes(from)).map((move) => move.to)
553
- )
554
- ];
555
- const held = (state) => {
556
- const into = states.moves.filter((move) => move.to === state);
557
- const [first, ...rest] = into.map((move) => move.requires ?? []);
558
- return (first ?? []).filter((name) => rest.every((list) => list.includes(name)));
559
- };
560
- const refuse = (write, rule, message, fields, to, from, extra = {}) => new StateRuleError(message, {
561
- ...ruleBase(write, rule, fields),
562
- rule,
563
- state: ref(to),
564
- from: ref(from),
565
- ...extra
566
- });
567
- const customerRules = async (write, rules, what, to, from) => {
568
- const refusal = await customerRefusal(write.ctx, write.object, write.after, rules, what);
569
- if (refusal) {
570
- throw refuse(write, refusal.rule, refusal.message, [field], to, from, refusal.times);
571
- }
572
- };
573
- return {
574
- form: "states",
575
- field,
576
- async place(write) {
577
- const { before, after, object: o } = write;
578
- const stored = before?.[field];
579
- const fromId = typeof stored === "string" && stored !== "" ? stored : null;
580
- const from = fromId ? position(fromId) : null;
581
- const wanted = after[field];
582
- let toId = typeof wanted === "string" && wanted !== "" ? wanted : null;
583
- if (toId === null) {
584
- if (fromId !== null) {
585
- throw refuse(write, "no_state", `${o.label} must have a state`, [field], null, from);
586
- }
587
- toId = states.initial;
588
- write.set(field, toId);
589
- }
590
- const to = position(toId);
591
- const base = { fromId, from, to, group: () => null };
592
- const closedPaths = states.create?.closed;
593
- if (closedPaths && write.by !== "host" && (before === null || ruleSources({ staffOnly: closedPaths }).some((f) => write.changed(f)))) {
594
- const reader = pathReader(write.ctx, o, after);
595
- if (await staffOnlySet(reader, closedPaths)) {
596
- throw refuse(
597
- write,
598
- "state_closed",
599
- `${o.label} cannot be made now: what it is for is closed`,
600
- [field],
601
- to,
602
- from
603
- );
604
- }
605
- }
606
- if (before === null && write.by === "customer" && toId !== states.initial && !states.create?.in?.[toId]?.includes("customer")) {
607
- throw refuse(
608
- write,
609
- "state_move_not_permitted",
610
- `A customer creates ${o.label.toLowerCase()} in ${position(states.initial).title} only`,
611
- [field],
612
- to,
613
- null,
614
- { by: [] }
615
- );
616
- }
617
- if (before === null && write.by === "customer" && states.create) {
618
- await customerRules(write, states.create, `Creating ${o.label.toLowerCase()}`, to, null);
619
- }
620
- if (before !== null && write.by === "customer" && states.create && ruleSources(states.create).some((f) => write.changed(f))) {
621
- await customerRules(write, states.create, `Creating ${o.label.toLowerCase()}`, to, from);
622
- }
623
- const createdIn = before === null && toId !== states.initial ? states.create?.in?.[toId] : void 0;
624
- if (createdIn) {
625
- return { ...base, by: createdIn, requires: held(toId) };
626
- }
627
- if (toId === fromId) return { ...base, by: ALL_MOVERS, requires: held(toId) };
628
- const origin = fromId ?? states.initial;
629
- if (toId === origin) return { ...base, by: ALL_MOVERS, requires: [] };
630
- const originPosition = position(origin);
631
- if (finals.has(origin)) {
632
- throw refuse(
633
- write,
634
- "state_final",
635
- `${o.label} is ${originPosition.title}, which is final: it cannot move to ${to.title}`,
636
- [field],
637
- to,
638
- originPosition,
639
- { allowed: [] }
640
- );
641
- }
642
- const move = moveBetween(origin, toId);
643
- if (!move) {
644
- throw refuse(
645
- write,
646
- "state_move_not_declared",
647
- `${o.label} cannot move from ${originPosition.title} to ${to.title}`,
648
- [field],
649
- to,
650
- originPosition,
651
- { allowed: reachable(origin) }
652
- );
653
- }
654
- if (write.by === "customer" && move.by.includes("customer")) {
655
- await customerRules(
656
- write,
657
- move,
658
- `Moving ${o.label.toLowerCase()} to ${to.title}`,
659
- to,
660
- originPosition
661
- );
662
- }
663
- const tool = write.by === "staff" ? personsTool(write.ctx, o.extension) : null;
664
- const byTool = tool !== null && (move.tools ?? []).includes(tool);
665
- if (write.by === "staff" && move.bindsStaff && move.by.includes("staff")) {
666
- await customerRules(
667
- write,
668
- { window: move.window },
669
- `Moving ${o.label.toLowerCase()} to ${to.title}`,
670
- to,
671
- originPosition
672
- );
673
- }
674
- return {
675
- ...base,
676
- from: originPosition,
677
- by: byTool ? [...move.by, "staff"] : move.by,
678
- requires: move.requires ?? []
679
- };
680
- },
681
- refusal(write, refusal, placement) {
682
- const rule = `state_${refusal.rule}`;
683
- return refuse(
684
- write,
685
- rule,
686
- refusal.message,
687
- refusal.fields,
688
- placement.to,
689
- placement.from,
690
- refusal.rule === "move_not_permitted" ? { by: [...placement.by] } : {}
691
- );
692
- }
693
- };
694
- }
695
- function ruleSources(rules) {
696
- const paths = [];
697
- if (typeof rules.staffOnly === "string") paths.push(rules.staffOnly);
698
- else if (rules.staffOnly) paths.push(...rules.staffOnly);
699
- for (const bound of [rules.window?.from, rules.window?.until]) {
700
- if (bound === void 0) continue;
701
- if (typeof bound === "string") {
702
- paths.push(bound);
703
- continue;
704
- }
705
- paths.push(bound.at);
706
- for (const part of [bound.daysBefore, bound.minutesBefore, bound.zone]) {
707
- if (typeof part === "string") paths.push(part);
708
- else if (typeof part === "object" && part.field) paths.push(part.field);
709
- }
710
- }
711
- return [...new Set(paths.map((p) => p.split(".")[0]))];
712
- }
713
- async function customerRefusal(ctx, object, after, rules, what) {
714
- if (!rules.window && !rules.staffOnly) return null;
715
- const reader = pathReader(ctx, object, after);
716
- if (await staffOnlySet(reader, rules.staffOnly)) {
717
- return { rule: "state_staff_only", message: staffOnlyMessage(what), times: {} };
718
- }
719
- const refusal = await windowRefusal(ctx, reader, rules.window, what);
720
- if (!refusal) return null;
721
- return {
722
- rule: `state_${refusal.rule}`,
723
- message: refusal.message,
724
- times: {
725
- ...refusal.opensAt ? { opensAt: refusal.opensAt } : {},
726
- ...refusal.closesAt ? { closesAt: refusal.closesAt } : {}
727
- }
728
- };
729
- }
730
- function isPerson(ctx) {
731
- try {
732
- return ctx.actor === "human";
733
- } catch {
734
- return false;
735
- }
736
- }
737
- async function resolveStateRequest(ctx, object, before, values, by) {
738
- const states = object.states;
739
- const field = states?.field;
740
- const requests = states?.requests;
741
- if (!states || !field || !requests) return values;
742
- const asked = values[field];
743
- if (typeof asked !== "string" || !Object.hasOwn(requests, asked)) return values;
744
- const stored = before?.[field];
745
- const origin = typeof stored === "string" && stored !== "" ? stored : states.initial;
746
- const after = { ...before ?? {}, ...values };
747
- const labelOf = (name) => object.fields.find((f) => f.name === name)?.label ?? name;
748
- const choices = object.fields.find((f) => f.name === field)?.options?.choices ?? [];
749
- const title = (value) => choices.find((c) => c.value === value)?.label ?? value;
750
- let refused = null;
751
- for (const to of requests[asked] ?? []) {
752
- const move = states.moves.find((m) => m.to === to && moveOrigins(m).includes(origin));
753
- if (!move?.by.includes(by)) continue;
754
- if (by === "customer" || by === "staff" && (!isPerson(ctx) || move.bindsStaff)) {
755
- const refusal = await customerRefusal(
756
- ctx,
757
- object,
758
- { ...after, [field]: to },
759
- move,
760
- `Moving ${object.label.toLowerCase()} to ${title(to)}`
761
- );
762
- if (refusal) {
763
- refused ??= refusal;
764
- continue;
765
- }
766
- }
767
- return { ...values, [field]: to };
768
- }
769
- const state = { id: origin, title: title(origin), final: false };
770
- throw new StateRuleError(
771
- refused?.message ?? `${object.label} cannot be moved by "${asked}" from ${title(origin)}`,
772
- {
773
- ...ruleBase({ object, labelOf }, refused?.rule ?? "state_request_refused", [field]),
774
- rule: refused?.rule ?? "state_request_refused",
775
- state: null,
776
- from: state,
777
- ...refused?.times ?? {}
778
- }
779
- );
780
- }
781
-
782
- // ../core/src/records/lifecycle.ts
783
- function callerMover(ctx) {
784
- const caller = callerOf(ctx);
785
- if (caller.kind === "staff") return "staff";
786
- if (caller.kind === "customer") return "customer";
787
- throw new ForbiddenError("This call cannot move a record");
788
- }
789
- var moveHooks = /* @__PURE__ */ new Map();
790
- function onRecordMove(object, hook) {
791
- const hooks = moveHooks.get(object) ?? [];
792
- hooks.push(hook);
793
- moveHooks.set(object, hooks);
794
- return () => {
795
- const at = hooks.indexOf(hook);
796
- if (at >= 0) hooks.splice(at, 1);
797
- };
798
- }
799
- async function applyTransition(ctx, object, id, before, written, options) {
800
- const run = async (lifecycle) => {
801
- assertClaimRelationKept(object, before, written);
802
- const outcome = await runTransition(lifecycle, ctx, object, id, before, written, options.by);
803
- if (outcome.moved && object.claims) {
804
- await claimantMove(ctx, object, id, before, {
805
- ...before ?? {},
806
- ...written,
807
- ...outcome.values
808
- });
809
- }
810
- const hooks = outcome.moved ? moveHooks.get(object.name) : void 0;
811
- if (outcome.moved && hooks?.length) {
812
- const move = {
813
- object,
814
- id,
815
- from: outcome.left,
816
- to: outcome.moved,
817
- by: options.by,
818
- before,
819
- after: { ...before ?? {}, ...written, ...outcome.values }
820
- };
821
- for (const hook of [...hooks]) await hook(ctx, move);
822
- }
823
- return outcome;
824
- };
825
- if (object.states) return run(statesLifecycle(object, object.states));
826
- if (object.stages) return run(stagesLifecycle(object, object.stages, options.cache));
827
- return NO_TRANSITION;
828
- }
829
-
830
- export {
831
- callerOf,
832
- transitionTimeline,
833
- resolveStateRequest,
834
- callerMover,
835
- onRecordMove,
836
- applyTransition
837
- };