@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,1370 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
recordHostChange
|
|
4
|
+
} from "./chunk-VTQNOQGA.js";
|
|
5
|
+
import {
|
|
6
|
+
currencyDecimals,
|
|
7
|
+
loadOrderCurrency,
|
|
8
|
+
loadOrderExpiryMinutes,
|
|
9
|
+
loadReturnOrigins,
|
|
10
|
+
localDaysBefore,
|
|
11
|
+
paymentsTarget,
|
|
12
|
+
toMinorUnits
|
|
13
|
+
} from "./chunk-NSSUOI3Z.js";
|
|
14
|
+
import {
|
|
15
|
+
CompiledQuery,
|
|
16
|
+
assertClaimRelationKept,
|
|
17
|
+
claimantMove,
|
|
18
|
+
confirmStatements,
|
|
19
|
+
loadGeneralSettings,
|
|
20
|
+
newId,
|
|
21
|
+
queueClaim,
|
|
22
|
+
releaseStatements
|
|
23
|
+
} from "./chunk-OV3OFYPI.js";
|
|
24
|
+
import {
|
|
25
|
+
ConfigError,
|
|
26
|
+
ConflictError,
|
|
27
|
+
FIELD_TYPE_REGISTRY,
|
|
28
|
+
ForbiddenError,
|
|
29
|
+
NotFoundError,
|
|
30
|
+
ValidationError,
|
|
31
|
+
buyableSource,
|
|
32
|
+
orgReader,
|
|
33
|
+
refreshSchemaRegistry,
|
|
34
|
+
scopeOf,
|
|
35
|
+
sql,
|
|
36
|
+
viewColumnOf,
|
|
37
|
+
visibleSource
|
|
38
|
+
} from "./chunk-7O4F3NU4.js";
|
|
39
|
+
import {
|
|
40
|
+
getObject,
|
|
41
|
+
listObjects
|
|
42
|
+
} from "./chunk-3MIEYXRY.js";
|
|
43
|
+
import {
|
|
44
|
+
orderObject
|
|
45
|
+
} from "./chunk-ZSR5H4O7.js";
|
|
46
|
+
import {
|
|
47
|
+
moveOrigins
|
|
48
|
+
} from "./chunk-2MLAPQU7.js";
|
|
49
|
+
|
|
50
|
+
// ../core/src/records/transitions.ts
|
|
51
|
+
function callerOf(ctx) {
|
|
52
|
+
return ctx.onBehalfOf ?? ctx.principal;
|
|
53
|
+
}
|
|
54
|
+
function enteredBy(ctx) {
|
|
55
|
+
return callerOf(ctx).kind === "staff" ? ctx.user.id : null;
|
|
56
|
+
}
|
|
57
|
+
var ALL_MOVERS = ["staff", "customer", "host"];
|
|
58
|
+
var TransitionRuleError = class extends ValidationError {
|
|
59
|
+
name = "TransitionRuleError";
|
|
60
|
+
};
|
|
61
|
+
var NO_TRANSITION = {
|
|
62
|
+
values: {},
|
|
63
|
+
history: [],
|
|
64
|
+
moved: null,
|
|
65
|
+
left: null,
|
|
66
|
+
field: null
|
|
67
|
+
};
|
|
68
|
+
function isEmptyValue(value) {
|
|
69
|
+
return value === null || value === void 0 || typeof value === "string" && value.trim() === "" || Array.isArray(value) && value.length === 0;
|
|
70
|
+
}
|
|
71
|
+
function ruleBase(write, rule, fields) {
|
|
72
|
+
return {
|
|
73
|
+
rule,
|
|
74
|
+
object: write.object.name,
|
|
75
|
+
field: fields[0],
|
|
76
|
+
fields,
|
|
77
|
+
labels: fields.map(write.labelOf)
|
|
78
|
+
};
|
|
79
|
+
}
|
|
80
|
+
async function runTransition(lifecycle, ctx, object, id, before, written, by) {
|
|
81
|
+
const values = {};
|
|
82
|
+
const after = { ...before ?? {}, ...written };
|
|
83
|
+
const has = (field) => Object.hasOwn(written, field);
|
|
84
|
+
const write = {
|
|
85
|
+
ctx,
|
|
86
|
+
object,
|
|
87
|
+
id,
|
|
88
|
+
before,
|
|
89
|
+
written,
|
|
90
|
+
after,
|
|
91
|
+
by,
|
|
92
|
+
has,
|
|
93
|
+
changed: (field) => has(field) && JSON.stringify(written[field] ?? null) !== JSON.stringify(before?.[field] ?? null),
|
|
94
|
+
set: (field, value) => {
|
|
95
|
+
if (!field) return;
|
|
96
|
+
values[field] = value;
|
|
97
|
+
after[field] = value;
|
|
98
|
+
},
|
|
99
|
+
labelOf: (field) => object.fields.find((f) => f.name === field)?.label ?? field
|
|
100
|
+
};
|
|
101
|
+
const placement = await lifecycle.place(write);
|
|
102
|
+
if (!placement) return NO_TRANSITION;
|
|
103
|
+
const { to } = placement;
|
|
104
|
+
const moved = to.id !== placement.fromId;
|
|
105
|
+
if (moved && !placement.by.includes(by)) {
|
|
106
|
+
throw lifecycle.refusal(
|
|
107
|
+
write,
|
|
108
|
+
{
|
|
109
|
+
rule: "move_not_permitted",
|
|
110
|
+
message: notPermittedMessage(object, to, placement.by),
|
|
111
|
+
fields: [lifecycle.field]
|
|
112
|
+
},
|
|
113
|
+
placement
|
|
114
|
+
);
|
|
115
|
+
}
|
|
116
|
+
lifecycle.follow?.(write, placement, moved);
|
|
117
|
+
const required = [...new Set(placement.requires)].filter(
|
|
118
|
+
(field) => object.fields.some((f) => f.name === field)
|
|
119
|
+
);
|
|
120
|
+
const checked = moved || before === null ? required : required.filter(write.changed);
|
|
121
|
+
const missing = checked.filter((field) => isEmptyValue(after[field]));
|
|
122
|
+
if (missing.length) {
|
|
123
|
+
throw lifecycle.refusal(
|
|
124
|
+
write,
|
|
125
|
+
{
|
|
126
|
+
rule: "required_fields",
|
|
127
|
+
message: `${to.title} needs ${missing.map(write.labelOf).join(", ")}`,
|
|
128
|
+
fields: missing
|
|
129
|
+
},
|
|
130
|
+
placement
|
|
131
|
+
);
|
|
132
|
+
}
|
|
133
|
+
const history = [];
|
|
134
|
+
if (moved) {
|
|
135
|
+
if (before !== null) {
|
|
136
|
+
const column3 = object.fields.find((f) => f.name === lifecycle.field)?.column;
|
|
137
|
+
if (!column3) {
|
|
138
|
+
throw new ValidationError(`${object.label} has no column for ${lifecycle.field}`);
|
|
139
|
+
}
|
|
140
|
+
ctx.write(
|
|
141
|
+
CompiledQuery.raw(
|
|
142
|
+
`UPDATE core_transition_history SET left_at = ? WHERE object_type = ? AND record_id = ? AND left_at IS NULL AND EXISTS (SELECT 1 FROM ${object.source} WHERE id = ? AND ${column3} IS ?)`,
|
|
143
|
+
[ctx.now, object.name, id, id, storedPosition(before[lifecycle.field])]
|
|
144
|
+
)
|
|
145
|
+
);
|
|
146
|
+
}
|
|
147
|
+
history.push(
|
|
148
|
+
CompiledQuery.raw(
|
|
149
|
+
"INSERT INTO core_transition_history (id, object_type, record_id, form, position_id, group_id, position_type, entered_at, left_at, entered_by, entered_as) VALUES (?, ?, ?, ?, ?, ?, ?, ?, NULL, ?, ?)",
|
|
150
|
+
[
|
|
151
|
+
newId("stageHistory"),
|
|
152
|
+
object.name,
|
|
153
|
+
id,
|
|
154
|
+
lifecycle.form,
|
|
155
|
+
to.id,
|
|
156
|
+
placement.group(),
|
|
157
|
+
to.type,
|
|
158
|
+
ctx.now,
|
|
159
|
+
enteredBy(ctx),
|
|
160
|
+
by
|
|
161
|
+
]
|
|
162
|
+
)
|
|
163
|
+
);
|
|
164
|
+
}
|
|
165
|
+
return {
|
|
166
|
+
values,
|
|
167
|
+
history,
|
|
168
|
+
moved: moved ? to : null,
|
|
169
|
+
left: moved ? placement.from : null,
|
|
170
|
+
field: lifecycle.field
|
|
171
|
+
};
|
|
172
|
+
}
|
|
173
|
+
function storedPosition(value) {
|
|
174
|
+
if (value === null || value === void 0) return null;
|
|
175
|
+
if (typeof value === "object" && value && "id" in value)
|
|
176
|
+
return String(value.id);
|
|
177
|
+
return String(value);
|
|
178
|
+
}
|
|
179
|
+
function notPermittedMessage(object, to, by) {
|
|
180
|
+
if (by.length === 1 && by[0] === "host") {
|
|
181
|
+
return `${object.label} becomes ${to.title} when the platform confirms it; it cannot be set`;
|
|
182
|
+
}
|
|
183
|
+
const who = by.map((mover) => mover === "host" ? "the platform" : mover).join(" or ");
|
|
184
|
+
return `Only ${who} can move ${object.label.toLowerCase()} to ${to.title}`;
|
|
185
|
+
}
|
|
186
|
+
function transitionTimeline(outcome) {
|
|
187
|
+
if (!outcome.moved || !outcome.field) return void 0;
|
|
188
|
+
return {
|
|
189
|
+
subject: `Moved to ${outcome.moved.title}`,
|
|
190
|
+
field: outcome.field,
|
|
191
|
+
labels: { before: outcome.left?.title ?? null, after: outcome.moved.title }
|
|
192
|
+
};
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
// ../core/src/records/stages.ts
|
|
196
|
+
var StageRuleError = class extends TransitionRuleError {
|
|
197
|
+
name = "StageRuleError";
|
|
198
|
+
constructor(message, details) {
|
|
199
|
+
super(message, details);
|
|
200
|
+
}
|
|
201
|
+
};
|
|
202
|
+
function column(object, field) {
|
|
203
|
+
const definition = object.fields.find((f) => f.name === field);
|
|
204
|
+
return definition ? viewColumnOf(definition) : null;
|
|
205
|
+
}
|
|
206
|
+
function readValue(field, raw) {
|
|
207
|
+
if (!field?.fieldType) return raw ?? null;
|
|
208
|
+
const type = field.fieldType;
|
|
209
|
+
return FIELD_TYPE_REGISTRY[type]?.fromStorage(raw ?? null) ?? raw ?? null;
|
|
210
|
+
}
|
|
211
|
+
function stageObjectOf(object, stages) {
|
|
212
|
+
const to = object.fields.find((f) => f.name === stages.field)?.options?.to;
|
|
213
|
+
const target = to ? getObject(to) : void 0;
|
|
214
|
+
if (!target) throw new ValidationError(`${object.name}: its stage object is not installed`);
|
|
215
|
+
return target;
|
|
216
|
+
}
|
|
217
|
+
async function loadStages(ctx, stageObject, stages, ids, cache = /* @__PURE__ */ new Map()) {
|
|
218
|
+
const out = /* @__PURE__ */ new Map();
|
|
219
|
+
const missing = [...new Set(ids)].filter((id) => {
|
|
220
|
+
const hit = cache.get(id);
|
|
221
|
+
if (hit) out.set(id, hit);
|
|
222
|
+
return !cache.has(id);
|
|
223
|
+
});
|
|
224
|
+
if (missing.length) {
|
|
225
|
+
const fieldOf = (name) => name ? stageObject.fields.find((f) => f.name === name) : void 0;
|
|
226
|
+
const rows = await sql`
|
|
227
|
+
SELECT * FROM ${visibleSource(ctx, stageObject)}
|
|
228
|
+
WHERE id IN (SELECT value FROM json_each(${JSON.stringify(missing)}))
|
|
229
|
+
`.execute(ctx.db);
|
|
230
|
+
const titleColumn = stageObject.titleField ? column(stageObject, stageObject.titleField) : null;
|
|
231
|
+
const get = (row, name) => {
|
|
232
|
+
const field = fieldOf(name);
|
|
233
|
+
const col = field ? viewColumnOf(field) : null;
|
|
234
|
+
return col ? readValue(field, row[col]) : null;
|
|
235
|
+
};
|
|
236
|
+
for (const row of rows.rows) {
|
|
237
|
+
const type = get(row, stages.stage.type);
|
|
238
|
+
const required = get(row, stages.stage.requiredFields);
|
|
239
|
+
const order2 = get(row, stages.stage.order);
|
|
240
|
+
const probability = get(row, stages.stage.probability);
|
|
241
|
+
const group = get(row, stages.stage.group);
|
|
242
|
+
const info = {
|
|
243
|
+
id: String(row.id),
|
|
244
|
+
title: titleColumn ? String(row[titleColumn] ?? row.id) : String(row.id),
|
|
245
|
+
type: type === "won" || type === "lost" ? type : "open",
|
|
246
|
+
order: typeof order2 === "number" ? order2 : null,
|
|
247
|
+
requiredFields: Array.isArray(required) ? required.map(String) : [],
|
|
248
|
+
probability: typeof probability === "number" ? probability : null,
|
|
249
|
+
group: typeof group === "string" ? group : null
|
|
250
|
+
};
|
|
251
|
+
cache.set(info.id, info);
|
|
252
|
+
out.set(info.id, info);
|
|
253
|
+
}
|
|
254
|
+
for (const id of missing) if (!out.has(id)) cache.set(id, null);
|
|
255
|
+
}
|
|
256
|
+
return out;
|
|
257
|
+
}
|
|
258
|
+
async function firstStage(ctx, stageObject, stages, group) {
|
|
259
|
+
const order2 = column(stageObject, stages.stage.order);
|
|
260
|
+
const groupColumn = stages.stage.group ? column(stageObject, stages.stage.group) : null;
|
|
261
|
+
if (!order2) return null;
|
|
262
|
+
const where = groupColumn ? sql`WHERE ${sql.ref(groupColumn)} = ${group}` : sql``;
|
|
263
|
+
const row = await sql`
|
|
264
|
+
SELECT id FROM ${visibleSource(ctx, stageObject)} ${where}
|
|
265
|
+
ORDER BY ${sql.ref(order2)} IS NULL, ${sql.ref(order2)}, id LIMIT 1
|
|
266
|
+
`.execute(ctx.db);
|
|
267
|
+
return row.rows[0]?.id ?? null;
|
|
268
|
+
}
|
|
269
|
+
async function defaultGroup(ctx, object, stages, group) {
|
|
270
|
+
const setting = stages.defaultGroupSetting;
|
|
271
|
+
const ext = object.extension;
|
|
272
|
+
const to = object.fields.find((f) => f.name === group)?.options?.to;
|
|
273
|
+
const groupObject = to ? getObject(to) : void 0;
|
|
274
|
+
if (!setting || !ext || !groupObject?.titleField) return null;
|
|
275
|
+
const [stored, installed] = await Promise.all([
|
|
276
|
+
ctx.db.selectFrom("core_extension_settings").select("value").where("extension_id", "=", ext).executeTakeFirst(),
|
|
277
|
+
ctx.db.selectFrom("core_extensions").select("manifest").where("id", "=", ext).executeTakeFirst()
|
|
278
|
+
]);
|
|
279
|
+
const value = (stored ? JSON.parse(stored.value)[setting] : void 0) ?? (installed ? JSON.parse(installed.manifest).settings?.[setting]?.default : void 0);
|
|
280
|
+
if (typeof value !== "string" || !value.trim()) return null;
|
|
281
|
+
const title = column(groupObject, groupObject.titleField);
|
|
282
|
+
if (!title) return null;
|
|
283
|
+
const row = await sql`
|
|
284
|
+
SELECT id FROM ${visibleSource(ctx, groupObject)}
|
|
285
|
+
WHERE id = ${value.trim()} OR lower(${sql.ref(title)}) = ${value.trim().toLowerCase()}
|
|
286
|
+
ORDER BY id = ${value.trim()} DESC, id LIMIT 1
|
|
287
|
+
`.execute(ctx.db);
|
|
288
|
+
return row.rows[0]?.id ?? null;
|
|
289
|
+
}
|
|
290
|
+
var STAGE_MOVERS = ["staff", "host"];
|
|
291
|
+
var stageRef = (stage) => ({ id: stage.id, title: stage.title, type: stage.type });
|
|
292
|
+
function stagesLifecycle(object, stages, cache = /* @__PURE__ */ new Map()) {
|
|
293
|
+
const group = stages.group;
|
|
294
|
+
const refuse = (write, rule, message, fields, stage, by) => new StageRuleError(message, {
|
|
295
|
+
...ruleBase(write, rule, fields),
|
|
296
|
+
rule,
|
|
297
|
+
stage: stage ? stageRef(stage) : null,
|
|
298
|
+
...by ? { by: [...by] } : {}
|
|
299
|
+
});
|
|
300
|
+
return {
|
|
301
|
+
form: "stages",
|
|
302
|
+
field: stages.field,
|
|
303
|
+
async place(write) {
|
|
304
|
+
const { ctx, before, written, after, has, set, labelOf } = write;
|
|
305
|
+
const stageObject = stageObjectOf(object, stages);
|
|
306
|
+
const beforeStage = before?.[stages.field] ?? null;
|
|
307
|
+
let stageId = after[stages.field] ?? null;
|
|
308
|
+
const groupChanged = Boolean(
|
|
309
|
+
group && has(group) && written[group] !== (before?.[group] ?? null)
|
|
310
|
+
);
|
|
311
|
+
const stageWritten = has(stages.field);
|
|
312
|
+
if (!stageWritten && (before === null || groupChanged) || stageWritten && stageId === null) {
|
|
313
|
+
if (stageWritten && stageId === null && before !== null) {
|
|
314
|
+
throw refuse(
|
|
315
|
+
write,
|
|
316
|
+
"no_stage",
|
|
317
|
+
`${object.label} must be in a stage`,
|
|
318
|
+
[stages.field],
|
|
319
|
+
null
|
|
320
|
+
);
|
|
321
|
+
}
|
|
322
|
+
let groupId = group ? after[group] ?? null : null;
|
|
323
|
+
if (group && !groupId && before === null && stages.defaultGroupSetting) {
|
|
324
|
+
groupId = await defaultGroup(ctx, object, stages, group);
|
|
325
|
+
if (groupId) set(group, groupId);
|
|
326
|
+
}
|
|
327
|
+
if (!group || groupId) {
|
|
328
|
+
stageId = await firstStage(ctx, stageObject, stages, groupId);
|
|
329
|
+
if (stageId) set(stages.field, stageId);
|
|
330
|
+
}
|
|
331
|
+
}
|
|
332
|
+
if (!stageId) {
|
|
333
|
+
if (before === null && !group) return null;
|
|
334
|
+
throw refuse(
|
|
335
|
+
write,
|
|
336
|
+
"no_stage",
|
|
337
|
+
group ? `Choose a ${labelOf(group).toLowerCase()} with at least one stage, or a stage` : `${object.label} needs a stage`,
|
|
338
|
+
[group ?? stages.field],
|
|
339
|
+
null
|
|
340
|
+
);
|
|
341
|
+
}
|
|
342
|
+
const loaded = await loadStages(
|
|
343
|
+
ctx,
|
|
344
|
+
stageObject,
|
|
345
|
+
stages,
|
|
346
|
+
beforeStage ? [stageId, beforeStage] : [stageId],
|
|
347
|
+
cache
|
|
348
|
+
);
|
|
349
|
+
const stage = loaded.get(stageId);
|
|
350
|
+
if (!stage) {
|
|
351
|
+
throw new ValidationError(`${labelOf(stages.field)}: no live stage with id ${stageId}`, {
|
|
352
|
+
field: stages.field
|
|
353
|
+
});
|
|
354
|
+
}
|
|
355
|
+
if (group && stage.group) {
|
|
356
|
+
const groupId = after[group] ?? null;
|
|
357
|
+
if (groupId === null) set(group, stage.group);
|
|
358
|
+
else if (groupId !== stage.group) {
|
|
359
|
+
throw refuse(
|
|
360
|
+
write,
|
|
361
|
+
"stage_not_in_group",
|
|
362
|
+
`${stage.title} is not a stage of this ${labelOf(group).toLowerCase()}`,
|
|
363
|
+
[stages.field],
|
|
364
|
+
stage
|
|
365
|
+
);
|
|
366
|
+
}
|
|
367
|
+
}
|
|
368
|
+
const left = beforeStage ? loaded.get(beforeStage) ?? null : null;
|
|
369
|
+
return {
|
|
370
|
+
stage,
|
|
371
|
+
fromId: beforeStage,
|
|
372
|
+
from: left ? stageRef(left) : null,
|
|
373
|
+
to: stageRef(stage),
|
|
374
|
+
by: STAGE_MOVERS,
|
|
375
|
+
requires: [...stage.requiredFields, ...stages.requiredByType?.[stage.type] ?? []],
|
|
376
|
+
group: () => group ? after[group] ?? null : stage.group
|
|
377
|
+
};
|
|
378
|
+
},
|
|
379
|
+
follow(write, { stage }, moved) {
|
|
380
|
+
const { ctx, before, written, after, changed, set } = write;
|
|
381
|
+
if (stages.status && (moved || after[stages.status] !== stage.type)) {
|
|
382
|
+
set(stages.status, stage.type);
|
|
383
|
+
}
|
|
384
|
+
if (stages.closedDate && moved) {
|
|
385
|
+
const field = object.fields.find((f) => f.name === stages.closedDate);
|
|
386
|
+
const now = field?.fieldType === "datetime" ? ctx.now : ctx.now.slice(0, 10);
|
|
387
|
+
set(stages.closedDate, stage.type === "open" ? null : now);
|
|
388
|
+
}
|
|
389
|
+
if (stages.probability) {
|
|
390
|
+
const { field, overridden } = stages.probability;
|
|
391
|
+
let isOverridden = before?.[overridden] === true;
|
|
392
|
+
if (changed(overridden) && written[overridden] !== true) isOverridden = false;
|
|
393
|
+
else if (changed(field)) {
|
|
394
|
+
isOverridden = written[field] !== null && written[field] !== void 0;
|
|
395
|
+
} else if (changed(overridden)) isOverridden = true;
|
|
396
|
+
if (after[overridden] !== isOverridden) set(overridden, isOverridden);
|
|
397
|
+
if (!isOverridden && after[field] !== stage.probability) set(field, stage.probability);
|
|
398
|
+
}
|
|
399
|
+
},
|
|
400
|
+
refusal(write, refusal, placement) {
|
|
401
|
+
return refuse(
|
|
402
|
+
write,
|
|
403
|
+
`stage_${refusal.rule}`,
|
|
404
|
+
refusal.message,
|
|
405
|
+
refusal.fields,
|
|
406
|
+
placement.stage,
|
|
407
|
+
refusal.rule === "move_not_permitted" ? placement.by : void 0
|
|
408
|
+
);
|
|
409
|
+
}
|
|
410
|
+
};
|
|
411
|
+
}
|
|
412
|
+
|
|
413
|
+
// ../core/src/records/windows.ts
|
|
414
|
+
function pathReader(ctx, object, after) {
|
|
415
|
+
const records = /* @__PURE__ */ new Map();
|
|
416
|
+
const load = (relation) => {
|
|
417
|
+
const cached = records.get(relation);
|
|
418
|
+
if (cached) return cached;
|
|
419
|
+
const promise = (async () => {
|
|
420
|
+
const id = after[relation];
|
|
421
|
+
const to = object.fields.find((f) => f.name === relation)?.options?.to;
|
|
422
|
+
const target = to ? getObject(to) : void 0;
|
|
423
|
+
if (typeof id !== "string" || !id || !target) return null;
|
|
424
|
+
const stored = await ctx.db.selectFrom(visibleSource(ctx, target)).selectAll().where("id", "=", id).executeTakeFirst();
|
|
425
|
+
if (!stored) return null;
|
|
426
|
+
const values = {};
|
|
427
|
+
for (const field of target.fields) {
|
|
428
|
+
if (field.column && Object.hasOwn(stored, field.column)) {
|
|
429
|
+
values[field.name] = stored[field.column];
|
|
430
|
+
}
|
|
431
|
+
}
|
|
432
|
+
return values;
|
|
433
|
+
})();
|
|
434
|
+
records.set(relation, promise);
|
|
435
|
+
return promise;
|
|
436
|
+
};
|
|
437
|
+
return {
|
|
438
|
+
async read(path) {
|
|
439
|
+
const dot = path.indexOf(".");
|
|
440
|
+
if (dot < 0) return after[path] ?? null;
|
|
441
|
+
const record = await load(path.slice(0, dot));
|
|
442
|
+
return record?.[path.slice(dot + 1)] ?? null;
|
|
443
|
+
}
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
function asNumber(value) {
|
|
447
|
+
if (typeof value === "number" && Number.isFinite(value)) return value;
|
|
448
|
+
if (typeof value === "string" && value.trim() !== "" && Number.isFinite(Number(value))) {
|
|
449
|
+
return Number(value);
|
|
450
|
+
}
|
|
451
|
+
return null;
|
|
452
|
+
}
|
|
453
|
+
async function boundMoment(ctx, reader, bound) {
|
|
454
|
+
const b = typeof bound === "string" ? { at: bound } : bound;
|
|
455
|
+
const at = await reader.read(b.at);
|
|
456
|
+
const instant = typeof at === "string" ? Date.parse(at) : Number.NaN;
|
|
457
|
+
if (Number.isNaN(instant)) return null;
|
|
458
|
+
const part = async (value) => value === void 0 ? 0 : typeof value === "number" ? value : asNumber(await reader.read(value));
|
|
459
|
+
const days = await part(b.daysBefore);
|
|
460
|
+
const minutes = await part(b.minutesBefore);
|
|
461
|
+
if (days === null || minutes === null) return null;
|
|
462
|
+
let moment = instant;
|
|
463
|
+
if (days !== 0) {
|
|
464
|
+
const zoneValue = b.zone ? await reader.read(b.zone) : null;
|
|
465
|
+
if (b.zone && (typeof zoneValue !== "string" || !zoneValue)) return null;
|
|
466
|
+
const zone = typeof zoneValue === "string" && zoneValue ? zoneValue : (await loadGeneralSettings(ctx.db)).timezone;
|
|
467
|
+
moment = localDaysBefore(instant, Math.trunc(days), zone);
|
|
468
|
+
}
|
|
469
|
+
return moment - Math.round(minutes * 6e4);
|
|
470
|
+
}
|
|
471
|
+
async function windowRefusal(ctx, reader, window, what) {
|
|
472
|
+
if (!window) return null;
|
|
473
|
+
const now = Date.parse(ctx.now);
|
|
474
|
+
const from = window.from === void 0 ? void 0 : await boundMoment(ctx, reader, window.from);
|
|
475
|
+
const until = window.until === void 0 ? void 0 : await boundMoment(ctx, reader, window.until);
|
|
476
|
+
if (from === null || until === null) {
|
|
477
|
+
return {
|
|
478
|
+
rule: "window_unknown",
|
|
479
|
+
message: `${what} cannot be done now: when it is allowed cannot be worked out`
|
|
480
|
+
};
|
|
481
|
+
}
|
|
482
|
+
const iso = (ms) => new Date(ms).toISOString();
|
|
483
|
+
const times = {
|
|
484
|
+
...from !== void 0 ? { opensAt: iso(from) } : {},
|
|
485
|
+
...until !== void 0 ? { closesAt: iso(until) } : {}
|
|
486
|
+
};
|
|
487
|
+
if (from !== void 0 && now < from) {
|
|
488
|
+
return { rule: "window_not_open", message: `${what} opens at ${iso(from)}`, ...times };
|
|
489
|
+
}
|
|
490
|
+
if (until !== void 0 && now >= until) {
|
|
491
|
+
return { rule: "window_closed", message: `${what} closed at ${iso(until)}`, ...times };
|
|
492
|
+
}
|
|
493
|
+
return null;
|
|
494
|
+
}
|
|
495
|
+
async function staffOnlySet(reader, path) {
|
|
496
|
+
if (!path) return false;
|
|
497
|
+
const value = await reader.read(path);
|
|
498
|
+
return value === true || value === 1 || value === "1" || value === "true";
|
|
499
|
+
}
|
|
500
|
+
function staffOnlyMessage(what) {
|
|
501
|
+
return `${what} is made by staff only`;
|
|
502
|
+
}
|
|
503
|
+
|
|
504
|
+
// ../core/src/records/states.ts
|
|
505
|
+
var StateRuleError = class extends TransitionRuleError {
|
|
506
|
+
name = "StateRuleError";
|
|
507
|
+
constructor(message, details) {
|
|
508
|
+
super(message, details);
|
|
509
|
+
}
|
|
510
|
+
};
|
|
511
|
+
var ref = (position) => position ? { id: position.id, title: position.title, final: position.type === "final" } : null;
|
|
512
|
+
function statesLifecycle(object, states) {
|
|
513
|
+
const field = states.field;
|
|
514
|
+
const choices = object.fields.find((f) => f.name === field)?.options?.choices ?? [];
|
|
515
|
+
const finals = new Set(states.moves.filter((move) => move.final).map((move) => move.to));
|
|
516
|
+
const position = (value) => ({
|
|
517
|
+
id: value,
|
|
518
|
+
title: choices.find((choice) => choice.value === value)?.label ?? value,
|
|
519
|
+
type: finals.has(value) ? "final" : "open"
|
|
520
|
+
});
|
|
521
|
+
const moveBetween = (from, to) => states.moves.find((move) => move.to === to && moveOrigins(move).includes(from));
|
|
522
|
+
const reachable = (from) => [
|
|
523
|
+
...new Set(
|
|
524
|
+
states.moves.filter((move) => moveOrigins(move).includes(from)).map((move) => move.to)
|
|
525
|
+
)
|
|
526
|
+
];
|
|
527
|
+
const held = (state) => {
|
|
528
|
+
const into = states.moves.filter((move) => move.to === state);
|
|
529
|
+
const [first, ...rest] = into.map((move) => move.requires ?? []);
|
|
530
|
+
return (first ?? []).filter((name) => rest.every((list) => list.includes(name)));
|
|
531
|
+
};
|
|
532
|
+
const refuse = (write, rule, message, fields, to, from, extra = {}) => new StateRuleError(message, {
|
|
533
|
+
...ruleBase(write, rule, fields),
|
|
534
|
+
rule,
|
|
535
|
+
state: ref(to),
|
|
536
|
+
from: ref(from),
|
|
537
|
+
...extra
|
|
538
|
+
});
|
|
539
|
+
const customerRules = async (write, rules, what, to, from) => {
|
|
540
|
+
const refusal = await customerRefusal(write.ctx, write.object, write.after, rules, what);
|
|
541
|
+
if (refusal) {
|
|
542
|
+
throw refuse(write, refusal.rule, refusal.message, [field], to, from, refusal.times);
|
|
543
|
+
}
|
|
544
|
+
};
|
|
545
|
+
return {
|
|
546
|
+
form: "states",
|
|
547
|
+
field,
|
|
548
|
+
async place(write) {
|
|
549
|
+
const { before, after, object: o } = write;
|
|
550
|
+
const stored = before?.[field];
|
|
551
|
+
const fromId = typeof stored === "string" && stored !== "" ? stored : null;
|
|
552
|
+
const from = fromId ? position(fromId) : null;
|
|
553
|
+
const wanted = after[field];
|
|
554
|
+
let toId = typeof wanted === "string" && wanted !== "" ? wanted : null;
|
|
555
|
+
if (toId === null) {
|
|
556
|
+
if (fromId !== null) {
|
|
557
|
+
throw refuse(write, "no_state", `${o.label} must have a state`, [field], null, from);
|
|
558
|
+
}
|
|
559
|
+
toId = states.initial;
|
|
560
|
+
write.set(field, toId);
|
|
561
|
+
}
|
|
562
|
+
const to = position(toId);
|
|
563
|
+
const base = { fromId, from, to, group: () => null };
|
|
564
|
+
if (before === null && write.by === "customer" && states.create) {
|
|
565
|
+
await customerRules(write, states.create, `Creating ${o.label.toLowerCase()}`, to, null);
|
|
566
|
+
}
|
|
567
|
+
if (before !== null && write.by === "customer" && states.create && ruleSources(states.create).some((f) => write.changed(f))) {
|
|
568
|
+
await customerRules(write, states.create, `Creating ${o.label.toLowerCase()}`, to, from);
|
|
569
|
+
}
|
|
570
|
+
const createdIn = before === null && toId !== states.initial ? states.create?.in?.[toId] : void 0;
|
|
571
|
+
if (createdIn) {
|
|
572
|
+
return { ...base, by: createdIn, requires: held(toId) };
|
|
573
|
+
}
|
|
574
|
+
if (toId === fromId) return { ...base, by: ALL_MOVERS, requires: held(toId) };
|
|
575
|
+
const origin = fromId ?? states.initial;
|
|
576
|
+
if (toId === origin) return { ...base, by: ALL_MOVERS, requires: [] };
|
|
577
|
+
const originPosition = position(origin);
|
|
578
|
+
if (finals.has(origin)) {
|
|
579
|
+
throw refuse(
|
|
580
|
+
write,
|
|
581
|
+
"state_final",
|
|
582
|
+
`${o.label} is ${originPosition.title}, which is final: it cannot move to ${to.title}`,
|
|
583
|
+
[field],
|
|
584
|
+
to,
|
|
585
|
+
originPosition,
|
|
586
|
+
{ allowed: [] }
|
|
587
|
+
);
|
|
588
|
+
}
|
|
589
|
+
const move = moveBetween(origin, toId);
|
|
590
|
+
if (!move) {
|
|
591
|
+
throw refuse(
|
|
592
|
+
write,
|
|
593
|
+
"state_move_not_declared",
|
|
594
|
+
`${o.label} cannot move from ${originPosition.title} to ${to.title}`,
|
|
595
|
+
[field],
|
|
596
|
+
to,
|
|
597
|
+
originPosition,
|
|
598
|
+
{ allowed: reachable(origin) }
|
|
599
|
+
);
|
|
600
|
+
}
|
|
601
|
+
if (write.by === "customer" && move.by.includes("customer")) {
|
|
602
|
+
await customerRules(
|
|
603
|
+
write,
|
|
604
|
+
move,
|
|
605
|
+
`Moving ${o.label.toLowerCase()} to ${to.title}`,
|
|
606
|
+
to,
|
|
607
|
+
originPosition
|
|
608
|
+
);
|
|
609
|
+
}
|
|
610
|
+
return {
|
|
611
|
+
...base,
|
|
612
|
+
from: originPosition,
|
|
613
|
+
by: move.by,
|
|
614
|
+
requires: move.requires ?? []
|
|
615
|
+
};
|
|
616
|
+
},
|
|
617
|
+
refusal(write, refusal, placement) {
|
|
618
|
+
const rule = `state_${refusal.rule}`;
|
|
619
|
+
return refuse(
|
|
620
|
+
write,
|
|
621
|
+
rule,
|
|
622
|
+
refusal.message,
|
|
623
|
+
refusal.fields,
|
|
624
|
+
placement.to,
|
|
625
|
+
placement.from,
|
|
626
|
+
refusal.rule === "move_not_permitted" ? { by: [...placement.by] } : {}
|
|
627
|
+
);
|
|
628
|
+
}
|
|
629
|
+
};
|
|
630
|
+
}
|
|
631
|
+
function ruleSources(rules) {
|
|
632
|
+
const paths = [];
|
|
633
|
+
if (rules.staffOnly) paths.push(rules.staffOnly);
|
|
634
|
+
for (const bound of [rules.window?.from, rules.window?.until]) {
|
|
635
|
+
if (bound === void 0) continue;
|
|
636
|
+
if (typeof bound === "string") {
|
|
637
|
+
paths.push(bound);
|
|
638
|
+
continue;
|
|
639
|
+
}
|
|
640
|
+
paths.push(bound.at);
|
|
641
|
+
for (const part of [bound.daysBefore, bound.minutesBefore, bound.zone]) {
|
|
642
|
+
if (typeof part === "string") paths.push(part);
|
|
643
|
+
}
|
|
644
|
+
}
|
|
645
|
+
return [...new Set(paths.map((p) => p.split(".")[0]))];
|
|
646
|
+
}
|
|
647
|
+
async function customerRefusal(ctx, object, after, rules, what) {
|
|
648
|
+
if (!rules.window && !rules.staffOnly) return null;
|
|
649
|
+
const reader = pathReader(ctx, object, after);
|
|
650
|
+
if (await staffOnlySet(reader, rules.staffOnly)) {
|
|
651
|
+
return { rule: "state_staff_only", message: staffOnlyMessage(what), times: {} };
|
|
652
|
+
}
|
|
653
|
+
const refusal = await windowRefusal(ctx, reader, rules.window, what);
|
|
654
|
+
if (!refusal) return null;
|
|
655
|
+
return {
|
|
656
|
+
rule: `state_${refusal.rule}`,
|
|
657
|
+
message: refusal.message,
|
|
658
|
+
times: {
|
|
659
|
+
...refusal.opensAt ? { opensAt: refusal.opensAt } : {},
|
|
660
|
+
...refusal.closesAt ? { closesAt: refusal.closesAt } : {}
|
|
661
|
+
}
|
|
662
|
+
};
|
|
663
|
+
}
|
|
664
|
+
async function resolveStateRequest(ctx, object, before, values, by) {
|
|
665
|
+
const states = object.states;
|
|
666
|
+
const field = states?.field;
|
|
667
|
+
const requests = states?.requests;
|
|
668
|
+
if (!states || !field || !requests) return values;
|
|
669
|
+
const asked = values[field];
|
|
670
|
+
if (typeof asked !== "string" || !Object.hasOwn(requests, asked)) return values;
|
|
671
|
+
const stored = before?.[field];
|
|
672
|
+
const origin = typeof stored === "string" && stored !== "" ? stored : states.initial;
|
|
673
|
+
const after = { ...before ?? {}, ...values };
|
|
674
|
+
const labelOf = (name) => object.fields.find((f) => f.name === name)?.label ?? name;
|
|
675
|
+
const choices = object.fields.find((f) => f.name === field)?.options?.choices ?? [];
|
|
676
|
+
const title = (value) => choices.find((c) => c.value === value)?.label ?? value;
|
|
677
|
+
let refused = null;
|
|
678
|
+
for (const to of requests[asked] ?? []) {
|
|
679
|
+
const move = states.moves.find((m) => m.to === to && moveOrigins(m).includes(origin));
|
|
680
|
+
if (!move?.by.includes(by)) continue;
|
|
681
|
+
if (by === "customer" || ctx.actor === "assistant") {
|
|
682
|
+
const refusal = await customerRefusal(
|
|
683
|
+
ctx,
|
|
684
|
+
object,
|
|
685
|
+
{ ...after, [field]: to },
|
|
686
|
+
move,
|
|
687
|
+
`Moving ${object.label.toLowerCase()} to ${title(to)}`
|
|
688
|
+
);
|
|
689
|
+
if (refusal) {
|
|
690
|
+
refused ??= refusal;
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
}
|
|
694
|
+
return { ...values, [field]: to };
|
|
695
|
+
}
|
|
696
|
+
const state = { id: origin, title: title(origin), final: false };
|
|
697
|
+
throw new StateRuleError(
|
|
698
|
+
refused?.message ?? `${object.label} cannot be moved by "${asked}" from ${title(origin)}`,
|
|
699
|
+
{
|
|
700
|
+
...ruleBase({ object, labelOf }, refused?.rule ?? "state_request_refused", [field]),
|
|
701
|
+
rule: refused?.rule ?? "state_request_refused",
|
|
702
|
+
state: null,
|
|
703
|
+
from: state,
|
|
704
|
+
...refused?.times ?? {}
|
|
705
|
+
}
|
|
706
|
+
);
|
|
707
|
+
}
|
|
708
|
+
|
|
709
|
+
// ../core/src/records/lifecycle.ts
|
|
710
|
+
function callerMover(ctx) {
|
|
711
|
+
const caller = callerOf(ctx);
|
|
712
|
+
if (caller.kind === "staff") return "staff";
|
|
713
|
+
if (caller.kind === "customer") return "customer";
|
|
714
|
+
throw new ForbiddenError("This call cannot move a record");
|
|
715
|
+
}
|
|
716
|
+
var moveHooks = /* @__PURE__ */ new Map();
|
|
717
|
+
function onRecordMove(object, hook) {
|
|
718
|
+
const hooks = moveHooks.get(object) ?? [];
|
|
719
|
+
hooks.push(hook);
|
|
720
|
+
moveHooks.set(object, hooks);
|
|
721
|
+
return () => {
|
|
722
|
+
const at = hooks.indexOf(hook);
|
|
723
|
+
if (at >= 0) hooks.splice(at, 1);
|
|
724
|
+
};
|
|
725
|
+
}
|
|
726
|
+
async function applyTransition(ctx, object, id, before, written, options) {
|
|
727
|
+
const run = async (lifecycle) => {
|
|
728
|
+
assertClaimRelationKept(object, before, written);
|
|
729
|
+
const outcome = await runTransition(lifecycle, ctx, object, id, before, written, options.by);
|
|
730
|
+
if (outcome.moved && object.claims) {
|
|
731
|
+
await claimantMove(ctx, object, id, before, {
|
|
732
|
+
...before ?? {},
|
|
733
|
+
...written,
|
|
734
|
+
...outcome.values
|
|
735
|
+
});
|
|
736
|
+
}
|
|
737
|
+
const hooks = outcome.moved ? moveHooks.get(object.name) : void 0;
|
|
738
|
+
if (outcome.moved && hooks?.length) {
|
|
739
|
+
const move = {
|
|
740
|
+
object,
|
|
741
|
+
id,
|
|
742
|
+
from: outcome.left,
|
|
743
|
+
to: outcome.moved,
|
|
744
|
+
by: options.by,
|
|
745
|
+
before,
|
|
746
|
+
after: { ...before ?? {}, ...written, ...outcome.values }
|
|
747
|
+
};
|
|
748
|
+
for (const hook of [...hooks]) await hook(ctx, move);
|
|
749
|
+
}
|
|
750
|
+
return outcome;
|
|
751
|
+
};
|
|
752
|
+
if (object.states) return run(statesLifecycle(object, object.states));
|
|
753
|
+
if (object.stages) return run(stagesLifecycle(object, object.stages, options.cache));
|
|
754
|
+
return NO_TRANSITION;
|
|
755
|
+
}
|
|
756
|
+
|
|
757
|
+
// ../core/src/orders/holds.ts
|
|
758
|
+
var ORDER_CLAIM_TYPE = "order";
|
|
759
|
+
async function linesWithCapacity(ctx, orderId) {
|
|
760
|
+
const lines = await ctx.db.selectFrom("core_order_line").select(["object_type", "record_id", "quantity"]).where("order_id", "=", orderId).orderBy("position").execute();
|
|
761
|
+
return lines.filter((line) => getObject(line.object_type)?.capacity);
|
|
762
|
+
}
|
|
763
|
+
async function claimOrderPlaces(ctx, orderId, lines) {
|
|
764
|
+
for (const line of lines) {
|
|
765
|
+
if (!getObject(line.object)?.capacity) continue;
|
|
766
|
+
await queueClaim(ctx, {
|
|
767
|
+
object: line.object,
|
|
768
|
+
record: line.recordId,
|
|
769
|
+
quantity: line.quantity,
|
|
770
|
+
for: { type: ORDER_CLAIM_TYPE, id: orderId }
|
|
771
|
+
});
|
|
772
|
+
}
|
|
773
|
+
}
|
|
774
|
+
var orderHolds = async (ctx, move) => {
|
|
775
|
+
const from = move.from?.id ?? null;
|
|
776
|
+
const to = move.to.id;
|
|
777
|
+
const target = { for: { type: ORDER_CLAIM_TYPE, id: move.id } };
|
|
778
|
+
if ((to === "paid" || to === "part_paid") && from === "expired") {
|
|
779
|
+
const lines = await linesWithCapacity(ctx, move.id);
|
|
780
|
+
await claimOrderPlaces(
|
|
781
|
+
ctx,
|
|
782
|
+
move.id,
|
|
783
|
+
lines.map((l) => ({ object: l.object_type, recordId: l.record_id, quantity: l.quantity }))
|
|
784
|
+
);
|
|
785
|
+
ctx.write(...confirmStatements(target, ctx.now));
|
|
786
|
+
return;
|
|
787
|
+
}
|
|
788
|
+
if ((to === "paid" || to === "part_paid") && from === "pending") {
|
|
789
|
+
ctx.write(...confirmStatements(target, ctx.now));
|
|
790
|
+
return;
|
|
791
|
+
}
|
|
792
|
+
if (to === "cancelled" || to === "expired") {
|
|
793
|
+
ctx.write(...releaseStatements(target, ctx.now, { confirmed: from === "part_paid" }));
|
|
794
|
+
return;
|
|
795
|
+
}
|
|
796
|
+
if (to === "refunded") {
|
|
797
|
+
const lines = await linesWithCapacity(ctx, move.id);
|
|
798
|
+
const keeps = (line) => getObject(line.object_type)?.capacity?.releaseOnRefund === false;
|
|
799
|
+
if (!lines.some(keeps)) {
|
|
800
|
+
ctx.write(...releaseStatements(target, ctx.now, { confirmed: true }));
|
|
801
|
+
return;
|
|
802
|
+
}
|
|
803
|
+
const releasing = new Set(
|
|
804
|
+
lines.filter((l) => !keeps(l)).map((l) => `${l.object_type}\0${l.record_id}`)
|
|
805
|
+
);
|
|
806
|
+
if (!releasing.size) return;
|
|
807
|
+
const claims = await ctx.db.selectFrom("core_capacity_claim").select(["id", "object_type", "record_id"]).where("for_type", "=", ORDER_CLAIM_TYPE).where("for_id", "=", move.id).where("state", "=", "confirmed").execute();
|
|
808
|
+
for (const claim of claims) {
|
|
809
|
+
if (!releasing.has(`${claim.object_type}\0${claim.record_id}`)) continue;
|
|
810
|
+
ctx.write(...releaseStatements({ claim: claim.id }, ctx.now, { confirmed: true }));
|
|
811
|
+
}
|
|
812
|
+
}
|
|
813
|
+
};
|
|
814
|
+
onRecordMove("order", orderHolds);
|
|
815
|
+
|
|
816
|
+
// ../core/src/orders/sellable.ts
|
|
817
|
+
var GRANTS_PER_ORDER_CEILING = 100;
|
|
818
|
+
var GRANTS_PER_LINE_DEFAULT = 10;
|
|
819
|
+
function lineLimit(sellable, recordMax) {
|
|
820
|
+
const own = recordMax === null ? null : Math.max(Math.floor(recordMax), 0);
|
|
821
|
+
if (!sellable.grants) return own;
|
|
822
|
+
return Math.min(own ?? GRANTS_PER_LINE_DEFAULT, GRANTS_PER_ORDER_CEILING);
|
|
823
|
+
}
|
|
824
|
+
function sellableOf(object) {
|
|
825
|
+
return object.sellable;
|
|
826
|
+
}
|
|
827
|
+
function sellableProblems(sellable, object) {
|
|
828
|
+
const problems = [];
|
|
829
|
+
const field = (name) => object.fields.find((f) => f.name === name);
|
|
830
|
+
const numeric = (name, what) => {
|
|
831
|
+
const f = field(name);
|
|
832
|
+
if (!f?.column) problems.push(`${what} "${name}" is not a single-valued field`);
|
|
833
|
+
else if (f.type !== "number") problems.push(`${what} "${name}" is not a number`);
|
|
834
|
+
};
|
|
835
|
+
const date = (name, what) => {
|
|
836
|
+
const f = field(name);
|
|
837
|
+
if (!f?.column || f.type !== "date" && f.type !== "datetime") {
|
|
838
|
+
problems.push(`${what} "${name}" is not a date field`);
|
|
839
|
+
}
|
|
840
|
+
};
|
|
841
|
+
numeric(sellable.price, "price");
|
|
842
|
+
if (sellable.maxPerOrder) numeric(sellable.maxPerOrder, "maxPerOrder");
|
|
843
|
+
if (sellable.saleWindow?.from) date(sellable.saleWindow.from, "saleWindow.from");
|
|
844
|
+
if (sellable.saleWindow?.until) date(sellable.saleWindow.until, "saleWindow.until");
|
|
845
|
+
if (sellable.deposit) {
|
|
846
|
+
numeric(sellable.deposit.amount, "deposit.amount");
|
|
847
|
+
date(sellable.deposit.balanceDue, "deposit.balanceDue");
|
|
848
|
+
}
|
|
849
|
+
if (sellable.recurring?.trialDays) numeric(sellable.recurring.trialDays, "recurring.trialDays");
|
|
850
|
+
if (!object.titleField) problems.push("a sellable object needs a title field");
|
|
851
|
+
return problems;
|
|
852
|
+
}
|
|
853
|
+
|
|
854
|
+
// ../core/src/orders/orders.ts
|
|
855
|
+
var ORDER_MAX_LINES = 50;
|
|
856
|
+
var ORDER_MAX_QUANTITY = 1e3;
|
|
857
|
+
var ORDER_ACCESS_DAYS_AFTER_CLOSE = 30;
|
|
858
|
+
var CLOSED = /* @__PURE__ */ new Set(["paid", "cancelled", "expired", "refunded"]);
|
|
859
|
+
var order = () => getObject("order") ?? orderObject;
|
|
860
|
+
function orderSnapshot(row) {
|
|
861
|
+
return {
|
|
862
|
+
personId: row.person_id,
|
|
863
|
+
email: row.email,
|
|
864
|
+
state: row.state,
|
|
865
|
+
currency: row.currency,
|
|
866
|
+
total: row.total,
|
|
867
|
+
paid: row.paid,
|
|
868
|
+
balance: row.total - row.paid,
|
|
869
|
+
refunded: row.refunded,
|
|
870
|
+
pay: row.pay,
|
|
871
|
+
deposit: row.deposit,
|
|
872
|
+
balanceDueAt: row.balance_due_at,
|
|
873
|
+
expiresAt: row.expires_at,
|
|
874
|
+
placedAs: row.placed_as,
|
|
875
|
+
paidAt: row.paid_at,
|
|
876
|
+
cancelledAt: row.cancelled_at,
|
|
877
|
+
refundedAt: row.refunded_at,
|
|
878
|
+
taxAmount: row.tax_amount,
|
|
879
|
+
taxRefunded: row.tax_refunded,
|
|
880
|
+
taxCountry: row.tax_country
|
|
881
|
+
};
|
|
882
|
+
}
|
|
883
|
+
async function loadOrderRow(db, id) {
|
|
884
|
+
const row = await db.selectFrom("core_order").selectAll().where("id", "=", id).executeTakeFirst();
|
|
885
|
+
if (!row) throw new NotFoundError("order", id);
|
|
886
|
+
return row;
|
|
887
|
+
}
|
|
888
|
+
function refuseLine(rule, line, message, extra) {
|
|
889
|
+
throw new ValidationError(message, { rule, line, ...extra });
|
|
890
|
+
}
|
|
891
|
+
var column2 = (field) => field ? viewColumnOf(field) : null;
|
|
892
|
+
function dueMoment(value) {
|
|
893
|
+
if (typeof value !== "string" || value.trim() === "") return null;
|
|
894
|
+
const text = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T23:59:59.999Z` : value;
|
|
895
|
+
const at = new Date(text);
|
|
896
|
+
return Number.isNaN(at.getTime()) ? null : at.toISOString();
|
|
897
|
+
}
|
|
898
|
+
function windowMoment(value, end) {
|
|
899
|
+
if (typeof value !== "string" || value.trim() === "") return null;
|
|
900
|
+
const text = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}${end === "start" ? "T00:00:00.000Z" : "T23:59:59.999Z"}` : value;
|
|
901
|
+
const at = new Date(text);
|
|
902
|
+
return Number.isNaN(at.getTime()) ? null : at.toISOString();
|
|
903
|
+
}
|
|
904
|
+
async function readable(db, principal, object, id) {
|
|
905
|
+
let source;
|
|
906
|
+
try {
|
|
907
|
+
source = buyableSource({ principal }, object);
|
|
908
|
+
} catch {
|
|
909
|
+
return false;
|
|
910
|
+
}
|
|
911
|
+
const row = await db.selectFrom(source).select("id").where("id", "=", id).executeTakeFirst();
|
|
912
|
+
return Boolean(row);
|
|
913
|
+
}
|
|
914
|
+
async function priceLines(db, lines, currency, now = (/* @__PURE__ */ new Date()).toISOString(), buyer, options = {}) {
|
|
915
|
+
const reader = orgReader(db);
|
|
916
|
+
const seen = /* @__PURE__ */ new Set();
|
|
917
|
+
const priced2 = [];
|
|
918
|
+
let granting = 0;
|
|
919
|
+
for (const [index, line] of lines.entries()) {
|
|
920
|
+
const key = `${line.object}\0${line.id}`;
|
|
921
|
+
if (seen.has(key)) {
|
|
922
|
+
refuseLine("duplicate_line", index, "The same item is on the order twice: use a quantity");
|
|
923
|
+
}
|
|
924
|
+
seen.add(key);
|
|
925
|
+
const object = getObject(line.object);
|
|
926
|
+
const sellable = object ? sellableOf(object) : void 0;
|
|
927
|
+
if (!object || !sellable || sellableProblems(sellable, object).length) {
|
|
928
|
+
refuseLine("not_for_sale", index, "This cannot be bought");
|
|
929
|
+
}
|
|
930
|
+
if (Boolean(sellable.recurring) !== Boolean(options.plans)) {
|
|
931
|
+
refuseLine(
|
|
932
|
+
"not_for_sale",
|
|
933
|
+
index,
|
|
934
|
+
sellable.recurring ? "This is a plan: subscribe to it instead" : "This is not a plan"
|
|
935
|
+
);
|
|
936
|
+
}
|
|
937
|
+
const row = await db.selectFrom(visibleSource(reader, object)).selectAll().where("id", "=", line.id).executeTakeFirst();
|
|
938
|
+
if (!row) refuseLine("not_for_sale", index, "This cannot be bought");
|
|
939
|
+
if (buyer && buyer.kind !== "staff" && !await readable(db, buyer, object, line.id)) {
|
|
940
|
+
refuseLine("not_for_sale", index, "This cannot be bought");
|
|
941
|
+
}
|
|
942
|
+
const field = (name) => object.fields.find((f) => f.name === name);
|
|
943
|
+
const read = (name) => {
|
|
944
|
+
const col = column2(field(name));
|
|
945
|
+
return col ? row[col] ?? null : null;
|
|
946
|
+
};
|
|
947
|
+
const pricedIn = sellable.currency ?? field(sellable.price)?.options?.currency;
|
|
948
|
+
if (pricedIn && pricedIn.toUpperCase() !== currency) {
|
|
949
|
+
refuseLine(
|
|
950
|
+
"currency",
|
|
951
|
+
index,
|
|
952
|
+
`This is priced in ${pricedIn}, and orders are in ${currency}`,
|
|
953
|
+
{
|
|
954
|
+
currency: pricedIn
|
|
955
|
+
}
|
|
956
|
+
);
|
|
957
|
+
}
|
|
958
|
+
const unitPrice = toMinorUnits(read(sellable.price), currency);
|
|
959
|
+
if (unitPrice === null) refuseLine("no_price", index, "This has no price yet");
|
|
960
|
+
if (sellable.saleWindow) {
|
|
961
|
+
const from = windowMoment(read(sellable.saleWindow.from ?? ""), "start");
|
|
962
|
+
const until = windowMoment(read(sellable.saleWindow.until ?? ""), "end");
|
|
963
|
+
if (from && now < from || until && now > until) {
|
|
964
|
+
refuseLine(
|
|
965
|
+
"sale_window",
|
|
966
|
+
index,
|
|
967
|
+
from && now < from ? "This is not on sale yet" : "This is no longer on sale",
|
|
968
|
+
{ from, until }
|
|
969
|
+
);
|
|
970
|
+
}
|
|
971
|
+
}
|
|
972
|
+
const own = sellable.maxPerOrder ? read(sellable.maxPerOrder) : null;
|
|
973
|
+
const max = lineLimit(sellable, typeof own === "number" && Number.isFinite(own) ? own : null);
|
|
974
|
+
if (max !== null && line.quantity > max) {
|
|
975
|
+
refuseLine("max_per_order", index, `At most ${max} of this on one order`, {
|
|
976
|
+
max,
|
|
977
|
+
asked: line.quantity
|
|
978
|
+
});
|
|
979
|
+
}
|
|
980
|
+
if (sellable.grants) {
|
|
981
|
+
if (granting + line.quantity > GRANTS_PER_ORDER_CEILING) {
|
|
982
|
+
refuseLine(
|
|
983
|
+
"max_per_order",
|
|
984
|
+
index,
|
|
985
|
+
`At most ${GRANTS_PER_ORDER_CEILING} tickets or other grants on one order`,
|
|
986
|
+
{
|
|
987
|
+
max: GRANTS_PER_ORDER_CEILING - granting,
|
|
988
|
+
asked: line.quantity,
|
|
989
|
+
ceiling: GRANTS_PER_ORDER_CEILING
|
|
990
|
+
}
|
|
991
|
+
);
|
|
992
|
+
}
|
|
993
|
+
granting += line.quantity;
|
|
994
|
+
}
|
|
995
|
+
let deposit = null;
|
|
996
|
+
if (sellable.deposit) {
|
|
997
|
+
const amount = toMinorUnits(read(sellable.deposit.amount), currency);
|
|
998
|
+
const balanceDueAt = dueMoment(read(sellable.deposit.balanceDue));
|
|
999
|
+
if (amount !== null && amount > 0 && balanceDueAt) deposit = { amount, balanceDueAt };
|
|
1000
|
+
}
|
|
1001
|
+
const title = object.titleField ? read(object.titleField) : null;
|
|
1002
|
+
const trial = sellable.recurring?.trialDays ? read(sellable.recurring.trialDays) : null;
|
|
1003
|
+
priced2.push({
|
|
1004
|
+
...sellable.recurring ? {
|
|
1005
|
+
recurring: {
|
|
1006
|
+
interval: sellable.recurring.interval,
|
|
1007
|
+
trialDays: typeof trial === "number" && Number.isInteger(trial) && trial > 0 ? trial : null
|
|
1008
|
+
}
|
|
1009
|
+
} : {},
|
|
1010
|
+
id: newId("orderLine"),
|
|
1011
|
+
position: index,
|
|
1012
|
+
object: object.name,
|
|
1013
|
+
recordId: line.id,
|
|
1014
|
+
title: title == null || title === "" ? object.label : String(title),
|
|
1015
|
+
quantity: line.quantity,
|
|
1016
|
+
unitPrice,
|
|
1017
|
+
total: unitPrice * line.quantity,
|
|
1018
|
+
deposit
|
|
1019
|
+
});
|
|
1020
|
+
}
|
|
1021
|
+
return priced2;
|
|
1022
|
+
}
|
|
1023
|
+
async function createOrder(ctx, input) {
|
|
1024
|
+
if (!input.lines.length) throw new ValidationError("An order needs at least one line");
|
|
1025
|
+
if (input.lines.length > ORDER_MAX_LINES) {
|
|
1026
|
+
throw new ValidationError(`An order has at most ${ORDER_MAX_LINES} lines`);
|
|
1027
|
+
}
|
|
1028
|
+
for (const [index, line] of input.lines.entries()) {
|
|
1029
|
+
if (!Number.isInteger(line.quantity) || line.quantity < 1 || line.quantity > ORDER_MAX_QUANTITY) {
|
|
1030
|
+
throw new ValidationError("A quantity is a whole number, at least 1", { line: index });
|
|
1031
|
+
}
|
|
1032
|
+
}
|
|
1033
|
+
const currency = await loadOrderCurrency(ctx.db);
|
|
1034
|
+
if (!currency) {
|
|
1035
|
+
throw new ConfigError("No currency is set for orders yet, so nothing can be sold");
|
|
1036
|
+
}
|
|
1037
|
+
const lines = await priceLines(ctx.db, input.lines, currency, ctx.now, callerOf(ctx));
|
|
1038
|
+
const total = lines.reduce((sum, line) => sum + line.total, 0);
|
|
1039
|
+
if (total <= 0) {
|
|
1040
|
+
throw new ValidationError("An order with nothing to pay cannot be started", { rule: "total" });
|
|
1041
|
+
}
|
|
1042
|
+
let deposit = null;
|
|
1043
|
+
let balanceDueAt = null;
|
|
1044
|
+
if (input.pay === "deposit") {
|
|
1045
|
+
for (const line of lines) {
|
|
1046
|
+
if (!line.deposit) {
|
|
1047
|
+
refuseLine("deposit_not_offered", line.position, "This cannot be paid by deposit");
|
|
1048
|
+
}
|
|
1049
|
+
}
|
|
1050
|
+
const offered = lines.map((line) => line.deposit);
|
|
1051
|
+
deposit = lines.reduce((sum, line, i) => sum + (offered[i]?.amount ?? 0) * line.quantity, 0);
|
|
1052
|
+
balanceDueAt = offered.map((d) => d.balanceDueAt).sort()[0];
|
|
1053
|
+
if (deposit >= total) {
|
|
1054
|
+
throw new ValidationError("The deposit is the whole price: pay in full", {
|
|
1055
|
+
rule: "deposit_not_offered"
|
|
1056
|
+
});
|
|
1057
|
+
}
|
|
1058
|
+
if (balanceDueAt <= ctx.now) {
|
|
1059
|
+
throw new ValidationError("The balance was due before today: pay in full", {
|
|
1060
|
+
rule: "deposit_not_offered"
|
|
1061
|
+
});
|
|
1062
|
+
}
|
|
1063
|
+
}
|
|
1064
|
+
const minutes = await loadOrderExpiryMinutes(ctx.db);
|
|
1065
|
+
const id = newId("order");
|
|
1066
|
+
const row = {
|
|
1067
|
+
id,
|
|
1068
|
+
person_id: input.personId,
|
|
1069
|
+
email: input.email,
|
|
1070
|
+
currency,
|
|
1071
|
+
total,
|
|
1072
|
+
paid: 0,
|
|
1073
|
+
state: "pending",
|
|
1074
|
+
pay: input.pay,
|
|
1075
|
+
deposit,
|
|
1076
|
+
balance_due_at: balanceDueAt,
|
|
1077
|
+
expires_at: new Date(Date.parse(ctx.now) + minutes * 6e4).toISOString(),
|
|
1078
|
+
placed_as: input.placedAs,
|
|
1079
|
+
provider: null,
|
|
1080
|
+
provider_ref: null,
|
|
1081
|
+
access_hash: input.accessHash ?? null,
|
|
1082
|
+
access_until: null,
|
|
1083
|
+
email_link_hash: null,
|
|
1084
|
+
refunded: 0,
|
|
1085
|
+
tax_amount: 0,
|
|
1086
|
+
tax_refunded: 0,
|
|
1087
|
+
tax_country: null,
|
|
1088
|
+
subscription_id: null,
|
|
1089
|
+
period_start: null,
|
|
1090
|
+
period_end: null,
|
|
1091
|
+
invoice_ref: null,
|
|
1092
|
+
period_flag: null,
|
|
1093
|
+
paid_at: null,
|
|
1094
|
+
cancelled_at: null,
|
|
1095
|
+
refunded_at: null,
|
|
1096
|
+
created_at: ctx.now,
|
|
1097
|
+
updated_at: ctx.now,
|
|
1098
|
+
version: 0
|
|
1099
|
+
};
|
|
1100
|
+
const outcome = await applyTransition(
|
|
1101
|
+
ctx,
|
|
1102
|
+
order(),
|
|
1103
|
+
id,
|
|
1104
|
+
null,
|
|
1105
|
+
{ state: "pending" },
|
|
1106
|
+
{ by: "host" }
|
|
1107
|
+
);
|
|
1108
|
+
await claimOrderPlaces(ctx, id, lines);
|
|
1109
|
+
ctx.write(
|
|
1110
|
+
ctx.db.insertInto("core_order").values(row),
|
|
1111
|
+
...lines.map(
|
|
1112
|
+
(line) => ctx.db.insertInto("core_order_line").values({
|
|
1113
|
+
id: line.id,
|
|
1114
|
+
order_id: id,
|
|
1115
|
+
position: line.position,
|
|
1116
|
+
object_type: line.object,
|
|
1117
|
+
record_id: line.recordId,
|
|
1118
|
+
title: line.title,
|
|
1119
|
+
quantity: line.quantity,
|
|
1120
|
+
unit_price: line.unitPrice,
|
|
1121
|
+
line_total: line.total,
|
|
1122
|
+
created_at: ctx.now
|
|
1123
|
+
})
|
|
1124
|
+
),
|
|
1125
|
+
...outcome.history
|
|
1126
|
+
);
|
|
1127
|
+
recordHostChange(ctx, { object: "order", id, action: "create", after: orderSnapshot(row) });
|
|
1128
|
+
postOrderMove(ctx, row, null);
|
|
1129
|
+
return { row, lines };
|
|
1130
|
+
}
|
|
1131
|
+
async function changeOrder(ctx, row, to, change, by) {
|
|
1132
|
+
const before = orderSnapshot(row);
|
|
1133
|
+
const next = {
|
|
1134
|
+
...row,
|
|
1135
|
+
...change,
|
|
1136
|
+
state: to,
|
|
1137
|
+
updated_at: ctx.now,
|
|
1138
|
+
version: row.version + 1,
|
|
1139
|
+
// A guest's link outlives the order's closing by a while, then stops.
|
|
1140
|
+
access_until: CLOSED.has(to) ? new Date(Date.parse(ctx.now) + ORDER_ACCESS_DAYS_AFTER_CLOSE * 864e5).toISOString() : null
|
|
1141
|
+
};
|
|
1142
|
+
const outcome = await applyTransition(ctx, order(), row.id, before, orderSnapshot(next), { by });
|
|
1143
|
+
ctx.write(
|
|
1144
|
+
ctx.db.updateTable("core_order").set({
|
|
1145
|
+
...change,
|
|
1146
|
+
state: to,
|
|
1147
|
+
updated_at: next.updated_at,
|
|
1148
|
+
version: next.version,
|
|
1149
|
+
access_until: next.access_until
|
|
1150
|
+
}).where("id", "=", row.id),
|
|
1151
|
+
...outcome.history
|
|
1152
|
+
);
|
|
1153
|
+
recordHostChange(ctx, {
|
|
1154
|
+
object: "order",
|
|
1155
|
+
id: row.id,
|
|
1156
|
+
action: "update",
|
|
1157
|
+
before,
|
|
1158
|
+
after: orderSnapshot(next)
|
|
1159
|
+
});
|
|
1160
|
+
if (to !== row.state) postOrderMove(ctx, next, row.state);
|
|
1161
|
+
return next;
|
|
1162
|
+
}
|
|
1163
|
+
var MOVE_WORDS = {
|
|
1164
|
+
pending: "started",
|
|
1165
|
+
part_paid: "part paid",
|
|
1166
|
+
paid: "paid",
|
|
1167
|
+
cancelled: "cancelled",
|
|
1168
|
+
expired: "expired",
|
|
1169
|
+
refunded: "refunded"
|
|
1170
|
+
};
|
|
1171
|
+
function formatMoney(amount, currency) {
|
|
1172
|
+
const digits = currencyDecimals(currency);
|
|
1173
|
+
return `${(amount / 10 ** digits).toFixed(digits)} ${currency}`;
|
|
1174
|
+
}
|
|
1175
|
+
function postOrderMove(ctx, row, from) {
|
|
1176
|
+
if (!row.person_id) return;
|
|
1177
|
+
const money = row.state === "pending" ? formatMoney(row.total, row.currency) : row.state === "refunded" ? formatMoney(row.refunded, row.currency) : `${formatMoney(row.paid, row.currency)} of ${formatMoney(row.total, row.currency)}`;
|
|
1178
|
+
ctx.postActivity({
|
|
1179
|
+
subject: `Order ${MOVE_WORDS[row.state]}: ${money}`,
|
|
1180
|
+
payload: {
|
|
1181
|
+
kind: "order.moved",
|
|
1182
|
+
orderId: row.id,
|
|
1183
|
+
from,
|
|
1184
|
+
to: row.state,
|
|
1185
|
+
total: row.total,
|
|
1186
|
+
paid: row.paid,
|
|
1187
|
+
refunded: row.refunded,
|
|
1188
|
+
currency: row.currency
|
|
1189
|
+
},
|
|
1190
|
+
links: [{ object: "person", id: row.person_id }]
|
|
1191
|
+
});
|
|
1192
|
+
}
|
|
1193
|
+
function chargeFor(row, minPart, amount) {
|
|
1194
|
+
const refuse = (message, rule, extra) => {
|
|
1195
|
+
throw new ValidationError(message, { rule, order: row.id, ...extra });
|
|
1196
|
+
};
|
|
1197
|
+
if (row.state === "pending") {
|
|
1198
|
+
const due = row.pay === "deposit" ? row.deposit : row.total;
|
|
1199
|
+
if (amount !== void 0 && amount !== due) {
|
|
1200
|
+
refuse("The first payment on an order is not the buyer's to choose", "charge_amount", {
|
|
1201
|
+
due
|
|
1202
|
+
});
|
|
1203
|
+
}
|
|
1204
|
+
return {
|
|
1205
|
+
amount: due,
|
|
1206
|
+
currency: row.currency,
|
|
1207
|
+
kind: row.pay === "deposit" ? "deposit" : "full"
|
|
1208
|
+
};
|
|
1209
|
+
}
|
|
1210
|
+
if (row.state === "part_paid") {
|
|
1211
|
+
const balance = row.total - row.paid;
|
|
1212
|
+
const least = Math.min(minPart, balance);
|
|
1213
|
+
const wanted = amount ?? balance;
|
|
1214
|
+
if (!Number.isInteger(wanted) || wanted < least || wanted > balance) {
|
|
1215
|
+
refuse(`A payment towards this order is between ${least} and ${balance}`, "charge_amount", {
|
|
1216
|
+
least,
|
|
1217
|
+
balance
|
|
1218
|
+
});
|
|
1219
|
+
}
|
|
1220
|
+
return {
|
|
1221
|
+
amount: wanted,
|
|
1222
|
+
currency: row.currency,
|
|
1223
|
+
kind: wanted === balance ? "balance" : "part"
|
|
1224
|
+
};
|
|
1225
|
+
}
|
|
1226
|
+
return refuse("Nothing can be paid on this order", "charge_state", { state: row.state });
|
|
1227
|
+
}
|
|
1228
|
+
var OVERDUE_LIMIT = 200;
|
|
1229
|
+
function overdueOrders(db, now, limit = OVERDUE_LIMIT) {
|
|
1230
|
+
return db.selectFrom("core_order").selectAll().where("state", "=", "part_paid").where("balance_due_at", "<", now).orderBy("balance_due_at").limit(Math.min(Math.max(limit, 1), OVERDUE_LIMIT)).execute();
|
|
1231
|
+
}
|
|
1232
|
+
function requireState(row, states, what) {
|
|
1233
|
+
if (!states.includes(row.state)) {
|
|
1234
|
+
throw new ConflictError(`An order that is ${row.state} cannot be ${what}`, {
|
|
1235
|
+
order: row.id,
|
|
1236
|
+
state: row.state
|
|
1237
|
+
});
|
|
1238
|
+
}
|
|
1239
|
+
}
|
|
1240
|
+
|
|
1241
|
+
// ../core/src/orders/subscription-setup.ts
|
|
1242
|
+
async function subscriptionSetup(db) {
|
|
1243
|
+
let target = null;
|
|
1244
|
+
try {
|
|
1245
|
+
target = await paymentsTarget(db);
|
|
1246
|
+
} catch (error) {
|
|
1247
|
+
if (!(error instanceof ConfigError)) throw error;
|
|
1248
|
+
}
|
|
1249
|
+
return {
|
|
1250
|
+
returnOrigins: [...await loadReturnOrigins(db)],
|
|
1251
|
+
currency: await loadOrderCurrency(db),
|
|
1252
|
+
target
|
|
1253
|
+
};
|
|
1254
|
+
}
|
|
1255
|
+
function setupComplete(setup) {
|
|
1256
|
+
return setup.returnOrigins.length > 0 && setup.currency !== null && setup.target !== null;
|
|
1257
|
+
}
|
|
1258
|
+
|
|
1259
|
+
// ../core/src/customers/plan-on-sale.ts
|
|
1260
|
+
var PUBLIC = Object.freeze({ kind: "public" });
|
|
1261
|
+
var PLANS_LOOKED_AT = 50;
|
|
1262
|
+
var PLAN_ON_SALE_MEMO_MS = 6e4;
|
|
1263
|
+
var memo = null;
|
|
1264
|
+
function forgetPlanOnSale() {
|
|
1265
|
+
memo = null;
|
|
1266
|
+
}
|
|
1267
|
+
async function findPlanOnSale(db, now = (/* @__PURE__ */ new Date()).toISOString(), options = {}) {
|
|
1268
|
+
const at = Date.now();
|
|
1269
|
+
if (options.memo && memo && at - memo.at < PLAN_ON_SALE_MEMO_MS) return memo.value;
|
|
1270
|
+
let value;
|
|
1271
|
+
try {
|
|
1272
|
+
value = await compute(db, now);
|
|
1273
|
+
} catch (error) {
|
|
1274
|
+
value = { state: "unknown", reason: error instanceof Error ? error.message : String(error) };
|
|
1275
|
+
}
|
|
1276
|
+
memo = { at, value };
|
|
1277
|
+
return value;
|
|
1278
|
+
}
|
|
1279
|
+
async function hasPlanOnSale(db, now = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
1280
|
+
return (await findPlanOnSale(db, now)).state === "on_sale";
|
|
1281
|
+
}
|
|
1282
|
+
async function compute(db, now) {
|
|
1283
|
+
const setup = await subscriptionSetup(db);
|
|
1284
|
+
if (!setupComplete(setup)) return { state: "none" };
|
|
1285
|
+
await refreshSchemaRegistry(db);
|
|
1286
|
+
let unanswered = false;
|
|
1287
|
+
for (const object of listObjects()) {
|
|
1288
|
+
const sellable = sellableOf(object);
|
|
1289
|
+
if (!sellable?.recurring || sellableProblems(sellable, object).length) continue;
|
|
1290
|
+
const scope = scopeOf(PUBLIC, object, false);
|
|
1291
|
+
if (scope.kind !== "public") continue;
|
|
1292
|
+
let source;
|
|
1293
|
+
try {
|
|
1294
|
+
source = buyableSource({ principal: PUBLIC }, object);
|
|
1295
|
+
} catch {
|
|
1296
|
+
continue;
|
|
1297
|
+
}
|
|
1298
|
+
const readable2 = new Set(scope.columns);
|
|
1299
|
+
const columnOf = (name) => {
|
|
1300
|
+
const field = name ? object.fields.find((f) => f.name === name) : void 0;
|
|
1301
|
+
const column3 = field ? viewColumnOf(field) : null;
|
|
1302
|
+
return column3 && readable2.has(column3) ? column3 : null;
|
|
1303
|
+
};
|
|
1304
|
+
let query = db.selectFrom(source).select("id");
|
|
1305
|
+
const price = columnOf(sellable.price);
|
|
1306
|
+
if (price) query = query.where(sql.ref(price), ">", 0);
|
|
1307
|
+
const day = now.slice(0, 10);
|
|
1308
|
+
const from = columnOf(sellable.saleWindow?.from);
|
|
1309
|
+
if (from) {
|
|
1310
|
+
query = query.where(
|
|
1311
|
+
(eb) => eb.or([eb(sql.ref(from), "is", null), eb(sql.ref(from), "<=", now)])
|
|
1312
|
+
);
|
|
1313
|
+
}
|
|
1314
|
+
const until = columnOf(sellable.saleWindow?.until);
|
|
1315
|
+
if (until) {
|
|
1316
|
+
query = query.where(
|
|
1317
|
+
(eb) => eb.or([eb(sql.ref(until), "is", null), eb(sql.ref(until), ">=", day)])
|
|
1318
|
+
);
|
|
1319
|
+
}
|
|
1320
|
+
const rows = await query.orderBy("id").limit(PLANS_LOOKED_AT + 1).execute();
|
|
1321
|
+
for (const { id } of rows.slice(0, PLANS_LOOKED_AT)) {
|
|
1322
|
+
const found = await priced(db, object, id, setup.currency, now);
|
|
1323
|
+
if (found) return { state: "on_sale", plan: found };
|
|
1324
|
+
}
|
|
1325
|
+
if (rows.length > PLANS_LOOKED_AT) unanswered = true;
|
|
1326
|
+
}
|
|
1327
|
+
return unanswered ? { state: "unknown", reason: `more than ${PLANS_LOOKED_AT} plans to look at` } : { state: "none" };
|
|
1328
|
+
}
|
|
1329
|
+
async function priced(db, object, id, currency, now) {
|
|
1330
|
+
try {
|
|
1331
|
+
const [line] = await priceLines(
|
|
1332
|
+
db,
|
|
1333
|
+
[{ object: object.name, id, quantity: 1 }],
|
|
1334
|
+
currency,
|
|
1335
|
+
now,
|
|
1336
|
+
PUBLIC,
|
|
1337
|
+
{ plans: true }
|
|
1338
|
+
);
|
|
1339
|
+
return line?.recurring && line.unitPrice > 0 ? { object: object.name, id, title: line.title } : null;
|
|
1340
|
+
} catch (error) {
|
|
1341
|
+
if (error instanceof ValidationError) return null;
|
|
1342
|
+
throw error;
|
|
1343
|
+
}
|
|
1344
|
+
}
|
|
1345
|
+
|
|
1346
|
+
export {
|
|
1347
|
+
callerOf,
|
|
1348
|
+
transitionTimeline,
|
|
1349
|
+
resolveStateRequest,
|
|
1350
|
+
callerMover,
|
|
1351
|
+
onRecordMove,
|
|
1352
|
+
applyTransition,
|
|
1353
|
+
ORDER_MAX_LINES,
|
|
1354
|
+
ORDER_MAX_QUANTITY,
|
|
1355
|
+
orderSnapshot,
|
|
1356
|
+
loadOrderRow,
|
|
1357
|
+
priceLines,
|
|
1358
|
+
createOrder,
|
|
1359
|
+
changeOrder,
|
|
1360
|
+
formatMoney,
|
|
1361
|
+
chargeFor,
|
|
1362
|
+
overdueOrders,
|
|
1363
|
+
requireState,
|
|
1364
|
+
subscriptionSetup,
|
|
1365
|
+
PLANS_LOOKED_AT,
|
|
1366
|
+
PLAN_ON_SALE_MEMO_MS,
|
|
1367
|
+
forgetPlanOnSale,
|
|
1368
|
+
findPlanOnSale,
|
|
1369
|
+
hasPlanOnSale
|
|
1370
|
+
};
|