@volter/twin-stripe 0.1.2 → 2.0.1
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/README.md +96 -27
- package/client/dashboard-api.ts +286 -0
- package/client/stripe-mirror.css +272 -159
- package/client/stripe-mirror.tsx +1384 -541
- package/dist/client/dashboard-api.d.ts +107 -0
- package/dist/client/dashboard-api.js +238 -0
- package/dist/client/dashboard-api.ts +286 -0
- package/dist/client/stripe-mirror.bundle.js +236 -0
- package/dist/client/stripe-mirror.css +275 -0
- package/dist/client/stripe-mirror.d.ts +134 -0
- package/dist/client/stripe-mirror.js +823 -0
- package/dist/client/stripe-mirror.tsx +1534 -0
- package/dist/src/cli.d.ts +2 -0
- package/dist/src/cli.js +39 -0
- package/dist/src/generated/events.gen.json +1 -0
- package/dist/src/generated/surface.gen.json +1 -0
- package/dist/src/generated/ui.gen.json +1 -0
- package/dist/src/index.d.ts +14 -0
- package/dist/src/index.js +75 -0
- package/dist/src/manifest.d.ts +2 -0
- package/dist/src/manifest.js +1070 -0
- package/dist/src/screens/checkout.d.ts +31 -0
- package/dist/src/screens/checkout.js +255 -0
- package/dist/src/screens/connect-oauth.d.ts +27 -0
- package/dist/src/screens/connect-oauth.js +414 -0
- package/dist/src/screens/connect-settings.d.ts +22 -0
- package/dist/src/screens/connect-settings.js +103 -0
- package/dist/src/screens/consent-skin.d.ts +4 -0
- package/dist/src/screens/consent-skin.js +18 -0
- package/dist/src/screens/financial-connections.d.ts +5 -0
- package/dist/src/screens/financial-connections.js +90 -0
- package/dist/src/screens/identity.d.ts +5 -0
- package/dist/src/screens/identity.js +86 -0
- package/dist/src/screens/industries.d.ts +1 -0
- package/dist/src/screens/industries.js +267 -0
- package/dist/src/screens/onboarding.d.ts +13 -0
- package/dist/src/screens/onboarding.js +225 -0
- package/dist/src/screens/portal.d.ts +5 -0
- package/dist/src/screens/portal.js +216 -0
- package/dist/src/screens/public-details.d.ts +5 -0
- package/dist/src/screens/public-details.js +90 -0
- package/dist/src/semantics/after-payment.d.ts +22 -0
- package/dist/src/semantics/after-payment.js +99 -0
- package/dist/src/semantics/apps-secrets.d.ts +2 -0
- package/dist/src/semantics/apps-secrets.js +54 -0
- package/dist/src/semantics/balance.d.ts +11 -0
- package/dist/src/semantics/balance.js +195 -0
- package/dist/src/semantics/billing.d.ts +2 -0
- package/dist/src/semantics/billing.js +220 -0
- package/dist/src/semantics/charges.d.ts +28 -0
- package/dist/src/semantics/charges.js +209 -0
- package/dist/src/semantics/checkout.d.ts +15 -0
- package/dist/src/semantics/checkout.js +316 -0
- package/dist/src/semantics/connect.d.ts +5 -0
- package/dist/src/semantics/connect.js +493 -0
- package/dist/src/semantics/coupons.d.ts +6 -0
- package/dist/src/semantics/coupons.js +92 -0
- package/dist/src/semantics/credit-notes.d.ts +2 -0
- package/dist/src/semantics/credit-notes.js +172 -0
- package/dist/src/semantics/customers.d.ts +6 -0
- package/dist/src/semantics/customers.js +429 -0
- package/dist/src/semantics/disputes.d.ts +2 -0
- package/dist/src/semantics/disputes.js +51 -0
- package/dist/src/semantics/entitlements.d.ts +2 -0
- package/dist/src/semantics/entitlements.js +95 -0
- package/dist/src/semantics/ephemeral-keys.d.ts +2 -0
- package/dist/src/semantics/ephemeral-keys.js +34 -0
- package/dist/src/semantics/files.d.ts +2 -0
- package/dist/src/semantics/files.js +125 -0
- package/dist/src/semantics/invoices.d.ts +18 -0
- package/dist/src/semantics/invoices.js +545 -0
- package/dist/src/semantics/issuing.d.ts +13 -0
- package/dist/src/semantics/issuing.js +575 -0
- package/dist/src/semantics/ledger.d.ts +59 -0
- package/dist/src/semantics/ledger.js +200 -0
- package/dist/src/semantics/payment-intents.d.ts +18 -0
- package/dist/src/semantics/payment-intents.js +404 -0
- package/dist/src/semantics/payment-links.d.ts +2 -0
- package/dist/src/semantics/payment-links.js +133 -0
- package/dist/src/semantics/payment-methods.d.ts +20 -0
- package/dist/src/semantics/payment-methods.js +140 -0
- package/dist/src/semantics/plans.d.ts +5 -0
- package/dist/src/semantics/plans.js +121 -0
- package/dist/src/semantics/platform.d.ts +9 -0
- package/dist/src/semantics/platform.js +206 -0
- package/dist/src/semantics/products.d.ts +2 -0
- package/dist/src/semantics/products.js +140 -0
- package/dist/src/semantics/radar.d.ts +2 -0
- package/dist/src/semantics/radar.js +83 -0
- package/dist/src/semantics/refunds.d.ts +9 -0
- package/dist/src/semantics/refunds.js +195 -0
- package/dist/src/semantics/renewals.d.ts +47 -0
- package/dist/src/semantics/renewals.js +251 -0
- package/dist/src/semantics/setup-intents.d.ts +2 -0
- package/dist/src/semantics/setup-intents.js +84 -0
- package/dist/src/semantics/shared.d.ts +82 -0
- package/dist/src/semantics/shared.js +203 -0
- package/dist/src/semantics/subscription-schedules.d.ts +2 -0
- package/dist/src/semantics/subscription-schedules.js +119 -0
- package/dist/src/semantics/subscriptions.d.ts +11 -0
- package/dist/src/semantics/subscriptions.js +605 -0
- package/dist/src/semantics/tax.d.ts +2 -0
- package/dist/src/semantics/tax.js +197 -0
- package/dist/src/semantics/terminal.d.ts +5 -0
- package/dist/src/semantics/terminal.js +182 -0
- package/dist/src/semantics/test-cards.d.ts +4 -0
- package/dist/src/semantics/test-cards.js +7 -0
- package/dist/src/semantics/test-clocks.d.ts +6 -0
- package/dist/src/semantics/test-clocks.js +73 -0
- package/dist/src/semantics/tokens.d.ts +4 -0
- package/dist/src/semantics/tokens.js +44 -0
- package/dist/src/semantics/transfers.d.ts +2 -0
- package/dist/src/semantics/transfers.js +154 -0
- package/dist/src/semantics/treasury.d.ts +2 -0
- package/dist/src/semantics/treasury.js +377 -0
- package/dist/src/semantics/webhook-endpoints.d.ts +3 -0
- package/dist/src/semantics/webhook-endpoints.js +85 -0
- package/dist/src/stripe-budget.d.ts +55 -0
- package/dist/src/stripe-budget.js +155 -0
- package/dist/src/stripe-capabilities.d.ts +3 -0
- package/dist/src/stripe-capabilities.js +5695 -0
- package/dist/src/stripe-conformance.d.ts +43 -0
- package/dist/src/stripe-conformance.js +105 -0
- package/dist/src/stripe-connector.d.ts +161 -0
- package/dist/src/stripe-connector.js +414 -0
- package/dist/src/stripe-emit.d.ts +2 -0
- package/dist/src/stripe-emit.js +145 -0
- package/dist/src/stripe-events.d.ts +93 -0
- package/dist/src/stripe-events.js +392 -0
- package/dist/src/stripe-js.d.ts +4 -0
- package/dist/src/stripe-js.js +70 -0
- package/dist/src/stripe-mirror-ui.d.ts +15 -0
- package/dist/src/stripe-mirror-ui.js +87 -0
- package/dist/src/stripe-params.d.ts +3 -0
- package/dist/src/stripe-params.js +43 -0
- package/dist/src/stripe-perform-harness.d.ts +9 -0
- package/dist/src/stripe-perform-harness.js +26 -0
- package/dist/src/stripe-server.d.ts +33 -0
- package/dist/src/stripe-server.js +393 -0
- package/dist/src/stripe-shared.d.ts +109 -0
- package/dist/src/stripe-shared.js +276 -0
- package/dist/src/stripe-twin.d.ts +155 -0
- package/dist/src/stripe-twin.js +1232 -0
- package/dist/src/stripe-ui-conformance.d.ts +5 -0
- package/dist/src/stripe-ui-conformance.js +79 -0
- package/dist/src/stripe-ui-structure.d.ts +3 -0
- package/dist/src/stripe-ui-structure.js +168 -0
- package/dist/src/stripe-version.d.ts +12 -0
- package/dist/src/stripe-version.js +287 -0
- package/dist/test-fixtures/stripe-known-deviations.json +110 -0
- package/dist/test-fixtures/stripe-openapi-operations.SOURCE.md +14 -0
- package/dist/test-fixtures/stripe-openapi-operations.json +4717 -0
- package/dist/test-fixtures/stripe-schemas.SOURCE.md +35 -0
- package/dist/test-fixtures/stripe-schemas.json +3813 -0
- package/package.json +18 -10
- package/src/cli.ts +7 -7
- package/src/generated/events.gen.json +1 -0
- package/src/generated/surface.gen.json +1 -0
- package/src/generated/ui.gen.json +1 -0
- package/src/index.ts +34 -10
- package/src/manifest.ts +1102 -0
- package/src/screens/checkout.tsx +267 -0
- package/src/screens/connect-oauth.tsx +400 -0
- package/src/screens/connect-settings.tsx +121 -0
- package/src/screens/consent-skin.ts +20 -0
- package/src/screens/financial-connections.tsx +101 -0
- package/src/screens/identity.tsx +96 -0
- package/src/screens/industries.ts +267 -0
- package/src/screens/onboarding.tsx +243 -0
- package/src/screens/portal.tsx +220 -0
- package/src/screens/public-details.tsx +105 -0
- package/src/semantics/after-payment.ts +118 -0
- package/src/semantics/apps-secrets.ts +58 -0
- package/src/semantics/balance.ts +209 -0
- package/src/semantics/billing.ts +216 -0
- package/src/semantics/charges.ts +220 -0
- package/src/semantics/checkout.ts +310 -0
- package/src/semantics/connect.ts +487 -0
- package/src/semantics/coupons.ts +97 -0
- package/src/semantics/credit-notes.ts +168 -0
- package/src/semantics/customers.ts +432 -0
- package/src/semantics/disputes.ts +62 -0
- package/src/semantics/entitlements.ts +94 -0
- package/src/semantics/ephemeral-keys.ts +34 -0
- package/src/semantics/files.ts +143 -0
- package/src/semantics/invoices.ts +545 -0
- package/src/semantics/issuing.ts +590 -0
- package/src/semantics/ledger.ts +253 -0
- package/src/semantics/payment-intents.ts +420 -0
- package/src/semantics/payment-links.ts +148 -0
- package/src/semantics/payment-methods.ts +145 -0
- package/src/semantics/plans.ts +131 -0
- package/src/semantics/platform.ts +220 -0
- package/src/semantics/products.ts +154 -0
- package/src/semantics/radar.ts +85 -0
- package/src/semantics/refunds.ts +218 -0
- package/src/semantics/renewals.ts +274 -0
- package/src/semantics/setup-intents.ts +87 -0
- package/src/semantics/shared.ts +226 -0
- package/src/semantics/subscription-schedules.ts +129 -0
- package/src/semantics/subscriptions.ts +610 -0
- package/src/semantics/tax.ts +220 -0
- package/src/semantics/terminal.ts +195 -0
- package/src/semantics/test-cards.ts +7 -0
- package/src/semantics/test-clocks.ts +77 -0
- package/src/semantics/tokens.ts +52 -0
- package/src/semantics/transfers.ts +174 -0
- package/src/semantics/treasury.ts +383 -0
- package/src/semantics/webhook-endpoints.ts +87 -0
- package/src/stripe-budget.ts +4 -4
- package/src/stripe-capabilities.ts +2258 -380
- package/src/stripe-conformance.ts +19 -7
- package/src/stripe-connector.ts +68 -40
- package/src/stripe-emit.ts +15 -8
- package/src/stripe-events.ts +102 -40
- package/src/stripe-js.ts +70 -0
- package/src/stripe-mirror-ui.ts +28 -298
- package/src/stripe-params.ts +44 -0
- package/src/stripe-perform-harness.ts +29 -0
- package/src/stripe-server.ts +318 -38
- package/src/stripe-shared.ts +297 -0
- package/src/stripe-twin.ts +434 -5325
- package/src/stripe-ui-conformance.ts +70 -107
- package/src/stripe-ui-structure.ts +124 -348
- package/src/stripe-version.ts +281 -0
- package/test-fixtures/stripe-known-deviations.json +8 -8
- package/test-fixtures/stripe-openapi-operations.json +1188 -2855
- package/test-fixtures/stripe-schemas.json +85 -12
- package/src/stripe-form.ts +0 -35
|
@@ -0,0 +1,99 @@
|
|
|
1
|
+
import { disputeEvidence } from "../stripe-twin.js";
|
|
2
|
+
import { actingAccount, settleApplicationFee, settleDispute, settleTransfer } from "./ledger.js";
|
|
3
|
+
import { BYPASS_PENDING_CARDS } from "./test-cards.js";
|
|
4
|
+
import { created } from "./shared.js";
|
|
5
|
+
const DAY = 86_400;
|
|
6
|
+
/** The test cards whose success Stripe follows with its own act, by number and by their documented test names. */
|
|
7
|
+
export const AFTER_SUCCESS_CARDS = {
|
|
8
|
+
pm_card_createDispute: { brand: 'visa', number: '4000000000000259', outcome: 'dispute' },
|
|
9
|
+
pm_card_createDisputeProductNotReceived: { brand: 'visa', number: '4000000000002685', outcome: 'dispute_not_received' },
|
|
10
|
+
pm_card_createDisputeInquiry: { brand: 'visa', number: '4000000000001976', outcome: 'inquiry' },
|
|
11
|
+
pm_card_riskLevelElevated: { brand: 'visa', number: '4000000000009235', outcome: 'review' },
|
|
12
|
+
// its funds go straight to the available balance (ledger.ts reads it; no act follows here)
|
|
13
|
+
...Object.fromEntries(Object.entries(BYPASS_PENDING_CARDS).map(([name, c]) => [name, { ...c, outcome: 'available' }])),
|
|
14
|
+
};
|
|
15
|
+
const BY_NUMBER = Object.fromEntries(Object.values(AFTER_SUCCESS_CARDS).map((c) => [c.number, c.outcome]));
|
|
16
|
+
/** What Stripe does after a card succeeds: from a raw number, a test name (pm_card_* or tok_*), or a stored
|
|
17
|
+
* PaymentMethod that recorded it when it was made. */
|
|
18
|
+
export function afterSuccessOf(ctx, ref) {
|
|
19
|
+
// a card given as a token (card[token], payment_method_data[card][token]) is the card the token names
|
|
20
|
+
if (ref && typeof ref === 'object' && typeof ref.token === 'string')
|
|
21
|
+
return afterSuccessOf(ctx, ref.token);
|
|
22
|
+
if (ref && typeof ref === 'object')
|
|
23
|
+
return BY_NUMBER[String(ref.number ?? '').replace(/\D/g, '')];
|
|
24
|
+
if (typeof ref !== 'string' || !ref)
|
|
25
|
+
return undefined;
|
|
26
|
+
const stored = ctx.row('payment_method', ref);
|
|
27
|
+
if (stored)
|
|
28
|
+
return stored._afterSuccess ?? undefined;
|
|
29
|
+
return AFTER_SUCCESS_CARDS[ref.replace(/^tok_/, 'pm_card_')]?.outcome ?? BY_NUMBER[ref.replace(/\D/g, '')];
|
|
30
|
+
}
|
|
31
|
+
/** Stripe's acts on a charge that just succeeded: a dispute or a review its card brings, and the platform's fee. */
|
|
32
|
+
export async function afterCharge(ctx, chargeId, charge, ref) {
|
|
33
|
+
const outcome = afterSuccessOf(ctx, ref);
|
|
34
|
+
const pi = charge.payment_intent ? { payment_intent: charge.payment_intent } : { payment_intent: null };
|
|
35
|
+
const now = Number(ctx.now());
|
|
36
|
+
if (outcome === 'dispute' || outcome === 'dispute_not_received' || outcome === 'inquiry') {
|
|
37
|
+
const dispute = await created(ctx, 'dispute', { charge: chargeId, ...pi, amount: charge.amount, currency: charge.currency }, {
|
|
38
|
+
reason: outcome === 'dispute_not_received' ? 'product_not_received' : 'fraudulent', status: outcome === 'inquiry' ? 'warning_needs_response' : 'needs_response', is_charge_refundable: false,
|
|
39
|
+
evidence: disputeEvidence(), evidence_details: { due_by: now + 7 * DAY, has_evidence: false, past_due: false, submission_count: 0, enhanced_eligibility: {} },
|
|
40
|
+
balance_transactions: [], livemode: false, metadata: {}, enhanced_eligibility_types: [],
|
|
41
|
+
});
|
|
42
|
+
// an inquiry moves no money; a dispute takes the amount and its fee until it is decided
|
|
43
|
+
if (outcome !== 'inquiry') {
|
|
44
|
+
const bt = await settleDispute(ctx, String(dispute.id), charge.amount, charge.currency);
|
|
45
|
+
await ctx.write('dispute', String(dispute.id), { balance_transactions: [ctx.get('balance_transaction', bt) ?? bt] }, 'dispute.funds_withdrawn');
|
|
46
|
+
}
|
|
47
|
+
await ctx.write('charge', chargeId, { disputed: true }, 'charge.dispute.created');
|
|
48
|
+
}
|
|
49
|
+
if (outcome === 'review')
|
|
50
|
+
await openReview(ctx, chargeId, pi);
|
|
51
|
+
const feeAmount = Math.trunc(Number(charge.application_fee_amount) || 0);
|
|
52
|
+
const destination = typeof charge.destination === 'string' && charge.destination ? charge.destination : undefined;
|
|
53
|
+
const direct = actingAccount(ctx);
|
|
54
|
+
const account = destination ?? direct;
|
|
55
|
+
// a destination charge transfers what it collected, less the platform's fee, available when the charge's funds are
|
|
56
|
+
if (destination) {
|
|
57
|
+
const amount = charge.amount - feeAmount;
|
|
58
|
+
const chargeBt = ctx.get('charge', chargeId)?.balance_transaction;
|
|
59
|
+
const availableOn = Number(ctx.get('balance_transaction', String(chargeBt))?.available_on ?? ctx.now());
|
|
60
|
+
const tr = await created(ctx, 'transfer', { amount, currency: charge.currency, destination }, {
|
|
61
|
+
amount_reversed: 0, balance_transaction: null, livemode: false, metadata: {}, reversed: false, source_type: 'card', source_transaction: chargeId,
|
|
62
|
+
reversals: { object: 'list', data: [], has_more: false, total_count: 0, url: '' },
|
|
63
|
+
});
|
|
64
|
+
const bt = await settleTransfer(ctx, String(tr.id), amount, charge.currency, destination, availableOn);
|
|
65
|
+
await ctx.write('transfer', String(tr.id), { balance_transaction: bt, destination_payment: `py_${String(tr.id).replace(/^tr_/, '')}`, reversals: { object: 'list', data: [], has_more: false, total_count: 0, url: `/v1/transfers/${String(tr.id)}/reversals` } }, 'transfer.created');
|
|
66
|
+
await ctx.write('charge', chargeId, { transfer: tr.id }, 'charge.updated');
|
|
67
|
+
}
|
|
68
|
+
if (feeAmount > 0 && account) {
|
|
69
|
+
const fee = await created(ctx, 'application_fee', { account, amount: feeAmount, charge: chargeId, currency: charge.currency }, {
|
|
70
|
+
amount_refunded: 0, application: 'ca_twin', balance_transaction: null, originating_transaction: null, refunded: false, livemode: false,
|
|
71
|
+
});
|
|
72
|
+
// a direct charge's fee moves from the connected account to the platform (a destination charge kept it back)
|
|
73
|
+
const bt = !destination && direct ? await settleApplicationFee(ctx, String(fee.id), feeAmount, charge.currency, direct) : null;
|
|
74
|
+
await ctx.write('application_fee', String(fee.id), { balance_transaction: bt, refunds: { object: 'list', data: [], has_more: false, total_count: 0, url: `/v1/application_fees/${String(fee.id)}/refunds` } }, 'application_fee.created');
|
|
75
|
+
await ctx.write('charge', chargeId, { application_fee: fee.id, application_fee_amount: feeAmount }, 'charge.updated');
|
|
76
|
+
}
|
|
77
|
+
}
|
|
78
|
+
/** Radar places an elevated-risk card's charge in review (docs.stripe.com/radar/reviews). */
|
|
79
|
+
async function openReview(ctx, chargeId, pi) {
|
|
80
|
+
const review = await created(ctx, 'review', { charge: chargeId, ...pi }, {
|
|
81
|
+
open: true, opened_reason: 'rule', reason: 'rule', closed_reason: null, billing_zip: null, ip_address: null, ip_address_location: null, session: null, livemode: false,
|
|
82
|
+
});
|
|
83
|
+
const existing = ctx.get('charge', chargeId)?.outcome ?? {};
|
|
84
|
+
await ctx.write('charge', chargeId, {
|
|
85
|
+
review: review.id,
|
|
86
|
+
outcome: { ...existing, type: 'manual_review', risk_level: 'elevated', risk_score: 67, seller_message: 'Stripe evaluated this payment as having elevated risk, and placed it in review.' },
|
|
87
|
+
}, 'review.opened');
|
|
88
|
+
}
|
|
89
|
+
/** The mandate a verified bank account carries for a payment (single use) or a setup (multi use). */
|
|
90
|
+
export async function mintMandate(ctx, paymentMethod, use, amount, currency) {
|
|
91
|
+
const now = Number(ctx.now());
|
|
92
|
+
const mandate = await created(ctx, 'mandate', { payment_method: typeof paymentMethod === 'string' ? paymentMethod : null }, {
|
|
93
|
+
status: 'active', type: use, livemode: false,
|
|
94
|
+
customer_acceptance: { type: 'online', accepted_at: now, online: { ip_address: '127.0.0.1', user_agent: 'twin' } },
|
|
95
|
+
payment_method_details: { type: 'us_bank_account', us_bank_account: { collection_method: 'paper' } },
|
|
96
|
+
...(use === 'single_use' ? { single_use: { amount: amount ?? 0, currency: currency ?? 'usd' } } : { multi_use: {} }),
|
|
97
|
+
}, { timeField: '_created' });
|
|
98
|
+
return String(mandate.id);
|
|
99
|
+
}
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import { created, fail, list, newest, kept } from "./shared.js";
|
|
2
|
+
const SECRET = 'apps.secret';
|
|
3
|
+
function scopeKeyOf(ctx) {
|
|
4
|
+
const scope = ctx.params.scope && typeof ctx.params.scope === 'object' ? ctx.params.scope : undefined;
|
|
5
|
+
const scopeType = scope && typeof scope.type === 'string' ? scope.type : 'account';
|
|
6
|
+
return scopeType === 'user' ? `user:${String(scope.user)}` : 'account';
|
|
7
|
+
}
|
|
8
|
+
const named = (ctx, name) => ctx.rows(SECRET).find((s) => s.name === name && kept(ctx, SECRET, s, '_scope_key') === scopeKeyOf(ctx));
|
|
9
|
+
const set = async (ctx) => {
|
|
10
|
+
const params = ctx.params;
|
|
11
|
+
const name = typeof params.name === 'string' ? params.name : '';
|
|
12
|
+
if (!name)
|
|
13
|
+
return fail(ctx, 'Missing required param: name.', 400, 'parameter_missing');
|
|
14
|
+
const scope = params.scope && typeof params.scope === 'object' ? params.scope : undefined;
|
|
15
|
+
const scopeType = scope && typeof scope.type === 'string' ? scope.type : '';
|
|
16
|
+
if (scopeType !== 'account' && scopeType !== 'user')
|
|
17
|
+
return fail(ctx, 'Invalid scope[type]: must be account or user.', 400, 'parameter_invalid_string_enum');
|
|
18
|
+
if (scopeType === 'user' && typeof scope.user !== 'string')
|
|
19
|
+
return fail(ctx, 'Missing required param: scope[user].', 400, 'parameter_missing');
|
|
20
|
+
if (params.payload === undefined)
|
|
21
|
+
return fail(ctx, 'Missing required param: payload.', 400, 'parameter_missing');
|
|
22
|
+
const expiresAt = params.expires_at !== undefined ? Math.trunc(Number(params.expires_at)) : null;
|
|
23
|
+
const existing = named(ctx, name);
|
|
24
|
+
if (existing)
|
|
25
|
+
return ctx.reply(await ctx.write(SECRET, String(existing.id), { payload: params.payload, expires_at: expiresAt, _updated: ctx.now() }, 'apps_secret.update'));
|
|
26
|
+
return ctx.reply(await created(ctx, SECRET, { name }, {
|
|
27
|
+
livemode: false, deleted: false, expires_at: expiresAt, payload: params.payload,
|
|
28
|
+
scope: scopeType === 'user' ? { type: 'user', user: scope.user } : { type: 'account' },
|
|
29
|
+
_scope_key: scopeKeyOf(ctx),
|
|
30
|
+
}));
|
|
31
|
+
};
|
|
32
|
+
const find = async (ctx) => {
|
|
33
|
+
const name = typeof ctx.params.name === 'string' ? ctx.params.name : '';
|
|
34
|
+
if (!name)
|
|
35
|
+
return fail(ctx, 'Missing required param: name.', 400, 'parameter_missing');
|
|
36
|
+
const s = named(ctx, name);
|
|
37
|
+
return s ? ctx.reply(s) : fail(ctx, `No such secret: '${name}'`, 404, 'resource_missing');
|
|
38
|
+
};
|
|
39
|
+
const remove = async (ctx) => {
|
|
40
|
+
const name = typeof ctx.params.name === 'string' ? ctx.params.name : '';
|
|
41
|
+
if (!name)
|
|
42
|
+
return fail(ctx, 'Missing required param: name.', 400, 'parameter_missing');
|
|
43
|
+
const s = named(ctx, name);
|
|
44
|
+
if (!s)
|
|
45
|
+
return fail(ctx, `No such secret: '${name}'`, 404, 'resource_missing');
|
|
46
|
+
return ctx.reply(await ctx.write(SECRET, String(s.id), { deleted: true }, 'apps_secret.delete'));
|
|
47
|
+
};
|
|
48
|
+
const listSecrets = async (ctx) => list(ctx, SECRET, newest(ctx, SECRET).filter((s) => kept(ctx, SECRET, s, '_scope_key') === scopeKeyOf(ctx)));
|
|
49
|
+
export const appsSecrets = {
|
|
50
|
+
PostAppsSecrets: set,
|
|
51
|
+
GetAppsSecretsFind: find,
|
|
52
|
+
PostAppsSecretsDelete: remove,
|
|
53
|
+
GetAppsSecrets: listSecrets,
|
|
54
|
+
};
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { Semantics, SemanticsContext } from '@volter/world-core';
|
|
2
|
+
import { type Row } from './shared.js';
|
|
3
|
+
/** The acting account's Balance object (docs.stripe.com/api/balance/balance_object). */
|
|
4
|
+
export declare function balanceBody(ctx: SemanticsContext): Row;
|
|
5
|
+
/** Time's arrivals, written: each of the acting account's payouts whose arrival date has come moves pending → paid
|
|
6
|
+
* (the clock's move, as asOf reads it), written as `payout.paid`, the event Stripe sends for it. Answers their ids. */
|
|
7
|
+
export declare function payDuePayouts(ctx: SemanticsContext): Promise<string[]>;
|
|
8
|
+
/** Time's payouts, caught up to the World's clock: each account on an automatic schedule is paid out, on each of its
|
|
9
|
+
* scheduled days that has come, what became available by then. */
|
|
10
|
+
export declare function advancePayouts(ctx: SemanticsContext): Promise<void>;
|
|
11
|
+
export declare const balances: Record<string, Semantics>;
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
import { validateMoney } from "../stripe-twin.js";
|
|
2
|
+
import { accountSettings, PLATFORM_ACCOUNT_ID } from "../stripe-twin.js";
|
|
3
|
+
import { actingAccount, balanceOf, refusePayout, settleAutomaticPayout, settlePayout, unpaidEntries } from "./ledger.js";
|
|
4
|
+
import { at, at_, created, fail, inRange, list, newest, send, where, kept } from "./shared.js";
|
|
5
|
+
const account = actingAccount;
|
|
6
|
+
const DAY = 86_400;
|
|
7
|
+
const payoutMissing = (ctx, id) => fail(ctx, `No such payout: '${id}'`, 404, 'resource_missing');
|
|
8
|
+
/** The acting account's Balance object (docs.stripe.com/api/balance/balance_object). */
|
|
9
|
+
export function balanceBody(ctx) {
|
|
10
|
+
const { available, pending, issuing } = balanceOf(ctx);
|
|
11
|
+
const toArr = (m) => {
|
|
12
|
+
const out = [...m.entries()].map(([currency, amount]) => ({ amount, currency, source_types: { card: amount } }));
|
|
13
|
+
return out.length ? out : [{ amount: 0, currency: 'usd', source_types: { card: 0 } }];
|
|
14
|
+
};
|
|
15
|
+
// a platform's balance holds its connected accounts' reserve, "Funds held due to negative balances on connected accounts
|
|
16
|
+
// where account.controller.requirement_collection is `application`" (docs.stripe.com/api/balance/balance_object, whose
|
|
17
|
+
// example answers `[{"amount": 0, "currency": "usd"}]`); the twin models no such reserve, so it is zero in each currency
|
|
18
|
+
const reserved = account(ctx) ? {} : { connect_reserved: toArr(available).map((b) => ({ amount: 0, currency: b.currency })) };
|
|
19
|
+
return {
|
|
20
|
+
object: 'balance', available: toArr(available), pending: toArr(pending), ...reserved, livemode: false,
|
|
21
|
+
...(issuing.size ? { issuing: { available: [...issuing.entries()].map(([currency, amount]) => ({ amount, currency, source_types: { card: amount } })) } } : {}),
|
|
22
|
+
};
|
|
23
|
+
}
|
|
24
|
+
const balance = async (ctx) => ctx.reply(balanceBody(ctx));
|
|
25
|
+
/** Time's arrivals, written: each of the acting account's payouts whose arrival date has come moves pending → paid
|
|
26
|
+
* (the clock's move, as asOf reads it), written as `payout.paid`, the event Stripe sends for it. Answers their ids. */
|
|
27
|
+
export async function payDuePayouts(ctx) {
|
|
28
|
+
const acct = account(ctx);
|
|
29
|
+
const now = Number(ctx.now());
|
|
30
|
+
const paid = [];
|
|
31
|
+
for (const p of newest(ctx, 'payout')) {
|
|
32
|
+
if ((acct ? kept(ctx, 'payout', p, '_account') !== acct : !!kept(ctx, 'payout', p, '_account')) || p.status !== 'pending' || Number(p.arrival_date) > now)
|
|
33
|
+
continue;
|
|
34
|
+
if (ctx.legal('payout', 'status', ctx.call.operation.id, 'pending', 'paid', String(p.id), 'time'))
|
|
35
|
+
continue;
|
|
36
|
+
await ctx.write('payout', String(p.id), { status: 'paid' }, 'payout.paid');
|
|
37
|
+
paid.push(String(p.id));
|
|
38
|
+
}
|
|
39
|
+
return paid;
|
|
40
|
+
}
|
|
41
|
+
/** Where a connected account's payout goes: "ID of the bank account or card the payout is sent to" (served spec,
|
|
42
|
+
* payout.destination), its default external account for the currency, "When multiple accounts are available for a given
|
|
43
|
+
* currency, Stripe uses the one set as `default_for_currency`" (docs.stripe.com/connect/payouts-bank-accounts), the
|
|
44
|
+
* newest such. Where the documentation stops and the twin decides: the platform's own bank account is not modelled, so
|
|
45
|
+
* its payouts name none. */
|
|
46
|
+
function payoutBank(ctx, account, currency) {
|
|
47
|
+
const banks = newest(ctx, 'external_account').filter((e) => e.account === account && String(e.currency ?? currency) === currency);
|
|
48
|
+
return String((banks.find((e) => e.default_for_currency === true) ?? banks[0])?.id ?? '') || null;
|
|
49
|
+
}
|
|
50
|
+
const payoutDefaults = (ctx) => ({
|
|
51
|
+
method: 'standard', type: 'bank_account', source_type: 'card', automatic: false,
|
|
52
|
+
reconciliation_status: 'not_applicable', arrival_date: Number(ctx.now()) + 2 * DAY, livemode: false, metadata: {},
|
|
53
|
+
});
|
|
54
|
+
/** A payout as the clock reads it: paid once its arrival date has come, the clock's move, asked of the
|
|
55
|
+
* machine as a write asks it. */
|
|
56
|
+
function asOf(ctx, p) {
|
|
57
|
+
if (p.status !== 'pending' || Number(p.arrival_date) > Number(ctx.now()))
|
|
58
|
+
return p;
|
|
59
|
+
ctx.legal('payout', 'status', ctx.call.operation.id, 'pending', 'paid', String(p.id), 'time');
|
|
60
|
+
return { ...p, status: 'paid' };
|
|
61
|
+
}
|
|
62
|
+
/** A connected account's payout in a currency none of its bank accounts takes. */
|
|
63
|
+
function noExternalAccount(ctx, currency) {
|
|
64
|
+
return fail(ctx, `Sorry, you don't have any external accounts in that currency (${currency}).`, 400);
|
|
65
|
+
}
|
|
66
|
+
const createPayout = async (ctx) => {
|
|
67
|
+
const bad = validateMoney(ctx.params);
|
|
68
|
+
if (bad)
|
|
69
|
+
return send(ctx, bad);
|
|
70
|
+
const acct = account(ctx);
|
|
71
|
+
if (acct && !ctx.get('account', acct))
|
|
72
|
+
return fail(ctx, `No such account: '${acct}'`, 400, 'account_invalid');
|
|
73
|
+
const amount = Math.trunc(Number(ctx.params.amount) || 0);
|
|
74
|
+
const currency = String(ctx.params.currency ?? 'usd');
|
|
75
|
+
// a connected account is paid out to its own bank account
|
|
76
|
+
if (acct && !ctx.rows('external_account').some((e) => e.account === acct && (e.currency ?? currency) === currency))
|
|
77
|
+
return noExternalAccount(ctx, currency);
|
|
78
|
+
const refused = refusePayout(ctx, amount, currency);
|
|
79
|
+
if (refused)
|
|
80
|
+
return refused;
|
|
81
|
+
const id = ctx.mint('payout');
|
|
82
|
+
const bt = await settlePayout(ctx, id, -amount, currency);
|
|
83
|
+
return ctx.reply(await created(ctx, 'payout', { ...ctx.params, id }, { status: 'pending', ...payoutDefaults(ctx), balance_transaction: bt, destination: acct ? payoutBank(ctx, acct, currency) : null, ...(acct ? { _account: acct } : {}) }));
|
|
84
|
+
};
|
|
85
|
+
const listPayouts = async (ctx) => {
|
|
86
|
+
const acct = account(ctx);
|
|
87
|
+
const scoped = newest(ctx, 'payout').filter((p) => (acct ? kept(ctx, 'payout', p, '_account') === acct : !kept(ctx, 'payout', p, '_account'))).map((p) => asOf(ctx, p));
|
|
88
|
+
return list(ctx, 'payout', where(ctx, scoped, { status: (p, v) => p.status === v, created: (p, v) => inRange(p.created, v), arrival_date: (p, v) => inRange(p.arrival_date, v) }));
|
|
89
|
+
};
|
|
90
|
+
const DAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday'];
|
|
91
|
+
/** The first scheduled payout time on or after `from`: midnight UTC of a day the schedule pays out on. */
|
|
92
|
+
function payoutDay(from, schedule) {
|
|
93
|
+
const first = Math.ceil(from / DAY) * DAY;
|
|
94
|
+
const pays = (day) => {
|
|
95
|
+
const d = new Date(day * 1000);
|
|
96
|
+
if (schedule.interval === 'weekly')
|
|
97
|
+
return DAYS[d.getUTCDay()] === String(schedule.weekly_anchor ?? 'monday');
|
|
98
|
+
if (schedule.interval === 'monthly')
|
|
99
|
+
return d.getUTCDate() === Math.min(Number(schedule.monthly_anchor ?? 1), new Date(Date.UTC(d.getUTCFullYear(), d.getUTCMonth() + 1, 0)).getUTCDate());
|
|
100
|
+
return true;
|
|
101
|
+
};
|
|
102
|
+
return Array.from({ length: 62 }, (_, i) => first + i * DAY).find(pays) ?? first;
|
|
103
|
+
}
|
|
104
|
+
/** Time's payouts, caught up to the World's clock: each account on an automatic schedule is paid out, on each of its
|
|
105
|
+
* scheduled days that has come, what became available by then. */
|
|
106
|
+
export async function advancePayouts(ctx) {
|
|
107
|
+
const now = Number(ctx.now());
|
|
108
|
+
const platform = ctx.get('account', PLATFORM_ACCOUNT_ID);
|
|
109
|
+
const accounts = [{ id: undefined, settings: platform?.settings }];
|
|
110
|
+
for (const a of ctx.rows('account')) {
|
|
111
|
+
if (a.id === PLATFORM_ACCOUNT_ID || a.payouts_enabled !== true)
|
|
112
|
+
continue;
|
|
113
|
+
if (!ctx.rows('external_account').some((e) => e.account === a.id))
|
|
114
|
+
continue;
|
|
115
|
+
accounts.push({ id: String(a.id), settings: a.settings });
|
|
116
|
+
}
|
|
117
|
+
for (const acct of accounts) {
|
|
118
|
+
const schedule = (accountSettings(acct.settings, acct.settings ?? undefined).payouts.schedule ?? {});
|
|
119
|
+
if (schedule.interval === 'manual')
|
|
120
|
+
continue;
|
|
121
|
+
const unpaid = unpaidEntries(ctx, acct.id);
|
|
122
|
+
const days = [...new Set(unpaid.map((t) => payoutDay(Number(t.available_on) || 0, schedule)))].filter((d) => d <= now).sort((x, y) => x - y);
|
|
123
|
+
const paid = new Set();
|
|
124
|
+
for (const day of days) {
|
|
125
|
+
const due = unpaid.filter((t) => !paid.has(t.id) && (Number(t.available_on) || 0) <= day);
|
|
126
|
+
const byCurrency = new Map();
|
|
127
|
+
for (const t of due)
|
|
128
|
+
byCurrency.set(String(t.currency ?? 'usd'), [...(byCurrency.get(String(t.currency ?? 'usd')) ?? []), t]);
|
|
129
|
+
for (const [currency, entries] of byCurrency) {
|
|
130
|
+
const amount = entries.reduce((n, t) => n + (Number(t.net) || 0), 0);
|
|
131
|
+
// nothing to pay yet: what came due is carried to the next payout
|
|
132
|
+
if (amount <= 0)
|
|
133
|
+
continue;
|
|
134
|
+
// made on its day, as Stripe makes it, whenever the request that catches it up comes
|
|
135
|
+
const c = await at_(ctx)(day);
|
|
136
|
+
const id = c.mint('payout');
|
|
137
|
+
const bt = await settleAutomaticPayout(c, id, amount, currency, acct.id, day, entries);
|
|
138
|
+
await created(c, 'payout', { id, amount, currency }, {
|
|
139
|
+
status: 'pending', ...payoutDefaults(c), arrival_date: day + 2 * DAY, automatic: true, balance_transaction: bt, destination: acct.id ? payoutBank(c, String(acct.id), currency) : null,
|
|
140
|
+
description: 'STRIPE PAYOUT', ...(acct.id ? { _account: acct.id } : {}),
|
|
141
|
+
});
|
|
142
|
+
for (const t of entries)
|
|
143
|
+
paid.add(t.id);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
}
|
|
148
|
+
const retrievePayout = async (ctx) => {
|
|
149
|
+
const p = ctx.get('payout', at(ctx, 'payout'));
|
|
150
|
+
return p ? ctx.reply(asOf(ctx, p)) : payoutMissing(ctx, at(ctx, 'payout'));
|
|
151
|
+
};
|
|
152
|
+
const cancelPayout = async (ctx) => {
|
|
153
|
+
const id = at(ctx, 'payout');
|
|
154
|
+
const po = ctx.get('payout', id);
|
|
155
|
+
if (!po)
|
|
156
|
+
return payoutMissing(ctx, id);
|
|
157
|
+
const refused = ctx.legal('payout', 'status', 'PostPayoutsPayoutCancel', asOf(ctx, po).status, undefined, id);
|
|
158
|
+
if (refused)
|
|
159
|
+
return ctx.refuse(refused);
|
|
160
|
+
// the money comes back to the balance it left
|
|
161
|
+
const owner = kept(ctx, 'payout', po, '_account');
|
|
162
|
+
await settlePayout(ctx, id, Number(po.amount) || 0, String(po.currency ?? 'usd'), typeof owner === 'string' ? owner : null);
|
|
163
|
+
return ctx.reply(await ctx.write('payout', id, { status: 'canceled' }, 'payout.cancel'));
|
|
164
|
+
};
|
|
165
|
+
// a reversal is itself a payout in the other direction, back into the connected account's balance, as the reverse page's
|
|
166
|
+
// example answers it: a negative amount, pending until it arrives, carrying the request's metadata
|
|
167
|
+
// (docs.stripe.com/api/payouts/reverse); the original stays paid and names it
|
|
168
|
+
const reversePayout = async (ctx) => {
|
|
169
|
+
const id = at(ctx, 'payout');
|
|
170
|
+
const po = ctx.get('payout', id);
|
|
171
|
+
if (!po)
|
|
172
|
+
return payoutMissing(ctx, id);
|
|
173
|
+
const owner = kept(ctx, 'payout', po, '_account');
|
|
174
|
+
if (typeof owner !== 'string')
|
|
175
|
+
return fail(ctx, "Payout reversals are only supported for payouts to connected accounts' bank accounts.", 400);
|
|
176
|
+
const status = String(asOf(ctx, po).status);
|
|
177
|
+
if (po.reversed_by || status !== 'paid')
|
|
178
|
+
return ctx.refuse({ status: 400, code: 'payout_reversal_not_allowed', message: po.reversed_by ? 'This payout has already been reversed.' : `This payout cannot be reversed because it has a status of ${status}. A pending payout can be canceled instead.` });
|
|
179
|
+
const reversalId = ctx.mint('payout');
|
|
180
|
+
const bt = await settlePayout(ctx, reversalId, Number(po.amount) || 0, String(po.currency ?? 'usd'), owner);
|
|
181
|
+
const metadata = ctx.params.metadata && typeof ctx.params.metadata === 'object' ? { metadata: ctx.params.metadata } : {};
|
|
182
|
+
const reversal = await created(ctx, 'payout', { id: reversalId, amount: -(Number(po.amount) || 0), currency: po.currency, ...metadata }, {
|
|
183
|
+
status: 'pending', ...payoutDefaults(ctx), balance_transaction: bt, original_payout: id, destination: po.destination ?? null, _account: owner,
|
|
184
|
+
});
|
|
185
|
+
await ctx.write('payout', id, { reversed_by: reversal.id }, 'payout.reversed');
|
|
186
|
+
return ctx.reply(reversal);
|
|
187
|
+
};
|
|
188
|
+
export const balances = {
|
|
189
|
+
GetBalance: balance,
|
|
190
|
+
PostPayouts: createPayout,
|
|
191
|
+
GetPayouts: listPayouts,
|
|
192
|
+
GetPayoutsPayout: retrievePayout,
|
|
193
|
+
PostPayoutsPayoutCancel: cancelPayout,
|
|
194
|
+
PostPayoutsPayoutReverse: reversePayout,
|
|
195
|
+
};
|
|
@@ -0,0 +1,220 @@
|
|
|
1
|
+
import { at, created, fail, list, newest, path, where } from "./shared.js";
|
|
2
|
+
const METER = 'billing.meter';
|
|
3
|
+
const meterMissing = (ctx, id) => fail(ctx, `No such meter: '${id}'`, 404, 'resource_missing');
|
|
4
|
+
const objectOf = (v) => (v && typeof v === 'object' ? v : {});
|
|
5
|
+
// a meter needs a display name, the event name it counts, and how it aggregates (sum or count)
|
|
6
|
+
const createMeter = async (ctx) => {
|
|
7
|
+
const params = ctx.params;
|
|
8
|
+
const displayName = typeof params.display_name === 'string' ? params.display_name : '';
|
|
9
|
+
if (!displayName)
|
|
10
|
+
return fail(ctx, 'Missing required param: display_name.', 400, 'parameter_missing');
|
|
11
|
+
if (!(params.event_name ?? ''))
|
|
12
|
+
return fail(ctx, 'Missing required param: event_name.', 400, 'parameter_missing');
|
|
13
|
+
const formula = objectOf(params.default_aggregation).formula;
|
|
14
|
+
if (typeof formula !== 'string' || !formula)
|
|
15
|
+
return fail(ctx, 'Missing required param: default_aggregation[formula] (sum or count).', 400, 'parameter_missing');
|
|
16
|
+
return ctx.reply(await created(ctx, METER, params, {
|
|
17
|
+
status: 'active', livemode: false,
|
|
18
|
+
customer_mapping: params.customer_mapping ?? { event_payload_key: 'stripe_customer_id', type: 'by_id' },
|
|
19
|
+
event_time_window: params.event_time_window ?? null,
|
|
20
|
+
value_settings: params.value_settings ?? { event_payload_key: 'value' },
|
|
21
|
+
status_transitions: { deactivated_at: null }, updated: ctx.now(),
|
|
22
|
+
}));
|
|
23
|
+
};
|
|
24
|
+
function activation(kind) {
|
|
25
|
+
return async (ctx) => {
|
|
26
|
+
const id = at(ctx, 'id');
|
|
27
|
+
const m = ctx.get(METER, id);
|
|
28
|
+
if (!m)
|
|
29
|
+
return meterMissing(ctx, id);
|
|
30
|
+
const refused = ctx.legal(METER, 'status', kind === 'deactivate' ? 'PostBillingMetersIdDeactivate' : 'PostBillingMetersIdReactivate', m.status, undefined, id);
|
|
31
|
+
if (refused)
|
|
32
|
+
return ctx.refuse(refused);
|
|
33
|
+
const fields = { ...(kind === 'deactivate' ? { status: 'inactive', status_transitions: { deactivated_at: ctx.now() } } : { status: 'active', status_transitions: { deactivated_at: null } }), updated: ctx.now() };
|
|
34
|
+
return ctx.reply(await ctx.write(METER, id, fields, `billing_meter.${kind}`));
|
|
35
|
+
};
|
|
36
|
+
}
|
|
37
|
+
// a meter event has no id of its own on Stripe (it carries an `identifier`); its object is billing.meter_event
|
|
38
|
+
const reportUsage = async (ctx) => {
|
|
39
|
+
const params = ctx.params;
|
|
40
|
+
if (typeof params.event_name !== 'string' || !params.event_name)
|
|
41
|
+
return fail(ctx, 'Missing required param: event_name.', 400, 'parameter_missing');
|
|
42
|
+
const payload = objectOf(params.payload);
|
|
43
|
+
const body = await created(ctx, 'billing.meter_event', { ...params }, {
|
|
44
|
+
livemode: false, timestamp: params.timestamp !== undefined ? Math.trunc(Number(params.timestamp)) : ctx.now(),
|
|
45
|
+
identifier: payload.identifier ?? null, payload,
|
|
46
|
+
});
|
|
47
|
+
return ctx.reply({ ...body, object: 'billing.meter_event' });
|
|
48
|
+
};
|
|
49
|
+
// the meter's events for one customer in [start_time, end_time), aggregated by its formula
|
|
50
|
+
const eventSummaries = async (ctx) => {
|
|
51
|
+
const id = at(ctx, 'id');
|
|
52
|
+
const m = ctx.get(METER, id);
|
|
53
|
+
if (!m)
|
|
54
|
+
return meterMissing(ctx, id);
|
|
55
|
+
const params = ctx.params;
|
|
56
|
+
const customer = typeof params.customer === 'string' ? params.customer : '';
|
|
57
|
+
if (!customer)
|
|
58
|
+
return fail(ctx, 'Missing required param: customer.', 400, 'parameter_missing');
|
|
59
|
+
if (params.start_time === undefined)
|
|
60
|
+
return fail(ctx, 'Missing required param: start_time.', 400, 'parameter_missing');
|
|
61
|
+
if (params.end_time === undefined)
|
|
62
|
+
return fail(ctx, 'Missing required param: end_time.', 400, 'parameter_missing');
|
|
63
|
+
const startTime = Math.trunc(Number(params.start_time) || 0);
|
|
64
|
+
const endTime = Math.trunc(Number(params.end_time) || 0);
|
|
65
|
+
// "Must be aligned with minute boundaries" (start_time, end_time); "For hourly granularity, start and end times must
|
|
66
|
+
// align with hour boundaries … For daily granularity, … with UTC day boundaries (00:00 UTC)" (value_grouping_window;
|
|
67
|
+
// the served spec). Where the documentation stops and the twin decides: Stripe documents no error for it, so the
|
|
68
|
+
// twin answers a 400 naming the parameter and the boundary.
|
|
69
|
+
const window = params.value_grouping_window === 'hour' ? 3600 : params.value_grouping_window === 'day' ? 86_400 : 60;
|
|
70
|
+
const unit = window === 3600 ? 'hour' : window === 86_400 ? 'UTC day' : 'minute';
|
|
71
|
+
for (const [name, t] of [['start_time', startTime], ['end_time', endTime]]) {
|
|
72
|
+
if (t % window !== 0)
|
|
73
|
+
return fail(ctx, `Invalid ${name}: ${t} is not aligned with ${unit} boundaries.`, 400);
|
|
74
|
+
}
|
|
75
|
+
const mapKey = typeof objectOf(m.customer_mapping).event_payload_key === 'string' ? String(objectOf(m.customer_mapping).event_payload_key) : 'stripe_customer_id';
|
|
76
|
+
const valueKey = typeof objectOf(m.value_settings).event_payload_key === 'string' ? String(objectOf(m.value_settings).event_payload_key) : 'value';
|
|
77
|
+
const formula = objectOf(m.default_aggregation).formula ?? 'sum';
|
|
78
|
+
let aggregate = 0;
|
|
79
|
+
for (const ev of ctx.rowsRaw('billing.meter_event', { withDeleted: true })) {
|
|
80
|
+
if (ev.event_name !== String(m.event_name ?? ''))
|
|
81
|
+
continue;
|
|
82
|
+
const ts = Number(ev.timestamp) || 0;
|
|
83
|
+
if (ts < startTime || ts >= endTime)
|
|
84
|
+
continue;
|
|
85
|
+
const payload = objectOf(ev.payload);
|
|
86
|
+
if (String(payload[mapKey] ?? '') !== customer)
|
|
87
|
+
continue;
|
|
88
|
+
aggregate += formula === 'count' ? 1 : Number(payload[valueKey]) || 0;
|
|
89
|
+
}
|
|
90
|
+
return ctx.reply({
|
|
91
|
+
object: 'list', url: path(ctx), has_more: false,
|
|
92
|
+
data: [{ id: `mtrusg_twin_${id}_${customer}`, object: 'billing.meter_event_summary', meter: id, aggregated_value: aggregate, start_time: startTime, end_time: endTime, livemode: false }],
|
|
93
|
+
});
|
|
94
|
+
};
|
|
95
|
+
// ── credit grants: a customer's prepaid credit, paid or promotional, in a monetary amount ──
|
|
96
|
+
const GRANT = 'billing.credit_grant';
|
|
97
|
+
const grantMissing = (ctx, id) => fail(ctx, `No such credit grant: '${id}'`, 404, 'resource_missing');
|
|
98
|
+
const createGrant = async (ctx) => {
|
|
99
|
+
const params = ctx.params;
|
|
100
|
+
const customer = typeof params.customer === 'string' ? params.customer : '';
|
|
101
|
+
if (!customer)
|
|
102
|
+
return fail(ctx, 'Missing required param: customer.', 400, 'parameter_missing');
|
|
103
|
+
if (!ctx.row('customer', customer, { withDeleted: true }))
|
|
104
|
+
return fail(ctx, `No such customer: '${customer}'`, 404, 'resource_missing');
|
|
105
|
+
const category = typeof params.category === 'string' ? params.category : '';
|
|
106
|
+
if (category !== 'paid' && category !== 'promotional')
|
|
107
|
+
return fail(ctx, 'Invalid category: must be paid or promotional.', 400, 'parameter_invalid_string_enum');
|
|
108
|
+
const monetary = params.amount && typeof params.amount === 'object' ? objectOf(params.amount.monetary) : undefined;
|
|
109
|
+
if (!monetary || monetary.value === undefined || monetary.currency === undefined)
|
|
110
|
+
return fail(ctx, 'Missing required param: amount[monetary][value] and amount[monetary][currency].', 400, 'parameter_missing');
|
|
111
|
+
return ctx.reply(await created(ctx, GRANT, { customer }, {
|
|
112
|
+
category, livemode: false, name: params.name ?? null,
|
|
113
|
+
amount: { type: 'monetary', monetary: { currency: String(monetary.currency), value: Math.trunc(Number(monetary.value) || 0) } },
|
|
114
|
+
applicability_config: params.applicability_config && typeof params.applicability_config === 'object' ? params.applicability_config : { scope: { price_type: 'metered' } },
|
|
115
|
+
effective_at: params.effective_at !== undefined ? Math.trunc(Number(params.effective_at)) : ctx.now(),
|
|
116
|
+
expires_at: params.expires_at !== undefined ? Math.trunc(Number(params.expires_at)) : null,
|
|
117
|
+
priority: params.priority !== undefined ? Math.trunc(Number(params.priority)) : 50,
|
|
118
|
+
voided_at: null, metadata: params.metadata && typeof params.metadata === 'object' ? params.metadata : {}, updated: ctx.now(),
|
|
119
|
+
}));
|
|
120
|
+
};
|
|
121
|
+
// expiring or voiding a grant stamps the instant; it no longer counts toward the balance
|
|
122
|
+
function endGrant(kind) {
|
|
123
|
+
return async (ctx) => {
|
|
124
|
+
const id = at(ctx, 'id');
|
|
125
|
+
if (!ctx.get(GRANT, id))
|
|
126
|
+
return grantMissing(ctx, id);
|
|
127
|
+
return ctx.reply(await ctx.write(GRANT, id, { ...(kind === 'void' ? { voided_at: ctx.now() } : { expires_at: ctx.now() }), updated: ctx.now() }, `credit_grant.${kind}`));
|
|
128
|
+
};
|
|
129
|
+
}
|
|
130
|
+
// only the expiry and metadata change
|
|
131
|
+
const updateGrant = async (ctx) => {
|
|
132
|
+
const id = at(ctx, 'id');
|
|
133
|
+
if (!ctx.get(GRANT, id))
|
|
134
|
+
return grantMissing(ctx, id);
|
|
135
|
+
const patch = { updated: ctx.now() };
|
|
136
|
+
if (ctx.params.expires_at !== undefined)
|
|
137
|
+
patch.expires_at = Math.trunc(Number(ctx.params.expires_at));
|
|
138
|
+
if (ctx.params.metadata !== undefined)
|
|
139
|
+
patch.metadata = ctx.params.metadata;
|
|
140
|
+
return ctx.reply(await ctx.write(GRANT, id, patch, 'credit_grant.update'));
|
|
141
|
+
};
|
|
142
|
+
// the customer's live (unvoided, unexpired) monetary grants, summed per currency
|
|
143
|
+
const creditBalance = async (ctx) => {
|
|
144
|
+
const customer = typeof ctx.params.customer === 'string' ? ctx.params.customer : '';
|
|
145
|
+
if (!customer)
|
|
146
|
+
return fail(ctx, 'Missing required param: customer.', 400, 'parameter_missing');
|
|
147
|
+
if (!ctx.row('customer', customer, { withDeleted: true }))
|
|
148
|
+
return fail(ctx, `No such customer: '${customer}'`, 404, 'resource_missing');
|
|
149
|
+
const now = Number(ctx.now());
|
|
150
|
+
const byCurrency = {};
|
|
151
|
+
for (const g of ctx.rows(GRANT)) {
|
|
152
|
+
if (g.customer !== customer || g.voided_at != null)
|
|
153
|
+
continue;
|
|
154
|
+
if (typeof g.expires_at === 'number' && g.expires_at <= now)
|
|
155
|
+
continue;
|
|
156
|
+
const monetary = objectOf(objectOf(g.amount).monetary);
|
|
157
|
+
const cur = String(monetary.currency ?? 'usd');
|
|
158
|
+
byCurrency[cur] = (byCurrency[cur] ?? 0) + (Number(monetary.value) || 0);
|
|
159
|
+
}
|
|
160
|
+
const balances = Object.entries(byCurrency).map(([currency, value]) => ({
|
|
161
|
+
available_balance: { type: 'monetary', monetary: { currency, value } },
|
|
162
|
+
ledger_balance: { type: 'monetary', monetary: { currency, value } },
|
|
163
|
+
}));
|
|
164
|
+
return ctx.reply({ object: 'billing.credit_balance_summary', customer, balances, livemode: false });
|
|
165
|
+
};
|
|
166
|
+
// ── alerts: a usage threshold on a meter ──
|
|
167
|
+
const ALERT = 'billing.alert';
|
|
168
|
+
const createAlert = async (ctx) => {
|
|
169
|
+
const params = ctx.params;
|
|
170
|
+
if (params.alert_type !== 'usage_threshold')
|
|
171
|
+
return fail(ctx, 'Invalid alert_type: must be usage_threshold.', 400, 'parameter_invalid_string_enum');
|
|
172
|
+
if (typeof params.title !== 'string' || !params.title)
|
|
173
|
+
return fail(ctx, 'Missing required param: title.', 400, 'parameter_missing');
|
|
174
|
+
const ut = params.usage_threshold && typeof params.usage_threshold === 'object' ? params.usage_threshold : undefined;
|
|
175
|
+
if (!ut || ut.gte === undefined || typeof ut.meter !== 'string')
|
|
176
|
+
return fail(ctx, 'Missing required param: usage_threshold[gte] and usage_threshold[meter].', 400, 'parameter_missing');
|
|
177
|
+
// the spec requires recurrence too (one_time: the alert fires once)
|
|
178
|
+
if (ut.recurrence === undefined || ut.recurrence === '')
|
|
179
|
+
return fail(ctx, 'Missing required param: usage_threshold[recurrence].', 400, 'parameter_missing');
|
|
180
|
+
if (!ctx.get(METER, ut.meter))
|
|
181
|
+
return fail(ctx, `No such meter: '${ut.meter}'`, 400, 'resource_missing');
|
|
182
|
+
return ctx.reply(await created(ctx, ALERT, {}, {
|
|
183
|
+
alert_type: 'usage_threshold', livemode: false, status: 'active', title: params.title,
|
|
184
|
+
usage_threshold: { gte: Math.trunc(Number(ut.gte) || 0), meter: ut.meter, recurrence: String(ut.recurrence), filters: null },
|
|
185
|
+
}));
|
|
186
|
+
};
|
|
187
|
+
const listAlerts = async (ctx) => list(ctx, ALERT, where(ctx, newest(ctx, ALERT), {
|
|
188
|
+
alert_type: (a, v) => a.alert_type === v,
|
|
189
|
+
meter: (a, v) => objectOf(a.usage_threshold).meter === v,
|
|
190
|
+
}));
|
|
191
|
+
function alertMove(kind, operationId) {
|
|
192
|
+
return async (ctx) => {
|
|
193
|
+
const id = at(ctx, 'id');
|
|
194
|
+
const a = ctx.get(ALERT, id);
|
|
195
|
+
if (!a)
|
|
196
|
+
return fail(ctx, `No such alert: '${id}'`, 404, 'resource_missing');
|
|
197
|
+
const refused = ctx.legal(ALERT, 'status', operationId, a.status, undefined, id);
|
|
198
|
+
if (refused)
|
|
199
|
+
return ctx.refuse(refused);
|
|
200
|
+
const status = kind === 'activate' ? 'active' : kind === 'deactivate' ? 'inactive' : 'archived';
|
|
201
|
+
return ctx.reply(await ctx.write(ALERT, id, { status }, `billing_alert.${kind}`));
|
|
202
|
+
};
|
|
203
|
+
}
|
|
204
|
+
export const billing = {
|
|
205
|
+
PostBillingMeters: createMeter,
|
|
206
|
+
PostBillingMetersIdDeactivate: activation('deactivate'),
|
|
207
|
+
PostBillingMetersIdReactivate: activation('reactivate'),
|
|
208
|
+
PostBillingMeterEvents: reportUsage,
|
|
209
|
+
GetBillingMetersIdEventSummaries: eventSummaries,
|
|
210
|
+
PostBillingCreditGrants: createGrant,
|
|
211
|
+
PostBillingCreditGrantsIdExpire: endGrant('expire'),
|
|
212
|
+
PostBillingCreditGrantsIdVoid: endGrant('void'),
|
|
213
|
+
PostBillingCreditGrantsId: updateGrant,
|
|
214
|
+
GetBillingCreditBalanceSummary: creditBalance,
|
|
215
|
+
PostBillingAlerts: createAlert,
|
|
216
|
+
GetBillingAlerts: listAlerts,
|
|
217
|
+
PostBillingAlertsIdActivate: alertMove('activate', 'PostBillingAlertsIdActivate'),
|
|
218
|
+
PostBillingAlertsIdDeactivate: alertMove('deactivate', 'PostBillingAlertsIdDeactivate'),
|
|
219
|
+
PostBillingAlertsIdArchive: alertMove('archive', 'PostBillingAlertsIdArchive'),
|
|
220
|
+
};
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import type { Semantics, SemanticsContext } from '@volter/world-core';
|
|
2
|
+
import { type Row } from './shared.js';
|
|
3
|
+
/** Every egress of a charge carries its refunds, derived from the refund rows in list order. */
|
|
4
|
+
export declare function chargeBody(ctx: SemanticsContext, c: Row): Row;
|
|
5
|
+
/** A capture=false charge refunded while uncaptured: its authorization is released by the refund, as it would be
|
|
6
|
+
* "automatically refunded if uncaptured" (spec/openapi.json.gz, `capture_before`). The charge stays uncaptured and
|
|
7
|
+
* becomes refunded in full, a Refund records the release, and no money moves: none was ever received. Written as
|
|
8
|
+
* charge.refunded. Where the documentation stops and the twin decides: Stripe's basil change ("Partially capturing or
|
|
9
|
+
* canceling payments no longer creates a Refund", docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-partial-
|
|
10
|
+
* capture-and-payment-cancellation-flow) names partial capture and cancellation, not a refund asked for, so a refund
|
|
11
|
+
* still makes one; its reason is null and it has no balance transaction. Answers the Refund. */
|
|
12
|
+
export declare function releaseAuthorization(ctx: SemanticsContext, ch: Row, operationId: string, given?: Row): Promise<Row>;
|
|
13
|
+
/** A PaymentIntent's authorization released by its cancel: "For PaymentIntents with a `status` of `requires_capture`, the
|
|
14
|
+
* remaining `amount_capturable` is automatically refunded" (docs.stripe.com/api/payment_intents/cancel), and since basil
|
|
15
|
+
* a cancellation makes no Refund: "`amount_captured` will be 0 instead of `nil` in payment cancellation flows",
|
|
16
|
+
* "`amount_refunded` will no longer be updated by these actions", "`refunded` will no longer be `true` for payment
|
|
17
|
+
* cancellation flows", and no charge.refunded is sent (docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-
|
|
18
|
+
* partial-capture-and-payment-cancellation-flow). The charge stays uncaptured; nothing is written as an event. */
|
|
19
|
+
export declare function cancelAuthorization(ctx: SemanticsContext, ch: Row): Promise<Row>;
|
|
20
|
+
/** An authorized charge captured, by the charge's capture or its PaymentIntent's: what is captured credits the balance.
|
|
21
|
+
* Written as charge.captured, "Occurs whenever a previously uncaptured charge is captured" (docs.stripe.com/api/events/types).
|
|
22
|
+
* A partial capture releases the rest with no Refund and leaves amount_refunded and refunded as they were: "The following
|
|
23
|
+
* flows no longer result in a `Refund` object created and linked to the payment: Partial capture", "`amount_refunded`
|
|
24
|
+
* will no longer be updated by these actions", and "There will only be a single balance transaction for partial captures"
|
|
25
|
+
* (docs.stripe.com/changelog/basil/2025-03-31/remove-refund-from-partial-capture-and-payment-cancellation-flow).
|
|
26
|
+
* The caller has asked the machine whether it may capture. */
|
|
27
|
+
export declare function captureAuthorization(ctx: SemanticsContext, ch: Row, toCapture: number, _operationId: string): Promise<Row>;
|
|
28
|
+
export declare const charges: Record<string, Semantics>;
|