@volter/twin-stripe 0.1.2 → 2.0.0
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 +64 -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 +73 -0
- package/dist/src/manifest.d.ts +2 -0
- package/dist/src/manifest.js +1065 -0
- package/dist/src/screens/checkout.d.ts +31 -0
- package/dist/src/screens/checkout.js +241 -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 +214 -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 +93 -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 +201 -0
- package/dist/src/semantics/checkout.d.ts +15 -0
- package/dist/src/semantics/checkout.js +303 -0
- package/dist/src/semantics/connect.d.ts +5 -0
- package/dist/src/semantics/connect.js +476 -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 +541 -0
- package/dist/src/semantics/issuing.d.ts +13 -0
- package/dist/src/semantics/issuing.js +570 -0
- package/dist/src/semantics/ledger.d.ts +54 -0
- package/dist/src/semantics/ledger.js +181 -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 +138 -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 +78 -0
- package/dist/src/semantics/shared.js +192 -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-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 +5052 -0
- package/dist/src/stripe-conformance.d.ts +41 -0
- package/dist/src/stripe-conformance.js +96 -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 +388 -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 +326 -0
- package/dist/src/stripe-shared.d.ts +106 -0
- package/dist/src/stripe-shared.js +273 -0
- package/dist/src/stripe-twin.d.ts +155 -0
- package/dist/src/stripe-twin.js +1226 -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 +10 -0
- package/dist/src/stripe-version.js +285 -0
- package/dist/test-fixtures/stripe-known-deviations.json +105 -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 +3740 -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 +31 -9
- package/src/manifest.ts +1097 -0
- package/src/screens/checkout.tsx +252 -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 +218 -0
- package/src/screens/public-details.tsx +105 -0
- package/src/semantics/after-payment.ts +113 -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 +211 -0
- package/src/semantics/checkout.ts +297 -0
- package/src/semantics/connect.ts +471 -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 +541 -0
- package/src/semantics/issuing.ts +585 -0
- package/src/semantics/ledger.ts +216 -0
- package/src/semantics/payment-intents.ts +420 -0
- package/src/semantics/payment-links.ts +148 -0
- package/src/semantics/payment-methods.ts +143 -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 +215 -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-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 +1456 -222
- package/src/stripe-conformance.ts +6 -5
- package/src/stripe-connector.ts +68 -40
- package/src/stripe-emit.ts +14 -7
- package/src/stripe-events.ts +94 -36
- 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 +263 -38
- package/src/stripe-shared.ts +294 -0
- package/src/stripe-twin.ts +429 -5325
- package/src/stripe-ui-conformance.ts +70 -107
- package/src/stripe-ui-structure.ts +124 -348
- package/src/stripe-version.ts +278 -0
- package/test-fixtures/stripe-known-deviations.json +2 -7
- package/test-fixtures/stripe-openapi-operations.json +1188 -2855
- package/src/stripe-form.ts +0 -35
|
@@ -0,0 +1,570 @@
|
|
|
1
|
+
import { emptySpendingControls, normalizeSpendingControls, nextStripeEventId, persistStripeEvent, spendingControlsViolation } from "../stripe-twin.js";
|
|
2
|
+
import { requestAuthorizationDecision, STRIPE_WEBHOOK_FALLBACK_SECRET, stripeEventMatches } from "../stripe-events.js";
|
|
3
|
+
import { at, created, fail, filePurposeRefused, list, newest, send, where } from "./shared.js";
|
|
4
|
+
import { balanceOf } from "./ledger.js";
|
|
5
|
+
const CH = 'issuing.cardholder';
|
|
6
|
+
/** The id of a card's cardholder: the card answers the cardholder in full (the served spec's issuing.card.cardholder is
|
|
7
|
+
* the Cardholder object, not an id); its id is read from it for filtering and for the objects that name it by id. */
|
|
8
|
+
export const holderId = (c) => (typeof c.cardholder === 'string' ? c.cardholder : String(c.cardholder?.id ?? ''));
|
|
9
|
+
const CARD = 'issuing.card';
|
|
10
|
+
const AUTH = 'issuing.authorization';
|
|
11
|
+
const TXN = 'issuing.transaction';
|
|
12
|
+
const DSP = 'issuing.dispute';
|
|
13
|
+
const TOK = 'issuing.token';
|
|
14
|
+
const PD = 'issuing.personalization_design';
|
|
15
|
+
// ── cardholders ──
|
|
16
|
+
const createCardholder = async (ctx) => {
|
|
17
|
+
const params = ctx.params;
|
|
18
|
+
if (params.name === undefined || params.name === '')
|
|
19
|
+
return fail(ctx, 'Missing required param: name.', 400, 'parameter_missing');
|
|
20
|
+
const chType = typeof params.type === 'string' ? params.type : '';
|
|
21
|
+
if (chType !== 'individual' && chType !== 'company')
|
|
22
|
+
return fail(ctx, "Invalid type: must be one of 'individual' or 'company'.", 400, 'parameter_invalid_string_enum');
|
|
23
|
+
const billing = params.billing && typeof params.billing === 'object' ? params.billing : undefined;
|
|
24
|
+
if (!billing || !billing.address || typeof billing.address !== 'object')
|
|
25
|
+
return fail(ctx, 'Missing required param: billing[address].', 400, 'parameter_missing');
|
|
26
|
+
const controls = normalizeSpendingControls(params.spending_controls, null);
|
|
27
|
+
if (controls.error)
|
|
28
|
+
return send(ctx, controls.error);
|
|
29
|
+
return ctx.reply(await created(ctx, CH, { ...params, spending_controls: controls.controls ?? emptySpendingControls() }, {
|
|
30
|
+
status: 'active', livemode: false, metadata: {}, phone_number: params.phone_number ?? null,
|
|
31
|
+
email: params.email ?? null, requirements: { disabled_reason: null, past_due: [] },
|
|
32
|
+
}));
|
|
33
|
+
};
|
|
34
|
+
/** A requested move of a state field the machine declares, legal or refused; a value the machine
|
|
35
|
+
* does not name is written as given, as the hand-written route did. */
|
|
36
|
+
function requestedMove(ctx, resource, operationId, current, values) {
|
|
37
|
+
const to = ctx.params.status;
|
|
38
|
+
if (typeof to !== 'string' || !values.includes(to))
|
|
39
|
+
return undefined;
|
|
40
|
+
const refused = ctx.legal(resource, 'status', operationId, current, to);
|
|
41
|
+
return refused ? ctx.refuse(refused) : undefined;
|
|
42
|
+
}
|
|
43
|
+
const updateCardholder = async (ctx) => {
|
|
44
|
+
const id = at(ctx, 'cardholder');
|
|
45
|
+
const ch = ctx.get(CH, id);
|
|
46
|
+
if (!ch)
|
|
47
|
+
return fail(ctx, `No such cardholder: '${id}'`, 404, 'resource_missing');
|
|
48
|
+
const controls = normalizeSpendingControls(ctx.params.spending_controls, null);
|
|
49
|
+
if (controls.error)
|
|
50
|
+
return send(ctx, controls.error);
|
|
51
|
+
const refused = requestedMove(ctx, CH, 'PostIssuingCardholdersCardholder', ch.status, ['active', 'inactive', 'blocked']);
|
|
52
|
+
if (refused)
|
|
53
|
+
return refused;
|
|
54
|
+
const updated = await ctx.write(CH, id, controls.controls ? { ...ctx.params, spending_controls: controls.controls } : ctx.params, 'issuing_cardholder.updated');
|
|
55
|
+
// each of the cardholder's cards answers it as it now stands
|
|
56
|
+
for (const card of ctx.rowsRaw(CARD).filter((c) => holderId(c) === id))
|
|
57
|
+
await ctx.write(CARD, String(card.id), { cardholder: updated }, 'issuing_card.cardholder_synced');
|
|
58
|
+
return ctx.reply(updated);
|
|
59
|
+
};
|
|
60
|
+
// ── cards: a virtual card is active at once, a physical one inactive until shipped ──
|
|
61
|
+
const createCard = async (ctx) => {
|
|
62
|
+
const params = ctx.params;
|
|
63
|
+
const cardholder = typeof params.cardholder === 'string' ? params.cardholder : '';
|
|
64
|
+
if (!cardholder)
|
|
65
|
+
return fail(ctx, 'Missing required param: cardholder.', 400, 'parameter_missing');
|
|
66
|
+
if (!ctx.get(CH, cardholder))
|
|
67
|
+
return fail(ctx, `No such cardholder: '${cardholder}'`, 400, 'resource_missing');
|
|
68
|
+
if (params.currency === undefined || params.currency === '')
|
|
69
|
+
return fail(ctx, 'Missing required param: currency.', 400, 'parameter_missing');
|
|
70
|
+
const cardType = typeof params.type === 'string' ? params.type : '';
|
|
71
|
+
if (cardType !== 'virtual' && cardType !== 'physical')
|
|
72
|
+
return fail(ctx, "Invalid type: must be one of 'virtual' or 'physical'.", 400, 'parameter_invalid_string_enum');
|
|
73
|
+
const last4 = String(4242 + ctx.rowsRaw(CARD, { withDeleted: true }).length + 1).slice(-4);
|
|
74
|
+
const controls = normalizeSpendingControls(params.spending_controls, typeof params.currency === 'string' ? params.currency : null);
|
|
75
|
+
if (controls.error)
|
|
76
|
+
return send(ctx, controls.error);
|
|
77
|
+
return ctx.reply(await created(ctx, CARD, { ...params, cardholder: ctx.get(CH, cardholder), spending_controls: controls.controls ?? emptySpendingControls() }, {
|
|
78
|
+
status: cardType === 'virtual' ? 'active' : 'inactive', livemode: false, metadata: {},
|
|
79
|
+
brand: 'Visa', last4, exp_month: 12, exp_year: 2030, cancellation_reason: null,
|
|
80
|
+
}));
|
|
81
|
+
};
|
|
82
|
+
// a card list filters on the cardholder's id, the card answering the cardholder in full
|
|
83
|
+
const listCards = async (ctx) => list(ctx, CARD, where(ctx, newest(ctx, CARD), {
|
|
84
|
+
cardholder: (c, v) => holderId(c) === v,
|
|
85
|
+
status: (c, v) => c.status === v,
|
|
86
|
+
type: (c, v) => c.type === v,
|
|
87
|
+
last4: (c, v) => c.last4 === v,
|
|
88
|
+
}));
|
|
89
|
+
const updateCard = async (ctx) => {
|
|
90
|
+
const id = at(ctx, 'card');
|
|
91
|
+
const card = ctx.get(CARD, id);
|
|
92
|
+
if (!card)
|
|
93
|
+
return fail(ctx, `No such card: '${id}'`, 404, 'resource_missing');
|
|
94
|
+
if (ctx.params.status !== undefined && !['active', 'inactive', 'canceled'].includes(String(ctx.params.status)))
|
|
95
|
+
return issuingRefusal(ctx, 'card_status');
|
|
96
|
+
const controls = normalizeSpendingControls(ctx.params.spending_controls, typeof card.currency === 'string' ? card.currency : null);
|
|
97
|
+
if (controls.error)
|
|
98
|
+
return send(ctx, controls.error);
|
|
99
|
+
const refused = requestedMove(ctx, CARD, 'PostIssuingCardsCard', card.status, ['active', 'inactive', 'canceled']);
|
|
100
|
+
if (refused)
|
|
101
|
+
return refused;
|
|
102
|
+
return ctx.reply(await ctx.write(CARD, id, controls.controls ? { ...ctx.params, spending_controls: controls.controls } : ctx.params, 'issuing_card.updated'));
|
|
103
|
+
};
|
|
104
|
+
// ── authorizations ──
|
|
105
|
+
/** An authorization as every egress carries it: its card embedded in full. */
|
|
106
|
+
function withCard(ctx, a) {
|
|
107
|
+
const out = { ...a };
|
|
108
|
+
if (typeof out.card === 'string') {
|
|
109
|
+
const card = ctx.get(CARD, out.card);
|
|
110
|
+
if (card)
|
|
111
|
+
out.card = card;
|
|
112
|
+
}
|
|
113
|
+
return out;
|
|
114
|
+
}
|
|
115
|
+
const authMissing = (ctx, id) => fail(ctx, `No such authorization: '${id}'`, 404, 'resource_missing');
|
|
116
|
+
const listAuthorizations = async (ctx) => list(ctx, AUTH, where(ctx, newest(ctx, AUTH), {
|
|
117
|
+
card: (a, v) => a.card === v,
|
|
118
|
+
cardholder: (a, v) => a.cardholder === v,
|
|
119
|
+
status: (a, v) => a.status === v,
|
|
120
|
+
}).map((a) => withCard(ctx, a)));
|
|
121
|
+
const retrieveAuthorization = async (ctx) => {
|
|
122
|
+
const a = ctx.get(AUTH, at(ctx, 'authorization'));
|
|
123
|
+
return a ? ctx.reply(withCard(ctx, a)) : authMissing(ctx, at(ctx, 'authorization'));
|
|
124
|
+
};
|
|
125
|
+
const updateAuthorization = async (ctx) => {
|
|
126
|
+
const id = at(ctx, 'authorization');
|
|
127
|
+
if (!ctx.get(AUTH, id))
|
|
128
|
+
return authMissing(ctx, id);
|
|
129
|
+
return ctx.reply(await ctx.write(AUTH, id, ctx.params, 'issuing_authorization.updated'));
|
|
130
|
+
};
|
|
131
|
+
/** One request_history entry; the authorization code is derived from the request time (Stripe's is not unique either). */
|
|
132
|
+
function historyEntry(o) {
|
|
133
|
+
return {
|
|
134
|
+
amount: o.amount, amount_details: null, approved: o.approved,
|
|
135
|
+
authorization_code: o.approved ? `S${String(100000 + (o.createdSec % 900000))}` : null,
|
|
136
|
+
created: o.createdSec, currency: o.currency,
|
|
137
|
+
merchant_amount: o.merchantAmount, merchant_currency: o.merchantCurrency,
|
|
138
|
+
network_risk_score: null, reason: o.reason, reason_message: o.reasonMessage,
|
|
139
|
+
requested_at: o.createdSec,
|
|
140
|
+
};
|
|
141
|
+
}
|
|
142
|
+
/** The test helper's default merchant, under any merchant_data the caller gives. */
|
|
143
|
+
function merchantData(param) {
|
|
144
|
+
const base = {
|
|
145
|
+
category: 'general', category_code: '5399', city: 'San Francisco', country: 'US',
|
|
146
|
+
name: 'Twin Test Merchant', network_id: '1234567890', postal_code: '94103', state: 'CA',
|
|
147
|
+
tax_id: null, terminal_id: null, url: null,
|
|
148
|
+
};
|
|
149
|
+
if (param && typeof param === 'object' && !Array.isArray(param))
|
|
150
|
+
Object.assign(base, param);
|
|
151
|
+
return base;
|
|
152
|
+
}
|
|
153
|
+
/** A capture: an Issuing transaction (negative: it debits) and the issuing balance's debit. */
|
|
154
|
+
async function capture(ctx, authId, auth, amountCents) {
|
|
155
|
+
const currency = typeof auth.currency === 'string' ? auth.currency : 'usd';
|
|
156
|
+
const bt = await created(ctx, 'balance_transaction', {}, {
|
|
157
|
+
amount: -amountCents, currency, fee: 0, net: -amountCents, type: 'issuing_transaction',
|
|
158
|
+
status: 'available', balance_type: 'issuing', reporting_category: 'issuing_transaction',
|
|
159
|
+
available_on: ctx.now(), fee_details: [],
|
|
160
|
+
});
|
|
161
|
+
const txn = await created(ctx, TXN, { authorization: authId, card: auth.card, cardholder: auth.cardholder }, {
|
|
162
|
+
type: 'capture', amount: -amountCents, currency,
|
|
163
|
+
merchant_amount: -amountCents, merchant_currency: typeof auth.merchant_currency === 'string' ? auth.merchant_currency : currency,
|
|
164
|
+
merchant_data: auth.merchant_data ?? merchantData(undefined),
|
|
165
|
+
livemode: false, metadata: {}, dispute: null, wallet: null, network_data: null,
|
|
166
|
+
amount_details: null, purchase_details: null, balance_transaction: bt.id,
|
|
167
|
+
});
|
|
168
|
+
return { txnId: String(txn.id), btId: String(bt.id) };
|
|
169
|
+
}
|
|
170
|
+
/** The card's stored id (an embedded card answers with its id). */
|
|
171
|
+
const cardId = (auth) => (auth.card && typeof auth.card === 'object' ? auth.card.id : auth.card);
|
|
172
|
+
/** Issuing refusals of a request no story sends: an unknown card status or authorization method, and a capture of an
|
|
173
|
+
* authorization that is not approved and pending. */
|
|
174
|
+
function issuingRefusal(ctx, what, auth) {
|
|
175
|
+
switch (what) {
|
|
176
|
+
case 'card_status': return fail(ctx, "Invalid status: must be one of 'active', 'inactive', or 'canceled'.", 400, 'parameter_invalid_string_enum');
|
|
177
|
+
case 'authorization_method': return fail(ctx, "Invalid authorization_method: must be one of 'chip', 'contactless', 'keyed_in', 'online', or 'swipe'.", 400, 'parameter_invalid_string_enum');
|
|
178
|
+
case 'not_capturable': return fail(ctx, `This authorization cannot be captured because it is not an approved pending authorization (status: ${String(auth?.status)}, approved: ${auth?.approved === true}).`, 400);
|
|
179
|
+
}
|
|
180
|
+
}
|
|
181
|
+
/** A partial approval's refusal: "You can specify the amount you want to approve by setting the amount in the webhook
|
|
182
|
+
* response body or the approve call" only "When an authorization is partially authorized, the is_amount_controllable
|
|
183
|
+
* field on the authorization request is set to true" (docs.stripe.com/issuing/purchases/authorizations), and never a
|
|
184
|
+
* credit. Answers the refusal, or undefined when the amount may be approved. */
|
|
185
|
+
function partialApprovalRefused(ctx, auth) {
|
|
186
|
+
if (Math.trunc(Number(ctx.params.amount) || 0) <= 0)
|
|
187
|
+
return fail(ctx, 'Invalid integer: amount must be a positive integer.', 400, 'parameter_invalid_integer');
|
|
188
|
+
if (auth.pending_request?.is_amount_controllable !== true)
|
|
189
|
+
return fail(ctx, 'amount may only be provided when the authorization was presented with is_amount_controllable.', 400);
|
|
190
|
+
return undefined;
|
|
191
|
+
}
|
|
192
|
+
// the (deprecated but real) API decision on a pending authorization: it lands in request_history
|
|
193
|
+
// as the webhook's answer would, consumes the pending request, and an approval captures
|
|
194
|
+
function decide(approved) {
|
|
195
|
+
return async (ctx) => {
|
|
196
|
+
const id = at(ctx, 'authorization');
|
|
197
|
+
const auth = ctx.get(AUTH, id);
|
|
198
|
+
if (!auth)
|
|
199
|
+
return authMissing(ctx, id);
|
|
200
|
+
const finalized = { status: 400, code: 'authorization_already_finalized', message: `This authorization has already been finalized (status ${String(auth.status)}).` };
|
|
201
|
+
// a webhook-approved authorization is decided, though still pending
|
|
202
|
+
if (auth.approved === true)
|
|
203
|
+
return ctx.refuse(finalized);
|
|
204
|
+
const refused = ctx.legal(AUTH, 'status', approved ? 'PostIssuingAuthorizationsAuthorizationApprove' : 'PostIssuingAuthorizationsAuthorizationDecline', auth.status, undefined, id);
|
|
205
|
+
if (refused)
|
|
206
|
+
return ctx.refuse(refused);
|
|
207
|
+
// a partial approval only for an amount-controllable presentment, and never a credit
|
|
208
|
+
const badAmount = approved && ctx.params.amount !== undefined ? partialApprovalRefused(ctx, auth) : undefined;
|
|
209
|
+
if (badAmount)
|
|
210
|
+
return badAmount;
|
|
211
|
+
const decidedAmount = approved && ctx.params.amount !== undefined ? Math.trunc(Number(ctx.params.amount) || 0) : Number(auth.amount) || 0;
|
|
212
|
+
const currency = typeof auth.currency === 'string' ? auth.currency : 'usd';
|
|
213
|
+
const history = Array.isArray(auth.request_history) ? auth.request_history : [];
|
|
214
|
+
// an approval holds the funds and waits for the merchant's capture; a decline closes it
|
|
215
|
+
// (docs.stripe.com/issuing/purchases/authorizations, docs.stripe.com/issuing/funding/balance)
|
|
216
|
+
const hold = approved ? await holdFor(ctx, id, decidedAmount, currency) : null;
|
|
217
|
+
return ctx.reply(await ctx.write(AUTH, id, {
|
|
218
|
+
...(approved ? {} : { status: 'closed' }), approved, pending_request: null,
|
|
219
|
+
...(approved && ctx.params.amount !== undefined ? { amount: decidedAmount } : {}),
|
|
220
|
+
request_history: [...history, historyEntry({
|
|
221
|
+
amount: decidedAmount, currency, approved, reason: approved ? 'webhook_approved' : 'webhook_declined', reasonMessage: null,
|
|
222
|
+
createdSec: Number(ctx.now()), merchantAmount: Number(auth.merchant_amount) || decidedAmount,
|
|
223
|
+
merchantCurrency: typeof auth.merchant_currency === 'string' ? auth.merchant_currency : currency,
|
|
224
|
+
})],
|
|
225
|
+
...(hold ? { balance_transactions: [...(Array.isArray(auth.balance_transactions) ? auth.balance_transactions : []), hold.id] } : {}),
|
|
226
|
+
}, 'issuing_authorization.updated'));
|
|
227
|
+
};
|
|
228
|
+
}
|
|
229
|
+
/** The real-time window: "If Stripe doesn't receive your approve or decline response within 2 seconds, the
|
|
230
|
+
* Authorization is automatically approved or declined based on your timeout settings"
|
|
231
|
+
* (docs.stripe.com/issuing/controls/real-time-authorizations). */
|
|
232
|
+
const REALTIME_WINDOW_SECONDS = 2;
|
|
233
|
+
/** Time's decision on a real-time request no one answered, caught up to the World's clock: once its window has ended,
|
|
234
|
+
* a pending authorization whose issuing_authorization.request went unanswered, and that no approve or decline decided,
|
|
235
|
+
* is decided automatically, its request_history reason webhook_timeout ("webhook_timeout for all other failure modes",
|
|
236
|
+
* the same page, beside webhook_error for a response Stripe cannot process).
|
|
237
|
+
* Where the documentation stops and the twin decides: the timeout setting is the Dashboard's, which the API does not
|
|
238
|
+
* answer, and the twin's is to decline; the window is measured in World time from the authorization's created. */
|
|
239
|
+
export async function lapseRealtimeRequests(ctx) {
|
|
240
|
+
const now = Number(ctx.now());
|
|
241
|
+
const requested = new Set(ctx.rowsRaw('event').filter((e) => e._stripe_type === 'issuing_authorization.request').map((e) => String(e.data?.object?.id ?? '')));
|
|
242
|
+
for (const a of ctx.rowsRaw(AUTH)) {
|
|
243
|
+
if (a.status !== 'pending' || a.approved === true || !a.pending_request || !requested.has(String(a.id)))
|
|
244
|
+
continue;
|
|
245
|
+
const at = Number(a.created) + REALTIME_WINDOW_SECONDS;
|
|
246
|
+
if (now < at)
|
|
247
|
+
continue;
|
|
248
|
+
const id = String(a.id);
|
|
249
|
+
const currency = typeof a.currency === 'string' ? a.currency : 'usd';
|
|
250
|
+
const amount = Number(a.amount) || 0;
|
|
251
|
+
ctx.legal(AUTH, 'status', ctx.call.operation.id, 'pending', 'closed', id, 'time');
|
|
252
|
+
await ctx.write(AUTH, id, {
|
|
253
|
+
status: 'closed', approved: false, pending_request: null,
|
|
254
|
+
request_history: [...(Array.isArray(a.request_history) ? a.request_history : []), historyEntry({
|
|
255
|
+
amount, currency, approved: false, reason: 'webhook_timeout', reasonMessage: null, createdSec: at,
|
|
256
|
+
merchantAmount: Number(a.merchant_amount) || amount, merchantCurrency: typeof a.merchant_currency === 'string' ? a.merchant_currency : currency,
|
|
257
|
+
})],
|
|
258
|
+
}, 'issuing_authorization.updated');
|
|
259
|
+
}
|
|
260
|
+
}
|
|
261
|
+
/** An approval's hold: "If you approve the authorization, we deduct the `amount` from your Issuing balance and hold it
|
|
262
|
+
* in reserve until the authorization is either captured, voided, or expired without capture"
|
|
263
|
+
* (docs.stripe.com/issuing/purchases/authorizations). */
|
|
264
|
+
async function holdFor(ctx, authId, amount, currency) {
|
|
265
|
+
return created(ctx, 'balance_transaction', {}, {
|
|
266
|
+
amount: -amount, currency, fee: 0, net: -amount, type: 'issuing_authorization_hold',
|
|
267
|
+
status: 'available', balance_type: 'issuing', reporting_category: 'issuing_authorization_hold',
|
|
268
|
+
available_on: ctx.now(), fee_details: [], source: authId,
|
|
269
|
+
});
|
|
270
|
+
}
|
|
271
|
+
/** An authorization approved as it is presented, its amount held: approved and pending until the merchant captures. */
|
|
272
|
+
async function approvedAtOnce(ctx, subject, fields, held, entry) {
|
|
273
|
+
const hold = await holdFor(ctx, String(subject.id), held, String(fields.currency ?? 'usd'));
|
|
274
|
+
return ctx.reply(await created(ctx, AUTH, subject, { ...fields, amount: held, status: 'pending', approved: true, pending_request: null, request_history: [entry], balance_transactions: [hold.id] }));
|
|
275
|
+
}
|
|
276
|
+
/** An authorization as the platform's real-time answer makes it: approved (in part, only when the request was
|
|
277
|
+
* amount-controllable), declined, or declined for an answer Stripe cannot read (docs.stripe.com/issuing/controls/
|
|
278
|
+
* real-time-authorizations: the response's `approved` and `amount`; webhook_error "if we can't process your response"). */
|
|
279
|
+
async function answeredByEndpoint(ctx, outcome, o) {
|
|
280
|
+
if (outcome.kind === 'approved') {
|
|
281
|
+
const held = o.controllable && outcome.amount !== undefined ? outcome.amount : o.amount;
|
|
282
|
+
return approvedAtOnce(ctx, o.subject, o.fields, held, o.entry({ amount: held, approved: true, reason: 'webhook_approved', reasonMessage: null }));
|
|
283
|
+
}
|
|
284
|
+
return outcome.kind === 'declined' ? o.decline('webhook_declined', null) : o.decline('webhook_error', outcome.message);
|
|
285
|
+
}
|
|
286
|
+
const present = async (ctx) => {
|
|
287
|
+
const params = ctx.params;
|
|
288
|
+
const card = typeof params.card === 'string' ? params.card : '';
|
|
289
|
+
if (!card)
|
|
290
|
+
return fail(ctx, 'Missing required param: card.', 400, 'parameter_missing');
|
|
291
|
+
const c = ctx.get(CARD, card);
|
|
292
|
+
if (!c)
|
|
293
|
+
return fail(ctx, `No such card: '${card}'`, 400, 'resource_missing');
|
|
294
|
+
if (params.amount === undefined)
|
|
295
|
+
return fail(ctx, 'Missing required param: amount.', 400, 'parameter_missing');
|
|
296
|
+
const amount = Math.trunc(Number(params.amount) || 0);
|
|
297
|
+
const currency = String(params.currency ?? c.currency ?? 'usd');
|
|
298
|
+
const createdSec = Number(ctx.now());
|
|
299
|
+
const cardholderId = holderId(c);
|
|
300
|
+
const merchant = merchantData(params.merchant_data);
|
|
301
|
+
const isAmountControllable = params.is_amount_controllable === true;
|
|
302
|
+
const authMethod = typeof params.authorization_method === 'string' ? params.authorization_method : 'online';
|
|
303
|
+
if (!['chip', 'contactless', 'keyed_in', 'online', 'swipe'].includes(authMethod))
|
|
304
|
+
return issuingRefusal(ctx, 'authorization_method');
|
|
305
|
+
const merchantAmount = params.merchant_amount !== undefined ? Math.trunc(Number(params.merchant_amount) || 0) : amount;
|
|
306
|
+
const merchantCurrency = typeof params.merchant_currency === 'string' ? params.merchant_currency : currency;
|
|
307
|
+
const authId = ctx.mint(AUTH);
|
|
308
|
+
const baseFields = {
|
|
309
|
+
amount, amount_details: null, authorization_method: authMethod,
|
|
310
|
+
balance_transactions: [], transactions: [],
|
|
311
|
+
currency, fleet: null, fuel: null, livemode: false,
|
|
312
|
+
merchant_amount: merchantAmount, merchant_currency: merchantCurrency, merchant_data: merchant,
|
|
313
|
+
metadata: params.metadata && typeof params.metadata === 'object' ? params.metadata : {},
|
|
314
|
+
network_data: null,
|
|
315
|
+
verification_data: {
|
|
316
|
+
address_line1_check: 'not_provided', address_postal_code_check: 'not_provided',
|
|
317
|
+
authentication_exemption: null, cvc_check: 'match', expiry_check: 'match',
|
|
318
|
+
postal_code: null, three_d_secure: null,
|
|
319
|
+
},
|
|
320
|
+
wallet: null,
|
|
321
|
+
};
|
|
322
|
+
const subject = { id: authId, card, cardholder: cardholderId };
|
|
323
|
+
const entry = (o) => historyEntry({ ...o, currency, createdSec, merchantAmount, merchantCurrency });
|
|
324
|
+
const decline = async (reason, reasonMessage) => ctx.reply(await created(ctx, AUTH, subject, { ...baseFields, status: 'closed', approved: false, pending_request: null, request_history: [entry({ amount, approved: false, reason, reasonMessage })] }));
|
|
325
|
+
if (c.status === 'canceled')
|
|
326
|
+
return decline('card_canceled', 'The card has been canceled.');
|
|
327
|
+
if (c.status !== 'active')
|
|
328
|
+
return decline('card_inactive', 'The card is inactive.');
|
|
329
|
+
// what earlier approved authorizations on the card (or cardholder) already spent, for the limits
|
|
330
|
+
const prior = (key, value) => ctx.rows(AUTH).filter((a) => a[key] === value && a.approved === true)
|
|
331
|
+
.map((a) => ({ amount: Number(a.amount) || 0, created: Number(a.created) || 0, category: String(a.merchant_data?.category ?? '') }));
|
|
332
|
+
const controlsOpts = { amount, category: String(merchant.category ?? ''), country: merchant.country == null ? null : String(merchant.country), nowSec: createdSec };
|
|
333
|
+
const cardholderRow = cardholderId ? ctx.get(CH, cardholderId) : undefined;
|
|
334
|
+
const violation = spendingControlsViolation(c.spending_controls, { ...controlsOpts, priorApproved: prior('card', card) }) ??
|
|
335
|
+
spendingControlsViolation(cardholderRow?.spending_controls, { ...controlsOpts, priorApproved: prior('cardholder', cardholderId) });
|
|
336
|
+
if (violation)
|
|
337
|
+
return decline('spending_controls', violation);
|
|
338
|
+
// an authorization is paid from the Issuing balance, and declined when it cannot cover it
|
|
339
|
+
// (docs.stripe.com/issuing/funding/balance)
|
|
340
|
+
if ((balanceOf(ctx).issuing.get(currency) ?? 0) < amount)
|
|
341
|
+
return decline('insufficient_funds', 'Your Issuing balance does not have enough funds for this authorization.');
|
|
342
|
+
const pendingRequest = {
|
|
343
|
+
amount, amount_details: null, currency, is_amount_controllable: isAmountControllable,
|
|
344
|
+
merchant_amount: merchantAmount, merchant_currency: merchantCurrency, network_risk_score: null,
|
|
345
|
+
};
|
|
346
|
+
const endpoint = ctx.rows('webhook_endpoint').find((w) => w.status === 'enabled' && stripeEventMatches(w.enabled_events, 'issuing_authorization.request'));
|
|
347
|
+
// no real-time enrollment: "If you don't have a real-time authorization webhook, we approve the authorization without
|
|
348
|
+
// sending the issuing_authorization.request" (docs.stripe.com/issuing/purchases/authorizations), its outcome
|
|
349
|
+
// card_active, "approved according to your default Issuing settings"
|
|
350
|
+
if (!endpoint)
|
|
351
|
+
return approvedAtOnce(ctx, subject, baseFields, amount, entry({ amount, approved: true, reason: 'card_active', reasonMessage: null }));
|
|
352
|
+
// the request event's authorization carries pending_request, non-null only during the request
|
|
353
|
+
const requestObject = withCard(ctx, { object: 'issuing.authorization', id: authId, created: createdSec, ...baseFields, card, cardholder: cardholderId, status: 'pending', approved: false, pending_request: pendingRequest, request_history: [] });
|
|
354
|
+
// the delivered request and the stored event are one event under one id
|
|
355
|
+
const requestEvent = { id: nextStripeEventId(ctx.root), object: 'event', type: 'issuing_authorization.request', created: createdSec, livemode: false, data: { object: requestObject } };
|
|
356
|
+
const version = ctx.call.request.headers.get('stripe-version') ?? undefined;
|
|
357
|
+
await persistStripeEvent('issuing_authorization.request', requestObject, ctx.root, ctx.occurredAt, version, undefined, requestEvent.id);
|
|
358
|
+
const secret = typeof endpoint.secret === 'string' && endpoint.secret ? endpoint.secret : STRIPE_WEBHOOK_FALLBACK_SECRET;
|
|
359
|
+
const outcome = await requestAuthorizationDecision(String(endpoint.url), requestEvent, secret);
|
|
360
|
+
// a request no one answered (the World refused the delivery, it failed, or it timed out) is not a decision: the
|
|
361
|
+
// authorization stays pending with its request, for the deprecated approve or decline "within the timeout window of
|
|
362
|
+
// the real-time authorization flow" (the served spec), until lapseRealtimeRequests decides it when the window ends
|
|
363
|
+
if (outcome.kind === 'timeout')
|
|
364
|
+
return ctx.reply(await created(ctx, AUTH, subject, { ...baseFields, status: 'pending', approved: false, request_history: [], pending_request: pendingRequest }));
|
|
365
|
+
return answeredByEndpoint(ctx, outcome, { subject, fields: baseFields, amount, controllable: isAmountControllable, entry, decline });
|
|
366
|
+
};
|
|
367
|
+
// capturing an approved pending authorization, up to what it still holds; it closes unless told not to
|
|
368
|
+
const captureAuthorization = async (ctx) => {
|
|
369
|
+
const id = at(ctx, 'authorization');
|
|
370
|
+
const auth = ctx.get(AUTH, id);
|
|
371
|
+
if (!auth)
|
|
372
|
+
return authMissing(ctx, id);
|
|
373
|
+
if (auth.approved !== true || auth.status !== 'pending')
|
|
374
|
+
return issuingRefusal(ctx, 'not_capturable', auth);
|
|
375
|
+
const closeAuthorization = ctx.params.close_authorization !== false;
|
|
376
|
+
const refused = ctx.legal(AUTH, 'status', 'PostTestHelpersIssuingAuthorizationsAuthorizationCapture', auth.status, closeAuthorization ? 'closed' : 'pending');
|
|
377
|
+
if (refused)
|
|
378
|
+
return ctx.refuse(refused);
|
|
379
|
+
const txns = Array.isArray(auth.transactions) ? auth.transactions : [];
|
|
380
|
+
const capturedSoFar = txns.map((t) => ctx.get(TXN, String(t))).reduce((s, t) => s + Math.abs(Number(t?.amount) || 0), 0);
|
|
381
|
+
const remaining = (Number(auth.amount) || 0) - capturedSoFar;
|
|
382
|
+
const captureAmount = ctx.params.capture_amount !== undefined ? Math.trunc(Number(ctx.params.capture_amount) || 0) : remaining;
|
|
383
|
+
if (captureAmount <= 0 || captureAmount > remaining)
|
|
384
|
+
return fail(ctx, 'Invalid capture_amount: must be a positive integer no greater than the uncaptured authorized amount.', 400, 'parameter_invalid_integer');
|
|
385
|
+
// the capture releases what the approval held and debits the transaction
|
|
386
|
+
const currency = typeof auth.currency === 'string' ? auth.currency : 'usd';
|
|
387
|
+
const release = await created(ctx, 'balance_transaction', {}, {
|
|
388
|
+
amount: captureAmount, currency, fee: 0, net: captureAmount, type: 'issuing_authorization_release',
|
|
389
|
+
status: 'available', balance_type: 'issuing', reporting_category: 'issuing_authorization_release',
|
|
390
|
+
available_on: ctx.now(), fee_details: [], source: id,
|
|
391
|
+
});
|
|
392
|
+
const captured = await capture(ctx, id, { ...auth, card: cardId(auth) }, captureAmount);
|
|
393
|
+
return ctx.reply(await ctx.write(AUTH, id, {
|
|
394
|
+
...(closeAuthorization ? { status: 'closed' } : {}),
|
|
395
|
+
transactions: [...txns, captured.txnId],
|
|
396
|
+
balance_transactions: [...(Array.isArray(auth.balance_transactions) ? auth.balance_transactions : []), release.id, captured.btId],
|
|
397
|
+
}, 'issuing_authorization.updated'));
|
|
398
|
+
};
|
|
399
|
+
// ── transactions ──
|
|
400
|
+
const updateTransaction = async (ctx) => {
|
|
401
|
+
const id = at(ctx, 'transaction');
|
|
402
|
+
if (!ctx.get(TXN, id))
|
|
403
|
+
return fail(ctx, `No such transaction: '${id}'`, 404, 'resource_missing');
|
|
404
|
+
return ctx.reply(await ctx.write(TXN, id, ctx.params, 'issuing_transaction.updated'));
|
|
405
|
+
};
|
|
406
|
+
// a settlement with no authorization before it still debits the issuing balance
|
|
407
|
+
const forceCapture = async (ctx) => {
|
|
408
|
+
const card = typeof ctx.params.card === 'string' ? ctx.params.card : '';
|
|
409
|
+
if (!card)
|
|
410
|
+
return fail(ctx, 'Missing required param: card.', 400, 'parameter_missing');
|
|
411
|
+
const c = ctx.get(CARD, card);
|
|
412
|
+
if (!c)
|
|
413
|
+
return fail(ctx, `No such card: '${card}'`, 400, 'resource_missing');
|
|
414
|
+
if (ctx.params.amount === undefined)
|
|
415
|
+
return fail(ctx, 'Missing required param: amount.', 400, 'parameter_missing');
|
|
416
|
+
const amount = Math.trunc(Number(ctx.params.amount) || 0);
|
|
417
|
+
if (amount <= 0)
|
|
418
|
+
return fail(ctx, 'Invalid integer: amount must be a positive integer.', 400, 'parameter_invalid_integer');
|
|
419
|
+
const currency = String(ctx.params.currency ?? c.currency ?? 'usd');
|
|
420
|
+
const bt = await created(ctx, 'balance_transaction', {}, {
|
|
421
|
+
amount: -amount, currency, fee: 0, net: -amount, type: 'issuing_transaction',
|
|
422
|
+
status: 'available', balance_type: 'issuing', reporting_category: 'issuing_transaction',
|
|
423
|
+
available_on: ctx.now(), fee_details: [],
|
|
424
|
+
});
|
|
425
|
+
return ctx.reply(await created(ctx, TXN, { card, cardholder: holderId(c) }, {
|
|
426
|
+
type: 'capture', amount: -amount, currency,
|
|
427
|
+
merchant_amount: -amount, merchant_currency: typeof ctx.params.merchant_currency === 'string' ? ctx.params.merchant_currency : currency,
|
|
428
|
+
merchant_data: merchantData(ctx.params.merchant_data),
|
|
429
|
+
authorization: null, dispute: null, balance_transaction: bt.id,
|
|
430
|
+
livemode: false, metadata: {}, wallet: null, network_data: null, amount_details: null, purchase_details: null,
|
|
431
|
+
}));
|
|
432
|
+
};
|
|
433
|
+
// ── disputes: opened against a transaction, unsubmitted until submitted ──
|
|
434
|
+
const disputeMissing = (ctx, id) => fail(ctx, `No such dispute: '${id}'`, 404, 'resource_missing');
|
|
435
|
+
const openDispute = async (ctx) => {
|
|
436
|
+
const txn = typeof ctx.params.transaction === 'string' ? ctx.params.transaction : '';
|
|
437
|
+
if (!txn)
|
|
438
|
+
return fail(ctx, 'Missing required param: transaction.', 400, 'parameter_missing');
|
|
439
|
+
const t = ctx.get(TXN, txn);
|
|
440
|
+
if (!t)
|
|
441
|
+
return fail(ctx, `No such transaction: '${txn}'`, 400, 'resource_missing');
|
|
442
|
+
const ev = ctx.params.evidence && typeof ctx.params.evidence === 'object' ? ctx.params.evidence : undefined;
|
|
443
|
+
if (!ev || ev.reason === undefined || ev.reason === '')
|
|
444
|
+
return fail(ctx, 'Missing required param: evidence[reason].', 400, 'parameter_missing');
|
|
445
|
+
const amount = ctx.params.amount !== undefined ? Math.trunc(Number(ctx.params.amount) || 0) : Math.abs(Number(t.amount) || 0);
|
|
446
|
+
return ctx.reply(await created(ctx, DSP, ctx.params, { status: 'unsubmitted', amount, currency: t.currency ?? 'usd', livemode: false, metadata: {}, balance_transactions: null }));
|
|
447
|
+
};
|
|
448
|
+
const submitDispute = async (ctx) => {
|
|
449
|
+
const id = at(ctx, 'dispute');
|
|
450
|
+
const d = ctx.get(DSP, id);
|
|
451
|
+
if (!d)
|
|
452
|
+
return disputeMissing(ctx, id);
|
|
453
|
+
const refused = ctx.legal(DSP, 'status', 'PostIssuingDisputesDisputeSubmit', d.status, undefined, id);
|
|
454
|
+
if (refused)
|
|
455
|
+
return ctx.refuse(refused);
|
|
456
|
+
return ctx.reply(await ctx.write(DSP, id, { status: 'submitted' }, 'issuing_dispute.submitted'));
|
|
457
|
+
};
|
|
458
|
+
const updateDispute = async (ctx) => {
|
|
459
|
+
const id = at(ctx, 'dispute');
|
|
460
|
+
if (!ctx.get(DSP, id))
|
|
461
|
+
return disputeMissing(ctx, id);
|
|
462
|
+
return ctx.reply(await ctx.write(DSP, id, ctx.params, 'issuing_dispute.updated'));
|
|
463
|
+
};
|
|
464
|
+
// ── network tokens: minted by the card network (the twin's mint is a test helper outside Stripe's
|
|
465
|
+
// surface); Stripe lets a token be set active, deleted or suspended ──
|
|
466
|
+
const updateToken = async (ctx) => {
|
|
467
|
+
const id = at(ctx, 'token');
|
|
468
|
+
const t = ctx.get(TOK, id);
|
|
469
|
+
if (!t)
|
|
470
|
+
return fail(ctx, `No such issuing token: '${id}'`, 404, 'resource_missing');
|
|
471
|
+
const status = typeof ctx.params.status === 'string' ? ctx.params.status : '';
|
|
472
|
+
if (!['active', 'deleted', 'suspended'].includes(status))
|
|
473
|
+
return fail(ctx, 'Invalid status: must be active, deleted, or suspended.', 400, 'parameter_invalid_string_enum');
|
|
474
|
+
const refused = ctx.legal(TOK, 'status', 'PostIssuingTokensToken', t.status, status);
|
|
475
|
+
if (refused)
|
|
476
|
+
return ctx.refuse(refused);
|
|
477
|
+
return ctx.reply(await ctx.write(TOK, id, { status }, 'issuing_token.updated'));
|
|
478
|
+
};
|
|
479
|
+
// ── personalization designs: in review until Stripe's review (the test helpers in test mode) decides ──
|
|
480
|
+
const designMissing = (ctx, id) => fail(ctx, `No such personalization design: '${id}'`, 404, 'resource_missing');
|
|
481
|
+
/** Stripe's physical bundles are its catalog, not the account's: the twin serves the one its reference publishes
|
|
482
|
+
* (docs.stripe.com/api/issuing/physical_bundles: "US Visa Credit White", standard, active, a card logo required and
|
|
483
|
+
* carrier text optional). Where the documentation stops and the twin decides: the catalog is that one bundle, and its
|
|
484
|
+
* second_line (required by the served spec, absent from the example) is optional. */
|
|
485
|
+
const PHYSICAL_BUNDLES = [
|
|
486
|
+
{ id: 'ics_NLuXJPDYSTjFON', object: 'issuing.physical_bundle', livemode: false, name: 'US Visa Credit White', features: { card_logo: 'required', carrier_text: 'optional', second_line: 'optional' }, status: 'active', type: 'standard' },
|
|
487
|
+
];
|
|
488
|
+
const listBundles = async (ctx) => ctx.reply({ object: 'list', url: '/v1/issuing/physical_bundles', has_more: false, data: PHYSICAL_BUNDLES.filter((b) => (ctx.params.status === undefined || b.status === ctx.params.status) && (ctx.params.type === undefined || b.type === ctx.params.type)) });
|
|
489
|
+
const retrieveBundle = async (ctx) => {
|
|
490
|
+
const b = PHYSICAL_BUNDLES.find((x) => x.id === at(ctx, 'physical_bundle'));
|
|
491
|
+
return b ? ctx.reply(b) : fail(ctx, `No such physical bundle: '${at(ctx, 'physical_bundle')}'`, 404, 'resource_missing');
|
|
492
|
+
};
|
|
493
|
+
const createDesign = async (ctx) => {
|
|
494
|
+
const bundle = typeof ctx.params.physical_bundle === 'string' ? ctx.params.physical_bundle : '';
|
|
495
|
+
if (!bundle)
|
|
496
|
+
return fail(ctx, 'Missing required param: physical_bundle.', 400, 'parameter_missing');
|
|
497
|
+
if (!PHYSICAL_BUNDLES.some((b) => b.id === bundle))
|
|
498
|
+
return fail(ctx, `No such physical bundle: '${bundle}'`, 400, 'resource_missing');
|
|
499
|
+
const logo = filePurposeRefused(ctx, 'card_logo', ['issuing_logo']);
|
|
500
|
+
if (logo)
|
|
501
|
+
return logo;
|
|
502
|
+
return ctx.reply(await created(ctx, PD, {}, {
|
|
503
|
+
livemode: false, status: 'review', physical_bundle: bundle,
|
|
504
|
+
name: ctx.params.name ?? null, lookup_key: ctx.params.lookup_key ?? null,
|
|
505
|
+
card_logo: ctx.params.card_logo ?? null, carrier_text: ctx.params.carrier_text ?? null,
|
|
506
|
+
preferences: { is_default: false, is_platform_default: null },
|
|
507
|
+
rejection_reasons: { card_logo: [], carrier_text: [] },
|
|
508
|
+
metadata: ctx.params.metadata && typeof ctx.params.metadata === 'object' ? ctx.params.metadata : {},
|
|
509
|
+
}));
|
|
510
|
+
};
|
|
511
|
+
const listDesigns = async (ctx) => list(ctx, PD, where(ctx, newest(ctx, PD), {
|
|
512
|
+
status: (d, v) => d.status === v,
|
|
513
|
+
lookup_keys: (d, v) => (Array.isArray(v) ? v.map(String).includes(String(d.lookup_key)) : String(d.lookup_key) === String(v)),
|
|
514
|
+
}));
|
|
515
|
+
const updateDesign = async (ctx) => {
|
|
516
|
+
const id = at(ctx, 'personalization_design');
|
|
517
|
+
if (!ctx.get(PD, id))
|
|
518
|
+
return designMissing(ctx, id);
|
|
519
|
+
const logo = filePurposeRefused(ctx, 'card_logo', ['issuing_logo']);
|
|
520
|
+
if (logo)
|
|
521
|
+
return logo;
|
|
522
|
+
return ctx.reply(await ctx.write(PD, id, ctx.params, 'personalization_design.updated'));
|
|
523
|
+
};
|
|
524
|
+
function review(action, operationId) {
|
|
525
|
+
return async (ctx) => {
|
|
526
|
+
const id = at(ctx, 'personalization_design');
|
|
527
|
+
const d = ctx.get(PD, id);
|
|
528
|
+
if (!d)
|
|
529
|
+
return designMissing(ctx, id);
|
|
530
|
+
const refused = ctx.legal(PD, 'status', operationId, d.status, undefined, id);
|
|
531
|
+
if (refused)
|
|
532
|
+
return ctx.refuse(refused);
|
|
533
|
+
const status = action === 'activate' ? 'active' : action === 'deactivate' ? 'inactive' : 'rejected';
|
|
534
|
+
// a rejection records its reasons: the reject helper's required rejection_reasons, "The reason(s) the
|
|
535
|
+
// personalization design was rejected" (the served spec), per card_logo and carrier_text
|
|
536
|
+
const given = ctx.params.rejection_reasons && typeof ctx.params.rejection_reasons === 'object' ? ctx.params.rejection_reasons : undefined;
|
|
537
|
+
if (action === 'reject' && !given)
|
|
538
|
+
return fail(ctx, 'Missing required param: rejection_reasons.', 400, 'parameter_missing');
|
|
539
|
+
const reasons = action === 'reject' ? { rejection_reasons: { card_logo: Array.isArray(given.card_logo) ? given.card_logo : [], carrier_text: Array.isArray(given.carrier_text) ? given.carrier_text : [] } } : {};
|
|
540
|
+
return ctx.reply(await ctx.write(PD, id, { status, ...reasons }, `personalization_design.${action}`));
|
|
541
|
+
};
|
|
542
|
+
}
|
|
543
|
+
export const issuing = {
|
|
544
|
+
PostIssuingCardholders: createCardholder,
|
|
545
|
+
PostIssuingCardholdersCardholder: updateCardholder,
|
|
546
|
+
PostIssuingCards: createCard,
|
|
547
|
+
GetIssuingCards: listCards,
|
|
548
|
+
PostIssuingCardsCard: updateCard,
|
|
549
|
+
GetIssuingAuthorizations: listAuthorizations,
|
|
550
|
+
GetIssuingAuthorizationsAuthorization: retrieveAuthorization,
|
|
551
|
+
PostIssuingAuthorizationsAuthorization: updateAuthorization,
|
|
552
|
+
PostIssuingAuthorizationsAuthorizationApprove: decide(true),
|
|
553
|
+
PostIssuingAuthorizationsAuthorizationDecline: decide(false),
|
|
554
|
+
PostTestHelpersIssuingAuthorizations: present,
|
|
555
|
+
PostTestHelpersIssuingAuthorizationsAuthorizationCapture: captureAuthorization,
|
|
556
|
+
PostIssuingTransactionsTransaction: updateTransaction,
|
|
557
|
+
PostTestHelpersIssuingTransactionsCreateForceCapture: forceCapture,
|
|
558
|
+
PostIssuingDisputes: openDispute,
|
|
559
|
+
PostIssuingDisputesDisputeSubmit: submitDispute,
|
|
560
|
+
PostIssuingDisputesDispute: updateDispute,
|
|
561
|
+
PostIssuingTokensToken: updateToken,
|
|
562
|
+
GetIssuingPhysicalBundles: listBundles,
|
|
563
|
+
GetIssuingPhysicalBundlesPhysicalBundle: retrieveBundle,
|
|
564
|
+
PostIssuingPersonalizationDesigns: createDesign,
|
|
565
|
+
GetIssuingPersonalizationDesigns: listDesigns,
|
|
566
|
+
PostIssuingPersonalizationDesignsPersonalizationDesign: updateDesign,
|
|
567
|
+
PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignActivate: review('activate', 'PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignActivate'),
|
|
568
|
+
PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignDeactivate: review('deactivate', 'PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignDeactivate'),
|
|
569
|
+
PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignReject: review('reject', 'PostTestHelpersIssuingPersonalizationDesignsPersonalizationDesignReject'),
|
|
570
|
+
};
|
|
@@ -0,0 +1,54 @@
|
|
|
1
|
+
import type { Semantics, SemanticsContext } from '@volter/world-core';
|
|
2
|
+
import { type Row } from './shared.js';
|
|
3
|
+
/** The connected account a request acts for, or undefined for the platform. */
|
|
4
|
+
export declare const actingAccount: (ctx: SemanticsContext) => string | undefined;
|
|
5
|
+
/** A captured charge's credit: its amount less the fee, pending two days unless the card (a number, or a test
|
|
6
|
+
* payment method or token named for it) settles at once. The
|
|
7
|
+
* caller mints the charge's id first and stores the returned id as the charge's balance_transaction. */
|
|
8
|
+
export declare function settleCharge(ctx: SemanticsContext, chargeId: string, amount: number, currency: string, card?: string): Promise<string>;
|
|
9
|
+
/** A refund's debit, at once, on the acting account's balance unless one is named (null names the platform). */
|
|
10
|
+
export declare function settleRefund(ctx: SemanticsContext, refundId: string, amount: number, currency: string, account?: string | null | undefined): Promise<string>;
|
|
11
|
+
/** What an account had available in a currency at a moment: every entry of its payments balance whose funds had come
|
|
12
|
+
* due by then. */
|
|
13
|
+
export declare function availableAt(ctx: SemanticsContext, account: string | undefined, currency: string, at: number): number;
|
|
14
|
+
/** The moments after `from` and up to `until` when funds of an account came due, in order: when a held refund can
|
|
15
|
+
* next be covered. */
|
|
16
|
+
export declare function fundsDueBetween(ctx: SemanticsContext, account: string | undefined, currency: string, from: number, until: number): number[];
|
|
17
|
+
/** A dispute's debit, at once: the disputed amount and the dispute fee (the twin's 1500 cents, Stripe's US $15). */
|
|
18
|
+
export declare function settleDispute(ctx: SemanticsContext, disputeId: string, amount: number, currency: string): Promise<string>;
|
|
19
|
+
/** A won dispute's credit, at once: the disputed amount returned (docs.stripe.com/disputes/how-disputes-work). Where the
|
|
20
|
+
* documentation stops and the twin decides: the dispute fee is not returned. */
|
|
21
|
+
export declare function settleDisputeWon(ctx: SemanticsContext, disputeId: string, amount: number, currency: string): Promise<string>;
|
|
22
|
+
/** An account's ledger entries an automatic payout has not yet paid out: every entry on its payments balance that no
|
|
23
|
+
* automatic payout took (the automatic payouts' own debits excluded), as stored. */
|
|
24
|
+
export declare function unpaidEntries(ctx: SemanticsContext, account: string | undefined): Row[];
|
|
25
|
+
/** An automatic payout's debit at `at`, and the entries it pays out marked with it, so the ledger lists them under
|
|
26
|
+
* the payout (docs.stripe.com/api/balance_transactions/list#balance_transaction_list-payout). */
|
|
27
|
+
export declare function settleAutomaticPayout(ctx: SemanticsContext, payoutId: string, amount: number, currency: string, account: string | undefined, at: number, entries: Row[]): Promise<string>;
|
|
28
|
+
/** A payout's debit (negative) or a cancellation's or reversal's credit (positive), at once, on the payout's account. */
|
|
29
|
+
export declare function settlePayout(ctx: SemanticsContext, payoutId: string, amount: number, currency: string, account?: string | null | undefined): Promise<string>;
|
|
30
|
+
/** A transfer's two entries: out of the platform's balance at once, into the destination's when `availableOn` comes
|
|
31
|
+
* (a plain transfer's funds are available already). Answers the platform's entry. */
|
|
32
|
+
export declare function settleTransfer(ctx: SemanticsContext, transferId: string, amount: number, currency: string, destination: string, availableOn?: number, fromPending?: boolean): Promise<string>;
|
|
33
|
+
/** A transfer reversal's two entries: back into the platform's balance, out of the destination's. */
|
|
34
|
+
export declare function settleTransferReversal(ctx: SemanticsContext, reversalId: string, amount: number, currency: string, destination: string): Promise<string>;
|
|
35
|
+
/** A direct charge's application fee: out of the connected account's balance, into the platform's. */
|
|
36
|
+
export declare function settleApplicationFee(ctx: SemanticsContext, feeId: string, amount: number, currency: string, account: string): Promise<string>;
|
|
37
|
+
/** A top-up's credit, to the payments balance or, with `destination_balance=issuing`, to Issuing's
|
|
38
|
+
* (docs.stripe.com/issuing/funding/balance). Where the documentation stops and the twin decides: a test-mode top-up
|
|
39
|
+
* is available at once. */
|
|
40
|
+
export declare function settleTopup(ctx: SemanticsContext, topupId: string, amount: number, currency: string, destination: string): Promise<string>;
|
|
41
|
+
/** Time's settlements, written: each entry on the acting account's balance whose funds came due by the World's clock
|
|
42
|
+
* moves pending → available (the clock's move the machine allows), so a settlement is recorded once. A read already
|
|
43
|
+
* sees it (asOf); the record is what lets Stripe's balance.available be sent once (stripe-server.ts, the drain).
|
|
44
|
+
* Answers the entries that moved. */
|
|
45
|
+
export declare function settleDueEntries(ctx: SemanticsContext): Promise<Row[]>;
|
|
46
|
+
/** An account's balance, by currency: what the clock has made available, what is still pending, and Issuing's own. */
|
|
47
|
+
export declare function balanceOf(ctx: SemanticsContext, account?: string | undefined): {
|
|
48
|
+
available: Map<string, number>;
|
|
49
|
+
pending: Map<string, number>;
|
|
50
|
+
issuing: Map<string, number>;
|
|
51
|
+
};
|
|
52
|
+
/** balance_insufficient when a payout or transfer would take more than the account has available in its currency. */
|
|
53
|
+
export declare function refusePayout(ctx: SemanticsContext, amount: number, currency: string, account?: string | undefined): Response | undefined;
|
|
54
|
+
export declare const ledger: Record<string, Semantics>;
|