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