@composable-os/cli 0.0.0-stage → 0.1.0-beta.10
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/LICENSE +109 -0
- package/README.md +24 -2
- package/dist/accounts-X4CKM3HL.js +46 -0
- package/dist/blocks-YWDHEBOK.js +233 -0
- package/dist/chunk-2ABSVMGB.js +13 -0
- package/dist/chunk-5KSXSK7Y.js +47 -0
- package/dist/chunk-6GDEDOV7.js +157 -0
- package/dist/chunk-6UPUF4ML.js +29998 -0
- package/dist/chunk-6UWRT4VM.js +220 -0
- package/dist/chunk-6VXHPKGG.js +1302 -0
- package/dist/chunk-7CQGMVDO.js +63 -0
- package/dist/chunk-A4NTSYWV.js +11092 -0
- package/dist/chunk-CP6BXI6F.js +25825 -0
- package/dist/chunk-DU6OIFOU.js +2358 -0
- package/dist/chunk-E4WCYTCT.js +347 -0
- package/dist/chunk-GYSGVT6R.js +284 -0
- package/dist/chunk-GYTEW66E.js +50 -0
- package/dist/chunk-HDIOVFAZ.js +544 -0
- package/dist/chunk-IFG4FRW5.js +504 -0
- package/dist/chunk-JJHHNV46.js +227 -0
- package/dist/chunk-K6T42YCH.js +704 -0
- package/dist/chunk-KGHA67HG.js +765 -0
- package/dist/chunk-LJFLENFC.js +88 -0
- package/dist/chunk-LLULPZAJ.js +365 -0
- package/dist/chunk-M7A6FR2Z.js +2586 -0
- package/dist/chunk-O2UIZHND.js +249 -0
- package/dist/chunk-Q4N55M2Z.js +552 -0
- package/dist/chunk-QGGJ2G6Z.js +349 -0
- package/dist/chunk-R4W5XAUD.js +837 -0
- package/dist/chunk-TQFGGSA4.js +748 -0
- package/dist/chunk-VY64DMQO.js +15302 -0
- package/dist/chunk-WC5LHBBA.js +426 -0
- package/dist/chunk-WO6D3XP3.js +9351 -0
- package/dist/chunk-Y7JZFSTQ.js +1425 -0
- package/dist/chunk-YJJHF65I.js +759 -0
- package/dist/chunk-Z3RMMB6S.js +668 -0
- package/dist/cli-2DFENR62.js +134 -0
- package/dist/cli-YIOVSKOD.js +24531 -0
- package/dist/cli.js +25 -0
- package/dist/client-repo-PRU3VCQQ.js +55 -0
- package/dist/create.js +25 -0
- package/dist/fields-2NC7LSYE.js +50 -0
- package/dist/grants-QXMKYMGB.js +32 -0
- package/dist/invoke-I3NNNXVL.js +39 -0
- package/dist/order-PUWD65BC.js +19 -0
- package/dist/person-WIQQ7ITU.js +68 -0
- package/dist/plan-on-sale-NB774CQL.js +26 -0
- package/dist/platform/migrations/0001_init.sql +59 -0
- package/dist/platform/migrations/0002_users_settings.sql +34 -0
- package/dist/platform/migrations/0003_people_organisations.sql +225 -0
- package/dist/platform/migrations/0004_activities_tasks.sql +88 -0
- package/dist/platform/migrations/0005_views_audit.sql +79 -0
- package/dist/platform/migrations/0006_search.sql +223 -0
- package/dist/platform/migrations/0007_crm_views.sql +141 -0
- package/dist/platform/migrations/0008_audit_redaction.sql +116 -0
- package/dist/platform/migrations/0010_approval_queue.sql +90 -0
- package/dist/platform/migrations/0011_connected_apps.sql +36 -0
- package/dist/platform/migrations/0020_extensions.sql +373 -0
- package/dist/platform/migrations/0030_extension_proposals.sql +29 -0
- package/dist/platform/migrations/0050_live_row_indexes.sql +32 -0
- package/dist/platform/migrations/0060_audit_read_counts.sql +31 -0
- package/dist/platform/migrations/0061_audit_retention.sql +95 -0
- package/dist/platform/migrations/0062_run_history_retention.sql +6 -0
- package/dist/platform/migrations/0063_pending_action_compaction.sql +18 -0
- package/dist/platform/migrations/0064_drop_rate_limit.sql +6 -0
- package/dist/platform/migrations/0065_storage_stats.sql +13 -0
- package/dist/platform/migrations/0070_drop_proposals_ext_idx.sql +9 -0
- package/dist/platform/migrations/0080_views_dashboards.sql +46 -0
- package/dist/platform/migrations/0100_stage_history.sql +54 -0
- package/dist/platform/migrations/0110_integrations.sql +103 -0
- package/dist/platform/migrations/0111_email_calendar_sync.sql +137 -0
- package/dist/platform/migrations/0112_sync_item_occurred_at.sql +8 -0
- package/dist/platform/migrations/0130_automations.sql +113 -0
- package/dist/platform/migrations/0131_notifications.sql +29 -0
- package/dist/platform/migrations/0132_automation_runtime.sql +14 -0
- package/dist/platform/migrations/0150_ai_summaries_embeddings.sql +48 -0
- package/dist/platform/migrations/0160_releases.sql +41 -0
- package/dist/platform/migrations/0161_setup_wizard.sql +30 -0
- package/dist/platform/migrations/0170_automation_connections.sql +32 -0
- package/dist/platform/migrations/0171_automation_outbox.sql +23 -0
- package/dist/platform/migrations/0172_notification_delivery.sql +46 -0
- package/dist/platform/migrations/0200_assistant_conversations.sql +25 -0
- package/dist/platform/migrations/0205_policy_adjudicator.sql +61 -0
- package/dist/platform/migrations/0210_daily_digest.sql +33 -0
- package/dist/platform/migrations/0220_entitlements.sql +13 -0
- package/dist/platform/migrations/0221_support_grants.sql +33 -0
- package/dist/platform/migrations/0250_judge.sql +11 -0
- package/dist/platform/migrations/0251_adjudication_judgement.sql +8 -0
- package/dist/platform/migrations/0252_judge_usage.sql +14 -0
- package/dist/platform/migrations/0255_summary_checks.sql +9 -0
- package/dist/platform/migrations/0256_outbound_check.sql +9 -0
- package/dist/platform/migrations/0260_ai_usage.sql +20 -0
- package/dist/platform/migrations/0270_assistant_conversation_refs.sql +29 -0
- package/dist/platform/migrations/0310_assignment_rules.sql +54 -0
- package/dist/platform/migrations/0320_duplicates.sql +41 -0
- package/dist/platform/migrations/0330_erase_completeness.sql +54 -0
- package/dist/platform/migrations/0350_assistant_thread.sql +38 -0
- package/dist/platform/migrations/0351_assistant_model_roles.sql +26 -0
- package/dist/platform/migrations/0352_assistant_memory.sql +74 -0
- package/dist/platform/migrations/0358_ai_cache_observation.sql +24 -0
- package/dist/platform/migrations/0359_ai_compaction_decision.sql +25 -0
- package/dist/platform/migrations/0360_ai_cache_estimate.sql +35 -0
- package/dist/platform/migrations/0361_voice_preferences.sql +27 -0
- package/dist/platform/migrations/0362_voice_usage.sql +17 -0
- package/dist/platform/migrations/0365_routines.sql +38 -0
- package/dist/platform/migrations/0370_approval_execution.sql +20 -0
- package/dist/platform/migrations/0371_agent_jobs.sql +65 -0
- package/dist/platform/migrations/0380_rec_views.sql +94 -0
- package/dist/platform/migrations/0400_customer_audit_actor.sql +142 -0
- package/dist/platform/migrations/0401_customer_accounts.sql +61 -0
- package/dist/platform/migrations/0402_erase_requests.sql +34 -0
- package/dist/platform/migrations/0410_idempotency_keys.sql +45 -0
- package/dist/platform/migrations/0411_device_sessions.sql +33 -0
- package/dist/platform/migrations/0420_transition_history.sql +100 -0
- package/dist/platform/migrations/0421_orders.sql +134 -0
- package/dist/platform/migrations/0422_order_payments.sql +109 -0
- package/dist/platform/migrations/0440_capacity.sql +100 -0
- package/dist/platform/migrations/0441_capacity_views.sql +40 -0
- package/dist/platform/migrations/0450_order_grants.sql +21 -0
- package/dist/platform/migrations/0451_pack_roles.sql +18 -0
- package/dist/platform/migrations/0460_content.sql +59 -0
- package/dist/platform/migrations/0461_media.sql +52 -0
- package/dist/platform/migrations/0470_publish_versions.sql +36 -0
- package/dist/platform/migrations/0471_permission_grants.sql +18 -0
- package/dist/platform/migrations/0490_staff_invites.sql +40 -0
- package/dist/platform/migrations/0491_sign_in_mail_kind.sql +10 -0
- package/dist/platform/migrations/0492_email_confirmation_and_sign_in_confirm.sql +30 -0
- package/dist/platform/migrations/0500_published_media_field.sql +25 -0
- package/dist/platform/migrations/0501_import_keys.sql +23 -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/migrations/0580_subscription_grants.sql +21 -0
- package/dist/platform/migrations/0581_once_per_person.sql +34 -0
- package/dist/platform/migrations/0600_tool_actions_ran_at_queue.sql +22 -0
- package/dist/platform/sdk/allowance.ts +522 -0
- package/dist/platform/sdk/automation-check.ts +534 -0
- package/dist/platform/sdk/automation.ts +743 -0
- package/dist/platform/sdk/behaviour.ts +215 -0
- package/dist/platform/sdk/capacity.ts +201 -0
- package/dist/platform/sdk/contract.ts +884 -0
- package/dist/platform/sdk/document.ts +935 -0
- package/dist/platform/sdk/field-types.ts +111 -0
- package/dist/platform/sdk/formula/ast.ts +72 -0
- package/dist/platform/sdk/formula/compile.ts +454 -0
- package/dist/platform/sdk/formula/index.ts +4 -0
- package/dist/platform/sdk/formula/parser.ts +417 -0
- package/dist/platform/sdk/index.ts +36 -0
- package/dist/platform/sdk/manifest.ts +1709 -0
- package/dist/platform/sdk/media.ts +108 -0
- package/dist/platform/sdk/permissions.ts +60 -0
- package/dist/platform/sdk/recurring.ts +321 -0
- package/dist/platform/sdk/renamed.ts +63 -0
- package/dist/platform/sdk/rich-text-fixture.ts +68 -0
- package/dist/platform/sdk/rich-text.ts +221 -0
- package/dist/platform/sdk/runtime.ts +410 -0
- package/dist/platform/sdk/sellable.ts +888 -0
- package/dist/platform/sdk/slug.ts +25 -0
- package/dist/platform/sdk/states.ts +484 -0
- package/dist/platform/sdk/testing.ts +847 -0
- package/dist/platform/sdk/unique.ts +81 -0
- package/dist/products-2H5DR232.js +11 -0
- package/dist/run-PZUCSDDL.js +508 -0
- package/dist/run-RT2HVWMK.js +648 -0
- package/dist/run-Y7T4TVOL.js +309 -0
- package/dist/src-GYS6NBQB.js +44 -0
- package/dist/src-XTOD7EXW.js +348 -0
- package/dist/token-MOJUA2U6.js +70 -0
- package/dist/token-util-TENRN4V7.js +6 -0
- package/dist/visibility-DLGHU4YN.js +33 -0
- package/package.json +33 -4
|
@@ -0,0 +1,759 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import {
|
|
3
|
+
applyTransition,
|
|
4
|
+
callerOf,
|
|
5
|
+
onRecordMove
|
|
6
|
+
} from "./chunk-R4W5XAUD.js";
|
|
7
|
+
import {
|
|
8
|
+
recordHostChange
|
|
9
|
+
} from "./chunk-6GDEDOV7.js";
|
|
10
|
+
import {
|
|
11
|
+
paymentsTarget
|
|
12
|
+
} from "./chunk-LJFLENFC.js";
|
|
13
|
+
import {
|
|
14
|
+
currencyDecimals,
|
|
15
|
+
loadOrderCurrency,
|
|
16
|
+
loadOrderExpiryMinutes,
|
|
17
|
+
loadReturnOrigins,
|
|
18
|
+
toMinorUnits
|
|
19
|
+
} from "./chunk-O2UIZHND.js";
|
|
20
|
+
import {
|
|
21
|
+
confirmStatements,
|
|
22
|
+
newId,
|
|
23
|
+
queueClaim,
|
|
24
|
+
releaseStatements
|
|
25
|
+
} from "./chunk-TQFGGSA4.js";
|
|
26
|
+
import {
|
|
27
|
+
ConfigError,
|
|
28
|
+
ConflictError,
|
|
29
|
+
NotFoundError,
|
|
30
|
+
ValidationError,
|
|
31
|
+
buyableSource,
|
|
32
|
+
orgReader,
|
|
33
|
+
refreshSchemaRegistry,
|
|
34
|
+
scopeOf,
|
|
35
|
+
sql,
|
|
36
|
+
viewColumnOf,
|
|
37
|
+
visibleSource
|
|
38
|
+
} from "./chunk-A4NTSYWV.js";
|
|
39
|
+
import {
|
|
40
|
+
getObject,
|
|
41
|
+
listObjects
|
|
42
|
+
} from "./chunk-IFG4FRW5.js";
|
|
43
|
+
import {
|
|
44
|
+
orderObject
|
|
45
|
+
} from "./chunk-Q4N55M2Z.js";
|
|
46
|
+
|
|
47
|
+
// ../core/src/orders/holds.ts
|
|
48
|
+
var ORDER_CLAIM_TYPE = "order";
|
|
49
|
+
async function linesWithCapacity(ctx, orderId) {
|
|
50
|
+
const lines = await ctx.db.selectFrom("core_order_line").select(["object_type", "record_id", "quantity"]).where("order_id", "=", orderId).orderBy("position").execute();
|
|
51
|
+
return lines.filter((line) => getObject(line.object_type)?.capacity);
|
|
52
|
+
}
|
|
53
|
+
async function claimOrderPlaces(ctx, orderId, lines) {
|
|
54
|
+
for (const line of lines) {
|
|
55
|
+
if (!getObject(line.object)?.capacity) continue;
|
|
56
|
+
await queueClaim(ctx, {
|
|
57
|
+
object: line.object,
|
|
58
|
+
record: line.recordId,
|
|
59
|
+
quantity: line.quantity,
|
|
60
|
+
for: { type: ORDER_CLAIM_TYPE, id: orderId }
|
|
61
|
+
});
|
|
62
|
+
}
|
|
63
|
+
}
|
|
64
|
+
var orderHolds = async (ctx, move) => {
|
|
65
|
+
const from = move.from?.id ?? null;
|
|
66
|
+
const to = move.to.id;
|
|
67
|
+
const target = { for: { type: ORDER_CLAIM_TYPE, id: move.id } };
|
|
68
|
+
if ((to === "paid" || to === "part_paid") && from === "expired") {
|
|
69
|
+
const lines = await linesWithCapacity(ctx, move.id);
|
|
70
|
+
await claimOrderPlaces(
|
|
71
|
+
ctx,
|
|
72
|
+
move.id,
|
|
73
|
+
lines.map((l) => ({ object: l.object_type, recordId: l.record_id, quantity: l.quantity }))
|
|
74
|
+
);
|
|
75
|
+
ctx.write(...confirmStatements(target, ctx.now));
|
|
76
|
+
return;
|
|
77
|
+
}
|
|
78
|
+
if ((to === "paid" || to === "part_paid") && from === "pending") {
|
|
79
|
+
ctx.write(...confirmStatements(target, ctx.now));
|
|
80
|
+
return;
|
|
81
|
+
}
|
|
82
|
+
if (to === "cancelled" || to === "expired") {
|
|
83
|
+
ctx.write(...releaseStatements(target, ctx.now, { confirmed: from === "part_paid" }));
|
|
84
|
+
return;
|
|
85
|
+
}
|
|
86
|
+
if (to === "refunded") {
|
|
87
|
+
const lines = await linesWithCapacity(ctx, move.id);
|
|
88
|
+
const keeps = (line) => getObject(line.object_type)?.capacity?.releaseOnRefund === false;
|
|
89
|
+
if (!lines.some(keeps)) {
|
|
90
|
+
ctx.write(...releaseStatements(target, ctx.now, { confirmed: true }));
|
|
91
|
+
return;
|
|
92
|
+
}
|
|
93
|
+
const releasing = new Set(
|
|
94
|
+
lines.filter((l) => !keeps(l)).map((l) => `${l.object_type}\0${l.record_id}`)
|
|
95
|
+
);
|
|
96
|
+
if (!releasing.size) return;
|
|
97
|
+
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();
|
|
98
|
+
for (const claim of claims) {
|
|
99
|
+
if (!releasing.has(`${claim.object_type}\0${claim.record_id}`)) continue;
|
|
100
|
+
ctx.write(...releaseStatements({ claim: claim.id }, ctx.now, { confirmed: true }));
|
|
101
|
+
}
|
|
102
|
+
}
|
|
103
|
+
};
|
|
104
|
+
onRecordMove("order", orderHolds);
|
|
105
|
+
|
|
106
|
+
// ../core/src/orders/once.ts
|
|
107
|
+
async function holdOncePerPerson(ctx, orderId, lines, buyer) {
|
|
108
|
+
if (!lines.length) return;
|
|
109
|
+
const refuse = (reason, message, line) => {
|
|
110
|
+
throw new ValidationError(message, { rule: "once_per_person", reason, line });
|
|
111
|
+
};
|
|
112
|
+
const objects = /* @__PURE__ */ new Set();
|
|
113
|
+
for (const line of lines) {
|
|
114
|
+
if (buyer.placedAs === "public") {
|
|
115
|
+
refuse("sign_in", "Sign in to buy this: it is one per person", line.position);
|
|
116
|
+
}
|
|
117
|
+
if (!buyer.personId) {
|
|
118
|
+
refuse(
|
|
119
|
+
"no_person",
|
|
120
|
+
"This is one per person, and the order is not for one person yet: its address belongs to several people here. Merge them, or start it for one of them",
|
|
121
|
+
line.position
|
|
122
|
+
);
|
|
123
|
+
}
|
|
124
|
+
if (line.quantity !== 1 || objects.has(line.object)) {
|
|
125
|
+
refuse("one", "This is one per person: one on one order", line.position);
|
|
126
|
+
}
|
|
127
|
+
objects.add(line.object);
|
|
128
|
+
}
|
|
129
|
+
const personId = buyer.personId;
|
|
130
|
+
const had = await ctx.db.selectFrom("core_sellable_once").select(["object_type", "state"]).where("person_id", "=", personId).where("object_type", "in", [...objects]).where("state", "in", ["held", "used"]).execute();
|
|
131
|
+
for (const line of lines) {
|
|
132
|
+
const row = had.find((h) => h.object_type === line.object);
|
|
133
|
+
if (!row) continue;
|
|
134
|
+
refuse(
|
|
135
|
+
row.state === "used" ? "used" : "held",
|
|
136
|
+
row.state === "used" ? "This is one per person, and it has been bought for this person already" : "This is one per person, and an order for it is waiting to be paid",
|
|
137
|
+
line.position
|
|
138
|
+
);
|
|
139
|
+
}
|
|
140
|
+
for (const line of lines) {
|
|
141
|
+
ctx.write(
|
|
142
|
+
ctx.db.insertInto("core_sellable_once").values({
|
|
143
|
+
id: newId("sellableOnce"),
|
|
144
|
+
person_id: personId,
|
|
145
|
+
object_type: line.object,
|
|
146
|
+
record_id: line.recordId,
|
|
147
|
+
order_id: orderId,
|
|
148
|
+
state: "held",
|
|
149
|
+
created_at: ctx.now,
|
|
150
|
+
updated_at: ctx.now
|
|
151
|
+
})
|
|
152
|
+
);
|
|
153
|
+
}
|
|
154
|
+
}
|
|
155
|
+
var orderOnce = async (ctx, move) => {
|
|
156
|
+
const from = move.from?.id ?? null;
|
|
157
|
+
const to = move.to.id;
|
|
158
|
+
if ((to === "paid" || to === "part_paid") && from === "pending") {
|
|
159
|
+
ctx.write(
|
|
160
|
+
ctx.db.updateTable("core_sellable_once").set({ state: "used", updated_at: ctx.now }).where("order_id", "=", move.id).where("state", "=", "held")
|
|
161
|
+
);
|
|
162
|
+
return;
|
|
163
|
+
}
|
|
164
|
+
if ((to === "paid" || to === "part_paid") && from === "expired") {
|
|
165
|
+
const released = await ctx.db.selectFrom("core_sellable_once").select(["person_id", "object_type", "record_id"]).where("order_id", "=", move.id).where("state", "=", "released").execute();
|
|
166
|
+
for (const row of released) {
|
|
167
|
+
if (!getObject(row.object_type)?.sellable?.onePerPerson) continue;
|
|
168
|
+
const since = await ctx.db.selectFrom("core_sellable_once").select("id").where("person_id", "=", row.person_id).where("object_type", "=", row.object_type).where("state", "in", ["held", "used"]).executeTakeFirst();
|
|
169
|
+
if (since) {
|
|
170
|
+
throw new ConflictError(
|
|
171
|
+
"This late payment cannot be honoured: it is for something one per person, and the person has had theirs since the order expired. Refund the payment instead",
|
|
172
|
+
{ rule: "once_per_person", reason: "had_since", order: move.id }
|
|
173
|
+
);
|
|
174
|
+
}
|
|
175
|
+
ctx.write(
|
|
176
|
+
ctx.db.insertInto("core_sellable_once").values({
|
|
177
|
+
id: newId("sellableOnce"),
|
|
178
|
+
person_id: row.person_id,
|
|
179
|
+
object_type: row.object_type,
|
|
180
|
+
record_id: row.record_id,
|
|
181
|
+
order_id: move.id,
|
|
182
|
+
state: "used",
|
|
183
|
+
created_at: ctx.now,
|
|
184
|
+
updated_at: ctx.now
|
|
185
|
+
})
|
|
186
|
+
);
|
|
187
|
+
}
|
|
188
|
+
return;
|
|
189
|
+
}
|
|
190
|
+
if ((to === "expired" || to === "cancelled") && from === "pending") {
|
|
191
|
+
ctx.write(
|
|
192
|
+
ctx.db.updateTable("core_sellable_once").set({ state: "released", updated_at: ctx.now }).where("order_id", "=", move.id).where("state", "=", "held")
|
|
193
|
+
);
|
|
194
|
+
}
|
|
195
|
+
};
|
|
196
|
+
onRecordMove("order", orderOnce);
|
|
197
|
+
|
|
198
|
+
// ../core/src/orders/sellable.ts
|
|
199
|
+
var GRANTS_PER_ORDER_CEILING = 100;
|
|
200
|
+
var GRANTS_PER_LINE_DEFAULT = 10;
|
|
201
|
+
function lineLimit(sellable, recordMax) {
|
|
202
|
+
const own = recordMax === null ? null : Math.max(Math.floor(recordMax), 0);
|
|
203
|
+
if (!sellable.grants) return own;
|
|
204
|
+
return Math.min(own ?? GRANTS_PER_LINE_DEFAULT, GRANTS_PER_ORDER_CEILING);
|
|
205
|
+
}
|
|
206
|
+
function sellableOf(object) {
|
|
207
|
+
return object.sellable;
|
|
208
|
+
}
|
|
209
|
+
function sellableProblems(sellable, object) {
|
|
210
|
+
const problems = [];
|
|
211
|
+
const field = (name) => object.fields.find((f) => f.name === name);
|
|
212
|
+
const numeric = (name, what) => {
|
|
213
|
+
const f = field(name);
|
|
214
|
+
if (!f?.column) problems.push(`${what} "${name}" is not a single-valued field`);
|
|
215
|
+
else if (f.type !== "number") problems.push(`${what} "${name}" is not a number`);
|
|
216
|
+
};
|
|
217
|
+
const date = (name, what) => {
|
|
218
|
+
const f = field(name);
|
|
219
|
+
if (!f?.column || f.type !== "date" && f.type !== "datetime") {
|
|
220
|
+
problems.push(`${what} "${name}" is not a date field`);
|
|
221
|
+
}
|
|
222
|
+
};
|
|
223
|
+
numeric(sellable.price, "price");
|
|
224
|
+
if (sellable.maxPerOrder) numeric(sellable.maxPerOrder, "maxPerOrder");
|
|
225
|
+
if (sellable.saleWindow?.from) date(sellable.saleWindow.from, "saleWindow.from");
|
|
226
|
+
if (sellable.saleWindow?.until) date(sellable.saleWindow.until, "saleWindow.until");
|
|
227
|
+
if (sellable.deposit) {
|
|
228
|
+
numeric(sellable.deposit.amount, "deposit.amount");
|
|
229
|
+
date(sellable.deposit.balanceDue, "deposit.balanceDue");
|
|
230
|
+
}
|
|
231
|
+
if (sellable.recurring?.trialDays) numeric(sellable.recurring.trialDays, "recurring.trialDays");
|
|
232
|
+
if (!object.titleField) problems.push("a sellable object needs a title field");
|
|
233
|
+
return problems;
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
// ../core/src/orders/orders.ts
|
|
237
|
+
var ORDER_MAX_LINES = 50;
|
|
238
|
+
var ORDER_MAX_QUANTITY = 1e3;
|
|
239
|
+
var ORDER_ACCESS_DAYS_AFTER_CLOSE = 30;
|
|
240
|
+
var CLOSED = /* @__PURE__ */ new Set(["paid", "cancelled", "expired", "refunded"]);
|
|
241
|
+
var order = () => getObject("order") ?? orderObject;
|
|
242
|
+
function orderSnapshot(row) {
|
|
243
|
+
return {
|
|
244
|
+
personId: row.person_id,
|
|
245
|
+
email: row.email,
|
|
246
|
+
state: row.state,
|
|
247
|
+
currency: row.currency,
|
|
248
|
+
total: row.total,
|
|
249
|
+
paid: row.paid,
|
|
250
|
+
balance: row.total - row.paid,
|
|
251
|
+
refunded: row.refunded,
|
|
252
|
+
pay: row.pay,
|
|
253
|
+
deposit: row.deposit,
|
|
254
|
+
balanceDueAt: row.balance_due_at,
|
|
255
|
+
expiresAt: row.expires_at,
|
|
256
|
+
placedAs: row.placed_as,
|
|
257
|
+
paidAt: row.paid_at,
|
|
258
|
+
cancelledAt: row.cancelled_at,
|
|
259
|
+
refundedAt: row.refunded_at,
|
|
260
|
+
taxAmount: row.tax_amount,
|
|
261
|
+
taxRefunded: row.tax_refunded,
|
|
262
|
+
taxCountry: row.tax_country
|
|
263
|
+
};
|
|
264
|
+
}
|
|
265
|
+
async function loadOrderRow(db, id) {
|
|
266
|
+
const row = await db.selectFrom("core_order").selectAll().where("id", "=", id).executeTakeFirst();
|
|
267
|
+
if (!row) throw new NotFoundError("order", id);
|
|
268
|
+
return row;
|
|
269
|
+
}
|
|
270
|
+
function refuseLine(rule, line, message, extra) {
|
|
271
|
+
throw new ValidationError(message, { rule, line, ...extra });
|
|
272
|
+
}
|
|
273
|
+
var column = (field) => field ? viewColumnOf(field) : null;
|
|
274
|
+
function dueMoment(value) {
|
|
275
|
+
if (typeof value !== "string" || value.trim() === "") return null;
|
|
276
|
+
const text = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}T23:59:59.999Z` : value;
|
|
277
|
+
const at = new Date(text);
|
|
278
|
+
return Number.isNaN(at.getTime()) ? null : at.toISOString();
|
|
279
|
+
}
|
|
280
|
+
function windowMoment(value, end) {
|
|
281
|
+
if (typeof value !== "string" || value.trim() === "") return null;
|
|
282
|
+
const text = /^\d{4}-\d{2}-\d{2}$/.test(value) ? `${value}${end === "start" ? "T00:00:00.000Z" : "T23:59:59.999Z"}` : value;
|
|
283
|
+
const at = new Date(text);
|
|
284
|
+
return Number.isNaN(at.getTime()) ? null : at.toISOString();
|
|
285
|
+
}
|
|
286
|
+
async function readable(db, principal, object, id) {
|
|
287
|
+
let source;
|
|
288
|
+
try {
|
|
289
|
+
source = buyableSource({ principal }, object);
|
|
290
|
+
} catch {
|
|
291
|
+
return false;
|
|
292
|
+
}
|
|
293
|
+
const row = await db.selectFrom(source).select("id").where("id", "=", id).executeTakeFirst();
|
|
294
|
+
return Boolean(row);
|
|
295
|
+
}
|
|
296
|
+
async function priceLines(db, lines, currency, now = (/* @__PURE__ */ new Date()).toISOString(), buyer, options = {}) {
|
|
297
|
+
const reader = orgReader(db);
|
|
298
|
+
const seen = /* @__PURE__ */ new Set();
|
|
299
|
+
const priced2 = [];
|
|
300
|
+
let granting = 0;
|
|
301
|
+
for (const [index, line] of lines.entries()) {
|
|
302
|
+
const key = `${line.object}\0${line.id}`;
|
|
303
|
+
if (seen.has(key)) {
|
|
304
|
+
refuseLine("duplicate_line", index, "The same item is on the order twice: use a quantity");
|
|
305
|
+
}
|
|
306
|
+
seen.add(key);
|
|
307
|
+
const object = getObject(line.object);
|
|
308
|
+
const sellable = object ? sellableOf(object) : void 0;
|
|
309
|
+
if (!object || !sellable || sellableProblems(sellable, object).length) {
|
|
310
|
+
refuseLine("not_for_sale", index, "This cannot be bought");
|
|
311
|
+
}
|
|
312
|
+
if (Boolean(sellable.recurring) !== Boolean(options.plans)) {
|
|
313
|
+
refuseLine(
|
|
314
|
+
"not_for_sale",
|
|
315
|
+
index,
|
|
316
|
+
sellable.recurring ? "This is a plan: subscribe to it instead" : "This is not a plan"
|
|
317
|
+
);
|
|
318
|
+
}
|
|
319
|
+
const row = await db.selectFrom(visibleSource(reader, object)).selectAll().where("id", "=", line.id).executeTakeFirst();
|
|
320
|
+
if (!row) refuseLine("not_for_sale", index, "This cannot be bought");
|
|
321
|
+
if (buyer && buyer.kind !== "staff" && !await readable(db, buyer, object, line.id)) {
|
|
322
|
+
refuseLine("not_for_sale", index, "This cannot be bought");
|
|
323
|
+
}
|
|
324
|
+
const field = (name) => object.fields.find((f) => f.name === name);
|
|
325
|
+
const read = (name) => {
|
|
326
|
+
const col = column(field(name));
|
|
327
|
+
return col ? row[col] ?? null : null;
|
|
328
|
+
};
|
|
329
|
+
const pricedIn = sellable.currency ?? field(sellable.price)?.options?.currency;
|
|
330
|
+
if (pricedIn && pricedIn.toUpperCase() !== currency) {
|
|
331
|
+
refuseLine(
|
|
332
|
+
"currency",
|
|
333
|
+
index,
|
|
334
|
+
`This is priced in ${pricedIn}, and orders are in ${currency}`,
|
|
335
|
+
{
|
|
336
|
+
currency: pricedIn
|
|
337
|
+
}
|
|
338
|
+
);
|
|
339
|
+
}
|
|
340
|
+
const unitPrice = toMinorUnits(read(sellable.price), currency);
|
|
341
|
+
if (unitPrice === null) refuseLine("no_price", index, "This has no price yet");
|
|
342
|
+
if (sellable.saleWindow) {
|
|
343
|
+
const from = windowMoment(read(sellable.saleWindow.from ?? ""), "start");
|
|
344
|
+
const until = windowMoment(read(sellable.saleWindow.until ?? ""), "end");
|
|
345
|
+
if (from && now < from || until && now > until) {
|
|
346
|
+
refuseLine(
|
|
347
|
+
"sale_window",
|
|
348
|
+
index,
|
|
349
|
+
from && now < from ? "This is not on sale yet" : "This is no longer on sale",
|
|
350
|
+
{ from, until }
|
|
351
|
+
);
|
|
352
|
+
}
|
|
353
|
+
}
|
|
354
|
+
const own = sellable.maxPerOrder ? read(sellable.maxPerOrder) : null;
|
|
355
|
+
const max = lineLimit(sellable, typeof own === "number" && Number.isFinite(own) ? own : null);
|
|
356
|
+
if (max !== null && line.quantity > max) {
|
|
357
|
+
refuseLine("max_per_order", index, `At most ${max} of this on one order`, {
|
|
358
|
+
max,
|
|
359
|
+
asked: line.quantity
|
|
360
|
+
});
|
|
361
|
+
}
|
|
362
|
+
if (sellable.grants) {
|
|
363
|
+
if (granting + line.quantity > GRANTS_PER_ORDER_CEILING) {
|
|
364
|
+
refuseLine(
|
|
365
|
+
"max_per_order",
|
|
366
|
+
index,
|
|
367
|
+
`At most ${GRANTS_PER_ORDER_CEILING} tickets or other grants on one order`,
|
|
368
|
+
{
|
|
369
|
+
max: GRANTS_PER_ORDER_CEILING - granting,
|
|
370
|
+
asked: line.quantity,
|
|
371
|
+
ceiling: GRANTS_PER_ORDER_CEILING
|
|
372
|
+
}
|
|
373
|
+
);
|
|
374
|
+
}
|
|
375
|
+
granting += line.quantity;
|
|
376
|
+
}
|
|
377
|
+
let deposit = null;
|
|
378
|
+
if (sellable.deposit) {
|
|
379
|
+
const amount = toMinorUnits(read(sellable.deposit.amount), currency);
|
|
380
|
+
const balanceDueAt = dueMoment(read(sellable.deposit.balanceDue));
|
|
381
|
+
if (amount !== null && amount > 0 && balanceDueAt) deposit = { amount, balanceDueAt };
|
|
382
|
+
}
|
|
383
|
+
const title = object.titleField ? read(object.titleField) : null;
|
|
384
|
+
const trial = sellable.recurring?.trialDays ? read(sellable.recurring.trialDays) : null;
|
|
385
|
+
const onceFlag = sellable.onePerPerson ? read(sellable.onePerPerson) : null;
|
|
386
|
+
priced2.push({
|
|
387
|
+
...onceFlag === 1 || onceFlag === true ? { once: true } : {},
|
|
388
|
+
...sellable.recurring ? {
|
|
389
|
+
recurring: {
|
|
390
|
+
interval: sellable.recurring.interval,
|
|
391
|
+
trialDays: typeof trial === "number" && Number.isInteger(trial) && trial > 0 ? trial : null
|
|
392
|
+
}
|
|
393
|
+
} : {},
|
|
394
|
+
id: newId("orderLine"),
|
|
395
|
+
position: index,
|
|
396
|
+
object: object.name,
|
|
397
|
+
recordId: line.id,
|
|
398
|
+
title: title == null || title === "" ? object.label : String(title),
|
|
399
|
+
quantity: line.quantity,
|
|
400
|
+
unitPrice,
|
|
401
|
+
total: unitPrice * line.quantity,
|
|
402
|
+
deposit
|
|
403
|
+
});
|
|
404
|
+
}
|
|
405
|
+
return priced2;
|
|
406
|
+
}
|
|
407
|
+
async function createOrder(ctx, input) {
|
|
408
|
+
if (!input.lines.length) throw new ValidationError("An order needs at least one line");
|
|
409
|
+
if (input.lines.length > ORDER_MAX_LINES) {
|
|
410
|
+
throw new ValidationError(`An order has at most ${ORDER_MAX_LINES} lines`);
|
|
411
|
+
}
|
|
412
|
+
for (const [index, line] of input.lines.entries()) {
|
|
413
|
+
if (!Number.isInteger(line.quantity) || line.quantity < 1 || line.quantity > ORDER_MAX_QUANTITY) {
|
|
414
|
+
throw new ValidationError("A quantity is a whole number, at least 1", { line: index });
|
|
415
|
+
}
|
|
416
|
+
}
|
|
417
|
+
const currency = await loadOrderCurrency(ctx.db);
|
|
418
|
+
if (!currency) {
|
|
419
|
+
throw new ConfigError("No currency is set for orders yet, so nothing can be sold");
|
|
420
|
+
}
|
|
421
|
+
const lines = await priceLines(ctx.db, input.lines, currency, ctx.now, callerOf(ctx));
|
|
422
|
+
const total = lines.reduce((sum, line) => sum + line.total, 0);
|
|
423
|
+
if (total <= 0) {
|
|
424
|
+
throw new ValidationError("An order with nothing to pay cannot be started", { rule: "total" });
|
|
425
|
+
}
|
|
426
|
+
let deposit = null;
|
|
427
|
+
let balanceDueAt = null;
|
|
428
|
+
if (input.pay === "deposit") {
|
|
429
|
+
for (const line of lines) {
|
|
430
|
+
if (!line.deposit) {
|
|
431
|
+
refuseLine("deposit_not_offered", line.position, "This cannot be paid by deposit");
|
|
432
|
+
}
|
|
433
|
+
}
|
|
434
|
+
const offered = lines.map((line) => line.deposit);
|
|
435
|
+
deposit = lines.reduce((sum, line, i) => sum + (offered[i]?.amount ?? 0) * line.quantity, 0);
|
|
436
|
+
balanceDueAt = offered.map((d) => d.balanceDueAt).sort()[0];
|
|
437
|
+
if (deposit >= total) {
|
|
438
|
+
throw new ValidationError("The deposit is the whole price: pay in full", {
|
|
439
|
+
rule: "deposit_not_offered"
|
|
440
|
+
});
|
|
441
|
+
}
|
|
442
|
+
if (balanceDueAt <= ctx.now) {
|
|
443
|
+
throw new ValidationError("The balance was due before today: pay in full", {
|
|
444
|
+
rule: "deposit_not_offered"
|
|
445
|
+
});
|
|
446
|
+
}
|
|
447
|
+
}
|
|
448
|
+
const minutes = await loadOrderExpiryMinutes(ctx.db);
|
|
449
|
+
const id = newId("order");
|
|
450
|
+
const row = {
|
|
451
|
+
id,
|
|
452
|
+
person_id: input.personId,
|
|
453
|
+
email: input.email,
|
|
454
|
+
currency,
|
|
455
|
+
total,
|
|
456
|
+
paid: 0,
|
|
457
|
+
state: "pending",
|
|
458
|
+
pay: input.pay,
|
|
459
|
+
deposit,
|
|
460
|
+
balance_due_at: balanceDueAt,
|
|
461
|
+
expires_at: new Date(Date.parse(ctx.now) + minutes * 6e4).toISOString(),
|
|
462
|
+
placed_as: input.placedAs,
|
|
463
|
+
provider: null,
|
|
464
|
+
provider_ref: null,
|
|
465
|
+
access_hash: input.accessHash ?? null,
|
|
466
|
+
access_until: null,
|
|
467
|
+
email_link_hash: null,
|
|
468
|
+
refunded: 0,
|
|
469
|
+
tax_amount: 0,
|
|
470
|
+
tax_refunded: 0,
|
|
471
|
+
tax_country: null,
|
|
472
|
+
subscription_id: null,
|
|
473
|
+
period_start: null,
|
|
474
|
+
period_end: null,
|
|
475
|
+
invoice_ref: null,
|
|
476
|
+
period_flag: null,
|
|
477
|
+
paid_at: null,
|
|
478
|
+
cancelled_at: null,
|
|
479
|
+
refunded_at: null,
|
|
480
|
+
created_at: ctx.now,
|
|
481
|
+
updated_at: ctx.now,
|
|
482
|
+
version: 0
|
|
483
|
+
};
|
|
484
|
+
const outcome = await applyTransition(
|
|
485
|
+
ctx,
|
|
486
|
+
order(),
|
|
487
|
+
id,
|
|
488
|
+
null,
|
|
489
|
+
{ state: "pending" },
|
|
490
|
+
{ by: "host" }
|
|
491
|
+
);
|
|
492
|
+
await claimOrderPlaces(ctx, id, lines);
|
|
493
|
+
ctx.write(
|
|
494
|
+
ctx.db.insertInto("core_order").values(row),
|
|
495
|
+
...lines.map(
|
|
496
|
+
(line) => ctx.db.insertInto("core_order_line").values({
|
|
497
|
+
id: line.id,
|
|
498
|
+
order_id: id,
|
|
499
|
+
position: line.position,
|
|
500
|
+
object_type: line.object,
|
|
501
|
+
record_id: line.recordId,
|
|
502
|
+
title: line.title,
|
|
503
|
+
quantity: line.quantity,
|
|
504
|
+
unit_price: line.unitPrice,
|
|
505
|
+
line_total: line.total,
|
|
506
|
+
created_at: ctx.now
|
|
507
|
+
})
|
|
508
|
+
),
|
|
509
|
+
...outcome.history
|
|
510
|
+
);
|
|
511
|
+
await holdOncePerPerson(
|
|
512
|
+
ctx,
|
|
513
|
+
id,
|
|
514
|
+
lines.filter((line) => line.once).map((line) => ({
|
|
515
|
+
object: line.object,
|
|
516
|
+
recordId: line.recordId,
|
|
517
|
+
quantity: line.quantity,
|
|
518
|
+
position: line.position
|
|
519
|
+
})),
|
|
520
|
+
{ personId: input.personId, placedAs: input.placedAs }
|
|
521
|
+
);
|
|
522
|
+
recordHostChange(ctx, { object: "order", id, action: "create", after: orderSnapshot(row) });
|
|
523
|
+
postOrderMove(ctx, row, null);
|
|
524
|
+
return { row, lines };
|
|
525
|
+
}
|
|
526
|
+
async function changeOrder(ctx, row, to, change, by) {
|
|
527
|
+
const before = orderSnapshot(row);
|
|
528
|
+
const next = {
|
|
529
|
+
...row,
|
|
530
|
+
...change,
|
|
531
|
+
state: to,
|
|
532
|
+
updated_at: ctx.now,
|
|
533
|
+
version: row.version + 1,
|
|
534
|
+
// A guest's link outlives the order's closing by a while, then stops.
|
|
535
|
+
access_until: CLOSED.has(to) ? new Date(Date.parse(ctx.now) + ORDER_ACCESS_DAYS_AFTER_CLOSE * 864e5).toISOString() : null
|
|
536
|
+
};
|
|
537
|
+
const outcome = await applyTransition(ctx, order(), row.id, before, orderSnapshot(next), { by });
|
|
538
|
+
ctx.write(
|
|
539
|
+
ctx.db.updateTable("core_order").set({
|
|
540
|
+
...change,
|
|
541
|
+
state: to,
|
|
542
|
+
updated_at: next.updated_at,
|
|
543
|
+
version: next.version,
|
|
544
|
+
access_until: next.access_until
|
|
545
|
+
}).where("id", "=", row.id),
|
|
546
|
+
...outcome.history
|
|
547
|
+
);
|
|
548
|
+
recordHostChange(ctx, {
|
|
549
|
+
object: "order",
|
|
550
|
+
id: row.id,
|
|
551
|
+
action: "update",
|
|
552
|
+
before,
|
|
553
|
+
after: orderSnapshot(next)
|
|
554
|
+
});
|
|
555
|
+
if (to !== row.state) postOrderMove(ctx, next, row.state);
|
|
556
|
+
return next;
|
|
557
|
+
}
|
|
558
|
+
var MOVE_WORDS = {
|
|
559
|
+
pending: "started",
|
|
560
|
+
part_paid: "part paid",
|
|
561
|
+
paid: "paid",
|
|
562
|
+
cancelled: "cancelled",
|
|
563
|
+
expired: "expired",
|
|
564
|
+
refunded: "refunded"
|
|
565
|
+
};
|
|
566
|
+
function formatMoney(amount, currency) {
|
|
567
|
+
const digits = currencyDecimals(currency);
|
|
568
|
+
return `${(amount / 10 ** digits).toFixed(digits)} ${currency}`;
|
|
569
|
+
}
|
|
570
|
+
function postOrderMove(ctx, row, from) {
|
|
571
|
+
if (!row.person_id) return;
|
|
572
|
+
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)}`;
|
|
573
|
+
ctx.postActivity({
|
|
574
|
+
subject: `Order ${MOVE_WORDS[row.state]}: ${money}`,
|
|
575
|
+
payload: {
|
|
576
|
+
kind: "order.moved",
|
|
577
|
+
orderId: row.id,
|
|
578
|
+
from,
|
|
579
|
+
to: row.state,
|
|
580
|
+
total: row.total,
|
|
581
|
+
paid: row.paid,
|
|
582
|
+
refunded: row.refunded,
|
|
583
|
+
currency: row.currency
|
|
584
|
+
},
|
|
585
|
+
links: [{ object: "person", id: row.person_id }]
|
|
586
|
+
});
|
|
587
|
+
}
|
|
588
|
+
function chargeFor(row, minPart, amount) {
|
|
589
|
+
const refuse = (message, rule, extra) => {
|
|
590
|
+
throw new ValidationError(message, { rule, order: row.id, ...extra });
|
|
591
|
+
};
|
|
592
|
+
if (row.state === "pending") {
|
|
593
|
+
const due = row.pay === "deposit" ? row.deposit : row.total;
|
|
594
|
+
if (amount !== void 0 && amount !== due) {
|
|
595
|
+
refuse("The first payment on an order is not the buyer's to choose", "charge_amount", {
|
|
596
|
+
due
|
|
597
|
+
});
|
|
598
|
+
}
|
|
599
|
+
return {
|
|
600
|
+
amount: due,
|
|
601
|
+
currency: row.currency,
|
|
602
|
+
kind: row.pay === "deposit" ? "deposit" : "full"
|
|
603
|
+
};
|
|
604
|
+
}
|
|
605
|
+
if (row.state === "part_paid") {
|
|
606
|
+
const balance = row.total - row.paid;
|
|
607
|
+
const least = Math.min(minPart, balance);
|
|
608
|
+
const wanted = amount ?? balance;
|
|
609
|
+
if (!Number.isInteger(wanted) || wanted < least || wanted > balance) {
|
|
610
|
+
refuse(`A payment towards this order is between ${least} and ${balance}`, "charge_amount", {
|
|
611
|
+
least,
|
|
612
|
+
balance
|
|
613
|
+
});
|
|
614
|
+
}
|
|
615
|
+
return {
|
|
616
|
+
amount: wanted,
|
|
617
|
+
currency: row.currency,
|
|
618
|
+
kind: wanted === balance ? "balance" : "part"
|
|
619
|
+
};
|
|
620
|
+
}
|
|
621
|
+
return refuse("Nothing can be paid on this order", "charge_state", { state: row.state });
|
|
622
|
+
}
|
|
623
|
+
var OVERDUE_LIMIT = 200;
|
|
624
|
+
function overdueOrders(db, now, limit = OVERDUE_LIMIT) {
|
|
625
|
+
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();
|
|
626
|
+
}
|
|
627
|
+
function requireState(row, states, what) {
|
|
628
|
+
if (!states.includes(row.state)) {
|
|
629
|
+
throw new ConflictError(`An order that is ${row.state} cannot be ${what}`, {
|
|
630
|
+
order: row.id,
|
|
631
|
+
state: row.state
|
|
632
|
+
});
|
|
633
|
+
}
|
|
634
|
+
}
|
|
635
|
+
|
|
636
|
+
// ../core/src/orders/subscription-setup.ts
|
|
637
|
+
async function subscriptionSetup(db) {
|
|
638
|
+
let target = null;
|
|
639
|
+
try {
|
|
640
|
+
target = await paymentsTarget(db);
|
|
641
|
+
} catch (error) {
|
|
642
|
+
if (!(error instanceof ConfigError)) throw error;
|
|
643
|
+
}
|
|
644
|
+
return {
|
|
645
|
+
returnOrigins: [...await loadReturnOrigins(db)],
|
|
646
|
+
currency: await loadOrderCurrency(db),
|
|
647
|
+
target
|
|
648
|
+
};
|
|
649
|
+
}
|
|
650
|
+
function setupComplete(setup) {
|
|
651
|
+
return setup.returnOrigins.length > 0 && setup.currency !== null && setup.target !== null;
|
|
652
|
+
}
|
|
653
|
+
|
|
654
|
+
// ../core/src/customers/plan-on-sale.ts
|
|
655
|
+
var PUBLIC = Object.freeze({ kind: "public" });
|
|
656
|
+
var PLANS_LOOKED_AT = 50;
|
|
657
|
+
var PLAN_ON_SALE_MEMO_MS = 6e4;
|
|
658
|
+
var memo = null;
|
|
659
|
+
function forgetPlanOnSale() {
|
|
660
|
+
memo = null;
|
|
661
|
+
}
|
|
662
|
+
async function findPlanOnSale(db, now = (/* @__PURE__ */ new Date()).toISOString(), options = {}) {
|
|
663
|
+
const at = Date.now();
|
|
664
|
+
if (options.memo && memo && at - memo.at < PLAN_ON_SALE_MEMO_MS) return memo.value;
|
|
665
|
+
let value;
|
|
666
|
+
try {
|
|
667
|
+
value = await compute(db, now);
|
|
668
|
+
} catch (error) {
|
|
669
|
+
value = { state: "unknown", reason: error instanceof Error ? error.message : String(error) };
|
|
670
|
+
}
|
|
671
|
+
memo = { at, value };
|
|
672
|
+
return value;
|
|
673
|
+
}
|
|
674
|
+
async function hasPlanOnSale(db, now = (/* @__PURE__ */ new Date()).toISOString()) {
|
|
675
|
+
return (await findPlanOnSale(db, now)).state === "on_sale";
|
|
676
|
+
}
|
|
677
|
+
async function compute(db, now) {
|
|
678
|
+
const setup = await subscriptionSetup(db);
|
|
679
|
+
if (!setupComplete(setup)) return { state: "none" };
|
|
680
|
+
await refreshSchemaRegistry(db);
|
|
681
|
+
let unanswered = false;
|
|
682
|
+
for (const object of listObjects()) {
|
|
683
|
+
const sellable = sellableOf(object);
|
|
684
|
+
if (!sellable?.recurring || sellableProblems(sellable, object).length) continue;
|
|
685
|
+
const scope = scopeOf(PUBLIC, object, false);
|
|
686
|
+
if (scope.kind !== "public") continue;
|
|
687
|
+
let source;
|
|
688
|
+
try {
|
|
689
|
+
source = buyableSource({ principal: PUBLIC }, object);
|
|
690
|
+
} catch {
|
|
691
|
+
continue;
|
|
692
|
+
}
|
|
693
|
+
const readable2 = new Set(scope.columns);
|
|
694
|
+
const columnOf = (name) => {
|
|
695
|
+
const field = name ? object.fields.find((f) => f.name === name) : void 0;
|
|
696
|
+
const column2 = field ? viewColumnOf(field) : null;
|
|
697
|
+
return column2 && readable2.has(column2) ? column2 : null;
|
|
698
|
+
};
|
|
699
|
+
let query = db.selectFrom(source).select("id");
|
|
700
|
+
const price = columnOf(sellable.price);
|
|
701
|
+
if (price) query = query.where(sql.ref(price), ">", 0);
|
|
702
|
+
const day = now.slice(0, 10);
|
|
703
|
+
const from = columnOf(sellable.saleWindow?.from);
|
|
704
|
+
if (from) {
|
|
705
|
+
query = query.where(
|
|
706
|
+
(eb) => eb.or([eb(sql.ref(from), "is", null), eb(sql.ref(from), "<=", now)])
|
|
707
|
+
);
|
|
708
|
+
}
|
|
709
|
+
const until = columnOf(sellable.saleWindow?.until);
|
|
710
|
+
if (until) {
|
|
711
|
+
query = query.where(
|
|
712
|
+
(eb) => eb.or([eb(sql.ref(until), "is", null), eb(sql.ref(until), ">=", day)])
|
|
713
|
+
);
|
|
714
|
+
}
|
|
715
|
+
const rows = await query.orderBy("id").limit(PLANS_LOOKED_AT + 1).execute();
|
|
716
|
+
for (const { id } of rows.slice(0, PLANS_LOOKED_AT)) {
|
|
717
|
+
const found = await priced(db, object, id, setup.currency, now);
|
|
718
|
+
if (found) return { state: "on_sale", plan: found };
|
|
719
|
+
}
|
|
720
|
+
if (rows.length > PLANS_LOOKED_AT) unanswered = true;
|
|
721
|
+
}
|
|
722
|
+
return unanswered ? { state: "unknown", reason: `more than ${PLANS_LOOKED_AT} plans to look at` } : { state: "none" };
|
|
723
|
+
}
|
|
724
|
+
async function priced(db, object, id, currency, now) {
|
|
725
|
+
try {
|
|
726
|
+
const [line] = await priceLines(
|
|
727
|
+
db,
|
|
728
|
+
[{ object: object.name, id, quantity: 1 }],
|
|
729
|
+
currency,
|
|
730
|
+
now,
|
|
731
|
+
PUBLIC,
|
|
732
|
+
{ plans: true }
|
|
733
|
+
);
|
|
734
|
+
return line?.recurring && line.unitPrice > 0 ? { object: object.name, id, title: line.title } : null;
|
|
735
|
+
} catch (error) {
|
|
736
|
+
if (error instanceof ValidationError) return null;
|
|
737
|
+
throw error;
|
|
738
|
+
}
|
|
739
|
+
}
|
|
740
|
+
|
|
741
|
+
export {
|
|
742
|
+
ORDER_MAX_LINES,
|
|
743
|
+
ORDER_MAX_QUANTITY,
|
|
744
|
+
orderSnapshot,
|
|
745
|
+
loadOrderRow,
|
|
746
|
+
priceLines,
|
|
747
|
+
createOrder,
|
|
748
|
+
changeOrder,
|
|
749
|
+
formatMoney,
|
|
750
|
+
chargeFor,
|
|
751
|
+
overdueOrders,
|
|
752
|
+
requireState,
|
|
753
|
+
subscriptionSetup,
|
|
754
|
+
PLANS_LOOKED_AT,
|
|
755
|
+
PLAN_ON_SALE_MEMO_MS,
|
|
756
|
+
forgetPlanOnSale,
|
|
757
|
+
findPlanOnSale,
|
|
758
|
+
hasPlanOnSale
|
|
759
|
+
};
|