@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,63 +0,0 @@
1
- #!/usr/bin/env node
2
-
3
- // src/import-door/records.ts
4
- var IMPORT_BATCH = 25;
5
- var chunks = (list, size) => Array.from(
6
- { length: Math.ceil(list.length / size) },
7
- (_, i) => list.slice(i * size, (i + 1) * size)
8
- );
9
- async function sha256(value) {
10
- const bytes = typeof value === "string" ? new TextEncoder().encode(value) : value;
11
- const digest = await crypto.subtle.digest("SHA-256", new Uint8Array(bytes));
12
- return [...new Uint8Array(digest)].map((b) => b.toString(16).padStart(2, "0")).join("");
13
- }
14
- async function importRecords(host, object, records, options) {
15
- const out = [];
16
- for (const part of chunks(records, IMPORT_BATCH)) {
17
- const answer = await host.call("record.import", {
18
- object,
19
- records: part.map(({ key, values }) => ({ key, values })),
20
- dryRun: options.dryRun,
21
- checkReferences: options.checkReferences
22
- });
23
- for (const result of answer.results) {
24
- const file = part.find((r) => r.key === result.key)?.file ?? null;
25
- out.push({ ...result, object, file });
26
- }
27
- }
28
- return out;
29
- }
30
- async function knownByHash(host, hashes) {
31
- const known = /* @__PURE__ */ new Map();
32
- for (const part of chunks([...new Set(hashes)], 200)) {
33
- if (!part.length) continue;
34
- const found = await host.call("media.findByHash", { sha256: part });
35
- for (const item of found.items) known.set(item.sha256, item);
36
- }
37
- return known;
38
- }
39
- function outcomeLines(records, dryRun) {
40
- const lines = [];
41
- const by = (outcome) => records.filter((r) => r.outcome === outcome);
42
- const verb = dryRun ? "would be" : "were";
43
- for (const outcome of ["created", "updated", "unchanged"]) {
44
- const list = by(outcome);
45
- if (list.length) {
46
- lines.push(`${list.length} record(s) ${outcome === "unchanged" ? "are" : verb} ${outcome}.`);
47
- }
48
- }
49
- const conflicts = by("conflict");
50
- if (conflicts.length) {
51
- lines.push(`${conflicts.length} conflict(s), left as they are:`);
52
- for (const c of conflicts) lines.push(` ${c.file ?? c.key}: ${c.problems.join("; ")}`);
53
- }
54
- return lines;
55
- }
56
-
57
- export {
58
- chunks,
59
- sha256,
60
- importRecords,
61
- knownByHash,
62
- outcomeLines
63
- };
@@ -1,284 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- checkPerson,
4
- erasedAddresses
5
- } from "./chunk-VY64DMQO.js";
6
- import {
7
- notifyStatements
8
- } from "./chunk-K6T42YCH.js";
9
- import {
10
- newId
11
- } from "./chunk-TQFGGSA4.js";
12
- import {
13
- ConfigError,
14
- ConflictError,
15
- NotFoundError,
16
- ValidationError
17
- } from "./chunk-A4NTSYWV.js";
18
- import {
19
- external_exports
20
- } from "./chunk-CP6BXI6F.js";
21
-
22
- // ../core/src/customers/settings.ts
23
- var CUSTOMER_SIGNUP_SETTING = "customer_signup";
24
- var CUSTOMER_SIGNUP_MODES = ["open", "buyers", "invite_only"];
25
- var customerSignupModeSchema = external_exports.enum(CUSTOMER_SIGNUP_MODES);
26
- var DEFAULT_CUSTOMER_SIGNUP = "invite_only";
27
- async function loadCustomerSignup(db) {
28
- const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_SIGNUP_SETTING).executeTakeFirst();
29
- if (!row) return DEFAULT_CUSTOMER_SIGNUP;
30
- try {
31
- const parsed = customerSignupModeSchema.safeParse(JSON.parse(row.value));
32
- return parsed.success ? parsed.data : DEFAULT_CUSTOMER_SIGNUP;
33
- } catch {
34
- return DEFAULT_CUSTOMER_SIGNUP;
35
- }
36
- }
37
- var CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING = "customer_signup_subscribers";
38
- var DEFAULT_CUSTOMER_SIGNUP_SUBSCRIBERS = false;
39
- async function loadCustomerSignupSubscribers(db) {
40
- const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING).executeTakeFirst();
41
- if (!row) return DEFAULT_CUSTOMER_SIGNUP_SUBSCRIBERS;
42
- try {
43
- return JSON.parse(row.value) === true;
44
- } catch {
45
- return DEFAULT_CUSTOMER_SIGNUP_SUBSCRIBERS;
46
- }
47
- }
48
- var CUSTOMER_ERASE_DUE_SETTING = "customer_erase_due_days";
49
- var DEFAULT_ERASE_DUE_DAYS = 30;
50
- var eraseDueDaysSchema = external_exports.number().int().min(1).max(365);
51
- async function loadEraseDueDays(db) {
52
- const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_ERASE_DUE_SETTING).executeTakeFirst();
53
- if (!row) return DEFAULT_ERASE_DUE_DAYS;
54
- try {
55
- const parsed = eraseDueDaysSchema.safeParse(JSON.parse(row.value));
56
- return parsed.success ? parsed.data : DEFAULT_ERASE_DUE_DAYS;
57
- } catch {
58
- return DEFAULT_ERASE_DUE_DAYS;
59
- }
60
- }
61
- var CUSTOMER_EMAIL_CONNECTION_SETTING = "customer_email_connection";
62
- async function loadCustomerEmailConnection(db) {
63
- const row = await db.selectFrom("core_settings").select("value").where("key", "=", CUSTOMER_EMAIL_CONNECTION_SETTING).executeTakeFirst();
64
- if (!row) return null;
65
- try {
66
- const value = JSON.parse(row.value);
67
- return typeof value === "string" && value ? value : null;
68
- } catch {
69
- return null;
70
- }
71
- }
72
-
73
- // ../core/src/customers/accounts.ts
74
- var emailSchema = external_exports.string().trim().toLowerCase().pipe(external_exports.email().max(320));
75
- function normaliseCustomerEmail(email) {
76
- const parsed = emailSchema.safeParse(email);
77
- return parsed.success ? parsed.data : null;
78
- }
79
- function toAccount(row) {
80
- return {
81
- id: row.id,
82
- personId: row.person_id,
83
- email: row.email,
84
- status: row.status,
85
- linkState: row.link_state
86
- };
87
- }
88
- var ACCOUNT_COLUMNS = ["id", "person_id", "email", "status", "link_state"];
89
- async function loadCustomer(db, id) {
90
- const row = await db.selectFrom("core_customer").select(ACCOUNT_COLUMNS).where("id", "=", id).executeTakeFirst();
91
- return row ? toAccount(row) : null;
92
- }
93
- async function loadCustomerSignIn(db, customerId, personId) {
94
- const row = await db.selectFrom("core_customer").select(["email", "email_verified"]).where("id", "=", customerId).where("person_id", "=", personId).where("status", "=", "active").executeTakeFirst();
95
- return row ? { email: row.email, verified: row.email_verified === 1 } : null;
96
- }
97
- async function loadCustomerByEmail(db, email) {
98
- const address = normaliseCustomerEmail(email);
99
- if (!address) return null;
100
- const row = await db.selectFrom("core_customer").select(ACCOUNT_COLUMNS).where("email", "=", address).executeTakeFirst();
101
- return row ? toAccount(row) : null;
102
- }
103
- async function isErased(db, address) {
104
- return (await erasedAddresses(db, [address])).size > 0;
105
- }
106
- async function customerCodeReason(db, email, now = (/* @__PURE__ */ new Date()).toISOString(), options = {}) {
107
- const address = normaliseCustomerEmail(email);
108
- if (!address) return null;
109
- if (await isErased(db, address)) return null;
110
- const account = await loadCustomerByEmail(db, address);
111
- if (account) return account.status === "active" ? "account" : null;
112
- const signup = await loadCustomerSignup(db);
113
- if (signup === "open") return "open";
114
- const invite = await db.selectFrom("core_customer_invite").select("email").where("email", "=", address).executeTakeFirst();
115
- if (invite) return "invite";
116
- if (signup === "buyers" && await hasBought(db, address)) return "buyer";
117
- if (await loadCustomerSignupSubscribers(db)) {
118
- const { findPlanOnSale } = await import("./plan-on-sale-NB774CQL.js");
119
- const found = await findPlanOnSale(db, now, options);
120
- if (found.state === "on_sale") return "subscription";
121
- }
122
- return null;
123
- }
124
- async function customerMayGetCode(db, email) {
125
- return await customerCodeReason(db, email) !== null;
126
- }
127
- async function hasBought(db, address) {
128
- const { orgReader, visibleSource } = await import("./visibility-DLGHU4YN.js");
129
- const { orderObject } = await import("./order-PUWD65BC.js");
130
- const owners = db.selectFrom("core_person_emails as e").innerJoin("core_person as p", "p.id", "e.person_id").select("e.person_id").where("e.email", "=", address).where("e.live", "=", 1).where("p.deleted_at", "is", null);
131
- const row = await db.selectFrom(visibleSource(orgReader(db), orderObject)).select("id").where((eb) => eb.or([eb("email", "=", address), eb("person_id", "in", owners)])).where("paid", ">", 0).executeTakeFirst();
132
- return Boolean(row);
133
- }
134
- async function inviteCustomerStatement(db, email, invitedByUserId, now) {
135
- const address = normaliseCustomerEmail(email);
136
- if (!address) throw new ValidationError("Not an email address", { field: "email" });
137
- if (await isErased(db, address)) {
138
- throw new ValidationError("This address belongs to an erased person", { field: "email" });
139
- }
140
- const statement = db.insertInto("core_customer_invite").values({ email: address, invited_by: invitedByUserId, invited_at: now }).onConflict(
141
- (oc) => oc.column("email").doUpdateSet({ invited_by: invitedByUserId, invited_at: now })
142
- );
143
- return { email: address, statement };
144
- }
145
- async function inviteCustomer(db, email, invitedByUserId, now = (/* @__PURE__ */ new Date()).toISOString()) {
146
- const { email: address, statement } = await inviteCustomerStatement(
147
- db.query,
148
- email,
149
- invitedByUserId,
150
- now
151
- );
152
- await db.batch([statement]);
153
- return { email: address };
154
- }
155
- var CUSTOMER_LINK_AUDIT = "customer.link";
156
- async function sameEmailPeople(db, address) {
157
- const { conflicts } = await checkPerson(db, { emails: [address] });
158
- return [...new Set(conflicts.map((c) => c.id))];
159
- }
160
- async function creatorFor(db, address) {
161
- const active = db.selectFrom("core_user").select(["id", "email", "name", "role"]).where("kind", "=", "human").where("deactivated_at", "is", null);
162
- const invite = await db.selectFrom("core_customer_invite").select("invited_by").where("email", "=", address).executeTakeFirst();
163
- const row = (invite ? await active.where("id", "=", invite.invited_by).executeTakeFirst() : void 0) ?? await active.where("role", "=", "admin").orderBy("id").limit(1).executeTakeFirst();
164
- return row ? { id: row.id, email: row.email, name: row.name, role: row.role } : null;
165
- }
166
- async function createPersonFor(db, address, customerId, now) {
167
- const user = await creatorFor(db.query, address);
168
- if (!user) throw new ConfigError("There is no admin to create the customer's Person for");
169
- const { invoke } = await import("./invoke-I3NNNXVL.js");
170
- const person = await invoke(
171
- "person.create",
172
- { emails: [{ email: address, primary: true }] },
173
- {
174
- actor: "automation",
175
- user,
176
- origin: { surface: "system", automationId: CUSTOMER_LINK_AUDIT, sessionId: customerId },
177
- db,
178
- clock: () => now
179
- }
180
- );
181
- return person.id;
182
- }
183
- async function linkCustomer(db, customerId, now = /* @__PURE__ */ new Date()) {
184
- const account = await loadCustomer(db.query, customerId);
185
- if (!account) throw new NotFoundError("customer", customerId);
186
- if (account.personId && account.linkState === "linked") {
187
- return { linkState: "linked", personId: account.personId, created: false };
188
- }
189
- if (await isErased(db.query, account.email)) {
190
- throw new ValidationError("This address belongs to an erased person");
191
- }
192
- let matches = await sameEmailPeople(db.query, account.email);
193
- let created = false;
194
- if (matches.length === 0) {
195
- try {
196
- matches = [await createPersonFor(db, account.email, account.id, now)];
197
- created = true;
198
- } catch (error) {
199
- if (!(error instanceof ConflictError)) throw error;
200
- matches = await sameEmailPeople(db.query, account.email);
201
- if (!matches.length) throw error;
202
- }
203
- }
204
- let result;
205
- if (matches.length === 1) {
206
- const personId = matches[0];
207
- const holder = await db.query.selectFrom("core_customer").select("id").where("person_id", "=", personId).where("id", "!=", account.id).executeTakeFirst();
208
- result = holder ? { linkState: "needs_merge", personId: null, created, reason: "person_has_account" } : { linkState: "linked", personId, created };
209
- } else {
210
- result = { linkState: "needs_merge", personId: null, created, reason: "several_people" };
211
- }
212
- const at = now.toISOString();
213
- const statements = [
214
- db.query.updateTable("core_customer").set({ person_id: result.personId, link_state: result.linkState, updated_at: at }).where("id", "=", account.id),
215
- db.query.insertInto("core_audit").values({
216
- id: newId("audit"),
217
- at,
218
- operation: CUSTOMER_LINK_AUDIT,
219
- risk: "write",
220
- actor: "customer",
221
- user_id: account.id,
222
- origin: JSON.stringify({ surface: "client" }),
223
- input: JSON.stringify({ customerId: account.id }),
224
- result: JSON.stringify({
225
- linkState: result.linkState,
226
- personId: result.personId,
227
- created: result.created,
228
- ...result.reason ? { reason: result.reason, people: matches } : {}
229
- }),
230
- gate_decision: "auto",
231
- outcome: "ok",
232
- error: null
233
- })
234
- ];
235
- if (result.linkState === "needs_merge") {
236
- const body = result.reason === "several_people" ? `${account.email} signed in to their customer account, and ${matches.length} people have this address. Merge them: the account links at the next sign-in.` : `${account.email} signed in to a new customer account, and the person with this address already has another one. Disable one account, then ask them to sign in again.`;
237
- const plan = await notifyStatements(
238
- db.query,
239
- {
240
- to: [{ role: "admin" }],
241
- type: "system.message",
242
- title: "A customer account needs a merge",
243
- body,
244
- link: matches[0] ? { kind: "record", object: "person", id: matches[0] } : null,
245
- dedupeKey: `customer.needs_merge:${account.id}`,
246
- source: { actor: "system" }
247
- },
248
- at
249
- );
250
- statements.push(...plan.statements);
251
- }
252
- await db.batch(statements);
253
- return result;
254
- }
255
- function customerSignedInStatement(db, customerId, now) {
256
- return db.updateTable("core_customer").set({ last_sign_in_at: now, updated_at: now }).where("id", "=", customerId);
257
- }
258
-
259
- export {
260
- CUSTOMER_SIGNUP_SETTING,
261
- customerSignupModeSchema,
262
- loadCustomerSignup,
263
- CUSTOMER_SIGNUP_SUBSCRIBERS_SETTING,
264
- loadCustomerSignupSubscribers,
265
- CUSTOMER_ERASE_DUE_SETTING,
266
- eraseDueDaysSchema,
267
- loadEraseDueDays,
268
- CUSTOMER_EMAIL_CONNECTION_SETTING,
269
- loadCustomerEmailConnection,
270
- normaliseCustomerEmail,
271
- loadCustomer,
272
- loadCustomerSignIn,
273
- loadCustomerByEmail,
274
- customerCodeReason,
275
- customerMayGetCode,
276
- hasBought,
277
- inviteCustomerStatement,
278
- inviteCustomer,
279
- CUSTOMER_LINK_AUDIT,
280
- sameEmailPeople,
281
- creatorFor,
282
- linkCustomer,
283
- customerSignedInStatement
284
- };
@@ -1,227 +0,0 @@
1
- #!/usr/bin/env node
2
- import {
3
- addLocalDays,
4
- localParts,
5
- wallClockToIso
6
- } from "./chunk-O2UIZHND.js";
7
- import {
8
- CompiledQuery,
9
- newId
10
- } from "./chunk-TQFGGSA4.js";
11
-
12
- // ../core/src/recurring/bookkeeping.ts
13
- function armSeriesStatement(object, id, at, now) {
14
- return CompiledQuery.raw(
15
- "INSERT INTO core_recurrence_series (object_type, record_id, next_run_at, version, updated_at) VALUES (?, ?, ?, 1, ?) ON CONFLICT (object_type, record_id) DO UPDATE SET next_run_at = excluded.next_run_at, version = core_recurrence_series.version + 1, updated_at = excluded.updated_at",
16
- [object, id, at, now]
17
- );
18
- }
19
- async function seriesVersion(db, object, id) {
20
- const row = await db.selectFrom("core_recurrence_series").select("version").where("object_type", "=", object).where("record_id", "=", id).executeTakeFirst();
21
- return row?.version ?? 0;
22
- }
23
- function guardStatement(kind, object, record, expected) {
24
- return CompiledQuery.raw(
25
- "INSERT INTO core_write_guard (kind, object_type, record_id, expected) VALUES (?, ?, ?, ?)",
26
- [kind, object, record, expected]
27
- );
28
- }
29
- function occurrenceStatement(input) {
30
- return CompiledQuery.raw(
31
- "INSERT INTO core_recurrence_occurrence (series_object, series_id, local_date, object_type, record_id, created_at) VALUES (?, ?, ?, ?, ?, ?)",
32
- [input.seriesObject, input.seriesId, input.date, input.object, input.record, input.now]
33
- );
34
- }
35
- function markEditedStatement(object, record, now) {
36
- return CompiledQuery.raw(
37
- "UPDATE core_recurrence_occurrence SET edited_at = ? WHERE object_type = ? AND record_id = ? AND edited_at IS NULL",
38
- [now, object, record]
39
- );
40
- }
41
- function dropRecurringStatements(object) {
42
- return [
43
- CompiledQuery.raw(
44
- "DELETE FROM core_recurrence_occurrence WHERE series_object = ? OR object_type = ?",
45
- [object, object]
46
- ),
47
- CompiledQuery.raw("DELETE FROM core_recurrence_series WHERE object_type = ?", [object])
48
- ];
49
- }
50
-
51
- // ../core/src/allowance/periods.ts
52
- var TOTAL_PERIOD = {
53
- key: "total",
54
- per: "total",
55
- startsAt: "0000-01-01T00:00:00.000Z",
56
- endsAt: "9999-12-31T23:59:59.999Z"
57
- };
58
- var pad = (n) => String(n).padStart(2, "0");
59
- function periodOf(at, per, zone) {
60
- if (per === "total") return { ...TOTAL_PERIOD };
61
- const local = localParts(at, zone);
62
- if (per === "week") {
63
- const monday = addLocalDays(local, 1 - local.weekday);
64
- return {
65
- key: `week:${monday.year}-${pad(monday.month)}-${pad(monday.day)}`,
66
- per,
67
- startsAt: wallClockToIso(monday, zone),
68
- endsAt: wallClockToIso(addLocalDays(monday, 7), zone)
69
- };
70
- }
71
- const first = { year: local.year, month: local.month, day: 1 };
72
- const next = local.month === 12 ? { year: local.year + 1, month: 1, day: 1 } : { year: local.year, month: local.month + 1, day: 1 };
73
- return {
74
- key: `month:${local.year}-${pad(local.month)}`,
75
- per,
76
- startsAt: wallClockToIso(first, zone),
77
- endsAt: wallClockToIso(next, zone)
78
- };
79
- }
80
- function boundOf(value, kind, fieldType, zone) {
81
- if (value === null || value === void 0 || value === "") return null;
82
- const text = String(value);
83
- const date = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
84
- if (date || fieldType === "date") {
85
- const [y, m, d] = date ? [Number(date[1]), Number(date[2]), Number(date[3])] : (() => {
86
- const p = localParts(text, zone);
87
- return [p.year, p.month, p.day];
88
- })();
89
- const day = { year: y, month: m, day: d };
90
- return wallClockToIso(kind === "until" ? addLocalDays(day, 1) : day, zone);
91
- }
92
- const at = new Date(text);
93
- return Number.isNaN(at.getTime()) ? null : at.toISOString();
94
- }
95
-
96
- // ../core/src/allowance/index.ts
97
- var q = (value) => `'${value.replaceAll("'", "''")}'`;
98
- function termsSyncStatements(storage, target, orgZone, now) {
99
- const t = (column) => `t.${column}`;
100
- const uses = `CASE WHEN typeof(${t(storage.uses)}) IN ('integer', 'real') AND ${t(storage.uses)} >= 0 AND ${t(storage.uses)} = CAST(${t(storage.uses)} AS INTEGER) THEN CAST(${t(storage.uses)} AS INTEGER) WHEN ${t(storage.uses)} IS NULL OR ${t(storage.uses)} = '' THEN ${storage.emptyIsUnlimited ? "NULL" : "0"} ELSE 0 END`;
101
- const per = "fixed" in storage.per ? q(storage.per.fixed) : `CASE WHEN ${t(storage.per.column)} IN ('total', 'week', 'month') THEN ${t(storage.per.column)} ELSE 'total' END`;
102
- const stored = `(SELECT s.zone FROM core_allowance s WHERE s.object_type = ${q(storage.object)} AND s.record_id = t.id)`;
103
- const zone = storage.zone ? `coalesce(nullif(${t(storage.zone)}, ''), ${stored}, ?)` : `coalesce(${stored}, ?)`;
104
- const instant = (bound) => bound && !bound.date ? `CASE WHEN ${t(bound.column)} IS NULL OR ${t(bound.column)} = '' THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%fZ', ${t(bound.column)}) END` : "NULL";
105
- const day = (bound) => bound?.date ? `nullif(substr(${t(bound.column)}, 1, 10), '')` : "NULL";
106
- const live = storage.live ? `CASE WHEN ${t(storage.live.column)} IN (${storage.live.states.map(q).join(", ") || "NULL"}) THEN 1 ELSE 0 END` : "1";
107
- const person = `CASE WHEN typeof(${t(storage.person)}) = 'text' AND ${t(storage.person)} <> '' THEN ${t(storage.person)} END`;
108
- const where = target === "all" ? "true" : "t.id = ?";
109
- return [
110
- CompiledQuery.raw(
111
- `INSERT INTO core_allowance (object_type, record_id, person_id, uses, per, zone, valid_from, valid_until, from_date, until_date, live, trashed, updated_at) SELECT ${q(storage.object)}, t.id, ${person}, ${uses}, ${per}, ${zone}, ${instant(storage.from)}, ${instant(storage.until)}, ${day(storage.from)}, ${day(storage.until)}, ${live}, CASE WHEN t.deleted_at IS NULL THEN 0 ELSE 1 END, ? FROM ${storage.table} t WHERE ${where} ON CONFLICT (object_type, record_id) DO UPDATE SET person_id = excluded.person_id, uses = excluded.uses, per = excluded.per, zone = excluded.zone, valid_from = excluded.valid_from, valid_until = excluded.valid_until, from_date = excluded.from_date, until_date = excluded.until_date, live = excluded.live, trashed = excluded.trashed, updated_at = excluded.updated_at`,
112
- [orgZone, now, ...target === "all" ? [] : [target.id]]
113
- ),
114
- CompiledQuery.raw(
115
- `UPDATE core_allowance_period SET uses = (SELECT a.uses FROM core_allowance a WHERE a.object_type = core_allowance_period.object_type AND a.record_id = core_allowance_period.record_id), updated_at = ? WHERE object_type = ? AND ends_at > ?${target === "all" ? "" : " AND record_id = ?"}`,
116
- [now, storage.object, now, ...target === "all" ? [] : [target.id]]
117
- )
118
- ];
119
- }
120
- function keyingChangeStatement(holder, previous, appliesFrom, now) {
121
- return CompiledQuery.raw(
122
- "UPDATE core_allowance SET prev_per = ?, prev_zone = ?, applies_from = ?, updated_at = ? WHERE object_type = ? AND record_id = ?",
123
- [previous.per, previous.zone, appliesFrom, now, holder.object, holder.id]
124
- );
125
- }
126
- function periodInsert(holder, period, zone, now) {
127
- return CompiledQuery.raw(
128
- "INSERT INTO core_allowance_period (object_type, record_id, period, per, zone, starts_at, ends_at, uses, used, updated_at) SELECT a.object_type, a.record_id, ?, ?, ?, ?, ?, a.uses, 0, ? FROM core_allowance a WHERE a.object_type = ? AND a.record_id = ? ON CONFLICT (object_type, record_id, period, zone) DO NOTHING",
129
- [period.key, period.per, zone, period.startsAt, period.endsAt, now, holder.object, holder.id]
130
- );
131
- }
132
- function spendStatements(request, now) {
133
- const id = request.id ?? newId("allowanceUse");
134
- const { holder, period, zone } = request;
135
- return {
136
- id,
137
- statements: [
138
- periodInsert(holder, period, zone, now),
139
- CompiledQuery.raw(
140
- "UPDATE core_allowance_period SET used = used + 1, updated_at = ? WHERE object_type = ? AND record_id = ? AND period = ? AND zone = ?",
141
- [now, holder.object, holder.id, period.key, zone]
142
- ),
143
- CompiledQuery.raw(
144
- "INSERT INTO core_allowance_use (id, object_type, record_id, period, zone, spender_type, spender_id, person_id, at, at_date, spent_at, spent_by, moved_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
145
- [
146
- id,
147
- holder.object,
148
- holder.id,
149
- period.key,
150
- zone,
151
- request.spender.object,
152
- request.spender.id,
153
- request.personId,
154
- request.at,
155
- request.atDate,
156
- now,
157
- request.by,
158
- request.movedFrom ?? null
159
- ]
160
- )
161
- ]
162
- };
163
- }
164
- function returnStatements(spender, by, now) {
165
- return [
166
- CompiledQuery.raw(
167
- "UPDATE core_allowance_period SET used = used - 1, updated_at = ? WHERE (object_type, record_id, period, zone) IN (SELECT object_type, record_id, period, zone FROM core_allowance_use WHERE spender_type = ? AND spender_id = ? AND returned_at IS NULL)",
168
- [now, spender.object, spender.id]
169
- ),
170
- CompiledQuery.raw(
171
- "UPDATE core_allowance_use SET returned_at = ?, returned_by = ? WHERE spender_type = ? AND spender_id = ? AND returned_at IS NULL",
172
- [now, by, spender.object, spender.id]
173
- )
174
- ];
175
- }
176
- function rekeyStatements(use, to, now) {
177
- const { holder } = use;
178
- return [
179
- periodInsert(holder, to.period, to.zone, now),
180
- CompiledQuery.raw(
181
- "UPDATE core_allowance_period SET used = used - 1, updated_at = ? WHERE object_type = ? AND record_id = ? AND period = ? AND zone = ?",
182
- [now, holder.object, holder.id, use.period, use.zone]
183
- ),
184
- CompiledQuery.raw(
185
- "UPDATE core_allowance_period SET used = used + 1, rekeyed = rekeyed + 1, updated_at = ? WHERE object_type = ? AND record_id = ? AND period = ? AND zone = ?",
186
- [now, holder.object, holder.id, to.period.key, to.zone]
187
- ),
188
- CompiledQuery.raw("UPDATE core_allowance_use SET period = ?, zone = ? WHERE id = ?", [
189
- to.period.key,
190
- to.zone,
191
- use.id
192
- ])
193
- ];
194
- }
195
- function dropAllowanceStatements(object, kind, now) {
196
- if (kind === "holder") {
197
- return [
198
- CompiledQuery.raw("DELETE FROM core_allowance_use WHERE object_type = ?", [object]),
199
- CompiledQuery.raw("DELETE FROM core_allowance_period WHERE object_type = ?", [object]),
200
- CompiledQuery.raw("DELETE FROM core_allowance WHERE object_type = ?", [object])
201
- ];
202
- }
203
- return [
204
- CompiledQuery.raw(
205
- "UPDATE core_allowance_period SET used = used - (SELECT count(*) FROM core_allowance_use u WHERE u.spender_type = ? AND u.returned_at IS NULL AND u.object_type = core_allowance_period.object_type AND u.record_id = core_allowance_period.record_id AND u.period = core_allowance_period.period AND u.zone = core_allowance_period.zone), updated_at = ? WHERE (object_type, record_id, period, zone) IN (SELECT object_type, record_id, period, zone FROM core_allowance_use WHERE spender_type = ? AND returned_at IS NULL)",
206
- [object, now, object]
207
- ),
208
- CompiledQuery.raw("DELETE FROM core_allowance_use WHERE spender_type = ?", [object])
209
- ];
210
- }
211
-
212
- export {
213
- periodOf,
214
- boundOf,
215
- termsSyncStatements,
216
- keyingChangeStatement,
217
- spendStatements,
218
- returnStatements,
219
- rekeyStatements,
220
- dropAllowanceStatements,
221
- armSeriesStatement,
222
- seriesVersion,
223
- guardStatement,
224
- occurrenceStatement,
225
- markEditedStatement,
226
- dropRecurringStatements
227
- };