@aglyn/tenant-data-admin 1.2.0 → 1.3.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/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@aglyn/tenant-data-admin",
3
- "version": "1.2.0",
3
+ "version": "1.3.0",
4
4
  "license": "Apache-2.0",
5
5
  "homepage": "https://aglyn.com",
6
6
  "repository": {
@@ -25,12 +25,12 @@
25
25
  "./package.json": "./package.json"
26
26
  },
27
27
  "dependencies": {
28
- "@aglyn/aglyn": "1.2.0",
29
- "@aglyn/shared-util-email": "1.2.0",
30
- "@aglyn/shared-util-fbserver": "1.2.0",
31
- "@aglyn/shared-util-first-touch": "1.2.0",
32
- "@aglyn/shared-util-http": "1.2.0",
33
- "@aglyn/shared-util-tools": "1.2.0",
28
+ "@aglyn/aglyn": "1.3.0",
29
+ "@aglyn/shared-util-email": "1.3.0",
30
+ "@aglyn/shared-util-fbserver": "1.3.0",
31
+ "@aglyn/shared-util-first-touch": "1.3.0",
32
+ "@aglyn/shared-util-http": "1.3.0",
33
+ "@aglyn/shared-util-tools": "1.3.0",
34
34
  "@msgpack/msgpack": "^3.1.3",
35
35
  "@swc/helpers": "0.5.23",
36
36
  "sharp": "^0.35.5",
@@ -27,6 +27,10 @@ export declare function requestThreeDSecureFor(use: CardAuthenticationUse): Requ
27
27
  * request's own fields in the `URLSearchParams` it builds.
28
28
  */
29
29
  export declare function cardAuthenticationParams(use: CardAuthenticationUse): Record<string, string>;
30
+ /** The param on an Invoice, whose PaymentIntent reads its options from `payment_settings`. */
31
+ export declare const INVOICE_REQUEST_THREE_D_SECURE_PARAM = "payment_settings[payment_method_options][card][request_three_d_secure]";
32
+ /** The same choice for an Invoice raised in this one's place. */
33
+ export declare function invoiceCardAuthenticationParams(use: CardAuthenticationUse): Record<string, string>;
30
34
  /**
31
35
  * The same params for a Checkout Session, chosen by its `mode`: a
32
36
  * `subscription` or `setup` session keeps the card for off-session charges,
@@ -52,6 +52,12 @@
52
52
  [REQUEST_THREE_D_SECURE_PARAM]: requestThreeDSecureFor(use)
53
53
  };
54
54
  }
55
+ /** The param on an Invoice, whose PaymentIntent reads its options from `payment_settings`. */ export const INVOICE_REQUEST_THREE_D_SECURE_PARAM = 'payment_settings[payment_method_options][card][request_three_d_secure]';
56
+ /** The same choice for an Invoice raised in this one's place. */ export function invoiceCardAuthenticationParams(use) {
57
+ return {
58
+ [INVOICE_REQUEST_THREE_D_SECURE_PARAM]: requestThreeDSecureFor(use)
59
+ };
60
+ }
55
61
  /**
56
62
  * The same params for a Checkout Session, chosen by its `mode`: a
57
63
  * `subscription` or `setup` session keeps the card for off-session charges,
@@ -1 +1 @@
1
- {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/stripe-card-authentication.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * 3-D SECURE, AT ONE SEAM (AGL-3356, AGL-3360).\n *\n * Every card payment and every card saved on Aglyn asks Stripe for 3-D\n * Secure through this one function: the workspace's own SetupIntent, and\n * every Checkout Session a plugin opens for a site's customer (storefront,\n * cart, draft order, POS, reservation, booking deposit, marketplace).\n *\n * TWO ANSWERS, by what the card is for:\n *\n * - `one-time`: `automatic`. Stripe authenticates when the issuer requires\n * it (SCA) or when Radar asks (a \"request 3D Secure\" rule). A shopper is\n * not challenged for a routine purchase, and a merchant's Radar rules can\n * still raise the bar. This is Stripe's default today; sending it\n * explicitly keeps the choice ours if the default moves.\n * - `off-session`: `any`. The card is kept and charged later with nobody\n * present (a membership renewal, the workspace's own plan). Authenticating\n * once now is what lets the issuer approve the unattended renewals, and it\n * moves fraud liability to the issuer. A card without 3DS still works.\n *\n * ONE CHALLENGE PER PAYMENT. The parameter is the whole request: Checkout\n * and `confirmSetup` run the challenge themselves when Stripe answers\n * `requires_action`, and a subscription's first invoice is authenticated\n * by the same step that saves the card. Nothing here adds a second prompt.\n *\n * Pure and dependency-free, so every plugin and the console share it\n * without a bundle cost.\n *=========================================*/\n\n/** What the card is being collected for. */\nexport type CardAuthenticationUse = 'one-time' | 'off-session'\n\n/** The value Stripe's `request_three_d_secure` takes. */\nexport type RequestThreeDSecure = 'automatic' | 'any'\n\n/** The param name, identical on PaymentIntents, SetupIntents and Checkout Sessions. */\nexport const REQUEST_THREE_D_SECURE_PARAM =\n 'payment_method_options[card][request_three_d_secure]'\n\n/** `automatic` for a one-time payment, `any` for a card kept for later. */\nexport function requestThreeDSecureFor(\n use: CardAuthenticationUse,\n): RequestThreeDSecure {\n return use === 'off-session' ? 'any' : 'automatic'\n}\n\n/**\n * The form-encoded params to spread into a Stripe request body, beside the\n * request's own fields in the `URLSearchParams` it builds.\n */\nexport function cardAuthenticationParams(\n use: CardAuthenticationUse,\n): Record<string, string> {\n return { [REQUEST_THREE_D_SECURE_PARAM]: requestThreeDSecureFor(use) }\n}\n\n/**\n * The same params for a Checkout Session, chosen by its `mode`: a\n * `subscription` or `setup` session keeps the card for off-session charges,\n * a `payment` session does not.\n */\nexport function checkoutSessionCardAuthenticationParams(\n mode: 'payment' | 'subscription' | 'setup',\n): Record<string, string> {\n return cardAuthenticationParams(mode === 'payment' ? 'one-time' : 'off-session')\n}\n"],"names":["REQUEST_THREE_D_SECURE_PARAM","requestThreeDSecureFor","use","cardAuthenticationParams","checkoutSessionCardAuthenticationParams","mode"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA2B2C,GAE3C,0CAA0C,GAM1C,qFAAqF,GACrF,OAAO,MAAMA,+BACX,uDAAsD;AAExD,yEAAyE,GACzE,OAAO,SAASC,uBACdC,GAA0B;IAE1B,OAAOA,QAAQ,gBAAgB,QAAQ;AACzC;AAEA;;;CAGC,GACD,OAAO,SAASC,yBACdD,GAA0B;IAE1B,OAAO;QAAE,CAACF,6BAA6B,EAAEC,uBAAuBC;IAAK;AACvE;AAEA;;;;CAIC,GACD,OAAO,SAASE,wCACdC,IAA0C;IAE1C,OAAOF,yBAAyBE,SAAS,YAAY,aAAa;AACpE"}
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/stripe-card-authentication.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/*==========================================\n * 3-D SECURE, AT ONE SEAM (AGL-3356, AGL-3360).\n *\n * Every card payment and every card saved on Aglyn asks Stripe for 3-D\n * Secure through this one function: the workspace's own SetupIntent, and\n * every Checkout Session a plugin opens for a site's customer (storefront,\n * cart, draft order, POS, reservation, booking deposit, marketplace).\n *\n * TWO ANSWERS, by what the card is for:\n *\n * - `one-time`: `automatic`. Stripe authenticates when the issuer requires\n * it (SCA) or when Radar asks (a \"request 3D Secure\" rule). A shopper is\n * not challenged for a routine purchase, and a merchant's Radar rules can\n * still raise the bar. This is Stripe's default today; sending it\n * explicitly keeps the choice ours if the default moves.\n * - `off-session`: `any`. The card is kept and charged later with nobody\n * present (a membership renewal, the workspace's own plan). Authenticating\n * once now is what lets the issuer approve the unattended renewals, and it\n * moves fraud liability to the issuer. A card without 3DS still works.\n *\n * ONE CHALLENGE PER PAYMENT. The parameter is the whole request: Checkout\n * and `confirmSetup` run the challenge themselves when Stripe answers\n * `requires_action`, and a subscription's first invoice is authenticated\n * by the same step that saves the card. Nothing here adds a second prompt.\n *\n * Pure and dependency-free, so every plugin and the console share it\n * without a bundle cost.\n *=========================================*/\n\n/** What the card is being collected for. */\nexport type CardAuthenticationUse = 'one-time' | 'off-session'\n\n/** The value Stripe's `request_three_d_secure` takes. */\nexport type RequestThreeDSecure = 'automatic' | 'any'\n\n/** The param name, identical on PaymentIntents, SetupIntents and Checkout Sessions. */\nexport const REQUEST_THREE_D_SECURE_PARAM =\n 'payment_method_options[card][request_three_d_secure]'\n\n/** `automatic` for a one-time payment, `any` for a card kept for later. */\nexport function requestThreeDSecureFor(\n use: CardAuthenticationUse,\n): RequestThreeDSecure {\n return use === 'off-session' ? 'any' : 'automatic'\n}\n\n/**\n * The form-encoded params to spread into a Stripe request body, beside the\n * request's own fields in the `URLSearchParams` it builds.\n */\nexport function cardAuthenticationParams(\n use: CardAuthenticationUse,\n): Record<string, string> {\n return { [REQUEST_THREE_D_SECURE_PARAM]: requestThreeDSecureFor(use) }\n}\n\n/** The param on an Invoice, whose PaymentIntent reads its options from `payment_settings`. */\nexport const INVOICE_REQUEST_THREE_D_SECURE_PARAM =\n 'payment_settings[payment_method_options][card][request_three_d_secure]'\n\n/** The same choice for an Invoice raised in this one's place. */\nexport function invoiceCardAuthenticationParams(\n use: CardAuthenticationUse,\n): Record<string, string> {\n return { [INVOICE_REQUEST_THREE_D_SECURE_PARAM]: requestThreeDSecureFor(use) }\n}\n\n/**\n * The same params for a Checkout Session, chosen by its `mode`: a\n * `subscription` or `setup` session keeps the card for off-session charges,\n * a `payment` session does not.\n */\nexport function checkoutSessionCardAuthenticationParams(\n mode: 'payment' | 'subscription' | 'setup',\n): Record<string, string> {\n return cardAuthenticationParams(mode === 'payment' ? 'one-time' : 'off-session')\n}\n"],"names":["REQUEST_THREE_D_SECURE_PARAM","requestThreeDSecureFor","use","cardAuthenticationParams","INVOICE_REQUEST_THREE_D_SECURE_PARAM","invoiceCardAuthenticationParams","checkoutSessionCardAuthenticationParams","mode"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED;;;;;;;;;;;;;;;;;;;;;;;;;;;2CA2B2C,GAE3C,0CAA0C,GAM1C,qFAAqF,GACrF,OAAO,MAAMA,+BACX,uDAAsD;AAExD,yEAAyE,GACzE,OAAO,SAASC,uBACdC,GAA0B;IAE1B,OAAOA,QAAQ,gBAAgB,QAAQ;AACzC;AAEA;;;CAGC,GACD,OAAO,SAASC,yBACdD,GAA0B;IAE1B,OAAO;QAAE,CAACF,6BAA6B,EAAEC,uBAAuBC;IAAK;AACvE;AAEA,4FAA4F,GAC5F,OAAO,MAAME,uCACX,yEAAwE;AAE1E,+DAA+D,GAC/D,OAAO,SAASC,gCACdH,GAA0B;IAE1B,OAAO;QAAE,CAACE,qCAAqC,EAAEH,uBAAuBC;IAAK;AAC/E;AAEA;;;;CAIC,GACD,OAAO,SAASI,wCACdC,IAA0C;IAE1C,OAAOJ,yBAAyBI,SAAS,YAAY,aAAa;AACpE"}
@@ -0,0 +1,81 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */
17
+ /** A payment method flattened for a billing card: staff's, the workspace's, or a purchase. */
18
+ export interface StripePaymentMethodSummary {
19
+ type: string | null;
20
+ brand: string | null;
21
+ last4: string | null;
22
+ expMonth: number | null;
23
+ expYear: number | null;
24
+ /** Link and the wallet methods identify by email, not a PAN. */
25
+ email: string | null;
26
+ }
27
+ /**
28
+ * Subscription statuses Stripe will actually bill against. A cancelled
29
+ * subscription's method is stale and must never outrank a live one.
30
+ *
31
+ * AGL-1715-EXEMPT: a deliberate SUPERSET of `isLiveSubscriptionStatus` — it
32
+ * adds `unpaid`. Different question. That predicate answers "may this org open
33
+ * a subscription", where an unpaid one must not block a new sale; this answers
34
+ * "which subscription is Stripe billing against, so whose payment method is
35
+ * the live one", and an unpaid subscription still has the card that failed on
36
+ * it. Sharing the list would show a stale method on exactly the orgs in
37
+ * dunning — the ones looking at this card. `stripe-payment-method.spec.ts`
38
+ * pins `unpaid` deliberately; do not converge them.
39
+ *
40
+ * EXPORTED because `/api/billing/profile` asks the identical question when it
41
+ * decides whether detaching the last card would break a renewal, and whether a
42
+ * subscription's own default payment method outranks the customer's. A third
43
+ * copy of the same four words is exactly the drift AGL-1715 exists to stop.
44
+ */
45
+ export declare const LIVE_SUBSCRIPTION_STATUSES: string[];
46
+ /**
47
+ * Shape an expanded Stripe PaymentMethod (AGL-940).
48
+ *
49
+ * Deliberately not card-only: Checkout offers Link, Amazon Pay, Cash App and
50
+ * Klarna, and those have no `.card` — reading it was why a Link method
51
+ * rendered as "No payment method". `pm[pm.type]` reaches whichever
52
+ * sub-object the type names.
53
+ *
54
+ * Returns null for an UNEXPANDED value too: without `expand[]` Stripe sends
55
+ * the id as a bare string, and treating that truthy string as a method
56
+ * yields an all-null object that renders as a blank chip rather than an
57
+ * honest "none".
58
+ */
59
+ export declare function describeStripePaymentMethod(pm: unknown): StripePaymentMethodSummary | null;
60
+ /** What a charge against a workspace's billing customer needs to know first. */
61
+ export interface BillingDetails {
62
+ /** The method a charge would use, or null when there is none on file. */
63
+ paymentMethodId: string | null;
64
+ /** That method, described, when Stripe sent it expanded. */
65
+ method: StripePaymentMethodSummary | null;
66
+ /** Whether a billing address names a country: sales tax is computed from it. */
67
+ hasAddress: boolean;
68
+ }
69
+ /**
70
+ * The card on file and the address for one billing customer.
71
+ *
72
+ * The effective default is the one Billing shows: a live subscription's own
73
+ * default outranks the customer's, because Stripe charges that one and
74
+ * Checkout routinely sets it while leaving `invoice_settings` empty (AGL-940).
75
+ * Reading only the customer would tell a workspace paying by that card that
76
+ * it has none.
77
+ *
78
+ * `null` when the customer cannot be read, which is not the same answer as
79
+ * "no card": the caller says "try again", not "add one".
80
+ */
81
+ export declare function readBillingDetails(secretKey: string, customerId: string): Promise<BillingDetails | null>;
@@ -0,0 +1,113 @@
1
+ /**
2
+ * @license
3
+ * Copyright 2026 Aglyn LLC
4
+ *
5
+ * Licensed under the Apache License, Version 2.0 (the "License");
6
+ * you may not use this file except in compliance with the License.
7
+ * You may obtain a copy of the License at
8
+ *
9
+ * http://www.apache.org/licenses/LICENSE-2.0
10
+ *
11
+ * Unless required by applicable law or agreed to in writing, software
12
+ * distributed under the License is distributed on an "AS IS" BASIS,
13
+ * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
14
+ * See the License for the specific language governing permissions and
15
+ * limitations under the License.
16
+ */ /** A payment method flattened for a billing card: staff's, the workspace's, or a purchase. */ /**
17
+ * Subscription statuses Stripe will actually bill against. A cancelled
18
+ * subscription's method is stale and must never outrank a live one.
19
+ *
20
+ * AGL-1715-EXEMPT: a deliberate SUPERSET of `isLiveSubscriptionStatus` — it
21
+ * adds `unpaid`. Different question. That predicate answers "may this org open
22
+ * a subscription", where an unpaid one must not block a new sale; this answers
23
+ * "which subscription is Stripe billing against, so whose payment method is
24
+ * the live one", and an unpaid subscription still has the card that failed on
25
+ * it. Sharing the list would show a stale method on exactly the orgs in
26
+ * dunning — the ones looking at this card. `stripe-payment-method.spec.ts`
27
+ * pins `unpaid` deliberately; do not converge them.
28
+ *
29
+ * EXPORTED because `/api/billing/profile` asks the identical question when it
30
+ * decides whether detaching the last card would break a renewal, and whether a
31
+ * subscription's own default payment method outranks the customer's. A third
32
+ * copy of the same four words is exactly the drift AGL-1715 exists to stop.
33
+ */ export const LIVE_SUBSCRIPTION_STATUSES = [
34
+ 'active',
35
+ 'trialing',
36
+ 'past_due',
37
+ 'unpaid'
38
+ ];
39
+ /**
40
+ * Shape an expanded Stripe PaymentMethod (AGL-940).
41
+ *
42
+ * Deliberately not card-only: Checkout offers Link, Amazon Pay, Cash App and
43
+ * Klarna, and those have no `.card` — reading it was why a Link method
44
+ * rendered as "No payment method". `pm[pm.type]` reaches whichever
45
+ * sub-object the type names.
46
+ *
47
+ * Returns null for an UNEXPANDED value too: without `expand[]` Stripe sends
48
+ * the id as a bare string, and treating that truthy string as a method
49
+ * yields an all-null object that renders as a blank chip rather than an
50
+ * honest "none".
51
+ */ export function describeStripePaymentMethod(pm) {
52
+ var _method_card, _ref, _ref1, _ref2, _ref3, _ref4, _ref5, _ref6;
53
+ var _method_billing_details;
54
+ if (!pm || typeof pm !== 'object') return null;
55
+ const method = pm;
56
+ const card = (_method_card = method['card']) != null ? _method_card : null;
57
+ const type = method['type'];
58
+ const detail = typeof type === 'string' ? method[type] : null;
59
+ return {
60
+ type: type != null ? type : card ? 'card' : null,
61
+ brand: (_ref = card == null ? void 0 : card.brand) != null ? _ref : null,
62
+ last4: (_ref1 = (_ref2 = card == null ? void 0 : card.last4) != null ? _ref2 : detail == null ? void 0 : detail.last4) != null ? _ref1 : null,
63
+ expMonth: (_ref3 = card == null ? void 0 : card.exp_month) != null ? _ref3 : null,
64
+ expYear: (_ref4 = card == null ? void 0 : card.exp_year) != null ? _ref4 : null,
65
+ email: (_ref5 = (_ref6 = detail == null ? void 0 : detail.email) != null ? _ref6 : (_method_billing_details = method['billing_details']) == null ? void 0 : _method_billing_details.email) != null ? _ref5 : null
66
+ };
67
+ }
68
+ /** A Stripe expandable reference read as its id, or null when unset. */ function expandableId(value) {
69
+ if (typeof value === 'string') return value || null;
70
+ const id = value == null ? void 0 : value.id;
71
+ return typeof id === 'string' && id ? id : null;
72
+ }
73
+ /**
74
+ * The card on file and the address for one billing customer.
75
+ *
76
+ * The effective default is the one Billing shows: a live subscription's own
77
+ * default outranks the customer's, because Stripe charges that one and
78
+ * Checkout routinely sets it while leaving `invoice_settings` empty (AGL-940).
79
+ * Reading only the customer would tell a workspace paying by that card that
80
+ * it has none.
81
+ *
82
+ * `null` when the customer cannot be read, which is not the same answer as
83
+ * "no card": the caller says "try again", not "add one".
84
+ */ export async function readBillingDetails(secretKey, customerId) {
85
+ var _ref, _ref1;
86
+ var _subscriptions_payload, _customer_payload_invoice_settings, _customer_payload, _customer_payload_address, _customer_payload1;
87
+ const read = async (path)=>{
88
+ const response = await fetch(`https://api.stripe.com/v1/${path}`, {
89
+ headers: {
90
+ Authorization: `Bearer ${secretKey}`
91
+ }
92
+ });
93
+ return {
94
+ ok: response.ok,
95
+ payload: await response.json().catch(()=>null)
96
+ };
97
+ };
98
+ const customerPath = encodeURIComponent(customerId);
99
+ const [customer, subscriptions] = await Promise.all([
100
+ read(`customers/${customerPath}?expand[]=invoice_settings.default_payment_method`),
101
+ read(`subscriptions?customer=${customerPath}&status=all&limit=20&expand[]=data.default_payment_method`)
102
+ ]);
103
+ if (!customer.ok) return null;
104
+ const billing = (Array.isArray((_subscriptions_payload = subscriptions.payload) == null ? void 0 : _subscriptions_payload.data) ? subscriptions.payload.data : []).find((subscription)=>LIVE_SUBSCRIPTION_STATUSES.includes(String(subscription == null ? void 0 : subscription.status)));
105
+ const chosen = (_ref = (_ref1 = billing == null ? void 0 : billing.default_payment_method) != null ? _ref1 : (_customer_payload = customer.payload) == null ? void 0 : (_customer_payload_invoice_settings = _customer_payload.invoice_settings) == null ? void 0 : _customer_payload_invoice_settings.default_payment_method) != null ? _ref : null;
106
+ return {
107
+ paymentMethodId: expandableId(chosen),
108
+ method: describeStripePaymentMethod(chosen),
109
+ hasAddress: Boolean((_customer_payload1 = customer.payload) == null ? void 0 : (_customer_payload_address = _customer_payload1.address) == null ? void 0 : _customer_payload_address.country)
110
+ };
111
+ }
112
+
113
+ //# sourceMappingURL=stripe-payment-method.js.map
@@ -0,0 +1 @@
1
+ {"version":3,"sources":["../../../../../../../../libs/tenant/data/admin/src/lib/server/stripe-payment-method.ts"],"sourcesContent":["/**\n * @license\n * Copyright 2026 Aglyn LLC\n *\n * Licensed under the Apache License, Version 2.0 (the \"License\");\n * you may not use this file except in compliance with the License.\n * You may obtain a copy of the License at\n *\n * http://www.apache.org/licenses/LICENSE-2.0\n *\n * Unless required by applicable law or agreed to in writing, software\n * distributed under the License is distributed on an \"AS IS\" BASIS,\n * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n * See the License for the specific language governing permissions and\n * limitations under the License.\n */\n\n/** A payment method flattened for a billing card: staff's, the workspace's, or a purchase. */\nexport interface StripePaymentMethodSummary {\n type: string | null\n brand: string | null\n last4: string | null\n expMonth: number | null\n expYear: number | null\n /** Link and the wallet methods identify by email, not a PAN. */\n email: string | null\n}\n\n/**\n * Subscription statuses Stripe will actually bill against. A cancelled\n * subscription's method is stale and must never outrank a live one.\n *\n * AGL-1715-EXEMPT: a deliberate SUPERSET of `isLiveSubscriptionStatus` — it\n * adds `unpaid`. Different question. That predicate answers \"may this org open\n * a subscription\", where an unpaid one must not block a new sale; this answers\n * \"which subscription is Stripe billing against, so whose payment method is\n * the live one\", and an unpaid subscription still has the card that failed on\n * it. Sharing the list would show a stale method on exactly the orgs in\n * dunning — the ones looking at this card. `stripe-payment-method.spec.ts`\n * pins `unpaid` deliberately; do not converge them.\n *\n * EXPORTED because `/api/billing/profile` asks the identical question when it\n * decides whether detaching the last card would break a renewal, and whether a\n * subscription's own default payment method outranks the customer's. A third\n * copy of the same four words is exactly the drift AGL-1715 exists to stop.\n */\nexport const LIVE_SUBSCRIPTION_STATUSES = [\n 'active',\n 'trialing',\n 'past_due',\n 'unpaid',\n]\n\n/**\n * Shape an expanded Stripe PaymentMethod (AGL-940).\n *\n * Deliberately not card-only: Checkout offers Link, Amazon Pay, Cash App and\n * Klarna, and those have no `.card` — reading it was why a Link method\n * rendered as \"No payment method\". `pm[pm.type]` reaches whichever\n * sub-object the type names.\n *\n * Returns null for an UNEXPANDED value too: without `expand[]` Stripe sends\n * the id as a bare string, and treating that truthy string as a method\n * yields an all-null object that renders as a blank chip rather than an\n * honest \"none\".\n */\nexport function describeStripePaymentMethod(\n pm: unknown,\n): StripePaymentMethodSummary | null {\n if (!pm || typeof pm !== 'object') return null\n const method = pm as Record<string, any>\n const card = method['card'] ?? null\n const type = method['type']\n const detail = typeof type === 'string' ? method[type] : null\n return {\n type: type ?? (card ? 'card' : null),\n brand: card?.brand ?? null,\n last4: card?.last4 ?? detail?.last4 ?? null,\n expMonth: card?.exp_month ?? null,\n expYear: card?.exp_year ?? null,\n email: detail?.email ?? method['billing_details']?.email ?? null,\n }\n}\n\n/** A Stripe expandable reference read as its id, or null when unset. */\nfunction expandableId(value: unknown): string | null {\n if (typeof value === 'string') return value || null\n const id = (value as { id?: unknown } | null | undefined)?.id\n return typeof id === 'string' && id ? id : null\n}\n\n/** What a charge against a workspace's billing customer needs to know first. */\nexport interface BillingDetails {\n /** The method a charge would use, or null when there is none on file. */\n paymentMethodId: string | null\n /** That method, described, when Stripe sent it expanded. */\n method: StripePaymentMethodSummary | null\n /** Whether a billing address names a country: sales tax is computed from it. */\n hasAddress: boolean\n}\n\n/**\n * The card on file and the address for one billing customer.\n *\n * The effective default is the one Billing shows: a live subscription's own\n * default outranks the customer's, because Stripe charges that one and\n * Checkout routinely sets it while leaving `invoice_settings` empty (AGL-940).\n * Reading only the customer would tell a workspace paying by that card that\n * it has none.\n *\n * `null` when the customer cannot be read, which is not the same answer as\n * \"no card\": the caller says \"try again\", not \"add one\".\n */\nexport async function readBillingDetails(\n secretKey: string,\n customerId: string,\n): Promise<BillingDetails | null> {\n const read = async (path: string) => {\n const response = await fetch(`https://api.stripe.com/v1/${path}`, {\n headers: { Authorization: `Bearer ${secretKey}` },\n })\n return { ok: response.ok, payload: (await response.json().catch(() => null)) as any }\n }\n const customerPath = encodeURIComponent(customerId)\n const [customer, subscriptions] = await Promise.all([\n read(`customers/${customerPath}?expand[]=invoice_settings.default_payment_method`),\n read(\n `subscriptions?customer=${customerPath}&status=all&limit=20&expand[]=data.default_payment_method`,\n ),\n ])\n if (!customer.ok) return null\n const billing = (\n Array.isArray(subscriptions.payload?.data) ? subscriptions.payload.data : []\n ).find((subscription: any) =>\n LIVE_SUBSCRIPTION_STATUSES.includes(String(subscription?.status)),\n )\n const chosen =\n billing?.default_payment_method ??\n customer.payload?.invoice_settings?.default_payment_method ??\n null\n return {\n paymentMethodId: expandableId(chosen),\n method: describeStripePaymentMethod(chosen),\n hasAddress: Boolean(customer.payload?.address?.country),\n }\n}\n"],"names":["LIVE_SUBSCRIPTION_STATUSES","describeStripePaymentMethod","pm","method","card","detail","type","brand","last4","expMonth","exp_month","expYear","exp_year","email","expandableId","value","id","readBillingDetails","secretKey","customerId","billing","subscriptions","customer","read","path","response","fetch","headers","Authorization","ok","payload","json","catch","customerPath","encodeURIComponent","Promise","all","Array","isArray","data","find","subscription","includes","String","status","chosen","default_payment_method","invoice_settings","paymentMethodId","hasAddress","Boolean","address","country"],"mappings":"AAAA;;;;;;;;;;;;;;;CAeC,GAED,4FAA4F,GAW5F;;;;;;;;;;;;;;;;;CAiBC,GACD,OAAO,MAAMA,6BAA6B;IACxC;IACA;IACA;IACA;CACD,CAAA;AAED;;;;;;;;;;;;CAYC,GACD,OAAO,SAASC,4BACdC,EAAW;QAIEC,oBAMJC,4BAGAC;QAAiBF;IAX1B,IAAI,CAACD,MAAM,OAAOA,OAAO,UAAU,OAAO;IAC1C,MAAMC,SAASD;IACf,MAAME,QAAOD,eAAAA,MAAM,CAAC,OAAO,YAAdA,eAAkB;IAC/B,MAAMG,OAAOH,MAAM,CAAC,OAAO;IAC3B,MAAME,SAAS,OAAOC,SAAS,WAAWH,MAAM,CAACG,KAAK,GAAG;IACzD,OAAO;QACLA,IAAI,EAAEA,eAAAA,OAASF,OAAO,SAAS;QAC/BG,KAAK,UAAEH,wBAAAA,KAAMG,KAAK,mBAAI;QACtBC,KAAK,GAAEJ,iBAAAA,wBAAAA,KAAMI,KAAK,oBAAIH,0BAAAA,OAAQG,KAAK,YAA5BJ,QAAgC;QACvCK,QAAQ,WAAEL,wBAAAA,KAAMM,SAAS,oBAAI;QAC7BC,OAAO,WAAEP,wBAAAA,KAAMQ,QAAQ,oBAAI;QAC3BC,KAAK,GAAER,iBAAAA,0BAAAA,OAAQQ,KAAK,qBAAIV,0BAAAA,MAAM,CAAC,kBAAkB,qBAAzBA,wBAA2BU,KAAK,YAAjDR,QAAqD;IAC9D;AACF;AAEA,sEAAsE,GACtE,SAASS,aAAaC,KAAc;IAClC,IAAI,OAAOA,UAAU,UAAU,OAAOA,SAAS;IAC/C,MAAMC,KAAMD,yBAAD,AAACA,MAA+CC,EAAE;IAC7D,OAAO,OAAOA,OAAO,YAAYA,KAAKA,KAAK;AAC7C;AAYA;;;;;;;;;;;CAWC,GACD,OAAO,eAAeC,mBACpBC,SAAiB,EACjBC,UAAkB;QAsBhBC;QALcC,wBAMdC,oCAAAA,mBAKoBA,2BAAAA;IA1BtB,MAAMC,OAAO,OAAOC;QAClB,MAAMC,WAAW,MAAMC,MAAM,CAAC,0BAA0B,EAAEF,MAAM,EAAE;YAChEG,SAAS;gBAAEC,eAAe,CAAC,OAAO,EAAEV,WAAW;YAAC;QAClD;QACA,OAAO;YAAEW,IAAIJ,SAASI,EAAE;YAAEC,SAAU,MAAML,SAASM,IAAI,GAAGC,KAAK,CAAC,IAAM;QAAc;IACtF;IACA,MAAMC,eAAeC,mBAAmBf;IACxC,MAAM,CAACG,UAAUD,cAAc,GAAG,MAAMc,QAAQC,GAAG,CAAC;QAClDb,KAAK,CAAC,UAAU,EAAEU,aAAa,iDAAiD,CAAC;QACjFV,KACE,CAAC,uBAAuB,EAAEU,aAAa,yDAAyD,CAAC;KAEpG;IACD,IAAI,CAACX,SAASO,EAAE,EAAE,OAAO;IACzB,MAAMT,UAAU,AACdiB,CAAAA,MAAMC,OAAO,EAACjB,yBAAAA,cAAcS,OAAO,qBAArBT,uBAAuBkB,IAAI,IAAIlB,cAAcS,OAAO,CAACS,IAAI,GAAG,EAAE,AAAD,EAC3EC,IAAI,CAAC,CAACC,eACNzC,2BAA2B0C,QAAQ,CAACC,OAAOF,gCAAAA,aAAcG,MAAM;IAEjE,MAAMC,UACJzB,gBAAAA,2BAAAA,QAAS0B,sBAAsB,qBAC/BxB,oBAAAA,SAASQ,OAAO,sBAAhBR,qCAAAA,kBAAkByB,gBAAgB,qBAAlCzB,mCAAoCwB,sBAAsB,YAD1D1B,OAEA;IACF,OAAO;QACL4B,iBAAiBlC,aAAa+B;QAC9B1C,QAAQF,4BAA4B4C;QACpCI,YAAYC,SAAQ5B,qBAAAA,SAASQ,OAAO,sBAAhBR,4BAAAA,mBAAkB6B,OAAO,qBAAzB7B,0BAA2B8B,OAAO;IACxD;AACF"}