@composable-os/cli 0.1.0-beta.7 → 0.1.0-beta.9
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-D6N77JGP.js +44 -0
- package/dist/{blocks-HVTAQ5W2.js → blocks-4CA4PP3P.js} +4 -4
- package/dist/{chunk-X6I2LWB3.js → chunk-2MLAPQU7.js} +1471 -359
- package/dist/{chunk-2S7375SC.js → chunk-3MIEYXRY.js} +3 -301
- package/dist/chunk-56A6RJIU.js +1040 -0
- package/dist/chunk-7CQGMVDO.js +63 -0
- package/dist/{chunk-STJZJIRA.js → chunk-7O4F3NU4.js} +1039 -1380
- package/dist/chunk-7U3OZLTK.js +1370 -0
- package/dist/{chunk-ZRWF6QZS.js → chunk-DU6OIFOU.js} +1 -0
- package/dist/chunk-E4WCYTCT.js +347 -0
- package/dist/{chunk-E5JLTLRM.js → chunk-GYTEW66E.js} +1 -1
- package/dist/chunk-LPD2VR5M.js +284 -0
- package/dist/chunk-NDKVIG23.js +2641 -0
- package/dist/chunk-NSSUOI3Z.js +333 -0
- package/dist/chunk-OV3OFYPI.js +746 -0
- package/dist/{chunk-2P4AZTFL.js → chunk-P6YZMS3F.js} +11 -5
- package/dist/{chunk-Y7PQ7NIL.js → chunk-RFJOPI42.js} +138 -14
- package/dist/{chunk-VL62IMBN.js → chunk-RXRD34QW.js} +10 -8
- package/dist/{chunk-BEKL3CA2.js → chunk-STBMGUTM.js} +7065 -4580
- package/dist/chunk-VTQNOQGA.js +150 -0
- package/dist/chunk-XSE37HK5.js +426 -0
- package/dist/{chunk-MINQ46RU.js → chunk-Z52IX5WL.js} +257 -844
- package/dist/chunk-ZSR5H4O7.js +552 -0
- package/dist/{cli-XHC6QBQW.js → cli-7A5XHYML.js} +16 -9
- package/dist/{cli-BRSACHSG.js → cli-T6MJM7TU.js} +20 -8
- package/dist/cli.js +4 -4
- package/dist/{client-repo-G55G4OLV.js → client-repo-PC4ISVEZ.js} +4 -4
- package/dist/create.js +4 -4
- package/dist/{fields-64BQJA62.js → fields-L24XAIOA.js} +13 -11
- package/dist/invoke-TLYT6CFI.js +33 -0
- package/dist/order-IKQBUFCV.js +19 -0
- package/dist/{person-AZFEPZOE.js → person-DXEOOH2A.js} +9 -5
- package/dist/plan-on-sale-LRCK5MJG.js +24 -0
- package/dist/platform/migrations/0510_video_and_file_media.sql +109 -0
- package/dist/platform/migrations/0516_order_tax.sql +63 -0
- package/dist/platform/migrations/0520_publish_requests.sql +20 -0
- package/dist/platform/migrations/0530_subscriptions.sql +173 -0
- package/dist/platform/migrations/0531_subscription_trials.sql +56 -0
- package/dist/platform/migrations/0532_subscription_offers.sql +80 -0
- package/dist/platform/migrations/0533_allowances.sql +262 -0
- package/dist/platform/migrations/0560_recurring.sql +75 -0
- package/dist/platform/sdk/allowance.ts +508 -0
- package/dist/platform/sdk/capacity.ts +89 -0
- package/dist/platform/sdk/contract.ts +97 -1
- package/dist/platform/sdk/document.ts +161 -14
- package/dist/platform/sdk/field-types.ts +5 -0
- package/dist/platform/sdk/index.ts +3 -0
- package/dist/platform/sdk/manifest.ts +206 -5
- package/dist/platform/sdk/media.ts +62 -0
- package/dist/platform/sdk/recurring.ts +314 -0
- package/dist/platform/sdk/rich-text.ts +52 -4
- package/dist/platform/sdk/sellable.ts +120 -0
- package/dist/platform/sdk/states.ts +162 -1
- package/dist/platform/sdk/unique.ts +81 -0
- package/dist/run-BMSZKTN3.js +648 -0
- package/dist/run-GMQBAV6H.js +309 -0
- package/dist/{run-4JNFLYXV.js → run-TNHMG5RI.js} +51 -390
- package/dist/src-7DXXGZG2.js +38 -0
- package/dist/{src-J27WXNLY.js → src-BDG7PERB.js} +73 -1
- package/dist/visibility-XSBZTO66.js +33 -0
- package/package.json +2 -2
- package/dist/chunk-MAXLUQKB.js +0 -1287
- package/dist/invoke-5SR5ZWW7.js +0 -26
- package/dist/src-SSVOBH6L.js +0 -31
|
@@ -0,0 +1,2641 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
addLocalDays,
|
|
4
|
+
callSubscriptionGatekeeper,
|
|
5
|
+
loadOrderCurrency,
|
|
6
|
+
localParts,
|
|
7
|
+
paymentsTarget,
|
|
8
|
+
realWallClock,
|
|
9
|
+
wallClockToIso,
|
|
10
|
+
zoneOffset
|
|
11
|
+
} from "./chunk-NSSUOI3Z.js";
|
|
12
|
+
import {
|
|
13
|
+
automationSyncStatements,
|
|
14
|
+
compileFilter,
|
|
15
|
+
filterSchema,
|
|
16
|
+
hasAccessSourceKind,
|
|
17
|
+
holdsAccess,
|
|
18
|
+
registerAccessSource,
|
|
19
|
+
runListQuery
|
|
20
|
+
} from "./chunk-56A6RJIU.js";
|
|
21
|
+
import {
|
|
22
|
+
CompiledQuery,
|
|
23
|
+
ORG_TIMEZONE_SETTING,
|
|
24
|
+
backfillCounters,
|
|
25
|
+
dropCapacityStatements,
|
|
26
|
+
loadGeneralSettings,
|
|
27
|
+
newId,
|
|
28
|
+
releaseAllClaimsStatements
|
|
29
|
+
} from "./chunk-OV3OFYPI.js";
|
|
30
|
+
import {
|
|
31
|
+
ConfigError,
|
|
32
|
+
ConflictError,
|
|
33
|
+
FIELD_TYPE_REGISTRY,
|
|
34
|
+
ForbiddenError,
|
|
35
|
+
NotFoundError,
|
|
36
|
+
OperationError,
|
|
37
|
+
ValidationError,
|
|
38
|
+
buildViews,
|
|
39
|
+
columnName,
|
|
40
|
+
coreFormulaFields,
|
|
41
|
+
formulaFromStorage,
|
|
42
|
+
holdsPermission,
|
|
43
|
+
ident,
|
|
44
|
+
isCoreTarget,
|
|
45
|
+
liveViewOf,
|
|
46
|
+
loadSchemaState,
|
|
47
|
+
objectTable,
|
|
48
|
+
objectView,
|
|
49
|
+
orgReader,
|
|
50
|
+
previewSource,
|
|
51
|
+
registryFieldName,
|
|
52
|
+
sideTable,
|
|
53
|
+
splitObjectName,
|
|
54
|
+
sql,
|
|
55
|
+
unknownObject,
|
|
56
|
+
viewColumnOf,
|
|
57
|
+
visibleObject,
|
|
58
|
+
visibleSource,
|
|
59
|
+
visibleTable
|
|
60
|
+
} from "./chunk-7O4F3NU4.js";
|
|
61
|
+
import {
|
|
62
|
+
getObject,
|
|
63
|
+
listObjects
|
|
64
|
+
} from "./chunk-3MIEYXRY.js";
|
|
65
|
+
import {
|
|
66
|
+
external_exports,
|
|
67
|
+
hostFilledFields,
|
|
68
|
+
isDocumentType,
|
|
69
|
+
isLosslessChange,
|
|
70
|
+
redactDocument,
|
|
71
|
+
spenderAllows,
|
|
72
|
+
spendsOnList,
|
|
73
|
+
validateManifest
|
|
74
|
+
} from "./chunk-2MLAPQU7.js";
|
|
75
|
+
|
|
76
|
+
// ../core/src/visibility/capacity.ts
|
|
77
|
+
var left = (places, held, taken) => places === null ? null : Math.max(places - held - taken, 0);
|
|
78
|
+
function capacityStatus(capacity, available) {
|
|
79
|
+
if (available === null) return "available";
|
|
80
|
+
if (available === 0) return "sold_out";
|
|
81
|
+
if (capacity.show === "low" && capacity.lowAt !== void 0 && available <= capacity.lowAt) {
|
|
82
|
+
return "low";
|
|
83
|
+
}
|
|
84
|
+
return "available";
|
|
85
|
+
}
|
|
86
|
+
function outsideView(object, id, available) {
|
|
87
|
+
const status = capacityStatus(object.capacity, available);
|
|
88
|
+
const base = { object: object.name, id, status };
|
|
89
|
+
switch (object.capacity.show) {
|
|
90
|
+
case "exact":
|
|
91
|
+
return { ...base, available };
|
|
92
|
+
case "low":
|
|
93
|
+
return status === "low" ? { ...base, available } : base;
|
|
94
|
+
default:
|
|
95
|
+
return base;
|
|
96
|
+
}
|
|
97
|
+
}
|
|
98
|
+
async function readableBy(reader, object, id) {
|
|
99
|
+
let source;
|
|
100
|
+
try {
|
|
101
|
+
source = visibleSource(reader, object);
|
|
102
|
+
} catch {
|
|
103
|
+
return false;
|
|
104
|
+
}
|
|
105
|
+
const row = await reader.db.selectFrom(source).select("id").where("id", "=", id).executeTakeFirst();
|
|
106
|
+
return Boolean(row);
|
|
107
|
+
}
|
|
108
|
+
async function readCapacity(reader, name, id) {
|
|
109
|
+
const object = getObject(name);
|
|
110
|
+
if (!object?.capacity) throw unknownObject(name);
|
|
111
|
+
const withCapacity = object;
|
|
112
|
+
const live = await orgReader(reader.db).db.selectFrom(visibleTable(orgReader(reader.db), object, "t")).select("t.deleted_at").where("t.id", "=", id).executeTakeFirst();
|
|
113
|
+
if (!live || live.deleted_at !== null) throw new NotFoundError(name, id);
|
|
114
|
+
if (reader.principal.kind !== "staff" && !await readableBy(reader, object, id)) {
|
|
115
|
+
throw new NotFoundError(name, id);
|
|
116
|
+
}
|
|
117
|
+
const row = await reader.db.selectFrom("core_capacity as c").leftJoin(
|
|
118
|
+
"core_capacity as p",
|
|
119
|
+
(join) => join.onRef("p.object_type", "=", "c.pool_object_type").onRef("p.record_id", "=", "c.pool_record_id")
|
|
120
|
+
).select([
|
|
121
|
+
"c.places",
|
|
122
|
+
"c.held",
|
|
123
|
+
"c.taken",
|
|
124
|
+
"c.pool_object_type",
|
|
125
|
+
"c.pool_record_id",
|
|
126
|
+
"p.places as pool_places",
|
|
127
|
+
"p.held as pool_held",
|
|
128
|
+
"p.taken as pool_taken"
|
|
129
|
+
]).where("c.object_type", "=", name).where("c.record_id", "=", id).executeTakeFirst();
|
|
130
|
+
const own = row ? left(row.places, row.held, row.taken) : null;
|
|
131
|
+
const pool = row?.pool_object_type && row.pool_record_id ? {
|
|
132
|
+
object: row.pool_object_type,
|
|
133
|
+
id: row.pool_record_id,
|
|
134
|
+
places: row.pool_places,
|
|
135
|
+
held: row.pool_held ?? 0,
|
|
136
|
+
taken: row.pool_taken ?? 0,
|
|
137
|
+
available: left(row.pool_places, row.pool_held ?? 0, row.pool_taken ?? 0)
|
|
138
|
+
} : null;
|
|
139
|
+
const available = own === null ? pool?.available ?? null : pool?.available == null ? own : Math.min(own, pool.available);
|
|
140
|
+
if (reader.principal.kind !== "staff") return outsideView(withCapacity, id, available);
|
|
141
|
+
return {
|
|
142
|
+
object: name,
|
|
143
|
+
id,
|
|
144
|
+
status: capacityStatus(object.capacity, available),
|
|
145
|
+
available,
|
|
146
|
+
places: row?.places ?? null,
|
|
147
|
+
held: row?.held ?? 0,
|
|
148
|
+
taken: row?.taken ?? 0,
|
|
149
|
+
show: object.capacity.show,
|
|
150
|
+
lowAt: object.capacity.lowAt ?? null,
|
|
151
|
+
pool
|
|
152
|
+
};
|
|
153
|
+
}
|
|
154
|
+
|
|
155
|
+
// ../core/src/visibility/records.ts
|
|
156
|
+
async function currencyOf(ctx, object) {
|
|
157
|
+
if (!getObject(object.name)?.sellable) return {};
|
|
158
|
+
return { currency: await loadOrderCurrency(ctx.db) };
|
|
159
|
+
}
|
|
160
|
+
function fieldValue(field, row) {
|
|
161
|
+
const column = viewColumnOf(field);
|
|
162
|
+
const raw2 = column ? row[column] ?? null : null;
|
|
163
|
+
if (!field.extension || !field.fieldType) return raw2;
|
|
164
|
+
const type = field.fieldType;
|
|
165
|
+
return type === "formula" ? formulaFromStorage(field.options?.resultType, raw2) : FIELD_TYPE_REGISTRY[type].fromStorage(raw2);
|
|
166
|
+
}
|
|
167
|
+
function toRecord(object, row, viewer, held = NONE_HELD) {
|
|
168
|
+
const outsider = viewer.principal.kind !== "staff";
|
|
169
|
+
const holder = held.has(String(row.id));
|
|
170
|
+
const values = {};
|
|
171
|
+
for (const field of object.fields) {
|
|
172
|
+
if (field.name === "id") continue;
|
|
173
|
+
const value = fieldValue(field, row);
|
|
174
|
+
const schema = field.options?.document?.schema;
|
|
175
|
+
values[field.name] = outsider && isDocumentType(field.fieldType) ? schema ? redactDocument(schema, value, { holder }) : null : value;
|
|
176
|
+
}
|
|
177
|
+
return { object: object.name, id: String(row.id), values };
|
|
178
|
+
}
|
|
179
|
+
var NONE_HELD = /* @__PURE__ */ new Set();
|
|
180
|
+
async function heldOf(ctx, object, rows) {
|
|
181
|
+
const definition = getObject(object.name) ?? object;
|
|
182
|
+
if (ctx.principal.kind === "staff" || !definition.access || !rows.length) return NONE_HELD;
|
|
183
|
+
if (!object.fields.some((f) => isDocumentType(f.fieldType))) return NONE_HELD;
|
|
184
|
+
return holdsAccess(
|
|
185
|
+
ctx,
|
|
186
|
+
definition,
|
|
187
|
+
rows.map((row) => String(row.id))
|
|
188
|
+
);
|
|
189
|
+
}
|
|
190
|
+
async function listVisible(ctx, object, input) {
|
|
191
|
+
const visible = visibleObject(ctx, object);
|
|
192
|
+
const page = await runListQuery(ctx, visible, input);
|
|
193
|
+
const held = await heldOf(ctx, visible, page.rows);
|
|
194
|
+
return {
|
|
195
|
+
items: page.rows.map((row) => toRecord(visible, row, ctx, held)),
|
|
196
|
+
nextCursor: page.nextCursor,
|
|
197
|
+
...await currencyOf(ctx, visible)
|
|
198
|
+
};
|
|
199
|
+
}
|
|
200
|
+
async function getVisible(ctx, object, id) {
|
|
201
|
+
const visible = visibleObject(ctx, object);
|
|
202
|
+
const row = await ctx.db.selectFrom(visibleSource(ctx, visible)).selectAll().where("id", "=", id).executeTakeFirst();
|
|
203
|
+
if (!row) throw new NotFoundError(visible.name, id);
|
|
204
|
+
const held = await heldOf(ctx, visible, [row]);
|
|
205
|
+
return {
|
|
206
|
+
...toRecord(visible, row, ctx, held),
|
|
207
|
+
...await currencyOf(ctx, visible)
|
|
208
|
+
};
|
|
209
|
+
}
|
|
210
|
+
async function previewVisible(ctx, object, id) {
|
|
211
|
+
const visible = visibleObject(ctx, object);
|
|
212
|
+
const row = await ctx.db.selectFrom(previewSource(object, id)).selectAll().executeTakeFirst();
|
|
213
|
+
return row ? toRecord(visible, row, ctx) : null;
|
|
214
|
+
}
|
|
215
|
+
var VISIBLE_COUNT_CAP = 1e4;
|
|
216
|
+
async function countVisible(ctx, object, filter) {
|
|
217
|
+
const visible = visibleObject(ctx, object);
|
|
218
|
+
const db = ctx.db;
|
|
219
|
+
let matching = db.selectFrom(visibleSource(ctx, visible)).select(sql`1`.as("one"));
|
|
220
|
+
if (filter) matching = matching.where(compileFilter(visible, filter, visible.source));
|
|
221
|
+
const row = await db.selectFrom(matching.limit(VISIBLE_COUNT_CAP + 1).as("matching")).select(sql`count(*)`.as("n")).executeTakeFirstOrThrow();
|
|
222
|
+
const n = Number(row.n);
|
|
223
|
+
return n > VISIBLE_COUNT_CAP ? { count: VISIBLE_COUNT_CAP, capped: true } : { count: n, capped: false };
|
|
224
|
+
}
|
|
225
|
+
function recordAccess(reader, writes) {
|
|
226
|
+
const none = () => {
|
|
227
|
+
throw new OperationError(
|
|
228
|
+
"internal",
|
|
229
|
+
"ctx.records writes are for a customer's call; staff use the record operations"
|
|
230
|
+
);
|
|
231
|
+
};
|
|
232
|
+
return {
|
|
233
|
+
list: (object, input = {}) => listVisible(reader, object, { ...input, limit: input.limit ?? 50 }),
|
|
234
|
+
get: (object, id) => getVisible(reader, object, id),
|
|
235
|
+
count: (object, filter) => countVisible(reader, object, filter),
|
|
236
|
+
capacity: (object, id) => readCapacity(reader, object, id),
|
|
237
|
+
create: writes?.create ?? none,
|
|
238
|
+
update: writes?.update ?? none
|
|
239
|
+
};
|
|
240
|
+
}
|
|
241
|
+
|
|
242
|
+
// ../core/src/allowance/check.ts
|
|
243
|
+
function allowanceHostIssues(m) {
|
|
244
|
+
const issues = [];
|
|
245
|
+
for (const [name, object] of Object.entries(m.objects)) {
|
|
246
|
+
const allowance = object.allowance;
|
|
247
|
+
if (!allowance) continue;
|
|
248
|
+
const ap = `objects.${name}.allowance`;
|
|
249
|
+
if ("holds" in allowance) {
|
|
250
|
+
spendsOnList(allowance.holds).forEach((target, i) => {
|
|
251
|
+
if (!target.object.includes(".") || target.object.startsWith(`${m.id}.`)) return;
|
|
252
|
+
const p = Array.isArray(allowance.holds.spendsOn) ? `${ap}.holds.spendsOn.${i}` : `${ap}.holds.spendsOn`;
|
|
253
|
+
const spender = getObject(target.object);
|
|
254
|
+
if (!spender) return;
|
|
255
|
+
const def = spender.allowance;
|
|
256
|
+
if (def?.kind !== "spender") {
|
|
257
|
+
issues.push({ path: `${p}.object`, message: `${target.object} does not spend uses` });
|
|
258
|
+
return;
|
|
259
|
+
}
|
|
260
|
+
const ext = target.object.split(".")[0];
|
|
261
|
+
if (!spenderAllows({ paidBy: def.paidBy }, ext, `${m.id}.${name}`)) {
|
|
262
|
+
issues.push({
|
|
263
|
+
path: `${p}.object`,
|
|
264
|
+
message: `${target.object} does not let ${m.id}.${name} pay for it: its paidBy must list ${m.id} or ${m.id}.${name}`
|
|
265
|
+
});
|
|
266
|
+
}
|
|
267
|
+
const filled = new Set(hostFilledFields({ copy: def.copy, local: def.local }));
|
|
268
|
+
(target.when ?? []).forEach((clause, j) => {
|
|
269
|
+
if (!filled.has(clause.field)) {
|
|
270
|
+
issues.push({
|
|
271
|
+
path: `${p}.when.${j}.field`,
|
|
272
|
+
message: `"${clause.field}" must be a field ${target.object}'s host fills (its copy or local), so no caller sets what pays for it`
|
|
273
|
+
});
|
|
274
|
+
}
|
|
275
|
+
});
|
|
276
|
+
});
|
|
277
|
+
continue;
|
|
278
|
+
}
|
|
279
|
+
const s = allowance.spends;
|
|
280
|
+
const hops = [
|
|
281
|
+
...s.at?.includes(".") ? [[`${ap}.spends.at`, s.at, "datetime"]] : [],
|
|
282
|
+
...s.local?.zone?.includes(".") ? [[`${ap}.spends.local.zone`, s.local.zone, "timezone"]] : [],
|
|
283
|
+
...Object.entries(s.copy ?? {}).map(
|
|
284
|
+
([local, source]) => [`${ap}.spends.copy.${local}`, source, null]
|
|
285
|
+
)
|
|
286
|
+
];
|
|
287
|
+
for (const [p, path, type] of hops) {
|
|
288
|
+
const [rel, target] = path.split(".");
|
|
289
|
+
const to = object.fields[rel]?.type === "relation" ? object.fields[rel]?.to : void 0;
|
|
290
|
+
if (!to || to.startsWith(`${m.id}.`)) continue;
|
|
291
|
+
const other = getObject(to);
|
|
292
|
+
if (!other) {
|
|
293
|
+
issues.push({ path: p, message: `${to} is not installed, so "${path}" cannot be read` });
|
|
294
|
+
continue;
|
|
295
|
+
}
|
|
296
|
+
const field = other.fields.find((f) => f.name === target);
|
|
297
|
+
if (!field) {
|
|
298
|
+
issues.push({ path: p, message: `"${target}" is not a field of ${to}` });
|
|
299
|
+
continue;
|
|
300
|
+
}
|
|
301
|
+
const actual = field.fieldType ?? field.type;
|
|
302
|
+
if (type && actual !== type) {
|
|
303
|
+
issues.push({ path: p, message: `"${path}" must be a ${type} field (it is ${actual})` });
|
|
304
|
+
}
|
|
305
|
+
}
|
|
306
|
+
}
|
|
307
|
+
return issues;
|
|
308
|
+
}
|
|
309
|
+
|
|
310
|
+
// ../core/src/dashboards/spec.ts
|
|
311
|
+
var WIDGET_TYPES = [
|
|
312
|
+
"kpi",
|
|
313
|
+
"bar",
|
|
314
|
+
"line",
|
|
315
|
+
"donut",
|
|
316
|
+
"funnel",
|
|
317
|
+
"table",
|
|
318
|
+
"leaderboard",
|
|
319
|
+
"markdown"
|
|
320
|
+
];
|
|
321
|
+
var DATA_WIDGET_TYPES = WIDGET_TYPES.filter(
|
|
322
|
+
(t) => t !== "markdown"
|
|
323
|
+
);
|
|
324
|
+
var DATE_PRESETS = [
|
|
325
|
+
"all_time",
|
|
326
|
+
"today",
|
|
327
|
+
"last_7_days",
|
|
328
|
+
"last_30_days",
|
|
329
|
+
"last_90_days",
|
|
330
|
+
"last_365_days",
|
|
331
|
+
"this_month",
|
|
332
|
+
"last_month",
|
|
333
|
+
"this_quarter",
|
|
334
|
+
"this_year"
|
|
335
|
+
];
|
|
336
|
+
var paramName = external_exports.string().regex(/^[a-z][a-z0-9_]{0,30}$/, "lowercase letters, digits and _; starts with a letter");
|
|
337
|
+
var filterBase = {
|
|
338
|
+
id: paramName.describe(
|
|
339
|
+
"The filter's id, which names its SQL parameter(s): a dateRange `date` binds :date_from and :date_to; any other filter `owner` binds :owner"
|
|
340
|
+
),
|
|
341
|
+
label: external_exports.string().min(1).max(100)
|
|
342
|
+
};
|
|
343
|
+
var dashboardFilterSchema = external_exports.discriminatedUnion("type", [
|
|
344
|
+
external_exports.object({
|
|
345
|
+
type: external_exports.literal("dateRange"),
|
|
346
|
+
...filterBase,
|
|
347
|
+
default: external_exports.enum(DATE_PRESETS).default("last_90_days")
|
|
348
|
+
}),
|
|
349
|
+
external_exports.object({
|
|
350
|
+
type: external_exports.literal("user"),
|
|
351
|
+
...filterBase,
|
|
352
|
+
default: external_exports.enum(["me", "anyone"]).default("anyone")
|
|
353
|
+
}),
|
|
354
|
+
external_exports.object({
|
|
355
|
+
type: external_exports.literal("select"),
|
|
356
|
+
...filterBase,
|
|
357
|
+
options: external_exports.array(external_exports.object({ value: external_exports.string().max(200), label: external_exports.string().max(200) })).min(1).max(100),
|
|
358
|
+
default: external_exports.string().max(200).nullish()
|
|
359
|
+
}),
|
|
360
|
+
external_exports.object({
|
|
361
|
+
type: external_exports.literal("field"),
|
|
362
|
+
...filterBase,
|
|
363
|
+
object: external_exports.string().min(1).max(80).describe("Object whose field supplies the choices"),
|
|
364
|
+
field: external_exports.string().min(1).max(80).describe("A select field (choices) or any text field"),
|
|
365
|
+
default: external_exports.string().max(200).nullish()
|
|
366
|
+
}),
|
|
367
|
+
external_exports.object({
|
|
368
|
+
type: external_exports.literal("text"),
|
|
369
|
+
...filterBase,
|
|
370
|
+
default: external_exports.string().max(200).nullish()
|
|
371
|
+
})
|
|
372
|
+
]);
|
|
373
|
+
var filterValueSchema = external_exports.union([
|
|
374
|
+
external_exports.enum(DATE_PRESETS),
|
|
375
|
+
external_exports.object({
|
|
376
|
+
from: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/),
|
|
377
|
+
to: external_exports.string().regex(/^\d{4}-\d{2}-\d{2}$/)
|
|
378
|
+
}),
|
|
379
|
+
external_exports.string().max(200),
|
|
380
|
+
external_exports.null()
|
|
381
|
+
]);
|
|
382
|
+
var filterValuesSchema = external_exports.record(external_exports.string().max(31), filterValueSchema).default({}).describe(
|
|
383
|
+
"Dashboard filter values by filter id: a date preset or { from, to } (YYYY-MM-DD, inclusive) for dateRange filters, a user id / 'me' / null for user filters, a value or null otherwise"
|
|
384
|
+
);
|
|
385
|
+
var widgetMappingSchema = external_exports.object({
|
|
386
|
+
x: external_exports.string().max(80).optional().describe("Category or time column (bar, line, funnel)"),
|
|
387
|
+
y: external_exports.union([external_exports.string().max(80), external_exports.array(external_exports.string().max(80)).min(1).max(8)]).optional().describe("Value column(s) (bar, line)"),
|
|
388
|
+
series: external_exports.string().max(80).optional().describe("A column whose values split rows into series (long format, bar/line)"),
|
|
389
|
+
label: external_exports.string().max(80).optional().describe("Segment or row label column (donut, leaderboard)"),
|
|
390
|
+
value: external_exports.string().max(80).optional().describe("Value column (kpi, donut, funnel, leaderboard)"),
|
|
391
|
+
columns: external_exports.array(external_exports.string().max(80)).max(20).optional().describe("Columns shown (table)")
|
|
392
|
+
}).default({});
|
|
393
|
+
var widgetOptionsSchema = external_exports.object({
|
|
394
|
+
orientation: external_exports.enum(["vertical", "horizontal"]).optional().describe("bar: columns or bars"),
|
|
395
|
+
stacked: external_exports.boolean().optional(),
|
|
396
|
+
area: external_exports.boolean().optional().describe("line: fill as an area chart"),
|
|
397
|
+
pie: external_exports.boolean().optional().describe("donut: a full pie instead of a ring"),
|
|
398
|
+
format: external_exports.enum(["number", "currency", "percent"]).optional(),
|
|
399
|
+
currency: external_exports.string().regex(/^[A-Z]{3}$/).optional(),
|
|
400
|
+
compare: external_exports.boolean().optional().describe("kpi: compare with the previous period of the date filter (default true)"),
|
|
401
|
+
limit: external_exports.number().int().min(1).max(100).optional().describe("table/leaderboard: top N rows")
|
|
402
|
+
}).default({});
|
|
403
|
+
var clickThroughSchema = external_exports.object({
|
|
404
|
+
object: external_exports.string().min(1).max(80).describe("The object whose list opens"),
|
|
405
|
+
objectColumn: external_exports.string().max(80).nullish().describe("A result column naming the object per row, when rows mix objects"),
|
|
406
|
+
filter: filterSchema.nullish()
|
|
407
|
+
});
|
|
408
|
+
var widgetLayoutSchema = external_exports.object({
|
|
409
|
+
w: external_exports.number().int().min(1).max(12).default(6).describe("Width in grid columns (of 12)"),
|
|
410
|
+
h: external_exports.number().int().min(1).max(8).default(2).describe("Height in grid rows (about 9rem each)")
|
|
411
|
+
}).default({ w: 6, h: 2 });
|
|
412
|
+
var widgetSpecSchema = external_exports.object({
|
|
413
|
+
id: external_exports.string().regex(/^[a-z0-9][a-z0-9_-]{0,40}$/).describe("Stable id within the dashboard, e.g. people-added"),
|
|
414
|
+
type: external_exports.enum(WIDGET_TYPES),
|
|
415
|
+
title: external_exports.string().min(1).max(200),
|
|
416
|
+
description: external_exports.string().max(1e3).nullish(),
|
|
417
|
+
sql: external_exports.string().max(2e4).nullish().describe(
|
|
418
|
+
"Data widgets: one read-only SELECT over rec_* views. Use named params for filters (:date_from, :date_to, :owner, \u2026) and the system params :now, :today and :me"
|
|
419
|
+
),
|
|
420
|
+
markdown: external_exports.string().max(2e4).nullish().describe("Markdown widgets: the text"),
|
|
421
|
+
mapping: widgetMappingSchema,
|
|
422
|
+
options: widgetOptionsSchema,
|
|
423
|
+
clickThrough: clickThroughSchema.nullish(),
|
|
424
|
+
layout: widgetLayoutSchema
|
|
425
|
+
}).superRefine((widget, ctx) => {
|
|
426
|
+
if (widget.type === "markdown") {
|
|
427
|
+
if (!widget.markdown?.trim()) {
|
|
428
|
+
ctx.addIssue({ code: "custom", path: ["markdown"], message: "markdown widgets need text" });
|
|
429
|
+
}
|
|
430
|
+
} else if (!widget.sql?.trim()) {
|
|
431
|
+
ctx.addIssue({ code: "custom", path: ["sql"], message: `${widget.type} widgets need sql` });
|
|
432
|
+
}
|
|
433
|
+
});
|
|
434
|
+
var dashboardSpecSchema = external_exports.object({
|
|
435
|
+
filters: external_exports.array(dashboardFilterSchema).max(8).default([]),
|
|
436
|
+
widgets: external_exports.array(widgetSpecSchema).max(30).default([])
|
|
437
|
+
});
|
|
438
|
+
var SYSTEM_PARAMS = {
|
|
439
|
+
now: "The current time (ISO-8601 UTC, to the minute)",
|
|
440
|
+
today: "Today's date (YYYY-MM-DD, UTC)",
|
|
441
|
+
me: "The id of the user viewing the dashboard",
|
|
442
|
+
record_id: "On a record tab or panel: the record's id (null elsewhere)"
|
|
443
|
+
};
|
|
444
|
+
function filterParamNames(filters) {
|
|
445
|
+
return filters.flatMap((f) => f.type === "dateRange" ? [`${f.id}_from`, `${f.id}_to`] : [f.id]);
|
|
446
|
+
}
|
|
447
|
+
function allowedParamNames(filters) {
|
|
448
|
+
return [...Object.keys(SYSTEM_PARAMS), ...filterParamNames(filters)];
|
|
449
|
+
}
|
|
450
|
+
|
|
451
|
+
// ../core/src/subscriptions/trial.ts
|
|
452
|
+
var TRIAL_HOLD_AFTER_EXPIRY_MS = 15 * 6e4;
|
|
453
|
+
var NO_TRIAL_REASONS = [
|
|
454
|
+
"sign_in",
|
|
455
|
+
"used",
|
|
456
|
+
"permission",
|
|
457
|
+
"held",
|
|
458
|
+
"unconfirmed",
|
|
459
|
+
"continuation"
|
|
460
|
+
];
|
|
461
|
+
async function trialUsed(ctx, holderPersonId, planObject) {
|
|
462
|
+
const held = await ctx.db.selectFrom("core_subscription_trial").select("checkout_id").where("holder_person_id", "=", holderPersonId).where("plan_object", "=", planObject).where("used_at", "is not", null).executeTakeFirst();
|
|
463
|
+
if (held) return true;
|
|
464
|
+
const had = await ctx.db.selectFrom("core_subscription as s").innerJoin("core_subscription_checkout as c", "c.id", "s.id").select("s.id").where("s.holder_person_id", "=", holderPersonId).where("s.plan_object", "=", planObject).where("s.trial_end", "is not", null).where("c.trial_days", "is not", null).executeTakeFirst();
|
|
465
|
+
return Boolean(had);
|
|
466
|
+
}
|
|
467
|
+
async function hasContinuation(ctx, holderPersonId, planObject) {
|
|
468
|
+
const open = await ctx.db.selectFrom("core_subscription_offer").select("id").where("person_id", "=", holderPersonId).where("plan_object", "=", planObject).where("subscription_id", "is", null).where("withdrawn_at", "is", null).where("free_until", ">", ctx.now).executeTakeFirst();
|
|
469
|
+
if (open) return true;
|
|
470
|
+
const running = await ctx.db.selectFrom("core_subscription as s").innerJoin("core_subscription_checkout as c", "c.id", "s.id").select("s.id").where("s.holder_person_id", "=", holderPersonId).where("s.plan_object", "=", planObject).where("c.offer_id", "is not", null).where("s.state", "not in", ["ended", "expired"]).executeTakeFirst();
|
|
471
|
+
return Boolean(running);
|
|
472
|
+
}
|
|
473
|
+
async function pageStatus(ctx, target, ref) {
|
|
474
|
+
try {
|
|
475
|
+
const result = await callSubscriptionGatekeeper(
|
|
476
|
+
ctx.integrations,
|
|
477
|
+
target,
|
|
478
|
+
"getSubscriptionCheckout",
|
|
479
|
+
ref
|
|
480
|
+
);
|
|
481
|
+
const status = result.value?.status;
|
|
482
|
+
return status === "open" || status === "complete" || status === "expired" ? status : null;
|
|
483
|
+
} catch {
|
|
484
|
+
return null;
|
|
485
|
+
}
|
|
486
|
+
}
|
|
487
|
+
async function decideTrial(ctx, start, trialDays) {
|
|
488
|
+
if (!trialDays || trialDays <= 0) return { give: false, reason: null };
|
|
489
|
+
if (start.allowed === "guest") return { give: false, reason: "sign_in" };
|
|
490
|
+
if (start.allowed === "no_permission") return { give: false, reason: "permission" };
|
|
491
|
+
if (await trialUsed(ctx, start.holderPersonId, start.planObject)) {
|
|
492
|
+
return { give: false, reason: "used" };
|
|
493
|
+
}
|
|
494
|
+
if (await hasContinuation(ctx, start.holderPersonId, start.planObject)) {
|
|
495
|
+
return { give: false, reason: "continuation" };
|
|
496
|
+
}
|
|
497
|
+
const pending = await ctx.db.selectFrom("core_subscription_trial").selectAll().where("holder_person_id", "=", start.holderPersonId).where("plan_object", "=", start.planObject).where("used_at", "is", null).where("released_at", "is", null).orderBy("created_at", "desc").execute();
|
|
498
|
+
let held = null;
|
|
499
|
+
let blocked = null;
|
|
500
|
+
for (const row of pending) {
|
|
501
|
+
const status = await pageStatus(ctx, start.target, row.checkout_ref);
|
|
502
|
+
if (status === "complete") {
|
|
503
|
+
ctx.write(
|
|
504
|
+
ctx.db.updateTable("core_subscription_trial").set({ used_at: ctx.now }).where("checkout_id", "=", row.checkout_id).where("used_at", "is", null)
|
|
505
|
+
);
|
|
506
|
+
return { give: false, reason: "used" };
|
|
507
|
+
}
|
|
508
|
+
if (status === "expired") {
|
|
509
|
+
ctx.write(
|
|
510
|
+
ctx.db.updateTable("core_subscription_trial").set({ released_at: ctx.now }).where("checkout_id", "=", row.checkout_id).where("used_at", "is", null).where("released_at", "is", null)
|
|
511
|
+
);
|
|
512
|
+
continue;
|
|
513
|
+
}
|
|
514
|
+
if (status === null) {
|
|
515
|
+
blocked = "unconfirmed";
|
|
516
|
+
continue;
|
|
517
|
+
}
|
|
518
|
+
const expiresAt = new Date(
|
|
519
|
+
Date.parse(row.held_until) - TRIAL_HOLD_AFTER_EXPIRY_MS
|
|
520
|
+
).toISOString();
|
|
521
|
+
if (!held && row.opened_by === start.caller && row.plan_id === start.planId) {
|
|
522
|
+
held = {
|
|
523
|
+
checkoutId: row.checkout_id,
|
|
524
|
+
url: row.url,
|
|
525
|
+
expiresAt,
|
|
526
|
+
amount: row.amount,
|
|
527
|
+
trialDays: row.trial_days
|
|
528
|
+
};
|
|
529
|
+
} else if (!blocked) {
|
|
530
|
+
blocked = "held";
|
|
531
|
+
}
|
|
532
|
+
}
|
|
533
|
+
if (held) return { give: false, reason: null, open: held };
|
|
534
|
+
if (blocked) return { give: false, reason: blocked };
|
|
535
|
+
return { give: true };
|
|
536
|
+
}
|
|
537
|
+
function readableInstant(value) {
|
|
538
|
+
if (typeof value !== "string") return null;
|
|
539
|
+
const at = Date.parse(value);
|
|
540
|
+
return Number.isNaN(at) ? null : new Date(at).toISOString();
|
|
541
|
+
}
|
|
542
|
+
function holdTrialStatement(ctx, hold) {
|
|
543
|
+
const expires = readableInstant(hold.expiresAt) ?? new Date(Date.parse(ctx.now) + 24 * 36e5).toISOString();
|
|
544
|
+
return ctx.db.insertInto("core_subscription_trial").values({
|
|
545
|
+
checkout_id: hold.checkoutId,
|
|
546
|
+
holder_person_id: hold.holderPersonId,
|
|
547
|
+
plan_object: hold.planObject,
|
|
548
|
+
plan_id: hold.planId,
|
|
549
|
+
url: hold.url,
|
|
550
|
+
checkout_ref: hold.checkoutRef,
|
|
551
|
+
opened_by: hold.openedBy,
|
|
552
|
+
amount: hold.amount,
|
|
553
|
+
trial_days: hold.trialDays,
|
|
554
|
+
held_until: new Date(Date.parse(expires) + TRIAL_HOLD_AFTER_EXPIRY_MS).toISOString(),
|
|
555
|
+
created_at: ctx.now
|
|
556
|
+
});
|
|
557
|
+
}
|
|
558
|
+
async function useTrial(ctx, row) {
|
|
559
|
+
if (!row.trial_end || !row.holder_person_id) return { second: false };
|
|
560
|
+
const checkout = await ctx.db.selectFrom("core_subscription_checkout").select("trial_days").where("id", "=", row.id).executeTakeFirst();
|
|
561
|
+
if (!checkout?.trial_days) return { second: false };
|
|
562
|
+
const mine = await ctx.db.selectFrom("core_subscription_trial").select(["used_at"]).where("checkout_id", "=", row.id).executeTakeFirst();
|
|
563
|
+
if (mine?.used_at) return { second: false };
|
|
564
|
+
const before = await ctx.db.selectFrom("core_subscription_trial").select("checkout_id").where("holder_person_id", "=", row.holder_person_id).where("plan_object", "=", row.plan_object).where("used_at", "is not", null).where("checkout_id", "!=", row.id).executeTakeFirst();
|
|
565
|
+
const otherSubscription = await ctx.db.selectFrom("core_subscription as s").innerJoin("core_subscription_checkout as c", "c.id", "s.id").select("s.id").where("s.holder_person_id", "=", row.holder_person_id).where("s.plan_object", "=", row.plan_object).where("s.trial_end", "is not", null).where("c.trial_days", "is not", null).where("s.id", "!=", row.id).executeTakeFirst();
|
|
566
|
+
if (mine) {
|
|
567
|
+
ctx.write(
|
|
568
|
+
ctx.db.updateTable("core_subscription_trial").set({ used_at: ctx.now }).where("checkout_id", "=", row.id).where("used_at", "is", null)
|
|
569
|
+
);
|
|
570
|
+
}
|
|
571
|
+
return { second: Boolean(before || otherSubscription) };
|
|
572
|
+
}
|
|
573
|
+
|
|
574
|
+
// ../core/src/subscriptions/offers.ts
|
|
575
|
+
var OFFER_MIN_FREE_MS = 48 * 36e5 + 15 * 6e4;
|
|
576
|
+
var OFFER_IMPORT_MAX = 50;
|
|
577
|
+
var OFFER_STATUSES = ["open", "taken", "expired", "withdrawn"];
|
|
578
|
+
var OFFER_IMPORT_OUTCOMES = [
|
|
579
|
+
"created",
|
|
580
|
+
"updated",
|
|
581
|
+
"unchanged",
|
|
582
|
+
"unmatched",
|
|
583
|
+
"several_people",
|
|
584
|
+
"invalid",
|
|
585
|
+
"conflict"
|
|
586
|
+
];
|
|
587
|
+
function offerStatus(row, now) {
|
|
588
|
+
if (row.subscription_id) return "taken";
|
|
589
|
+
if (row.withdrawn_at) return "withdrawn";
|
|
590
|
+
return row.free_until <= now ? "expired" : "open";
|
|
591
|
+
}
|
|
592
|
+
function requireManage(ctx) {
|
|
593
|
+
if (!holdsPermission(ctx.user, ctx.permissionGrants, "subscriptions:manage")) {
|
|
594
|
+
throw new ForbiddenError("The continuation offers report needs subscriptions:manage", {
|
|
595
|
+
permission: "subscriptions:manage"
|
|
596
|
+
});
|
|
597
|
+
}
|
|
598
|
+
}
|
|
599
|
+
async function heldPages(ctx, rows) {
|
|
600
|
+
const out = /* @__PURE__ */ new Map();
|
|
601
|
+
const held = rows.filter((r) => r.checkout_ref && !r.subscription_id);
|
|
602
|
+
if (!held.length) return out;
|
|
603
|
+
let target = null;
|
|
604
|
+
try {
|
|
605
|
+
target = await paymentsTarget(ctx.db);
|
|
606
|
+
} catch {
|
|
607
|
+
target = null;
|
|
608
|
+
}
|
|
609
|
+
for (const r of held) {
|
|
610
|
+
out.set(r.id, target ? await pageStatus(ctx, target, r.checkout_ref) : null);
|
|
611
|
+
}
|
|
612
|
+
return out;
|
|
613
|
+
}
|
|
614
|
+
function releaseStatement(ctx, row, version) {
|
|
615
|
+
return ctx.db.updateTable("core_subscription_offer").set({
|
|
616
|
+
checkout_id: null,
|
|
617
|
+
checkout_ref: null,
|
|
618
|
+
checkout_url: null,
|
|
619
|
+
held_until: null,
|
|
620
|
+
version
|
|
621
|
+
}).where("id", "=", row.id).where("checkout_id", "=", row.checkout_id);
|
|
622
|
+
}
|
|
623
|
+
async function offerPlan(records, planObject, planId) {
|
|
624
|
+
try {
|
|
625
|
+
await records.get(planObject, planId);
|
|
626
|
+
return { planId };
|
|
627
|
+
} catch (error) {
|
|
628
|
+
if (error.code !== "not_found") throw error;
|
|
629
|
+
}
|
|
630
|
+
const live = await records.list(planObject, { limit: 2 });
|
|
631
|
+
return live.items.length === 1 ? { planId: live.items[0].id } : { askUs: true };
|
|
632
|
+
}
|
|
633
|
+
var MOMENT = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2})(?::(\d{2})(\.\d+)?)?(Z|([+-])(\d{2}):(\d{2}))$/;
|
|
634
|
+
function paidUpMoment(text, timeZone) {
|
|
635
|
+
const value = text.trim();
|
|
636
|
+
const date = /^(\d{4})-(\d{2})-(\d{2})$/.exec(value);
|
|
637
|
+
if (date) {
|
|
638
|
+
const [y2, m2, d2] = [Number(date[1]), Number(date[2]), Number(date[3])];
|
|
639
|
+
if (!realWallClock(y2, m2, d2)) return null;
|
|
640
|
+
const wall = Date.UTC(y2, m2 - 1, d2);
|
|
641
|
+
let at2 = wall - zoneOffset(wall, timeZone);
|
|
642
|
+
at2 = wall - zoneOffset(at2, timeZone);
|
|
643
|
+
return new Date(at2).toISOString();
|
|
644
|
+
}
|
|
645
|
+
const moment = MOMENT.exec(value);
|
|
646
|
+
if (!moment) return null;
|
|
647
|
+
const [y, m, d, h, mi] = [1, 2, 3, 4, 5].map((i) => Number(moment[i]));
|
|
648
|
+
const s = moment[6] ? Number(moment[6]) : 0;
|
|
649
|
+
if (!realWallClock(y, m, d, h, mi, s)) return null;
|
|
650
|
+
let offset = 0;
|
|
651
|
+
if (moment[8] !== "Z") {
|
|
652
|
+
const [oh, om] = [Number(moment[10]), Number(moment[11])];
|
|
653
|
+
if (oh > 14 || om > 59) return null;
|
|
654
|
+
offset = (moment[9] === "-" ? -1 : 1) * (oh * 60 + om) * 6e4;
|
|
655
|
+
}
|
|
656
|
+
const fraction = moment[7] ? Math.floor(Number(moment[7]) * 1e3) : 0;
|
|
657
|
+
const at = Date.UTC(y, m - 1, d, h, mi, s) + fraction - offset;
|
|
658
|
+
return new Date(at).toISOString();
|
|
659
|
+
}
|
|
660
|
+
var MAX_YEARS_AHEAD = 2;
|
|
661
|
+
async function importOffers(ctx, input) {
|
|
662
|
+
const object = getObject(input.plan.object);
|
|
663
|
+
if (!object?.sellable?.recurring) {
|
|
664
|
+
throw new ValidationError(`${input.plan.object} is not a plan (an object sold every period)`, {
|
|
665
|
+
field: "plan",
|
|
666
|
+
rule: "not_a_plan"
|
|
667
|
+
});
|
|
668
|
+
}
|
|
669
|
+
await ctx.records.get(input.plan.object, input.plan.id);
|
|
670
|
+
if (input.invite && !holdsPermission(ctx.user, ctx.permissionGrants, "users:manage")) {
|
|
671
|
+
throw new ForbiddenError(
|
|
672
|
+
"Inviting the addresses to sign in needs the users:manage permission (customer.invite's)",
|
|
673
|
+
{ field: "invite" }
|
|
674
|
+
);
|
|
675
|
+
}
|
|
676
|
+
const { timezone } = await loadGeneralSettings(ctx.db);
|
|
677
|
+
const { normaliseCustomerEmail, inviteCustomerStatement } = await import("./accounts-D6N77JGP.js");
|
|
678
|
+
const addresses = input.rows.map((r) => normaliseCustomerEmail(r.email));
|
|
679
|
+
const valid = [...new Set(addresses.filter((a) => a !== null))];
|
|
680
|
+
const owners = /* @__PURE__ */ new Map();
|
|
681
|
+
const existing = /* @__PURE__ */ new Map();
|
|
682
|
+
const withdrawn = /* @__PURE__ */ new Map();
|
|
683
|
+
const accounts = /* @__PURE__ */ new Set();
|
|
684
|
+
const invites = /* @__PURE__ */ new Set();
|
|
685
|
+
if (valid.length) {
|
|
686
|
+
const people = await ctx.db.selectFrom("core_person_emails as e").innerJoin("core_person as p", "p.id", "e.person_id").select(["e.email", "e.person_id"]).where("e.email", "in", valid).where("e.live", "=", 1).where("p.deleted_at", "is", null).execute();
|
|
687
|
+
for (const p of people) {
|
|
688
|
+
owners.set(p.email, (owners.get(p.email) ?? /* @__PURE__ */ new Set()).add(p.person_id));
|
|
689
|
+
}
|
|
690
|
+
for (const row of await ctx.db.selectFrom("core_subscription_offer").selectAll().where("plan_object", "=", input.plan.object).where("email", "in", valid).orderBy("created_at").execute()) {
|
|
691
|
+
if (row.withdrawn_at) withdrawn.set(row.email, row);
|
|
692
|
+
else existing.set(row.email, row);
|
|
693
|
+
}
|
|
694
|
+
for (const a of await ctx.db.selectFrom("core_customer").select("email").where("email", "in", valid).execute()) {
|
|
695
|
+
accounts.add(a.email);
|
|
696
|
+
}
|
|
697
|
+
for (const i of await ctx.db.selectFrom("core_customer_invite").select("email").where("email", "in", valid).execute()) {
|
|
698
|
+
invites.add(i.email);
|
|
699
|
+
}
|
|
700
|
+
}
|
|
701
|
+
const pages = await heldPages(ctx, [...existing.values()]);
|
|
702
|
+
const latest = new Date(Date.parse(ctx.now) + MAX_YEARS_AHEAD * 365 * 864e5).toISOString();
|
|
703
|
+
const seen = /* @__PURE__ */ new Set();
|
|
704
|
+
const results = [];
|
|
705
|
+
for (const [index, row] of input.rows.entries()) {
|
|
706
|
+
const email = addresses[index] ?? null;
|
|
707
|
+
const result = (outcome2, extra = {}) => ({
|
|
708
|
+
email: email ?? row.email,
|
|
709
|
+
outcome: outcome2,
|
|
710
|
+
offerId: null,
|
|
711
|
+
personId: null,
|
|
712
|
+
freeUntil: null,
|
|
713
|
+
note: null,
|
|
714
|
+
signIn: null,
|
|
715
|
+
...extra
|
|
716
|
+
});
|
|
717
|
+
if (!email) {
|
|
718
|
+
results.push(result("invalid", { note: "not an email address" }));
|
|
719
|
+
continue;
|
|
720
|
+
}
|
|
721
|
+
if (seen.has(email)) {
|
|
722
|
+
results.push(result("invalid", { note: "twice" }));
|
|
723
|
+
continue;
|
|
724
|
+
}
|
|
725
|
+
seen.add(email);
|
|
726
|
+
const freeUntil = paidUpMoment(row.freeUntil, timezone);
|
|
727
|
+
if (!freeUntil) {
|
|
728
|
+
results.push(
|
|
729
|
+
result("invalid", {
|
|
730
|
+
note: "the paid-up date is not a real date (YYYY-MM-DD) or moment with its offset"
|
|
731
|
+
})
|
|
732
|
+
);
|
|
733
|
+
continue;
|
|
734
|
+
}
|
|
735
|
+
if (freeUntil > latest) {
|
|
736
|
+
results.push(
|
|
737
|
+
result("invalid", {
|
|
738
|
+
note: `the paid-up date is more than ${MAX_YEARS_AHEAD} years away`,
|
|
739
|
+
freeUntil
|
|
740
|
+
})
|
|
741
|
+
);
|
|
742
|
+
continue;
|
|
743
|
+
}
|
|
744
|
+
const reference = row.reference?.trim() ? row.reference.trim().slice(0, 200) : null;
|
|
745
|
+
const people = [...owners.get(email) ?? []];
|
|
746
|
+
if (people.length === 0) {
|
|
747
|
+
results.push(result("unmatched", { freeUntil, note: "no person has this address" }));
|
|
748
|
+
continue;
|
|
749
|
+
}
|
|
750
|
+
if (people.length > 1) {
|
|
751
|
+
results.push(result("several_people", { freeUntil, note: "merge them first" }));
|
|
752
|
+
continue;
|
|
753
|
+
}
|
|
754
|
+
const personId = people[0];
|
|
755
|
+
const timing = freeUntil <= ctx.now ? "past" : Date.parse(freeUntil) - Date.parse(ctx.now) < OFFER_MIN_FREE_MS ? "under_48_hours" : null;
|
|
756
|
+
const before = existing.get(email);
|
|
757
|
+
const prior = withdrawn.get(email);
|
|
758
|
+
let outcome;
|
|
759
|
+
let offerId;
|
|
760
|
+
let note = timing;
|
|
761
|
+
if (!before && prior && !input.reissue) {
|
|
762
|
+
outcome = "conflict";
|
|
763
|
+
offerId = prior.id;
|
|
764
|
+
note = "withdrawn";
|
|
765
|
+
} else if (!before) {
|
|
766
|
+
outcome = "created";
|
|
767
|
+
offerId = newId("subscriptionOffer");
|
|
768
|
+
if (prior) note = timing ?? "reissued";
|
|
769
|
+
if (!input.dryRun) {
|
|
770
|
+
ctx.write(
|
|
771
|
+
ctx.db.insertInto("core_subscription_offer").values({
|
|
772
|
+
id: offerId,
|
|
773
|
+
plan_object: input.plan.object,
|
|
774
|
+
plan_id: input.plan.id,
|
|
775
|
+
email,
|
|
776
|
+
person_id: personId,
|
|
777
|
+
free_until: freeUntil,
|
|
778
|
+
reference,
|
|
779
|
+
imported_by: ctx.user.id,
|
|
780
|
+
created_at: ctx.now,
|
|
781
|
+
updated_at: ctx.now
|
|
782
|
+
})
|
|
783
|
+
);
|
|
784
|
+
if (prior) {
|
|
785
|
+
ctx.write(
|
|
786
|
+
ctx.db.updateTable("core_subscription_offer").set({ reissued_as: offerId, version: prior.version + 1 }).where("id", "=", prior.id)
|
|
787
|
+
);
|
|
788
|
+
}
|
|
789
|
+
ctx.recordChange({
|
|
790
|
+
object: "subscription_offer",
|
|
791
|
+
id: offerId,
|
|
792
|
+
action: "create",
|
|
793
|
+
after: {
|
|
794
|
+
email,
|
|
795
|
+
personId,
|
|
796
|
+
plan: input.plan,
|
|
797
|
+
freeUntil,
|
|
798
|
+
reference,
|
|
799
|
+
...prior ? { reissuedFrom: prior.id } : {}
|
|
800
|
+
}
|
|
801
|
+
});
|
|
802
|
+
}
|
|
803
|
+
} else {
|
|
804
|
+
offerId = before.id;
|
|
805
|
+
let version = before.version;
|
|
806
|
+
const page = before.checkout_id ? pages.get(before.id) : void 0;
|
|
807
|
+
if (page === "expired") {
|
|
808
|
+
if (!input.dryRun) {
|
|
809
|
+
version += 1;
|
|
810
|
+
ctx.write(releaseStatement(ctx, before, version));
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
const same = before.free_until === freeUntil && (before.reference ?? null) === reference && before.plan_id === input.plan.id && before.person_id === personId;
|
|
814
|
+
const status = offerStatus(before, ctx.now);
|
|
815
|
+
const kept = status === "taken" ? "taken" : page === "complete" ? "completing" : page === "open" ? "held" : page === null ? "held_unconfirmed" : before.person_id !== personId ? "another_person" : null;
|
|
816
|
+
if (same) {
|
|
817
|
+
outcome = "unchanged";
|
|
818
|
+
note = kept === "taken" || kept === "completing" ? kept : timing;
|
|
819
|
+
} else if (kept) {
|
|
820
|
+
outcome = "conflict";
|
|
821
|
+
note = kept;
|
|
822
|
+
} else {
|
|
823
|
+
outcome = "updated";
|
|
824
|
+
if (!input.dryRun) {
|
|
825
|
+
ctx.write(
|
|
826
|
+
ctx.db.updateTable("core_subscription_offer").set({
|
|
827
|
+
plan_id: input.plan.id,
|
|
828
|
+
free_until: freeUntil,
|
|
829
|
+
reference,
|
|
830
|
+
updated_at: ctx.now,
|
|
831
|
+
version: version + 1
|
|
832
|
+
}).where("id", "=", before.id)
|
|
833
|
+
);
|
|
834
|
+
ctx.recordChange({
|
|
835
|
+
object: "subscription_offer",
|
|
836
|
+
id: before.id,
|
|
837
|
+
action: "update",
|
|
838
|
+
before: {
|
|
839
|
+
planId: before.plan_id,
|
|
840
|
+
freeUntil: before.free_until,
|
|
841
|
+
reference: before.reference
|
|
842
|
+
},
|
|
843
|
+
after: { planId: input.plan.id, freeUntil, reference }
|
|
844
|
+
});
|
|
845
|
+
}
|
|
846
|
+
}
|
|
847
|
+
}
|
|
848
|
+
let signIn = accounts.has(email) ? "has_account" : invites.has(email) ? "invited_before" : null;
|
|
849
|
+
const usable = outcome !== "conflict" && note !== "taken" && note !== "completing";
|
|
850
|
+
if (input.invite && signIn === null && usable && timing !== "past") {
|
|
851
|
+
try {
|
|
852
|
+
const invite = await inviteCustomerStatement(ctx.db, email, ctx.user.id, ctx.now);
|
|
853
|
+
if (!input.dryRun) {
|
|
854
|
+
ctx.write(invite.statement);
|
|
855
|
+
ctx.recordChange({
|
|
856
|
+
object: "customer_invite",
|
|
857
|
+
id: invite.email,
|
|
858
|
+
action: "create",
|
|
859
|
+
after: { email: invite.email, invitedBy: ctx.user.id }
|
|
860
|
+
});
|
|
861
|
+
}
|
|
862
|
+
signIn = "invited";
|
|
863
|
+
} catch {
|
|
864
|
+
signIn = "invite_refused";
|
|
865
|
+
}
|
|
866
|
+
}
|
|
867
|
+
results.push(result(outcome, { offerId, personId, freeUntil, note, signIn, email }));
|
|
868
|
+
}
|
|
869
|
+
return results;
|
|
870
|
+
}
|
|
871
|
+
async function prepareOfferTake(ctx, take) {
|
|
872
|
+
const offer = await ctx.db.selectFrom("core_subscription_offer").selectAll().where("id", "=", take.offerId).executeTakeFirst();
|
|
873
|
+
if (!offer || offer.email !== take.email || offer.person_id !== take.personId) {
|
|
874
|
+
throw new NotFoundError("subscription_offer", take.offerId);
|
|
875
|
+
}
|
|
876
|
+
if (offer.plan_object !== take.plan.object) {
|
|
877
|
+
throw new ValidationError("This offer is for another plan", {
|
|
878
|
+
field: "plan",
|
|
879
|
+
rule: "offer_plan"
|
|
880
|
+
});
|
|
881
|
+
}
|
|
882
|
+
if (offer.plan_id !== take.plan.id) {
|
|
883
|
+
const plan = await offerPlan(ctx.records, offer.plan_object, offer.plan_id);
|
|
884
|
+
if (!("planId" in plan) || plan.planId !== take.plan.id) {
|
|
885
|
+
throw new ValidationError("This offer is for another plan", {
|
|
886
|
+
field: "plan",
|
|
887
|
+
rule: "offer_plan"
|
|
888
|
+
});
|
|
889
|
+
}
|
|
890
|
+
}
|
|
891
|
+
if (offer.subscription_id) {
|
|
892
|
+
throw new ConflictError("You have taken this offer: your subscription is running", {
|
|
893
|
+
rule: "offer_taken"
|
|
894
|
+
});
|
|
895
|
+
}
|
|
896
|
+
if (offer.withdrawn_at) {
|
|
897
|
+
throw new ConflictError("This offer was withdrawn", { rule: "offer_withdrawn" });
|
|
898
|
+
}
|
|
899
|
+
let release = null;
|
|
900
|
+
if (offer.checkout_id && offer.checkout_ref) {
|
|
901
|
+
const status = await pageStatus(ctx, take.target, offer.checkout_ref);
|
|
902
|
+
if (status === "complete") {
|
|
903
|
+
throw new ConflictError(
|
|
904
|
+
"You have taken this offer: the payment provider is confirming your subscription",
|
|
905
|
+
{ rule: "offer_taken" }
|
|
906
|
+
);
|
|
907
|
+
}
|
|
908
|
+
if (status === null) {
|
|
909
|
+
throw new ConflictError(
|
|
910
|
+
"We could not check your earlier checkout with the payment provider just now. Try again in a few minutes.",
|
|
911
|
+
{ rule: "offer_unconfirmed" }
|
|
912
|
+
);
|
|
913
|
+
}
|
|
914
|
+
if (status === "open" && offer.checkout_url) {
|
|
915
|
+
const checkout = await ctx.db.selectFrom("core_subscription_checkout").select(["amount", "trial_end"]).where("id", "=", offer.checkout_id).executeTakeFirst();
|
|
916
|
+
if (checkout) {
|
|
917
|
+
return {
|
|
918
|
+
open: {
|
|
919
|
+
checkoutId: offer.checkout_id,
|
|
920
|
+
url: offer.checkout_url,
|
|
921
|
+
amount: checkout.amount,
|
|
922
|
+
freeUntil: checkout.trial_end ?? null,
|
|
923
|
+
expiresAt: offer.held_until ? new Date(Date.parse(offer.held_until) - TRIAL_HOLD_AFTER_EXPIRY_MS).toISOString() : null
|
|
924
|
+
}
|
|
925
|
+
};
|
|
926
|
+
}
|
|
927
|
+
}
|
|
928
|
+
release = offer.checkout_id;
|
|
929
|
+
}
|
|
930
|
+
if (offer.free_until <= ctx.now) {
|
|
931
|
+
throw new ConflictError(
|
|
932
|
+
`Your free time ended on ${offer.free_until.slice(0, 10)}: subscribe without the offer, charged from today`,
|
|
933
|
+
{ rule: "offer_expired" }
|
|
934
|
+
);
|
|
935
|
+
}
|
|
936
|
+
const left2 = Date.parse(offer.free_until) - Date.parse(ctx.now);
|
|
937
|
+
return {
|
|
938
|
+
offerId: offer.id,
|
|
939
|
+
trialEnd: left2 >= OFFER_MIN_FREE_MS ? offer.free_until : null,
|
|
940
|
+
releaseCheckoutId: release,
|
|
941
|
+
version: offer.version
|
|
942
|
+
};
|
|
943
|
+
}
|
|
944
|
+
function holdOfferStatements(ctx, hold) {
|
|
945
|
+
const expires = hold.expiresAt ?? new Date(Date.parse(ctx.now) + 24 * 36e5).toISOString();
|
|
946
|
+
let version = hold.version;
|
|
947
|
+
const release = hold.releaseCheckoutId ? [releaseStatement(ctx, { id: hold.offerId, checkout_id: hold.releaseCheckoutId }, ++version)] : [];
|
|
948
|
+
return [
|
|
949
|
+
...release,
|
|
950
|
+
ctx.db.updateTable("core_subscription_offer").set({
|
|
951
|
+
checkout_id: hold.checkoutId,
|
|
952
|
+
checkout_ref: hold.checkoutRef,
|
|
953
|
+
checkout_url: hold.url,
|
|
954
|
+
held_until: new Date(Date.parse(expires) + TRIAL_HOLD_AFTER_EXPIRY_MS).toISOString(),
|
|
955
|
+
updated_at: ctx.now,
|
|
956
|
+
version: version + 1
|
|
957
|
+
}).where("id", "=", hold.offerId)
|
|
958
|
+
];
|
|
959
|
+
}
|
|
960
|
+
async function myOffers(ctx) {
|
|
961
|
+
const caller = ctx.principal;
|
|
962
|
+
if (caller.kind !== "customer") {
|
|
963
|
+
throw new ValidationError("A continuation offer is read by its own person, signed in", {
|
|
964
|
+
rule: "customer"
|
|
965
|
+
});
|
|
966
|
+
}
|
|
967
|
+
const account = await ctx.db.selectFrom("core_customer").select("email").where("id", "=", caller.customerId).executeTakeFirst();
|
|
968
|
+
if (!account) return [];
|
|
969
|
+
const rows = await ctx.db.selectFrom("core_subscription_offer").selectAll().where("person_id", "=", caller.personId).where("email", "=", account.email).where("subscription_id", "is", null).where("withdrawn_at", "is", null).where("free_until", ">", ctx.now).orderBy("free_until").execute();
|
|
970
|
+
const out = [];
|
|
971
|
+
for (const r of rows) {
|
|
972
|
+
const plan = await offerPlan(ctx.records, r.plan_object, r.plan_id);
|
|
973
|
+
out.push({
|
|
974
|
+
id: r.id,
|
|
975
|
+
planObject: r.plan_object,
|
|
976
|
+
planId: "planId" in plan ? plan.planId : r.plan_id,
|
|
977
|
+
freeUntil: r.free_until,
|
|
978
|
+
chargedNow: Date.parse(r.free_until) - Date.parse(ctx.now) < OFFER_MIN_FREE_MS,
|
|
979
|
+
askUs: !("planId" in plan)
|
|
980
|
+
});
|
|
981
|
+
}
|
|
982
|
+
return out;
|
|
983
|
+
}
|
|
984
|
+
var RUNNING_STATES = ["trialing", "active", "past_due"];
|
|
985
|
+
function readCursor(cursor) {
|
|
986
|
+
let parsed;
|
|
987
|
+
try {
|
|
988
|
+
parsed = JSON.parse(atob(cursor));
|
|
989
|
+
} catch {
|
|
990
|
+
parsed = null;
|
|
991
|
+
}
|
|
992
|
+
const c = parsed;
|
|
993
|
+
if (!c || typeof c !== "object" || typeof c.e !== "string" || typeof c.i !== "string" || Object.keys(c).length !== 2) {
|
|
994
|
+
throw new ValidationError("Not a cursor this list gave", { field: "cursor" });
|
|
995
|
+
}
|
|
996
|
+
return { e: c.e, i: c.i };
|
|
997
|
+
}
|
|
998
|
+
async function offerCounts(ctx, planObject) {
|
|
999
|
+
let q2 = ctx.db.selectFrom("core_subscription_offer").select([
|
|
1000
|
+
sql`coalesce(sum(subscription_id IS NOT NULL), 0)`.as("taken"),
|
|
1001
|
+
sql`coalesce(sum(subscription_id IS NULL AND withdrawn_at IS NOT NULL), 0)`.as(
|
|
1002
|
+
"withdrawn"
|
|
1003
|
+
),
|
|
1004
|
+
sql`coalesce(sum(subscription_id IS NULL AND withdrawn_at IS NULL AND free_until <= ${ctx.now}), 0)`.as(
|
|
1005
|
+
"expired"
|
|
1006
|
+
),
|
|
1007
|
+
sql`coalesce(sum(subscription_id IS NULL AND withdrawn_at IS NULL AND free_until > ${ctx.now}), 0)`.as(
|
|
1008
|
+
"open"
|
|
1009
|
+
)
|
|
1010
|
+
]);
|
|
1011
|
+
if (planObject) q2 = q2.where("plan_object", "=", planObject);
|
|
1012
|
+
const row = await q2.executeTakeFirst();
|
|
1013
|
+
return {
|
|
1014
|
+
open: Number(row?.open ?? 0),
|
|
1015
|
+
taken: Number(row?.taken ?? 0),
|
|
1016
|
+
expired: Number(row?.expired ?? 0),
|
|
1017
|
+
withdrawn: Number(row?.withdrawn ?? 0)
|
|
1018
|
+
};
|
|
1019
|
+
}
|
|
1020
|
+
async function listOffers(ctx, input) {
|
|
1021
|
+
const after = input.cursor ? readCursor(input.cursor) : null;
|
|
1022
|
+
let q2 = ctx.db.selectFrom("core_subscription_offer as o").leftJoin("core_subscription as s", "s.id", "o.subscription_id").leftJoin("core_person as p", "p.id", "o.person_id").selectAll("o").select([
|
|
1023
|
+
"s.state as s_state",
|
|
1024
|
+
"s.trial_end as s_trial_end",
|
|
1025
|
+
"s.created_at as s_created_at",
|
|
1026
|
+
"p.display_name as person_name"
|
|
1027
|
+
]);
|
|
1028
|
+
if (input.planObject) q2 = q2.where("o.plan_object", "=", input.planObject);
|
|
1029
|
+
switch (input.status) {
|
|
1030
|
+
case "taken":
|
|
1031
|
+
q2 = q2.where("o.subscription_id", "is not", null);
|
|
1032
|
+
break;
|
|
1033
|
+
case "withdrawn":
|
|
1034
|
+
q2 = q2.where("o.subscription_id", "is", null).where("o.withdrawn_at", "is not", null);
|
|
1035
|
+
break;
|
|
1036
|
+
case "expired":
|
|
1037
|
+
q2 = q2.where("o.subscription_id", "is", null).where("o.withdrawn_at", "is", null).where("o.free_until", "<=", ctx.now);
|
|
1038
|
+
break;
|
|
1039
|
+
case "open":
|
|
1040
|
+
q2 = q2.where("o.subscription_id", "is", null).where("o.withdrawn_at", "is", null).where("o.free_until", ">", ctx.now);
|
|
1041
|
+
break;
|
|
1042
|
+
default:
|
|
1043
|
+
break;
|
|
1044
|
+
}
|
|
1045
|
+
if (after) {
|
|
1046
|
+
const { e, i } = after;
|
|
1047
|
+
q2 = q2.where(
|
|
1048
|
+
(eb) => eb.or([eb("o.email", ">", e), eb.and([eb("o.email", "=", e), eb("o.id", ">", i)])])
|
|
1049
|
+
);
|
|
1050
|
+
}
|
|
1051
|
+
const rows = await q2.orderBy("o.email").orderBy("o.id").limit(input.limit + 1).execute();
|
|
1052
|
+
const page = rows.slice(0, input.limit);
|
|
1053
|
+
const untaken = page.filter((r) => !r.subscription_id && r.person_id);
|
|
1054
|
+
const others = /* @__PURE__ */ new Map();
|
|
1055
|
+
if (untaken.length) {
|
|
1056
|
+
const subs = await ctx.db.selectFrom("core_subscription").select(["id", "state", "created_at", "holder_person_id", "plan_object"]).where(
|
|
1057
|
+
"holder_person_id",
|
|
1058
|
+
"in",
|
|
1059
|
+
untaken.map((r) => r.person_id)
|
|
1060
|
+
).where("state", "in", [...RUNNING_STATES]).orderBy("created_at", "desc").execute();
|
|
1061
|
+
for (const s of subs) {
|
|
1062
|
+
const key = `${s.holder_person_id}|${s.plan_object}`;
|
|
1063
|
+
if (!others.has(key)) others.set(key, { id: s.id, state: s.state, createdAt: s.created_at });
|
|
1064
|
+
}
|
|
1065
|
+
}
|
|
1066
|
+
const asked = input.pages === false ? /* @__PURE__ */ new Map() : await heldPages(
|
|
1067
|
+
ctx,
|
|
1068
|
+
page.filter((r) => offerStatus(r, ctx.now) === "open")
|
|
1069
|
+
);
|
|
1070
|
+
const items = page.map((r) => {
|
|
1071
|
+
const status = offerStatus(r, ctx.now);
|
|
1072
|
+
const chargedFromStart = r.charged_from_start === 1;
|
|
1073
|
+
const said = r.checkout_id && status === "open" ? asked.get(r.id) : void 0;
|
|
1074
|
+
return {
|
|
1075
|
+
id: r.id,
|
|
1076
|
+
email: r.email,
|
|
1077
|
+
personId: r.person_id,
|
|
1078
|
+
personName: r.person_name ?? null,
|
|
1079
|
+
planObject: r.plan_object,
|
|
1080
|
+
planId: r.plan_id,
|
|
1081
|
+
reference: r.reference,
|
|
1082
|
+
freeUntil: r.free_until,
|
|
1083
|
+
status,
|
|
1084
|
+
page: said === "open" ? "open" : said === "complete" ? "completing" : said === null ? "unconfirmed" : null,
|
|
1085
|
+
takenAt: r.taken_at,
|
|
1086
|
+
subscriptionId: r.subscription_id,
|
|
1087
|
+
subscriptionState: r.s_state ?? null,
|
|
1088
|
+
chargesFrom: r.subscription_id ? chargedFromStart ? r.s_created_at ?? r.taken_at : r.s_trial_end ?? r.free_until : null,
|
|
1089
|
+
chargedFromStart,
|
|
1090
|
+
subscribedWithout: !r.subscription_id && r.person_id ? others.get(`${r.person_id}|${r.plan_object}`) ?? null : null,
|
|
1091
|
+
withdrawnAt: r.withdrawn_at,
|
|
1092
|
+
withdrawReason: r.withdraw_reason,
|
|
1093
|
+
reissuedAs: r.reissued_as,
|
|
1094
|
+
createdAt: r.created_at
|
|
1095
|
+
};
|
|
1096
|
+
});
|
|
1097
|
+
const last = page.at(-1);
|
|
1098
|
+
return {
|
|
1099
|
+
items,
|
|
1100
|
+
nextCursor: rows.length > input.limit && last ? btoa(JSON.stringify({ e: last.email, i: last.id })) : null,
|
|
1101
|
+
counts: input.counts === false ? { open: 0, taken: 0, expired: 0, withdrawn: 0 } : await offerCounts(ctx, input.planObject)
|
|
1102
|
+
};
|
|
1103
|
+
}
|
|
1104
|
+
var CSV_COLUMNS = [
|
|
1105
|
+
"email",
|
|
1106
|
+
"name",
|
|
1107
|
+
"reference",
|
|
1108
|
+
"paid_up_to",
|
|
1109
|
+
"status",
|
|
1110
|
+
"taken_at",
|
|
1111
|
+
"charges_from",
|
|
1112
|
+
"charged_from_start",
|
|
1113
|
+
"subscription",
|
|
1114
|
+
"subscription_state",
|
|
1115
|
+
"subscribed_without_offer",
|
|
1116
|
+
"withdrawn_at",
|
|
1117
|
+
"withdraw_reason",
|
|
1118
|
+
"reissued_as"
|
|
1119
|
+
];
|
|
1120
|
+
function csvCell(value) {
|
|
1121
|
+
if (value === null || value === void 0) return "";
|
|
1122
|
+
let text = String(value);
|
|
1123
|
+
if (/^[=+\-@\t\r]/.test(text)) text = `'${text}`;
|
|
1124
|
+
return /[",\n\r]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text;
|
|
1125
|
+
}
|
|
1126
|
+
async function exportOffers(ctx, input) {
|
|
1127
|
+
const lines = [CSV_COLUMNS.join(",")];
|
|
1128
|
+
let cursor;
|
|
1129
|
+
let rowCount = 0;
|
|
1130
|
+
do {
|
|
1131
|
+
const page = await listOffers(ctx, {
|
|
1132
|
+
...input,
|
|
1133
|
+
limit: 200,
|
|
1134
|
+
counts: false,
|
|
1135
|
+
pages: false,
|
|
1136
|
+
...cursor ? { cursor } : {}
|
|
1137
|
+
});
|
|
1138
|
+
for (const o of page.items) {
|
|
1139
|
+
rowCount += 1;
|
|
1140
|
+
lines.push(
|
|
1141
|
+
[
|
|
1142
|
+
o.email,
|
|
1143
|
+
o.personName,
|
|
1144
|
+
o.reference,
|
|
1145
|
+
o.freeUntil,
|
|
1146
|
+
o.status,
|
|
1147
|
+
o.takenAt,
|
|
1148
|
+
o.chargesFrom,
|
|
1149
|
+
o.subscriptionId ? o.chargedFromStart ? "yes" : "no" : "",
|
|
1150
|
+
o.subscriptionId,
|
|
1151
|
+
o.subscriptionState,
|
|
1152
|
+
o.subscribedWithout ? `${o.subscribedWithout.id} (${o.subscribedWithout.state})` : "",
|
|
1153
|
+
o.withdrawnAt,
|
|
1154
|
+
o.withdrawReason,
|
|
1155
|
+
o.reissuedAs
|
|
1156
|
+
].map(csvCell).join(",")
|
|
1157
|
+
);
|
|
1158
|
+
}
|
|
1159
|
+
cursor = page.nextCursor ?? void 0;
|
|
1160
|
+
} while (cursor);
|
|
1161
|
+
return {
|
|
1162
|
+
filename: `continuation-offers-${input.status ?? "all"}-${ctx.now.slice(0, 10)}.csv`,
|
|
1163
|
+
csv: `${lines.join("\n")}
|
|
1164
|
+
`,
|
|
1165
|
+
rowCount
|
|
1166
|
+
};
|
|
1167
|
+
}
|
|
1168
|
+
async function withdrawOffer(ctx, id, reason) {
|
|
1169
|
+
const offer = await ctx.db.selectFrom("core_subscription_offer").selectAll().where("id", "=", id).executeTakeFirst();
|
|
1170
|
+
if (!offer) throw new NotFoundError("subscription_offer", id);
|
|
1171
|
+
if (offer.subscription_id) {
|
|
1172
|
+
throw new ConflictError(
|
|
1173
|
+
"This offer was taken: its subscription is running. End the subscription instead.",
|
|
1174
|
+
{ rule: "offer_taken", subscription: offer.subscription_id }
|
|
1175
|
+
);
|
|
1176
|
+
}
|
|
1177
|
+
if (offer.withdrawn_at) {
|
|
1178
|
+
throw new ConflictError("This offer is already withdrawn", { rule: "offer_withdrawn" });
|
|
1179
|
+
}
|
|
1180
|
+
const page = offer.checkout_id ? (await heldPages(ctx, [offer])).get(offer.id) : void 0;
|
|
1181
|
+
let version = offer.version;
|
|
1182
|
+
if (page === "expired") {
|
|
1183
|
+
version += 1;
|
|
1184
|
+
ctx.write(releaseStatement(ctx, offer, version));
|
|
1185
|
+
}
|
|
1186
|
+
ctx.write(
|
|
1187
|
+
ctx.db.updateTable("core_subscription_offer").set({
|
|
1188
|
+
withdrawn_at: ctx.now,
|
|
1189
|
+
withdrawn_by: ctx.user.id,
|
|
1190
|
+
withdraw_reason: reason,
|
|
1191
|
+
updated_at: ctx.now,
|
|
1192
|
+
version: version + 1
|
|
1193
|
+
}).where("id", "=", id)
|
|
1194
|
+
);
|
|
1195
|
+
ctx.recordChange({
|
|
1196
|
+
object: "subscription_offer",
|
|
1197
|
+
id,
|
|
1198
|
+
action: "update",
|
|
1199
|
+
before: { withdrawnAt: null },
|
|
1200
|
+
after: { withdrawnAt: ctx.now, reason }
|
|
1201
|
+
});
|
|
1202
|
+
return { id, pageOpen: page !== void 0 && page !== "expired" };
|
|
1203
|
+
}
|
|
1204
|
+
|
|
1205
|
+
// ../core/src/subscriptions/sweep.ts
|
|
1206
|
+
var PAST_DUE_GRACE_DAYS = 30;
|
|
1207
|
+
|
|
1208
|
+
// ../core/src/subscriptions/access.ts
|
|
1209
|
+
var SUBSCRIPTION_ACCESS_KIND = "subscription";
|
|
1210
|
+
var GIVING_STATES = ["trialing", "active", "past_due"];
|
|
1211
|
+
var optionsOf = (source) => "options" in source ? source.options ?? {} : {};
|
|
1212
|
+
function problems(object, source) {
|
|
1213
|
+
const options = optionsOf(source);
|
|
1214
|
+
const out = [];
|
|
1215
|
+
for (const key of Object.keys(options)) {
|
|
1216
|
+
if (key !== "plans" && key !== "covers")
|
|
1217
|
+
out.push(`a subscription source has no option "${key}"`);
|
|
1218
|
+
}
|
|
1219
|
+
if (options.covers !== "all") out.push('covers must be "all" (every live record)');
|
|
1220
|
+
const plans = options.plans;
|
|
1221
|
+
if (typeof plans !== "string" || !plans) {
|
|
1222
|
+
out.push("plans must name the plan object");
|
|
1223
|
+
return out;
|
|
1224
|
+
}
|
|
1225
|
+
const plan = getObject(plans);
|
|
1226
|
+
if (!plan || !object.extension || plan.extension !== object.extension || plan.name === object.name) {
|
|
1227
|
+
out.push(`plans "${plans}" must be another object of the same extension`);
|
|
1228
|
+
} else if (!plan.sellable?.recurring) {
|
|
1229
|
+
out.push(`plans "${plans}" must be a plan: an object whose sellable declares recurring`);
|
|
1230
|
+
}
|
|
1231
|
+
return out;
|
|
1232
|
+
}
|
|
1233
|
+
function givingSubscriptionSql(personId, planObject, now) {
|
|
1234
|
+
return sql`SELECT id FROM core_subscription
|
|
1235
|
+
WHERE holder_person_id = ${personId}
|
|
1236
|
+
AND plan_object = ${planObject}
|
|
1237
|
+
AND state IN (${sql.join(GIVING_STATES.map((s) => sql`${s}`))})
|
|
1238
|
+
AND NOT (cancel_at_period_end = 1 AND current_period_end IS NOT NULL AND current_period_end <= ${now})
|
|
1239
|
+
AND NOT (cancel_at IS NOT NULL AND cancel_at <= ${now})
|
|
1240
|
+
AND NOT (state = 'past_due' AND failing_since IS NOT NULL AND failing_since <= ${pastDueLapsesBefore(now)})
|
|
1241
|
+
LIMIT 1`;
|
|
1242
|
+
}
|
|
1243
|
+
function pastDueLapsesBefore(now) {
|
|
1244
|
+
return new Date(Date.parse(now) - PAST_DUE_GRACE_DAYS * 864e5).toISOString();
|
|
1245
|
+
}
|
|
1246
|
+
async function holders(query, source) {
|
|
1247
|
+
if (problems(query.object, source).length) return /* @__PURE__ */ new Set();
|
|
1248
|
+
const plans = String(optionsOf(source).plans);
|
|
1249
|
+
const rows = await givingSubscriptionSql(query.personId, plans, query.now).execute(query.db);
|
|
1250
|
+
if (!rows.rows.length) return /* @__PURE__ */ new Set();
|
|
1251
|
+
const object = query.object;
|
|
1252
|
+
const view = object.publishable && object.public && object.extension ? liveViewOf(object.name) : object.source;
|
|
1253
|
+
const live = await sql`SELECT id FROM ${sql.table(view)} WHERE id IN (${sql.join(
|
|
1254
|
+
query.ids.map((id) => sql`${id}`)
|
|
1255
|
+
)})`.execute(query.db);
|
|
1256
|
+
return new Set(live.rows.map((r) => String(r.id)));
|
|
1257
|
+
}
|
|
1258
|
+
registerAccessSource(SUBSCRIPTION_ACCESS_KIND, { holders, problems });
|
|
1259
|
+
|
|
1260
|
+
// ../core/src/allowance/periods.ts
|
|
1261
|
+
var TOTAL_PERIOD = {
|
|
1262
|
+
key: "total",
|
|
1263
|
+
per: "total",
|
|
1264
|
+
startsAt: "0000-01-01T00:00:00.000Z",
|
|
1265
|
+
endsAt: "9999-12-31T23:59:59.999Z"
|
|
1266
|
+
};
|
|
1267
|
+
var pad = (n) => String(n).padStart(2, "0");
|
|
1268
|
+
function periodOf(at, per, zone) {
|
|
1269
|
+
if (per === "total") return { ...TOTAL_PERIOD };
|
|
1270
|
+
const local = localParts(at, zone);
|
|
1271
|
+
if (per === "week") {
|
|
1272
|
+
const monday = addLocalDays(local, 1 - local.weekday);
|
|
1273
|
+
return {
|
|
1274
|
+
key: `week:${monday.year}-${pad(monday.month)}-${pad(monday.day)}`,
|
|
1275
|
+
per,
|
|
1276
|
+
startsAt: wallClockToIso(monday, zone),
|
|
1277
|
+
endsAt: wallClockToIso(addLocalDays(monday, 7), zone)
|
|
1278
|
+
};
|
|
1279
|
+
}
|
|
1280
|
+
const first = { year: local.year, month: local.month, day: 1 };
|
|
1281
|
+
const next = local.month === 12 ? { year: local.year + 1, month: 1, day: 1 } : { year: local.year, month: local.month + 1, day: 1 };
|
|
1282
|
+
return {
|
|
1283
|
+
key: `month:${local.year}-${pad(local.month)}`,
|
|
1284
|
+
per,
|
|
1285
|
+
startsAt: wallClockToIso(first, zone),
|
|
1286
|
+
endsAt: wallClockToIso(next, zone)
|
|
1287
|
+
};
|
|
1288
|
+
}
|
|
1289
|
+
function boundOf(value, kind, fieldType, zone) {
|
|
1290
|
+
if (value === null || value === void 0 || value === "") return null;
|
|
1291
|
+
const text = String(value);
|
|
1292
|
+
const date = /^(\d{4})-(\d{2})-(\d{2})$/.exec(text);
|
|
1293
|
+
if (date || fieldType === "date") {
|
|
1294
|
+
const [y, m, d] = date ? [Number(date[1]), Number(date[2]), Number(date[3])] : (() => {
|
|
1295
|
+
const p = localParts(text, zone);
|
|
1296
|
+
return [p.year, p.month, p.day];
|
|
1297
|
+
})();
|
|
1298
|
+
const day = { year: y, month: m, day: d };
|
|
1299
|
+
return wallClockToIso(kind === "until" ? addLocalDays(day, 1) : day, zone);
|
|
1300
|
+
}
|
|
1301
|
+
const at = new Date(text);
|
|
1302
|
+
return Number.isNaN(at.getTime()) ? null : at.toISOString();
|
|
1303
|
+
}
|
|
1304
|
+
|
|
1305
|
+
// ../core/src/allowance/index.ts
|
|
1306
|
+
var q = (value) => `'${value.replaceAll("'", "''")}'`;
|
|
1307
|
+
function termsSyncStatements(storage, target, orgZone, now) {
|
|
1308
|
+
const t = (column) => `t.${column}`;
|
|
1309
|
+
const uses = `CASE WHEN typeof(${t(storage.uses)}) IN ('integer', 'real') AND ${t(storage.uses)} >= 0 AND ${t(storage.uses)} = CAST(${t(storage.uses)} AS INTEGER) THEN CAST(${t(storage.uses)} AS INTEGER) WHEN ${t(storage.uses)} IS NULL OR ${t(storage.uses)} = '' THEN ${storage.emptyIsUnlimited ? "NULL" : "0"} ELSE 0 END`;
|
|
1310
|
+
const per = "fixed" in storage.per ? q(storage.per.fixed) : `CASE WHEN ${t(storage.per.column)} IN ('total', 'week', 'month') THEN ${t(storage.per.column)} ELSE 'total' END`;
|
|
1311
|
+
const stored = `(SELECT s.zone FROM core_allowance s WHERE s.object_type = ${q(storage.object)} AND s.record_id = t.id)`;
|
|
1312
|
+
const zone = storage.zone ? `coalesce(nullif(${t(storage.zone)}, ''), ${stored}, ?)` : `coalesce(${stored}, ?)`;
|
|
1313
|
+
const instant = (bound) => bound && !bound.date ? `CASE WHEN ${t(bound.column)} IS NULL OR ${t(bound.column)} = '' THEN NULL ELSE strftime('%Y-%m-%dT%H:%M:%fZ', ${t(bound.column)}) END` : "NULL";
|
|
1314
|
+
const day = (bound) => bound?.date ? `nullif(substr(${t(bound.column)}, 1, 10), '')` : "NULL";
|
|
1315
|
+
const live = storage.live ? `CASE WHEN ${t(storage.live.column)} IN (${storage.live.states.map(q).join(", ") || "NULL"}) THEN 1 ELSE 0 END` : "1";
|
|
1316
|
+
const person = `CASE WHEN typeof(${t(storage.person)}) = 'text' AND ${t(storage.person)} <> '' THEN ${t(storage.person)} END`;
|
|
1317
|
+
const where = target === "all" ? "true" : "t.id = ?";
|
|
1318
|
+
return [
|
|
1319
|
+
CompiledQuery.raw(
|
|
1320
|
+
`INSERT INTO core_allowance (object_type, record_id, person_id, uses, per, zone, valid_from, valid_until, from_date, until_date, live, trashed, updated_at) SELECT ${q(storage.object)}, t.id, ${person}, ${uses}, ${per}, ${zone}, ${instant(storage.from)}, ${instant(storage.until)}, ${day(storage.from)}, ${day(storage.until)}, ${live}, CASE WHEN t.deleted_at IS NULL THEN 0 ELSE 1 END, ? FROM ${storage.table} t WHERE ${where} ON CONFLICT (object_type, record_id) DO UPDATE SET person_id = excluded.person_id, uses = excluded.uses, per = excluded.per, zone = excluded.zone, valid_from = excluded.valid_from, valid_until = excluded.valid_until, from_date = excluded.from_date, until_date = excluded.until_date, live = excluded.live, trashed = excluded.trashed, updated_at = excluded.updated_at`,
|
|
1321
|
+
[orgZone, now, ...target === "all" ? [] : [target.id]]
|
|
1322
|
+
),
|
|
1323
|
+
CompiledQuery.raw(
|
|
1324
|
+
`UPDATE core_allowance_period SET uses = (SELECT a.uses FROM core_allowance a WHERE a.object_type = core_allowance_period.object_type AND a.record_id = core_allowance_period.record_id), updated_at = ? WHERE object_type = ? AND ends_at > ?${target === "all" ? "" : " AND record_id = ?"}`,
|
|
1325
|
+
[now, storage.object, now, ...target === "all" ? [] : [target.id]]
|
|
1326
|
+
)
|
|
1327
|
+
];
|
|
1328
|
+
}
|
|
1329
|
+
function keyingChangeStatement(holder, previous, appliesFrom, now) {
|
|
1330
|
+
return CompiledQuery.raw(
|
|
1331
|
+
"UPDATE core_allowance SET prev_per = ?, prev_zone = ?, applies_from = ?, updated_at = ? WHERE object_type = ? AND record_id = ?",
|
|
1332
|
+
[previous.per, previous.zone, appliesFrom, now, holder.object, holder.id]
|
|
1333
|
+
);
|
|
1334
|
+
}
|
|
1335
|
+
function periodInsert(holder, period, zone, now) {
|
|
1336
|
+
return CompiledQuery.raw(
|
|
1337
|
+
"INSERT INTO core_allowance_period (object_type, record_id, period, per, zone, starts_at, ends_at, uses, used, updated_at) SELECT a.object_type, a.record_id, ?, ?, ?, ?, ?, a.uses, 0, ? FROM core_allowance a WHERE a.object_type = ? AND a.record_id = ? ON CONFLICT (object_type, record_id, period, zone) DO NOTHING",
|
|
1338
|
+
[period.key, period.per, zone, period.startsAt, period.endsAt, now, holder.object, holder.id]
|
|
1339
|
+
);
|
|
1340
|
+
}
|
|
1341
|
+
function spendStatements(request, now) {
|
|
1342
|
+
const id = request.id ?? newId("allowanceUse");
|
|
1343
|
+
const { holder, period, zone } = request;
|
|
1344
|
+
return {
|
|
1345
|
+
id,
|
|
1346
|
+
statements: [
|
|
1347
|
+
periodInsert(holder, period, zone, now),
|
|
1348
|
+
CompiledQuery.raw(
|
|
1349
|
+
"UPDATE core_allowance_period SET used = used + 1, updated_at = ? WHERE object_type = ? AND record_id = ? AND period = ? AND zone = ?",
|
|
1350
|
+
[now, holder.object, holder.id, period.key, zone]
|
|
1351
|
+
),
|
|
1352
|
+
CompiledQuery.raw(
|
|
1353
|
+
"INSERT INTO core_allowance_use (id, object_type, record_id, period, zone, spender_type, spender_id, person_id, at, at_date, spent_at, spent_by, moved_from) VALUES (?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?, ?)",
|
|
1354
|
+
[
|
|
1355
|
+
id,
|
|
1356
|
+
holder.object,
|
|
1357
|
+
holder.id,
|
|
1358
|
+
period.key,
|
|
1359
|
+
zone,
|
|
1360
|
+
request.spender.object,
|
|
1361
|
+
request.spender.id,
|
|
1362
|
+
request.personId,
|
|
1363
|
+
request.at,
|
|
1364
|
+
request.atDate,
|
|
1365
|
+
now,
|
|
1366
|
+
request.by,
|
|
1367
|
+
request.movedFrom ?? null
|
|
1368
|
+
]
|
|
1369
|
+
)
|
|
1370
|
+
]
|
|
1371
|
+
};
|
|
1372
|
+
}
|
|
1373
|
+
function returnStatements(spender, by, now) {
|
|
1374
|
+
return [
|
|
1375
|
+
CompiledQuery.raw(
|
|
1376
|
+
"UPDATE core_allowance_period SET used = used - 1, updated_at = ? WHERE (object_type, record_id, period, zone) IN (SELECT object_type, record_id, period, zone FROM core_allowance_use WHERE spender_type = ? AND spender_id = ? AND returned_at IS NULL)",
|
|
1377
|
+
[now, spender.object, spender.id]
|
|
1378
|
+
),
|
|
1379
|
+
CompiledQuery.raw(
|
|
1380
|
+
"UPDATE core_allowance_use SET returned_at = ?, returned_by = ? WHERE spender_type = ? AND spender_id = ? AND returned_at IS NULL",
|
|
1381
|
+
[now, by, spender.object, spender.id]
|
|
1382
|
+
)
|
|
1383
|
+
];
|
|
1384
|
+
}
|
|
1385
|
+
function rekeyStatements(use, to, now) {
|
|
1386
|
+
const { holder } = use;
|
|
1387
|
+
return [
|
|
1388
|
+
periodInsert(holder, to.period, to.zone, now),
|
|
1389
|
+
CompiledQuery.raw(
|
|
1390
|
+
"UPDATE core_allowance_period SET used = used - 1, updated_at = ? WHERE object_type = ? AND record_id = ? AND period = ? AND zone = ?",
|
|
1391
|
+
[now, holder.object, holder.id, use.period, use.zone]
|
|
1392
|
+
),
|
|
1393
|
+
CompiledQuery.raw(
|
|
1394
|
+
"UPDATE core_allowance_period SET used = used + 1, rekeyed = rekeyed + 1, updated_at = ? WHERE object_type = ? AND record_id = ? AND period = ? AND zone = ?",
|
|
1395
|
+
[now, holder.object, holder.id, to.period.key, to.zone]
|
|
1396
|
+
),
|
|
1397
|
+
CompiledQuery.raw("UPDATE core_allowance_use SET period = ?, zone = ? WHERE id = ?", [
|
|
1398
|
+
to.period.key,
|
|
1399
|
+
to.zone,
|
|
1400
|
+
use.id
|
|
1401
|
+
])
|
|
1402
|
+
];
|
|
1403
|
+
}
|
|
1404
|
+
function dropAllowanceStatements(object, kind, now) {
|
|
1405
|
+
if (kind === "holder") {
|
|
1406
|
+
return [
|
|
1407
|
+
CompiledQuery.raw("DELETE FROM core_allowance_use WHERE object_type = ?", [object]),
|
|
1408
|
+
CompiledQuery.raw("DELETE FROM core_allowance_period WHERE object_type = ?", [object]),
|
|
1409
|
+
CompiledQuery.raw("DELETE FROM core_allowance WHERE object_type = ?", [object])
|
|
1410
|
+
];
|
|
1411
|
+
}
|
|
1412
|
+
return [
|
|
1413
|
+
CompiledQuery.raw(
|
|
1414
|
+
"UPDATE core_allowance_period SET used = used - (SELECT count(*) FROM core_allowance_use u WHERE u.spender_type = ? AND u.returned_at IS NULL AND u.object_type = core_allowance_period.object_type AND u.record_id = core_allowance_period.record_id AND u.period = core_allowance_period.period AND u.zone = core_allowance_period.zone), updated_at = ? WHERE (object_type, record_id, period, zone) IN (SELECT object_type, record_id, period, zone FROM core_allowance_use WHERE spender_type = ? AND returned_at IS NULL)",
|
|
1415
|
+
[object, now, object]
|
|
1416
|
+
),
|
|
1417
|
+
CompiledQuery.raw("DELETE FROM core_allowance_use WHERE spender_type = ?", [object])
|
|
1418
|
+
];
|
|
1419
|
+
}
|
|
1420
|
+
|
|
1421
|
+
// ../core/src/recurring/bookkeeping.ts
|
|
1422
|
+
function armSeriesStatement(object, id, at, now) {
|
|
1423
|
+
return CompiledQuery.raw(
|
|
1424
|
+
"INSERT INTO core_recurrence_series (object_type, record_id, next_run_at, version, updated_at) VALUES (?, ?, ?, 1, ?) ON CONFLICT (object_type, record_id) DO UPDATE SET next_run_at = excluded.next_run_at, version = core_recurrence_series.version + 1, updated_at = excluded.updated_at",
|
|
1425
|
+
[object, id, at, now]
|
|
1426
|
+
);
|
|
1427
|
+
}
|
|
1428
|
+
async function seriesVersion(db, object, id) {
|
|
1429
|
+
const row = await db.selectFrom("core_recurrence_series").select("version").where("object_type", "=", object).where("record_id", "=", id).executeTakeFirst();
|
|
1430
|
+
return row?.version ?? 0;
|
|
1431
|
+
}
|
|
1432
|
+
function guardStatement(kind, object, record, expected) {
|
|
1433
|
+
return CompiledQuery.raw(
|
|
1434
|
+
"INSERT INTO core_write_guard (kind, object_type, record_id, expected) VALUES (?, ?, ?, ?)",
|
|
1435
|
+
[kind, object, record, expected]
|
|
1436
|
+
);
|
|
1437
|
+
}
|
|
1438
|
+
function occurrenceStatement(input) {
|
|
1439
|
+
return CompiledQuery.raw(
|
|
1440
|
+
"INSERT INTO core_recurrence_occurrence (series_object, series_id, local_date, object_type, record_id, created_at) VALUES (?, ?, ?, ?, ?, ?)",
|
|
1441
|
+
[input.seriesObject, input.seriesId, input.date, input.object, input.record, input.now]
|
|
1442
|
+
);
|
|
1443
|
+
}
|
|
1444
|
+
function markEditedStatement(object, record, now) {
|
|
1445
|
+
return CompiledQuery.raw(
|
|
1446
|
+
"UPDATE core_recurrence_occurrence SET edited_at = ? WHERE object_type = ? AND record_id = ? AND edited_at IS NULL",
|
|
1447
|
+
[now, object, record]
|
|
1448
|
+
);
|
|
1449
|
+
}
|
|
1450
|
+
function dropRecurringStatements(object) {
|
|
1451
|
+
return [
|
|
1452
|
+
CompiledQuery.raw(
|
|
1453
|
+
"DELETE FROM core_recurrence_occurrence WHERE series_object = ? OR object_type = ?",
|
|
1454
|
+
[object, object]
|
|
1455
|
+
),
|
|
1456
|
+
CompiledQuery.raw("DELETE FROM core_recurrence_series WHERE object_type = ?", [object])
|
|
1457
|
+
];
|
|
1458
|
+
}
|
|
1459
|
+
|
|
1460
|
+
// ../core/src/extensions/seed.ts
|
|
1461
|
+
var ALPHABET = "0123456789ABCDEFGHJKMNPQRSTVWXYZ";
|
|
1462
|
+
function fnv(text, seed) {
|
|
1463
|
+
let hash = (2166136261 ^ seed) >>> 0;
|
|
1464
|
+
for (let i = 0; i < text.length; i++) {
|
|
1465
|
+
hash ^= text.charCodeAt(i);
|
|
1466
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
1467
|
+
}
|
|
1468
|
+
return hash;
|
|
1469
|
+
}
|
|
1470
|
+
function seedRecordId(extension, object, key) {
|
|
1471
|
+
const text = `${extension}.${object}.${key}`;
|
|
1472
|
+
let out = "";
|
|
1473
|
+
for (const seed of [1, 2, 3, 4]) {
|
|
1474
|
+
let hash = fnv(text, seed);
|
|
1475
|
+
for (let i = 0; i < 4; i++) {
|
|
1476
|
+
out += ALPHABET[hash % 32];
|
|
1477
|
+
hash = Math.floor(hash / 32);
|
|
1478
|
+
}
|
|
1479
|
+
}
|
|
1480
|
+
return `rec_0000000000${out}`;
|
|
1481
|
+
}
|
|
1482
|
+
function seedStatements(manifest, local, now) {
|
|
1483
|
+
const object = manifest.objects[local];
|
|
1484
|
+
const statements = [];
|
|
1485
|
+
const issues = [];
|
|
1486
|
+
if (!object?.seed) return { statements, issues };
|
|
1487
|
+
const table = objectTable(manifest.id, local);
|
|
1488
|
+
const principal = `extension:${manifest.id}`;
|
|
1489
|
+
for (const [key, values] of Object.entries(object.seed)) {
|
|
1490
|
+
const path = `objects.${local}.seed.${key}`;
|
|
1491
|
+
const id = seedRecordId(manifest.id, local, key);
|
|
1492
|
+
const columns = [];
|
|
1493
|
+
const params = [];
|
|
1494
|
+
for (const [name, raw2] of Object.entries(values)) {
|
|
1495
|
+
const field = object.fields[name];
|
|
1496
|
+
if (!field || field.type === "formula") continue;
|
|
1497
|
+
let value = raw2;
|
|
1498
|
+
if (field.type === "relation" && raw2 && typeof raw2 === "object" && !Array.isArray(raw2)) {
|
|
1499
|
+
const target = field.to?.split(".")[1] ?? "";
|
|
1500
|
+
value = seedRecordId(manifest.id, target, String(raw2.seed));
|
|
1501
|
+
}
|
|
1502
|
+
const spec = FIELD_TYPE_REGISTRY[field.type];
|
|
1503
|
+
const parsed = spec.schema(field).safeParse(value);
|
|
1504
|
+
if (!parsed.success) {
|
|
1505
|
+
issues.push({
|
|
1506
|
+
path: `${path}.${name}`,
|
|
1507
|
+
message: `Invalid seed value for ${name}: ${parsed.error.issues[0]?.message ?? "invalid"}`
|
|
1508
|
+
});
|
|
1509
|
+
continue;
|
|
1510
|
+
}
|
|
1511
|
+
columns.push(columnName(name));
|
|
1512
|
+
params.push(spec.toStorage(parsed.data));
|
|
1513
|
+
}
|
|
1514
|
+
const all = ["id", "created_at", "updated_at", "created_by", ...columns];
|
|
1515
|
+
statements.push(
|
|
1516
|
+
CompiledQuery.raw(
|
|
1517
|
+
`INSERT OR IGNORE INTO ${table} (${all.join(", ")}) VALUES (${all.map(() => "?").join(", ")})`,
|
|
1518
|
+
[id, now, now, principal, ...params]
|
|
1519
|
+
)
|
|
1520
|
+
);
|
|
1521
|
+
const title = values[object.titleField];
|
|
1522
|
+
statements.push(
|
|
1523
|
+
CompiledQuery.raw(
|
|
1524
|
+
"INSERT OR IGNORE INTO core_search_docs (object_type, record_id, title, body) VALUES (?, ?, ?, '')",
|
|
1525
|
+
[`${manifest.id}.${local}`, id, typeof title === "string" ? title : ""]
|
|
1526
|
+
)
|
|
1527
|
+
);
|
|
1528
|
+
}
|
|
1529
|
+
return { statements, issues };
|
|
1530
|
+
}
|
|
1531
|
+
|
|
1532
|
+
// ../core/src/extensions/reconciler.ts
|
|
1533
|
+
var HIDDEN_RETENTION_DAYS = 30;
|
|
1534
|
+
function clone(state) {
|
|
1535
|
+
return structuredClone(state);
|
|
1536
|
+
}
|
|
1537
|
+
function columnDdl(name, type) {
|
|
1538
|
+
const storage = FIELD_TYPE_REGISTRY[type].storage;
|
|
1539
|
+
if (!storage) throw new Error(`${type} fields have no column`);
|
|
1540
|
+
return `${ident(name)} ${storage}`;
|
|
1541
|
+
}
|
|
1542
|
+
function stateDefault(object, field) {
|
|
1543
|
+
const states = object?.states;
|
|
1544
|
+
return states?.field === field ? ` DEFAULT '${states.initial.replace(/'/g, "''")}'` : "";
|
|
1545
|
+
}
|
|
1546
|
+
function storedDefinition(field) {
|
|
1547
|
+
const { renamedFrom: _renamed, ...rest } = field;
|
|
1548
|
+
return rest;
|
|
1549
|
+
}
|
|
1550
|
+
function sameDefinition(a, b) {
|
|
1551
|
+
const { resultType: _a, ...left2 } = a;
|
|
1552
|
+
const { resultType: _b, ...right } = b;
|
|
1553
|
+
return JSON.stringify(left2) === JSON.stringify(right);
|
|
1554
|
+
}
|
|
1555
|
+
function sameStorage(a, b) {
|
|
1556
|
+
return FIELD_TYPE_REGISTRY[a].storage === FIELD_TYPE_REGISTRY[b].storage;
|
|
1557
|
+
}
|
|
1558
|
+
var raw = (text) => CompiledQuery.raw(text);
|
|
1559
|
+
async function planReconcile(db, manifest, options) {
|
|
1560
|
+
const { timezone } = await loadGeneralSettings(db);
|
|
1561
|
+
const current = await loadSchemaState(db);
|
|
1562
|
+
const plan = planFromState(db, current, manifest, options.now, timezone);
|
|
1563
|
+
plan.issues.push(...await dataIssues(db, current, plan.next, manifest.id));
|
|
1564
|
+
return plan;
|
|
1565
|
+
}
|
|
1566
|
+
function uniqueIndexes(state, object, ext) {
|
|
1567
|
+
const out = [];
|
|
1568
|
+
(object.definition.unique ?? []).forEach((rule, i) => {
|
|
1569
|
+
const columnOf = (local) => state.fields.find(
|
|
1570
|
+
(f) => f.object === object.name && f.extensionId === ext && f.localName === local && f.status === "active" && f.tableName === object.tableName
|
|
1571
|
+
)?.columnName ?? null;
|
|
1572
|
+
const columns = rule.fields.map(columnOf);
|
|
1573
|
+
const stateColumn = rule.states && object.definition.states ? columnOf(object.definition.states.field) : null;
|
|
1574
|
+
if (columns.some((c) => c === null) || rule.states && !stateColumn) return;
|
|
1575
|
+
const named = columns.map((c) => ident(c));
|
|
1576
|
+
const filled = named.map((c) => `${c} IS NOT NULL`);
|
|
1577
|
+
const states = rule.states ? [`${ident(stateColumn)} IN (${rule.states.map(sqlString).join(", ")})`] : [];
|
|
1578
|
+
const where = ["deleted_at IS NULL", ...filled, ...states].join(" AND ");
|
|
1579
|
+
const name = ident(`${object.tableName}__${named.join("__")}__u${shortHash(where)}`);
|
|
1580
|
+
out.push({ rule: i, name, columns: named, where });
|
|
1581
|
+
});
|
|
1582
|
+
return out;
|
|
1583
|
+
}
|
|
1584
|
+
async function dataIssues(db, current, next, ext) {
|
|
1585
|
+
const issues = [];
|
|
1586
|
+
const reader = orgReader(db);
|
|
1587
|
+
const anyDb = db;
|
|
1588
|
+
for (const object of next.objects) {
|
|
1589
|
+
if (object.extensionId !== ext || object.status !== "active") continue;
|
|
1590
|
+
const before = current.objects.find(
|
|
1591
|
+
(o) => o.name === object.name && o.tableName === object.tableName && o.status === "active"
|
|
1592
|
+
);
|
|
1593
|
+
const installed = getObject(object.name);
|
|
1594
|
+
if (!before || !installed) continue;
|
|
1595
|
+
const columnOf = (name) => name ? installed.fields.find((f) => f.name === name)?.column : void 0;
|
|
1596
|
+
for (const index of uniqueIndexes(next, object, ext)) {
|
|
1597
|
+
if ((current.indexes ?? []).some((i) => i.name === index.name)) continue;
|
|
1598
|
+
const rule = object.definition.unique?.[index.rule];
|
|
1599
|
+
const columns = (rule?.fields ?? []).map(columnOf);
|
|
1600
|
+
if (!rule || columns.some((c) => !c)) continue;
|
|
1601
|
+
const stateColumn = rule.states ? columnOf(object.definition.states?.field) : void 0;
|
|
1602
|
+
if (rule.states && !stateColumn) continue;
|
|
1603
|
+
let query = anyDb.selectFrom(visibleSource(reader, installed)).select(sql`group_concat(id, ', ')`.as("ids"));
|
|
1604
|
+
for (const column2 of columns) query = query.where(column2, "is not", null);
|
|
1605
|
+
if (rule.states && stateColumn) query = query.where(stateColumn, "in", [...rule.states]);
|
|
1606
|
+
const clash = await query.groupBy(columns).having(sql`count(*)`, ">", 1).limit(5).execute();
|
|
1607
|
+
if (clash.length) {
|
|
1608
|
+
issues.push({
|
|
1609
|
+
code: "unique_conflict",
|
|
1610
|
+
path: `objects.${object.localName}.unique.${index.rule}`,
|
|
1611
|
+
message: `${object.name}: live records already share these values: ${clash.map((r) => r.ids).join("; ")}. Change or delete them first.`
|
|
1612
|
+
});
|
|
1613
|
+
}
|
|
1614
|
+
}
|
|
1615
|
+
const was = before.definition.claims;
|
|
1616
|
+
const now = object.definition.claims;
|
|
1617
|
+
if (JSON.stringify(was ?? null) === JSON.stringify(now ?? null)) continue;
|
|
1618
|
+
const column = columnOf(object.definition.states?.field ?? before.definition.states?.field);
|
|
1619
|
+
const states = [
|
|
1620
|
+
.../* @__PURE__ */ new Set([
|
|
1621
|
+
...was?.held ?? [],
|
|
1622
|
+
...was?.confirmed ?? [],
|
|
1623
|
+
...now?.held ?? [],
|
|
1624
|
+
...now?.confirmed ?? []
|
|
1625
|
+
])
|
|
1626
|
+
];
|
|
1627
|
+
if (!column || !states.length) continue;
|
|
1628
|
+
const live = await anyDb.selectFrom(visibleSource(reader, installed)).select("id").where(column, "in", states).limit(10).execute();
|
|
1629
|
+
if (live.length) {
|
|
1630
|
+
issues.push({
|
|
1631
|
+
code: "claims_conflict",
|
|
1632
|
+
path: `objects.${object.localName}.claims`,
|
|
1633
|
+
message: `${object.name}: claims cannot change while records are in a state it names (${states.join(", ")}): ${live.map((r) => r.id).join(", ")}. Move them out of those states first.`
|
|
1634
|
+
});
|
|
1635
|
+
}
|
|
1636
|
+
}
|
|
1637
|
+
return issues;
|
|
1638
|
+
}
|
|
1639
|
+
function planFromState(db, current, manifest, now, orgZone = "UTC") {
|
|
1640
|
+
const ext = manifest.id;
|
|
1641
|
+
const next = clone(current);
|
|
1642
|
+
const tableDdl = [];
|
|
1643
|
+
const dataStatements = [];
|
|
1644
|
+
const changes = [];
|
|
1645
|
+
const issues = [];
|
|
1646
|
+
const seedWrites = [];
|
|
1647
|
+
const knownTables = /* @__PURE__ */ new Set([
|
|
1648
|
+
...current.objects.map((o) => o.tableName),
|
|
1649
|
+
...current.fields.map((f) => f.tableName)
|
|
1650
|
+
]);
|
|
1651
|
+
const declaredObjects = /* @__PURE__ */ new Set();
|
|
1652
|
+
for (const [local, object] of Object.entries(manifest.objects)) {
|
|
1653
|
+
const name = `${ext}.${local}`;
|
|
1654
|
+
declaredObjects.add(name);
|
|
1655
|
+
const definition = {
|
|
1656
|
+
label: object.label,
|
|
1657
|
+
plural: object.plural,
|
|
1658
|
+
...object.icon ? { icon: object.icon } : {},
|
|
1659
|
+
titleField: object.titleField,
|
|
1660
|
+
...object.description ? { description: object.description } : {},
|
|
1661
|
+
fieldOrder: Object.keys(object.fields),
|
|
1662
|
+
...object.navigation ? { navigation: object.navigation } : {},
|
|
1663
|
+
...object.indexes?.length ? { indexes: object.indexes } : {},
|
|
1664
|
+
...object.timelineLinks?.length ? { timelineLinks: object.timelineLinks } : {},
|
|
1665
|
+
...object.stages ? { stages: object.stages } : {},
|
|
1666
|
+
...object.capacity ? { capacity: object.capacity } : {},
|
|
1667
|
+
...object.sellable ? { sellable: object.sellable } : {},
|
|
1668
|
+
...object.allowance ? { allowance: object.allowance } : {},
|
|
1669
|
+
...object.states ? { states: object.states } : {},
|
|
1670
|
+
...object.claims ? { claims: object.claims } : {},
|
|
1671
|
+
...object.unique?.length ? { unique: object.unique } : {},
|
|
1672
|
+
...object.recurring ? { recurring: object.recurring } : {},
|
|
1673
|
+
...object.owner ? { owner: object.owner } : {},
|
|
1674
|
+
...object.customer ? { customer: object.customer } : {},
|
|
1675
|
+
...object.public ? { public: object.public } : {},
|
|
1676
|
+
...object.signedIn ? { signedIn: object.signedIn } : {},
|
|
1677
|
+
...object.customerVia ? { customerVia: object.customerVia } : {},
|
|
1678
|
+
...object.access ? { access: object.access } : {},
|
|
1679
|
+
...object.publishable ? { publishable: object.publishable } : {},
|
|
1680
|
+
...object.navigationOrder !== void 0 ? { navigationOrder: object.navigationOrder } : {},
|
|
1681
|
+
...object.requireOneOf?.length ? { requireOneOf: object.requireOneOf } : {},
|
|
1682
|
+
...object.titleDefault ? { titleDefault: object.titleDefault } : {}
|
|
1683
|
+
};
|
|
1684
|
+
let existing = next.objects.find((o) => o.name === name);
|
|
1685
|
+
if (!existing && object.renamedFrom) {
|
|
1686
|
+
const oldName = `${ext}.${object.renamedFrom}`;
|
|
1687
|
+
const old = next.objects.find((o) => o.name === oldName);
|
|
1688
|
+
if (old) {
|
|
1689
|
+
const table2 = objectTable(ext, local);
|
|
1690
|
+
if (knownTables.has(table2)) {
|
|
1691
|
+
issues.push({
|
|
1692
|
+
code: "rename_conflict",
|
|
1693
|
+
path: `objects.${local}.renamedFrom`,
|
|
1694
|
+
message: `Cannot rename ${oldName} to ${name}: table ${table2} already exists`
|
|
1695
|
+
});
|
|
1696
|
+
continue;
|
|
1697
|
+
}
|
|
1698
|
+
tableDdl.push(`ALTER TABLE ${ident(old.tableName)} RENAME TO ${table2}`);
|
|
1699
|
+
for (const table3 of [
|
|
1700
|
+
"core_activity_links",
|
|
1701
|
+
"core_task_links",
|
|
1702
|
+
"core_record_tags",
|
|
1703
|
+
"core_search_docs"
|
|
1704
|
+
]) {
|
|
1705
|
+
dataStatements.push(
|
|
1706
|
+
CompiledQuery.raw(`UPDATE ${table3} SET object_type = ? WHERE object_type = ?`, [
|
|
1707
|
+
name,
|
|
1708
|
+
oldName
|
|
1709
|
+
])
|
|
1710
|
+
);
|
|
1711
|
+
}
|
|
1712
|
+
for (const field of next.fields) {
|
|
1713
|
+
if (field.object === oldName) {
|
|
1714
|
+
field.object = name;
|
|
1715
|
+
if (field.tableName === old.tableName) field.tableName = table2;
|
|
1716
|
+
field.updatedAt = now;
|
|
1717
|
+
}
|
|
1718
|
+
}
|
|
1719
|
+
old.name = name;
|
|
1720
|
+
old.localName = local;
|
|
1721
|
+
old.tableName = table2;
|
|
1722
|
+
old.updatedAt = now;
|
|
1723
|
+
knownTables.add(table2);
|
|
1724
|
+
changes.push({ kind: "rename_object", object: name, from: oldName });
|
|
1725
|
+
existing = old;
|
|
1726
|
+
}
|
|
1727
|
+
}
|
|
1728
|
+
if (existing) {
|
|
1729
|
+
if (existing.status === "hidden") {
|
|
1730
|
+
existing.status = "active";
|
|
1731
|
+
existing.hiddenAt = null;
|
|
1732
|
+
changes.push({ kind: "restore_object", object: name });
|
|
1733
|
+
}
|
|
1734
|
+
if (JSON.stringify(existing.definition) !== JSON.stringify(definition)) {
|
|
1735
|
+
changes.push({ kind: "update_object", object: name });
|
|
1736
|
+
}
|
|
1737
|
+
existing.definition = definition;
|
|
1738
|
+
existing.updatedAt = now;
|
|
1739
|
+
continue;
|
|
1740
|
+
}
|
|
1741
|
+
const table = objectTable(ext, local);
|
|
1742
|
+
const columns = Object.entries(object.fields).filter(([, field]) => field.type !== "formula").map(
|
|
1743
|
+
([field, spec]) => columnDdl(columnName(field), spec.type) + stateDefault(object, field)
|
|
1744
|
+
);
|
|
1745
|
+
tableDdl.push(
|
|
1746
|
+
`CREATE TABLE ${table} (id TEXT PRIMARY KEY NOT NULL, created_at TEXT NOT NULL, updated_at TEXT NOT NULL, created_by TEXT, updated_by TEXT, deleted_at TEXT, deleted_by TEXT${columns.length ? `, ${columns.join(", ")}` : ""})`
|
|
1747
|
+
);
|
|
1748
|
+
knownTables.add(table);
|
|
1749
|
+
next.objects.push({
|
|
1750
|
+
name,
|
|
1751
|
+
extensionId: ext,
|
|
1752
|
+
localName: local,
|
|
1753
|
+
tableName: table,
|
|
1754
|
+
status: "active",
|
|
1755
|
+
hiddenAt: null,
|
|
1756
|
+
definition,
|
|
1757
|
+
createdAt: now,
|
|
1758
|
+
updatedAt: now
|
|
1759
|
+
});
|
|
1760
|
+
changes.push({ kind: "create_object", object: name });
|
|
1761
|
+
if (object.seed && Object.keys(object.seed).length) {
|
|
1762
|
+
const seeded = seedStatements(manifest, local, now);
|
|
1763
|
+
for (const issue of seeded.issues) issues.push({ code: "seed", ...issue });
|
|
1764
|
+
seedWrites.push(...seeded.statements);
|
|
1765
|
+
changes.push({
|
|
1766
|
+
kind: "seed_records",
|
|
1767
|
+
object: name,
|
|
1768
|
+
detail: `${Object.keys(object.seed).length} record(s)`
|
|
1769
|
+
});
|
|
1770
|
+
}
|
|
1771
|
+
for (const [field, spec] of Object.entries(object.fields)) {
|
|
1772
|
+
next.fields.push({
|
|
1773
|
+
extensionId: ext,
|
|
1774
|
+
object: name,
|
|
1775
|
+
localName: field,
|
|
1776
|
+
name: field,
|
|
1777
|
+
tableName: table,
|
|
1778
|
+
columnName: spec.type === "formula" ? null : columnName(field),
|
|
1779
|
+
type: spec.type,
|
|
1780
|
+
definition: storedDefinition(spec),
|
|
1781
|
+
status: "active",
|
|
1782
|
+
hiddenAt: null,
|
|
1783
|
+
createdAt: now,
|
|
1784
|
+
updatedAt: now
|
|
1785
|
+
});
|
|
1786
|
+
changes.push({ kind: "add_field", object: name, field });
|
|
1787
|
+
}
|
|
1788
|
+
}
|
|
1789
|
+
for (const object of next.objects) {
|
|
1790
|
+
if (object.extensionId !== ext || object.status !== "active") continue;
|
|
1791
|
+
if (!declaredObjects.has(object.name)) {
|
|
1792
|
+
object.status = "hidden";
|
|
1793
|
+
object.hiddenAt = now;
|
|
1794
|
+
object.updatedAt = now;
|
|
1795
|
+
changes.push({
|
|
1796
|
+
kind: "hide_object",
|
|
1797
|
+
object: object.name,
|
|
1798
|
+
detail: `Hidden; its records are kept and can be dropped after ${HIDDEN_RETENTION_DAYS} days`
|
|
1799
|
+
});
|
|
1800
|
+
}
|
|
1801
|
+
}
|
|
1802
|
+
const targets = [
|
|
1803
|
+
...Object.entries(manifest.objects).map(
|
|
1804
|
+
([local, o]) => [`${ext}.${local}`, o.fields, `objects.${local}.fields`]
|
|
1805
|
+
),
|
|
1806
|
+
...Object.entries(manifest.fields).map(
|
|
1807
|
+
([target, fields]) => [target, fields, `fields.${target}`]
|
|
1808
|
+
)
|
|
1809
|
+
];
|
|
1810
|
+
const declaredFields = /* @__PURE__ */ new Set();
|
|
1811
|
+
for (const [target, fields, basePath] of targets) {
|
|
1812
|
+
const own = target.startsWith(`${ext}.`);
|
|
1813
|
+
if (!own) {
|
|
1814
|
+
if (!isCoreTarget(target)) {
|
|
1815
|
+
const parts = splitObjectName(target);
|
|
1816
|
+
const exists = next.objects.some((o) => o.name === target && o.status === "active");
|
|
1817
|
+
if (!parts || !exists) {
|
|
1818
|
+
issues.push({
|
|
1819
|
+
code: "unknown_target",
|
|
1820
|
+
path: basePath,
|
|
1821
|
+
message: `Cannot add fields to ${target}: no such object is installed`
|
|
1822
|
+
});
|
|
1823
|
+
continue;
|
|
1824
|
+
}
|
|
1825
|
+
}
|
|
1826
|
+
}
|
|
1827
|
+
const table = own ? next.objects.find((o) => o.name === target).tableName : sideTable(ext, target);
|
|
1828
|
+
for (const [local, spec] of Object.entries(fields)) {
|
|
1829
|
+
const name = registryFieldName(ext, target, local);
|
|
1830
|
+
const path = `${basePath}.${local}`;
|
|
1831
|
+
declaredFields.add(`${target}|${name}`);
|
|
1832
|
+
const mine = (f) => f.extensionId === ext && f.object === target;
|
|
1833
|
+
let existing = next.fields.find((f) => mine(f) && f.localName === local);
|
|
1834
|
+
if (existing && existing.createdAt === now && existing.updatedAt === now && own) {
|
|
1835
|
+
if (changes.some((c) => c.kind === "create_object" && c.object === target)) continue;
|
|
1836
|
+
}
|
|
1837
|
+
if (!existing && spec.renamedFrom) {
|
|
1838
|
+
const old = next.fields.find(
|
|
1839
|
+
(f) => mine(f) && f.localName === spec.renamedFrom && f.status === "active"
|
|
1840
|
+
);
|
|
1841
|
+
if (old) {
|
|
1842
|
+
if (old.columnName) {
|
|
1843
|
+
const column2 = columnName(local);
|
|
1844
|
+
tableDdl.push(
|
|
1845
|
+
`ALTER TABLE ${ident(old.tableName)} RENAME COLUMN ${ident(old.columnName)} TO ${column2}`
|
|
1846
|
+
);
|
|
1847
|
+
old.columnName = column2;
|
|
1848
|
+
}
|
|
1849
|
+
changes.push({ kind: "rename_field", object: target, field: name, from: old.name });
|
|
1850
|
+
old.localName = local;
|
|
1851
|
+
old.name = name;
|
|
1852
|
+
old.updatedAt = now;
|
|
1853
|
+
existing = old;
|
|
1854
|
+
}
|
|
1855
|
+
}
|
|
1856
|
+
if (existing) {
|
|
1857
|
+
if (existing.status === "hidden") {
|
|
1858
|
+
if (!sameStorage(existing.type, spec.type) || existing.type === "formula" !== (spec.type === "formula")) {
|
|
1859
|
+
issues.push({
|
|
1860
|
+
code: "hidden_conflict",
|
|
1861
|
+
path,
|
|
1862
|
+
message: `A removed ${existing.type} field named ${local} still holds data on ${target}`,
|
|
1863
|
+
suggestion: `Choose another name, or drop the hidden field first (extension.dropHidden)`
|
|
1864
|
+
});
|
|
1865
|
+
continue;
|
|
1866
|
+
}
|
|
1867
|
+
existing.status = "active";
|
|
1868
|
+
existing.hiddenAt = null;
|
|
1869
|
+
changes.push({ kind: "restore_field", object: target, field: name });
|
|
1870
|
+
}
|
|
1871
|
+
if (existing.type !== spec.type) {
|
|
1872
|
+
const formulaSwap = existing.type === "formula" !== (spec.type === "formula");
|
|
1873
|
+
const manyChange = (existing.definition.many ?? false) !== (spec.many ?? false);
|
|
1874
|
+
if (formulaSwap || manyChange || !isLosslessChange(existing.type, spec.type)) {
|
|
1875
|
+
issues.push({
|
|
1876
|
+
code: "lossy_type_change",
|
|
1877
|
+
path: `${path}.type`,
|
|
1878
|
+
message: `Changing ${target}.${name} from ${existing.type} to ${spec.type} could lose data`,
|
|
1879
|
+
suggestion: `Add a new ${spec.type} field (e.g. ${local}${spec.type[0]?.toUpperCase()}${spec.type.slice(1)}), copy the values with a tool, then remove ${local}`
|
|
1880
|
+
});
|
|
1881
|
+
continue;
|
|
1882
|
+
}
|
|
1883
|
+
changes.push({
|
|
1884
|
+
kind: "change_type",
|
|
1885
|
+
object: target,
|
|
1886
|
+
field: name,
|
|
1887
|
+
detail: `${existing.type} \u2192 ${spec.type}`
|
|
1888
|
+
});
|
|
1889
|
+
existing.type = spec.type;
|
|
1890
|
+
} else if ((existing.definition.many ?? false) !== (spec.many ?? false)) {
|
|
1891
|
+
issues.push({
|
|
1892
|
+
code: "lossy_type_change",
|
|
1893
|
+
path: `${path}.many`,
|
|
1894
|
+
message: `Changing ${target}.${name} between one and many could lose data`,
|
|
1895
|
+
suggestion: "Add a new relation field instead"
|
|
1896
|
+
});
|
|
1897
|
+
continue;
|
|
1898
|
+
} else if (!sameDefinition(existing.definition, storedDefinition(spec))) {
|
|
1899
|
+
changes.push({ kind: "update_field", object: target, field: name });
|
|
1900
|
+
}
|
|
1901
|
+
existing.definition = storedDefinition(spec);
|
|
1902
|
+
existing.updatedAt = now;
|
|
1903
|
+
continue;
|
|
1904
|
+
}
|
|
1905
|
+
const column = spec.type === "formula" ? null : columnName(local);
|
|
1906
|
+
if (column) {
|
|
1907
|
+
if (!own && !knownTables.has(table)) {
|
|
1908
|
+
tableDdl.push(`CREATE TABLE ${table} (id TEXT PRIMARY KEY NOT NULL)`);
|
|
1909
|
+
knownTables.add(table);
|
|
1910
|
+
}
|
|
1911
|
+
if (next.fields.some((f) => f.tableName === table && f.columnName === column)) {
|
|
1912
|
+
issues.push({
|
|
1913
|
+
code: "rename_conflict",
|
|
1914
|
+
path,
|
|
1915
|
+
message: `Column ${column} already exists on ${table}`,
|
|
1916
|
+
suggestion: "Choose another field name"
|
|
1917
|
+
});
|
|
1918
|
+
continue;
|
|
1919
|
+
}
|
|
1920
|
+
const declaring = own ? manifest.objects[target.slice(ext.length + 1)] : void 0;
|
|
1921
|
+
tableDdl.push(
|
|
1922
|
+
`ALTER TABLE ${table} ADD COLUMN ${columnDdl(column, spec.type)}${stateDefault(declaring, local)}`
|
|
1923
|
+
);
|
|
1924
|
+
if (spec.type === "timezone" && !spec.default) {
|
|
1925
|
+
dataStatements.push(
|
|
1926
|
+
CompiledQuery.raw(
|
|
1927
|
+
`UPDATE ${table} SET ${ident(column)} = COALESCE((SELECT json_extract(value, '$') FROM core_settings WHERE key = ?), 'UTC') WHERE ${ident(column)} IS NULL`,
|
|
1928
|
+
[ORG_TIMEZONE_SETTING]
|
|
1929
|
+
)
|
|
1930
|
+
);
|
|
1931
|
+
}
|
|
1932
|
+
}
|
|
1933
|
+
next.fields.push({
|
|
1934
|
+
extensionId: ext,
|
|
1935
|
+
object: target,
|
|
1936
|
+
localName: local,
|
|
1937
|
+
name,
|
|
1938
|
+
tableName: table,
|
|
1939
|
+
columnName: column,
|
|
1940
|
+
type: spec.type,
|
|
1941
|
+
definition: storedDefinition(spec),
|
|
1942
|
+
status: "active",
|
|
1943
|
+
hiddenAt: null,
|
|
1944
|
+
createdAt: now,
|
|
1945
|
+
updatedAt: now
|
|
1946
|
+
});
|
|
1947
|
+
changes.push({ kind: "add_field", object: target, field: name });
|
|
1948
|
+
}
|
|
1949
|
+
}
|
|
1950
|
+
for (const field of next.fields) {
|
|
1951
|
+
if (field.extensionId !== ext || field.status !== "active") continue;
|
|
1952
|
+
if (!declaredFields.has(`${field.object}|${field.name}`)) {
|
|
1953
|
+
const objectHidden = next.objects.some(
|
|
1954
|
+
(o) => o.name === field.object && o.status === "hidden"
|
|
1955
|
+
);
|
|
1956
|
+
if (objectHidden) continue;
|
|
1957
|
+
field.status = "hidden";
|
|
1958
|
+
field.hiddenAt = now;
|
|
1959
|
+
field.updatedAt = now;
|
|
1960
|
+
changes.push({
|
|
1961
|
+
kind: "hide_field",
|
|
1962
|
+
object: field.object,
|
|
1963
|
+
field: field.name,
|
|
1964
|
+
detail: `Hidden; its data is kept and can be dropped after ${HIDDEN_RETENTION_DAYS} days`
|
|
1965
|
+
});
|
|
1966
|
+
}
|
|
1967
|
+
}
|
|
1968
|
+
for (const object of next.objects) {
|
|
1969
|
+
if (object.extensionId !== ext || object.status !== "active") continue;
|
|
1970
|
+
const wanted = /* @__PURE__ */ new Map();
|
|
1971
|
+
for (const fields of object.definition.indexes ?? []) {
|
|
1972
|
+
const columns = fields.map((field) => {
|
|
1973
|
+
if (field === "createdAt") return "created_at";
|
|
1974
|
+
if (field === "updatedAt") return "updated_at";
|
|
1975
|
+
const state = next.fields.find(
|
|
1976
|
+
(f) => f.object === object.name && f.extensionId === ext && f.localName === field
|
|
1977
|
+
);
|
|
1978
|
+
return state?.columnName ?? null;
|
|
1979
|
+
});
|
|
1980
|
+
if (columns.some((c) => c === null)) continue;
|
|
1981
|
+
const name = ident(`${object.tableName}__${columns.join("__")}`);
|
|
1982
|
+
wanted.set(
|
|
1983
|
+
name,
|
|
1984
|
+
`CREATE INDEX IF NOT EXISTS ${name} ON ${ident(object.tableName)} (${columns.join(", ")}) WHERE deleted_at IS NULL`
|
|
1985
|
+
);
|
|
1986
|
+
}
|
|
1987
|
+
for (const field of next.fields) {
|
|
1988
|
+
if (field.object !== object.name || field.extensionId !== ext || field.status !== "active" || field.type !== "slug" || !field.columnName || field.tableName !== object.tableName) {
|
|
1989
|
+
continue;
|
|
1990
|
+
}
|
|
1991
|
+
const column = ident(field.columnName);
|
|
1992
|
+
const name = ident(`${object.tableName}__${column}__unique`);
|
|
1993
|
+
wanted.set(
|
|
1994
|
+
name,
|
|
1995
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS ${name} ON ${ident(object.tableName)} (${column}) WHERE deleted_at IS NULL AND ${column} IS NOT NULL`
|
|
1996
|
+
);
|
|
1997
|
+
}
|
|
1998
|
+
for (const index of uniqueIndexes(next, object, ext)) {
|
|
1999
|
+
wanted.set(
|
|
2000
|
+
index.name,
|
|
2001
|
+
`CREATE UNIQUE INDEX IF NOT EXISTS ${index.name} ON ${ident(object.tableName)} (${index.columns.join(", ")}) WHERE ${index.where}`
|
|
2002
|
+
);
|
|
2003
|
+
}
|
|
2004
|
+
const existing = (current.indexes ?? []).filter(
|
|
2005
|
+
(index) => index.table === object.tableName && index.name.startsWith(`${object.tableName}__`)
|
|
2006
|
+
);
|
|
2007
|
+
for (const index of existing) {
|
|
2008
|
+
if (wanted.has(index.name)) continue;
|
|
2009
|
+
tableDdl.push(`DROP INDEX IF EXISTS ${ident(index.name)}`);
|
|
2010
|
+
changes.push({ kind: "drop_index", object: object.name, detail: index.name });
|
|
2011
|
+
}
|
|
2012
|
+
for (const [name, ddl] of wanted) {
|
|
2013
|
+
if (existing.some((index) => index.name === name)) continue;
|
|
2014
|
+
tableDdl.push(ddl);
|
|
2015
|
+
changes.push({ kind: "add_index", object: object.name, detail: name });
|
|
2016
|
+
}
|
|
2017
|
+
}
|
|
2018
|
+
return finishPlan(
|
|
2019
|
+
db,
|
|
2020
|
+
ext,
|
|
2021
|
+
current,
|
|
2022
|
+
next,
|
|
2023
|
+
tableDdl,
|
|
2024
|
+
[
|
|
2025
|
+
...dataStatements,
|
|
2026
|
+
...seedWrites,
|
|
2027
|
+
...capacityBackfill(next, ext, now),
|
|
2028
|
+
...allowanceBackfill(next, ext, orgZone, now)
|
|
2029
|
+
],
|
|
2030
|
+
changes,
|
|
2031
|
+
issues
|
|
2032
|
+
);
|
|
2033
|
+
}
|
|
2034
|
+
function finishPlan(db, ext, current, next, tableDdl, dataStatements, changes, issues) {
|
|
2035
|
+
const views = buildViews(next);
|
|
2036
|
+
for (const { object, field, error } of views.errors) {
|
|
2037
|
+
const f = next.fields.find((x) => x.object === object && x.name === field);
|
|
2038
|
+
if (f?.extensionId !== ext) continue;
|
|
2039
|
+
issues.push({
|
|
2040
|
+
code: "formula",
|
|
2041
|
+
path: `${object}.${field}`,
|
|
2042
|
+
message: `${object}.${field}: ${error.message}`
|
|
2043
|
+
});
|
|
2044
|
+
}
|
|
2045
|
+
for (const field of next.fields) {
|
|
2046
|
+
const type = views.formulaTypes.get(`${field.object}|${field.name}`);
|
|
2047
|
+
if (type) field.definition = { ...field.definition, resultType: type };
|
|
2048
|
+
}
|
|
2049
|
+
const staleViews = current.objects.filter(
|
|
2050
|
+
(o) => !next.objects.some((n) => n.tableName === o.tableName && n.localName === o.localName)
|
|
2051
|
+
).map((o) => `DROP VIEW IF EXISTS ${objectView(o.extensionId, o.localName)}`);
|
|
2052
|
+
const ddl = [.../* @__PURE__ */ new Set([...staleViews, ...views.drops]), ...tableDdl, ...views.creates];
|
|
2053
|
+
const touched = /* @__PURE__ */ new Set([
|
|
2054
|
+
ext,
|
|
2055
|
+
...next.fields.filter((f) => changes.some((c) => c.object === f.object)).map((f) => f.extensionId)
|
|
2056
|
+
]);
|
|
2057
|
+
const stateWrites = [];
|
|
2058
|
+
for (const extension of touched) {
|
|
2059
|
+
stateWrites.push(
|
|
2060
|
+
db.deleteFrom("core_extension_fields").where("extension_id", "=", extension).compile(),
|
|
2061
|
+
db.deleteFrom("core_extension_objects").where("extension_id", "=", extension).compile()
|
|
2062
|
+
);
|
|
2063
|
+
for (const object of next.objects.filter((o) => o.extensionId === extension)) {
|
|
2064
|
+
stateWrites.push(
|
|
2065
|
+
db.insertInto("core_extension_objects").values({
|
|
2066
|
+
name: object.name,
|
|
2067
|
+
extension_id: object.extensionId,
|
|
2068
|
+
local_name: object.localName,
|
|
2069
|
+
table_name: object.tableName,
|
|
2070
|
+
status: object.status,
|
|
2071
|
+
hidden_at: object.hiddenAt,
|
|
2072
|
+
definition: JSON.stringify(object.definition),
|
|
2073
|
+
created_at: object.createdAt,
|
|
2074
|
+
updated_at: object.updatedAt
|
|
2075
|
+
}).compile()
|
|
2076
|
+
);
|
|
2077
|
+
}
|
|
2078
|
+
const rows = next.fields.filter((f) => f.extensionId === extension);
|
|
2079
|
+
for (const field of rows) {
|
|
2080
|
+
stateWrites.push(
|
|
2081
|
+
db.insertInto("core_extension_fields").values({
|
|
2082
|
+
extension_id: field.extensionId,
|
|
2083
|
+
object: field.object,
|
|
2084
|
+
local_name: field.localName,
|
|
2085
|
+
name: field.name,
|
|
2086
|
+
table_name: field.tableName,
|
|
2087
|
+
column_name: field.columnName,
|
|
2088
|
+
type: field.type,
|
|
2089
|
+
definition: JSON.stringify(field.definition),
|
|
2090
|
+
status: field.status,
|
|
2091
|
+
hidden_at: field.hiddenAt,
|
|
2092
|
+
created_at: field.createdAt,
|
|
2093
|
+
updated_at: field.updatedAt
|
|
2094
|
+
}).compile()
|
|
2095
|
+
);
|
|
2096
|
+
}
|
|
2097
|
+
}
|
|
2098
|
+
return {
|
|
2099
|
+
extension: ext,
|
|
2100
|
+
ddl,
|
|
2101
|
+
statements: [...ddl.map(raw), ...dataStatements, ...stateWrites],
|
|
2102
|
+
changes,
|
|
2103
|
+
issues,
|
|
2104
|
+
next
|
|
2105
|
+
};
|
|
2106
|
+
}
|
|
2107
|
+
async function planDropHidden(db, ext, options) {
|
|
2108
|
+
const current = await loadSchemaState(db);
|
|
2109
|
+
const next = clone(current);
|
|
2110
|
+
const cutoff = new Date(
|
|
2111
|
+
Date.parse(options.now) - (options.minAgeDays ?? HIDDEN_RETENTION_DAYS) * 864e5
|
|
2112
|
+
).toISOString();
|
|
2113
|
+
const due = (hiddenAt) => hiddenAt !== null && hiddenAt <= cutoff;
|
|
2114
|
+
const wanted = (name) => !options.only || options.only.includes(name);
|
|
2115
|
+
const tableDdl = [];
|
|
2116
|
+
const changes = [];
|
|
2117
|
+
const droppedObjects = next.objects.filter(
|
|
2118
|
+
(o) => o.extensionId === ext && o.status === "hidden" && due(o.hiddenAt) && wanted(o.name)
|
|
2119
|
+
);
|
|
2120
|
+
for (const object of droppedObjects) {
|
|
2121
|
+
tableDdl.push(`DROP TABLE IF EXISTS ${ident(object.tableName)}`);
|
|
2122
|
+
changes.push({ kind: "drop_object", object: object.name });
|
|
2123
|
+
}
|
|
2124
|
+
next.objects = next.objects.filter((o) => !droppedObjects.includes(o));
|
|
2125
|
+
const droppedTables = new Set(droppedObjects.map((o) => o.tableName));
|
|
2126
|
+
const droppedFields = next.fields.filter(
|
|
2127
|
+
(f) => f.extensionId === ext && (droppedTables.has(f.tableName) || f.status === "hidden" && due(f.hiddenAt) && wanted(`${f.object}.${f.name}`))
|
|
2128
|
+
);
|
|
2129
|
+
for (const field of droppedFields) {
|
|
2130
|
+
if (droppedTables.has(field.tableName)) continue;
|
|
2131
|
+
if (field.columnName) {
|
|
2132
|
+
tableDdl.push(`ALTER TABLE ${ident(field.tableName)} DROP COLUMN ${ident(field.columnName)}`);
|
|
2133
|
+
}
|
|
2134
|
+
changes.push({ kind: "drop_field", object: field.object, field: field.name });
|
|
2135
|
+
}
|
|
2136
|
+
next.fields = next.fields.filter((f) => !droppedFields.includes(f));
|
|
2137
|
+
for (const table of new Set(droppedFields.map((f) => f.tableName))) {
|
|
2138
|
+
if (droppedTables.has(table)) continue;
|
|
2139
|
+
const isObjectTable = next.objects.some((o) => o.tableName === table);
|
|
2140
|
+
if (!isObjectTable && !next.fields.some((f) => f.tableName === table)) {
|
|
2141
|
+
tableDdl.push(`DROP TABLE IF EXISTS ${ident(table)}`);
|
|
2142
|
+
}
|
|
2143
|
+
}
|
|
2144
|
+
const capacityDrops = droppedObjects.filter((o) => o.definition.capacity).flatMap((o) => dropCapacityStatements(o.name));
|
|
2145
|
+
const claimantDrops = droppedObjects.filter((o) => o.definition.claims).flatMap((o) => releaseAllClaimsStatements(o.name, options.now));
|
|
2146
|
+
const recurringDrops = droppedObjects.flatMap((o) => dropRecurringStatements(o.name));
|
|
2147
|
+
const allowanceDrops = droppedObjects.flatMap((o) => {
|
|
2148
|
+
const declared = o.definition.allowance;
|
|
2149
|
+
if (!declared) return [];
|
|
2150
|
+
return dropAllowanceStatements(o.name, "holds" in declared ? "holder" : "spender", options.now);
|
|
2151
|
+
});
|
|
2152
|
+
const granted = new Set(
|
|
2153
|
+
current.objects.flatMap((o) => {
|
|
2154
|
+
const to = o.definition.sellable?.grants?.object;
|
|
2155
|
+
return to ? [to.includes(".") ? to : `${o.extensionId}.${to}`] : [];
|
|
2156
|
+
})
|
|
2157
|
+
);
|
|
2158
|
+
const grantDrops = droppedObjects.filter((o) => granted.has(o.name)).map((o) => CompiledQuery.raw("DELETE FROM core_order_grant WHERE object_type = ?", [o.name]));
|
|
2159
|
+
return finishPlan(
|
|
2160
|
+
db,
|
|
2161
|
+
ext,
|
|
2162
|
+
current,
|
|
2163
|
+
next,
|
|
2164
|
+
tableDdl,
|
|
2165
|
+
[...capacityDrops, ...claimantDrops, ...recurringDrops, ...allowanceDrops, ...grantDrops],
|
|
2166
|
+
changes,
|
|
2167
|
+
[]
|
|
2168
|
+
);
|
|
2169
|
+
}
|
|
2170
|
+
function capacityBackfill(state, ext, now) {
|
|
2171
|
+
const objects = state.objects.filter(
|
|
2172
|
+
(o) => o.extensionId === ext && o.status === "active" && o.definition.capacity
|
|
2173
|
+
);
|
|
2174
|
+
const ordered = [
|
|
2175
|
+
...objects.filter((o) => !o.definition.capacity?.pool),
|
|
2176
|
+
...objects.filter((o) => o.definition.capacity?.pool)
|
|
2177
|
+
];
|
|
2178
|
+
const statements = [];
|
|
2179
|
+
for (const object of ordered) {
|
|
2180
|
+
const capacity = object.definition.capacity;
|
|
2181
|
+
if (!capacity) continue;
|
|
2182
|
+
const column = (local) => state.fields.find(
|
|
2183
|
+
(f) => f.object === object.name && f.extensionId === ext && f.localName === local && f.tableName === object.tableName
|
|
2184
|
+
);
|
|
2185
|
+
const places = column(capacity.places);
|
|
2186
|
+
if (!places?.columnName) continue;
|
|
2187
|
+
const pool = capacity.pool ? column(capacity.pool) : void 0;
|
|
2188
|
+
statements.push(
|
|
2189
|
+
backfillCounters({
|
|
2190
|
+
object: object.name,
|
|
2191
|
+
table: ident(object.tableName),
|
|
2192
|
+
placesColumn: ident(places.columnName),
|
|
2193
|
+
pool: pool?.columnName && pool.definition.to ? { column: ident(pool.columnName), object: pool.definition.to } : void 0,
|
|
2194
|
+
now
|
|
2195
|
+
})
|
|
2196
|
+
);
|
|
2197
|
+
}
|
|
2198
|
+
return statements;
|
|
2199
|
+
}
|
|
2200
|
+
function allowanceBackfill(state, ext, orgZone, now) {
|
|
2201
|
+
const statements = [];
|
|
2202
|
+
for (const object of state.objects) {
|
|
2203
|
+
const declared = object.definition.allowance;
|
|
2204
|
+
if (object.extensionId !== ext || object.status !== "active") continue;
|
|
2205
|
+
if (!declared || !("holds" in declared)) continue;
|
|
2206
|
+
const h = declared.holds;
|
|
2207
|
+
const field = (local) => local === void 0 ? void 0 : state.fields.find(
|
|
2208
|
+
(f) => f.object === object.name && f.extensionId === ext && f.localName === local && f.tableName === object.tableName && f.status === "active"
|
|
2209
|
+
);
|
|
2210
|
+
const column = (local) => {
|
|
2211
|
+
const found = field(local);
|
|
2212
|
+
return found?.columnName ? ident(found.columnName) : void 0;
|
|
2213
|
+
};
|
|
2214
|
+
const person = column(h.person);
|
|
2215
|
+
const uses = column(h.uses);
|
|
2216
|
+
const per = typeof h.per === "string" ? { fixed: h.per } : { column: column(h.per.field) };
|
|
2217
|
+
const stateColumn = object.definition.states ? column(object.definition.states.field) : void 0;
|
|
2218
|
+
if (!person || !uses || !per.fixed && !per.column) continue;
|
|
2219
|
+
const bound = (local) => {
|
|
2220
|
+
const found = field(local);
|
|
2221
|
+
return found?.columnName ? { column: ident(found.columnName), date: found.type === "date" } : void 0;
|
|
2222
|
+
};
|
|
2223
|
+
statements.push(
|
|
2224
|
+
...termsSyncStatements(
|
|
2225
|
+
{
|
|
2226
|
+
object: object.name,
|
|
2227
|
+
table: ident(object.tableName),
|
|
2228
|
+
person,
|
|
2229
|
+
uses,
|
|
2230
|
+
per: per.fixed ? { fixed: per.fixed } : { column: per.column },
|
|
2231
|
+
from: bound(h.from),
|
|
2232
|
+
until: bound(h.until),
|
|
2233
|
+
zone: h.zone ? column(h.zone) : void 0,
|
|
2234
|
+
live: h.live && stateColumn ? { column: stateColumn, states: h.live } : void 0,
|
|
2235
|
+
emptyIsUnlimited: h.emptyIsUnlimited === true
|
|
2236
|
+
},
|
|
2237
|
+
"all",
|
|
2238
|
+
orgZone,
|
|
2239
|
+
now
|
|
2240
|
+
)
|
|
2241
|
+
);
|
|
2242
|
+
}
|
|
2243
|
+
return statements;
|
|
2244
|
+
}
|
|
2245
|
+
function sqlString(value) {
|
|
2246
|
+
return `'${value.replaceAll("'", "''")}'`;
|
|
2247
|
+
}
|
|
2248
|
+
function shortHash(text) {
|
|
2249
|
+
let hash = 2166136261;
|
|
2250
|
+
for (let i = 0; i < text.length; i += 1) {
|
|
2251
|
+
hash ^= text.charCodeAt(i);
|
|
2252
|
+
hash = Math.imul(hash, 16777619) >>> 0;
|
|
2253
|
+
}
|
|
2254
|
+
return hash.toString(16).padStart(8, "0");
|
|
2255
|
+
}
|
|
2256
|
+
|
|
2257
|
+
// ../core/src/extensions/install.ts
|
|
2258
|
+
function requireHost(ctx) {
|
|
2259
|
+
if (!ctx.extensionHost) {
|
|
2260
|
+
throw new ConfigError("The extension runtime is not available to this caller");
|
|
2261
|
+
}
|
|
2262
|
+
return ctx.extensionHost;
|
|
2263
|
+
}
|
|
2264
|
+
function fromSource(issue) {
|
|
2265
|
+
return { stage: "typecheck", code: issue.code, path: issue.path, message: issue.message };
|
|
2266
|
+
}
|
|
2267
|
+
function fromManifest(issue) {
|
|
2268
|
+
return {
|
|
2269
|
+
stage: issue.code === "contract" ? "contract" : "formula",
|
|
2270
|
+
code: issue.code,
|
|
2271
|
+
path: issue.path,
|
|
2272
|
+
message: issue.message,
|
|
2273
|
+
...issue.span ? { span: issue.span } : {}
|
|
2274
|
+
};
|
|
2275
|
+
}
|
|
2276
|
+
function fromReconcile(issue) {
|
|
2277
|
+
return {
|
|
2278
|
+
stage: issue.code === "formula" ? "formula" : "reconcile",
|
|
2279
|
+
code: issue.code,
|
|
2280
|
+
path: issue.path,
|
|
2281
|
+
message: issue.message,
|
|
2282
|
+
...issue.suggestion ? { suggestion: issue.suggestion } : {}
|
|
2283
|
+
};
|
|
2284
|
+
}
|
|
2285
|
+
async function checkManifest(db, id, rawManifest, now, options = {}) {
|
|
2286
|
+
const knownObjects = listObjects().map((o) => o.name).filter((name) => name.includes(".") && !name.startsWith(`${id}.`));
|
|
2287
|
+
const { manifest, issues } = validateManifest(rawManifest, {
|
|
2288
|
+
knownObjects,
|
|
2289
|
+
baseFields: (object) => isCoreTarget(object) ? coreFormulaFields(object) : {}
|
|
2290
|
+
});
|
|
2291
|
+
const all = issues.map(fromManifest);
|
|
2292
|
+
for (const [name, dashboard] of Object.entries(manifest?.dashboards ?? {})) {
|
|
2293
|
+
const parsed = dashboardSpecSchema.safeParse(dashboard);
|
|
2294
|
+
if (!parsed.success) {
|
|
2295
|
+
for (const issue of parsed.error.issues.slice(0, 10)) {
|
|
2296
|
+
all.push({
|
|
2297
|
+
stage: "contract",
|
|
2298
|
+
code: "contract",
|
|
2299
|
+
path: `dashboards.${name}.${issue.path.join(".")}`,
|
|
2300
|
+
message: issue.message
|
|
2301
|
+
});
|
|
2302
|
+
}
|
|
2303
|
+
}
|
|
2304
|
+
}
|
|
2305
|
+
if (manifest && options.source === "runtime") all.push(...outsideDeclarations(manifest));
|
|
2306
|
+
const raw2 = rawManifest?.requires;
|
|
2307
|
+
const required = Array.isArray(raw2) ? raw2.filter((r) => typeof r === "string").slice(0, 10) : [];
|
|
2308
|
+
if (required.length) {
|
|
2309
|
+
const present = new Set(
|
|
2310
|
+
(await db.selectFrom("core_extensions").select("id").where("id", "in", required).where("status", "=", "active").execute()).map((r) => r.id)
|
|
2311
|
+
);
|
|
2312
|
+
for (const id2 of options.installed ?? []) present.add(id2);
|
|
2313
|
+
required.forEach((id2, i) => {
|
|
2314
|
+
if (!present.has(id2)) {
|
|
2315
|
+
all.unshift({
|
|
2316
|
+
stage: "contract",
|
|
2317
|
+
code: "contract",
|
|
2318
|
+
path: `requires.${i}`,
|
|
2319
|
+
message: `This extension requires the ${id2} extension, which is not installed and on here`
|
|
2320
|
+
});
|
|
2321
|
+
}
|
|
2322
|
+
});
|
|
2323
|
+
}
|
|
2324
|
+
if (manifest) {
|
|
2325
|
+
for (const issue of allowanceHostIssues(manifest)) {
|
|
2326
|
+
all.push({ stage: "contract", code: "contract", path: issue.path, message: issue.message });
|
|
2327
|
+
}
|
|
2328
|
+
}
|
|
2329
|
+
for (const [name, object] of Object.entries(manifest?.objects ?? {})) {
|
|
2330
|
+
(object.access?.sources ?? []).forEach((source, i) => {
|
|
2331
|
+
if ("kind" in source && source.kind !== void 0 && !hasAccessSourceKind(source.kind)) {
|
|
2332
|
+
all.push({
|
|
2333
|
+
stage: "contract",
|
|
2334
|
+
code: "contract",
|
|
2335
|
+
path: `objects.${name}.access.sources.${i}.kind`,
|
|
2336
|
+
message: `The host provides no source of access of kind "${source.kind}"`
|
|
2337
|
+
});
|
|
2338
|
+
}
|
|
2339
|
+
});
|
|
2340
|
+
}
|
|
2341
|
+
if (manifest && manifest.id !== id) {
|
|
2342
|
+
all.push({
|
|
2343
|
+
stage: "contract",
|
|
2344
|
+
code: "contract",
|
|
2345
|
+
path: "id",
|
|
2346
|
+
message: `The extension declares id "${manifest.id}" but is installed as "${id}"`
|
|
2347
|
+
});
|
|
2348
|
+
}
|
|
2349
|
+
if (!manifest || all.length) return { issues: all, manifest, plan: null };
|
|
2350
|
+
const plan = await planReconcile(db, manifest, { now });
|
|
2351
|
+
return { issues: plan.issues.map(fromReconcile), manifest, plan };
|
|
2352
|
+
}
|
|
2353
|
+
function outsideDeclarations(manifest) {
|
|
2354
|
+
const issues = [];
|
|
2355
|
+
const why = "Only a shipped extension, or one in the org's own repository, can do that: it is a reviewed change. Remove it, or move the extension out of the workspace.";
|
|
2356
|
+
manifest.permissions.operations.forEach((operation, i) => {
|
|
2357
|
+
if (operation.startsWith("x.")) {
|
|
2358
|
+
issues.push({
|
|
2359
|
+
stage: "contract",
|
|
2360
|
+
code: "outside_audience",
|
|
2361
|
+
path: `permissions.operations.${i}`,
|
|
2362
|
+
message: `A runtime extension cannot call another extension's tool (${operation}). ${why}`
|
|
2363
|
+
});
|
|
2364
|
+
}
|
|
2365
|
+
});
|
|
2366
|
+
for (const [name, tool] of Object.entries(manifest.tools)) {
|
|
2367
|
+
const open = (tool.audiences ?? []).filter((audience) => audience !== "staff");
|
|
2368
|
+
if (open.length || tool.customerFields) {
|
|
2369
|
+
issues.push({
|
|
2370
|
+
stage: "contract",
|
|
2371
|
+
code: "outside_audience",
|
|
2372
|
+
path: `tools.${name}.audiences`,
|
|
2373
|
+
message: `A runtime extension cannot open a tool to ${open.join(" or ") || "customer"} callers. ${why}`
|
|
2374
|
+
});
|
|
2375
|
+
}
|
|
2376
|
+
}
|
|
2377
|
+
for (const [name, tool] of Object.entries(manifest.tools)) {
|
|
2378
|
+
if (tool.permission) {
|
|
2379
|
+
issues.push({
|
|
2380
|
+
stage: "contract",
|
|
2381
|
+
code: "outside_audience",
|
|
2382
|
+
path: `tools.${name}.permission`,
|
|
2383
|
+
message: `A runtime extension cannot declare a permission for a staff role. ${why}`
|
|
2384
|
+
});
|
|
2385
|
+
}
|
|
2386
|
+
}
|
|
2387
|
+
if (manifest.grantable?.length) {
|
|
2388
|
+
issues.push({
|
|
2389
|
+
stage: "contract",
|
|
2390
|
+
code: "outside_audience",
|
|
2391
|
+
path: "grantable",
|
|
2392
|
+
message: `A runtime extension cannot declare a permission an admin grants. ${why}`
|
|
2393
|
+
});
|
|
2394
|
+
}
|
|
2395
|
+
for (const name of Object.keys(manifest.roles ?? {})) {
|
|
2396
|
+
issues.push({
|
|
2397
|
+
stage: "contract",
|
|
2398
|
+
code: "outside_audience",
|
|
2399
|
+
path: `roles.${name}`,
|
|
2400
|
+
message: `A runtime extension cannot declare a staff role. ${why}`
|
|
2401
|
+
});
|
|
2402
|
+
}
|
|
2403
|
+
for (const [name, object] of Object.entries(manifest.objects)) {
|
|
2404
|
+
if (object.customer) {
|
|
2405
|
+
issues.push({
|
|
2406
|
+
stage: "contract",
|
|
2407
|
+
code: "outside_audience",
|
|
2408
|
+
path: `objects.${name}.customer`,
|
|
2409
|
+
message: `A runtime extension cannot make ${name} visible to customers. ${why}`
|
|
2410
|
+
});
|
|
2411
|
+
}
|
|
2412
|
+
if (object.public) {
|
|
2413
|
+
issues.push({
|
|
2414
|
+
stage: "contract",
|
|
2415
|
+
code: "outside_audience",
|
|
2416
|
+
path: `objects.${name}.public`,
|
|
2417
|
+
message: `A runtime extension cannot make ${name} readable by the public. ${why}`
|
|
2418
|
+
});
|
|
2419
|
+
}
|
|
2420
|
+
if (object.customerVia) {
|
|
2421
|
+
issues.push({
|
|
2422
|
+
stage: "contract",
|
|
2423
|
+
code: "outside_audience",
|
|
2424
|
+
path: `objects.${name}.customerVia`,
|
|
2425
|
+
message: `A runtime extension cannot make ${name} readable by customers through their own records. ${why}`
|
|
2426
|
+
});
|
|
2427
|
+
}
|
|
2428
|
+
if (object.access) {
|
|
2429
|
+
issues.push({
|
|
2430
|
+
stage: "contract",
|
|
2431
|
+
code: "outside_audience",
|
|
2432
|
+
path: `objects.${name}.access`,
|
|
2433
|
+
message: `A runtime extension cannot declare who holds access to ${name}. ${why}`
|
|
2434
|
+
});
|
|
2435
|
+
}
|
|
2436
|
+
if (object.signedIn) {
|
|
2437
|
+
issues.push({
|
|
2438
|
+
stage: "contract",
|
|
2439
|
+
code: "outside_audience",
|
|
2440
|
+
path: `objects.${name}.signedIn`,
|
|
2441
|
+
message: `A runtime extension cannot make ${name} readable by signed-in customers. ${why}`
|
|
2442
|
+
});
|
|
2443
|
+
}
|
|
2444
|
+
if (object.sellable) {
|
|
2445
|
+
issues.push({
|
|
2446
|
+
stage: "contract",
|
|
2447
|
+
code: "outside_audience",
|
|
2448
|
+
path: `objects.${name}.sellable`,
|
|
2449
|
+
message: `A runtime extension cannot make ${name} something customers and the public can buy. ${why}`
|
|
2450
|
+
});
|
|
2451
|
+
}
|
|
2452
|
+
}
|
|
2453
|
+
return issues;
|
|
2454
|
+
}
|
|
2455
|
+
async function checkEvaluated(db, id, evaluated, now, options = {}) {
|
|
2456
|
+
if (!evaluated.ok) {
|
|
2457
|
+
return { ok: false, issues: evaluated.issues.map(fromSource), manifest: null, plan: null };
|
|
2458
|
+
}
|
|
2459
|
+
const { issues, manifest, plan } = await checkManifest(db, id, evaluated.manifest, now, options);
|
|
2460
|
+
return {
|
|
2461
|
+
ok: issues.length === 0,
|
|
2462
|
+
issues,
|
|
2463
|
+
manifest,
|
|
2464
|
+
plan: plan ? { ddl: plan.ddl, changes: plan.changes } : null
|
|
2465
|
+
};
|
|
2466
|
+
}
|
|
2467
|
+
async function checkExtension(ctx, input) {
|
|
2468
|
+
const host = requireHost(ctx);
|
|
2469
|
+
return checkEvaluated(ctx.db, input.id, await host.evaluate(input), ctx.now, {
|
|
2470
|
+
source: "runtime"
|
|
2471
|
+
});
|
|
2472
|
+
}
|
|
2473
|
+
function firstIssue(issues) {
|
|
2474
|
+
const first = issues[0];
|
|
2475
|
+
if (!first) return "";
|
|
2476
|
+
const more = issues.length > 1 ? ` (and ${issues.length - 1} more)` : "";
|
|
2477
|
+
return `: ${first.path}: ${first.message}${more}`;
|
|
2478
|
+
}
|
|
2479
|
+
function extensionPrincipalId(id) {
|
|
2480
|
+
return `extension:${id}`;
|
|
2481
|
+
}
|
|
2482
|
+
async function installExtension(ctx, input) {
|
|
2483
|
+
const host = requireHost(ctx);
|
|
2484
|
+
const existing = await ctx.db.selectFrom("core_extensions").selectAll().where("id", "=", input.id).executeTakeFirst();
|
|
2485
|
+
const ejecting = input.eject && existing?.source === "shipped" && input.source === "runtime";
|
|
2486
|
+
if (existing && existing.source !== input.source && !ejecting) {
|
|
2487
|
+
throw new ValidationError(
|
|
2488
|
+
`${input.id} is already installed as a ${existing.source} extension`,
|
|
2489
|
+
{ id: input.id }
|
|
2490
|
+
);
|
|
2491
|
+
}
|
|
2492
|
+
const evaluated = await host.evaluate({ id: input.id, commit: input.commit });
|
|
2493
|
+
if (!evaluated.ok) {
|
|
2494
|
+
const issues2 = evaluated.issues.map(fromSource);
|
|
2495
|
+
throw new ValidationError(`${input.id} failed its check${firstIssue(issues2)}`, { issues: issues2 });
|
|
2496
|
+
}
|
|
2497
|
+
const { issues, manifest, plan } = await checkManifest(
|
|
2498
|
+
ctx.db,
|
|
2499
|
+
input.id,
|
|
2500
|
+
evaluated.manifest,
|
|
2501
|
+
ctx.now,
|
|
2502
|
+
{ source: input.source }
|
|
2503
|
+
);
|
|
2504
|
+
if (issues.length || !manifest || !plan) {
|
|
2505
|
+
throw new ValidationError(`${input.id} failed its check${firstIssue(issues)}`, { issues });
|
|
2506
|
+
}
|
|
2507
|
+
const unchanged = existing?.commit_oid === input.commit && existing.status === "active" && plan.changes.length === 0;
|
|
2508
|
+
if (unchanged) {
|
|
2509
|
+
return {
|
|
2510
|
+
id: input.id,
|
|
2511
|
+
version: manifest.version,
|
|
2512
|
+
commit: input.commit,
|
|
2513
|
+
source: input.source,
|
|
2514
|
+
changes: [],
|
|
2515
|
+
changed: false
|
|
2516
|
+
};
|
|
2517
|
+
}
|
|
2518
|
+
const principal = extensionPrincipalId(input.id);
|
|
2519
|
+
const user = await ctx.db.selectFrom("core_user").select("id").where("id", "=", principal).executeTakeFirst();
|
|
2520
|
+
if (!user) {
|
|
2521
|
+
ctx.write(
|
|
2522
|
+
ctx.db.insertInto("core_user").values({
|
|
2523
|
+
id: principal,
|
|
2524
|
+
name: manifest.label ?? input.id,
|
|
2525
|
+
email: `${input.id}@extensions.crm.invalid`,
|
|
2526
|
+
email_verified: 0,
|
|
2527
|
+
image: null,
|
|
2528
|
+
created_at: ctx.now,
|
|
2529
|
+
updated_at: ctx.now,
|
|
2530
|
+
role: "member",
|
|
2531
|
+
kind: "extension"
|
|
2532
|
+
})
|
|
2533
|
+
);
|
|
2534
|
+
}
|
|
2535
|
+
ctx.write(...plan.statements);
|
|
2536
|
+
const installedBy = ctx.user.id === "system" ? null : ctx.user.id;
|
|
2537
|
+
const manifestJson = JSON.stringify(manifest);
|
|
2538
|
+
ctx.write(
|
|
2539
|
+
ctx.db.insertInto("core_extensions").values({
|
|
2540
|
+
id: input.id,
|
|
2541
|
+
source: input.source,
|
|
2542
|
+
status: "active",
|
|
2543
|
+
status_reason: null,
|
|
2544
|
+
version: manifest.version,
|
|
2545
|
+
commit_oid: input.commit,
|
|
2546
|
+
last_good_commit: existing?.last_good_commit ?? null,
|
|
2547
|
+
manifest: manifestJson,
|
|
2548
|
+
failure_count: 0,
|
|
2549
|
+
user_id: principal,
|
|
2550
|
+
installed_at: ctx.now,
|
|
2551
|
+
installed_by: installedBy,
|
|
2552
|
+
updated_at: ctx.now
|
|
2553
|
+
}).onConflict(
|
|
2554
|
+
(oc) => oc.column("id").doUpdateSet({
|
|
2555
|
+
source: input.source,
|
|
2556
|
+
status: "active",
|
|
2557
|
+
status_reason: null,
|
|
2558
|
+
version: manifest.version,
|
|
2559
|
+
commit_oid: input.commit,
|
|
2560
|
+
manifest: manifestJson,
|
|
2561
|
+
failure_count: 0,
|
|
2562
|
+
updated_at: ctx.now
|
|
2563
|
+
})
|
|
2564
|
+
),
|
|
2565
|
+
ctx.db.insertInto("core_extension_versions").values({
|
|
2566
|
+
extension_id: input.id,
|
|
2567
|
+
commit_oid: input.commit,
|
|
2568
|
+
version: manifest.version,
|
|
2569
|
+
manifest: manifestJson,
|
|
2570
|
+
installed_at: ctx.now,
|
|
2571
|
+
installed_by: installedBy
|
|
2572
|
+
}).onConflict(
|
|
2573
|
+
(oc) => oc.columns(["extension_id", "commit_oid"]).doUpdateSet({ installed_at: ctx.now })
|
|
2574
|
+
)
|
|
2575
|
+
);
|
|
2576
|
+
ctx.write(
|
|
2577
|
+
...automationSyncStatements(ctx.db, {
|
|
2578
|
+
extensionId: input.id,
|
|
2579
|
+
commit: input.commit,
|
|
2580
|
+
automations: manifest.automations ?? {},
|
|
2581
|
+
now: ctx.now
|
|
2582
|
+
})
|
|
2583
|
+
);
|
|
2584
|
+
return {
|
|
2585
|
+
id: input.id,
|
|
2586
|
+
version: manifest.version,
|
|
2587
|
+
commit: input.commit,
|
|
2588
|
+
source: input.source,
|
|
2589
|
+
changes: plan.changes,
|
|
2590
|
+
changed: true
|
|
2591
|
+
};
|
|
2592
|
+
}
|
|
2593
|
+
|
|
2594
|
+
export {
|
|
2595
|
+
WIDGET_TYPES,
|
|
2596
|
+
dashboardFilterSchema,
|
|
2597
|
+
filterValuesSchema,
|
|
2598
|
+
widgetSpecSchema,
|
|
2599
|
+
dashboardSpecSchema,
|
|
2600
|
+
SYSTEM_PARAMS,
|
|
2601
|
+
allowedParamNames,
|
|
2602
|
+
listVisible,
|
|
2603
|
+
getVisible,
|
|
2604
|
+
previewVisible,
|
|
2605
|
+
recordAccess,
|
|
2606
|
+
NO_TRIAL_REASONS,
|
|
2607
|
+
decideTrial,
|
|
2608
|
+
readableInstant,
|
|
2609
|
+
holdTrialStatement,
|
|
2610
|
+
useTrial,
|
|
2611
|
+
periodOf,
|
|
2612
|
+
boundOf,
|
|
2613
|
+
termsSyncStatements,
|
|
2614
|
+
keyingChangeStatement,
|
|
2615
|
+
spendStatements,
|
|
2616
|
+
returnStatements,
|
|
2617
|
+
rekeyStatements,
|
|
2618
|
+
armSeriesStatement,
|
|
2619
|
+
seriesVersion,
|
|
2620
|
+
guardStatement,
|
|
2621
|
+
occurrenceStatement,
|
|
2622
|
+
markEditedStatement,
|
|
2623
|
+
HIDDEN_RETENTION_DAYS,
|
|
2624
|
+
planDropHidden,
|
|
2625
|
+
OFFER_IMPORT_MAX,
|
|
2626
|
+
OFFER_STATUSES,
|
|
2627
|
+
OFFER_IMPORT_OUTCOMES,
|
|
2628
|
+
requireManage,
|
|
2629
|
+
importOffers,
|
|
2630
|
+
prepareOfferTake,
|
|
2631
|
+
holdOfferStatements,
|
|
2632
|
+
myOffers,
|
|
2633
|
+
listOffers,
|
|
2634
|
+
exportOffers,
|
|
2635
|
+
withdrawOffer,
|
|
2636
|
+
requireHost,
|
|
2637
|
+
checkManifest,
|
|
2638
|
+
checkEvaluated,
|
|
2639
|
+
checkExtension,
|
|
2640
|
+
installExtension
|
|
2641
|
+
};
|