@simplelayer/graniteer-core 0.3.14 → 0.3.15

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.
@@ -4,6 +4,7 @@ import { jwtVerify, createRemoteJWKSet } from 'jose';
4
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
5
  import { logOps } from '../ops.js';
6
6
  import { hasEntitlement } from '../entitlements.js';
7
+ import { findBaseItem, countBaseItems, hasAddonItems, isRenewalInvoice, invoiceCoversPeriod } from '../membershipSubscriptionItems.js';
7
8
  const corsHeaders = {
8
9
  'Access-Control-Allow-Origin': '*',
9
10
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -116,6 +117,49 @@ export async function handle(req, operator = {}) {
116
117
  return json(400, { ok: false, error: 'invalid_idempotency_key' });
117
118
  }
118
119
  const dryRun = !!body.dry_run;
120
+ // Refunds are disabled for this release (including dry-run estimates).
121
+ // Under the 2024-11-20.acacia Stripe API pinned above, subscription items
122
+ // carry no period fields, so every refund computed by this handler so far
123
+ // has silently been $0 -- the refund path has never actually moved money.
124
+ // Enabling it for real needs two fixes first: a second cancel+refund
125
+ // stacking on an already-refunded scheduled cancel over-refunds (nothing
126
+ // subtracts the prior refund from the new one), and undoing a scheduled
127
+ // cancel after its refund went out leaves the member with both the money
128
+ // and continued service. See _review-verdict-multi-item-4.md, blockers #1
129
+ // and #2. Fail closed here, before the idempotency row is claimed and
130
+ // before any Stripe call, so cancel WITHOUT refund (including with
131
+ // add-ons) is completely unaffected.
132
+ if (issueRefund) {
133
+ return json(400, {
134
+ ok: false,
135
+ error: 'refunds_disabled',
136
+ detail: 'Automatic refunds are disabled in this release; cancel without a refund and refund manually in Stripe.',
137
+ });
138
+ }
139
+ // Deletes the idempotency row claimed in step 3 below. Call this from any
140
+ // error return that happens AFTER that insert but BEFORE the Stripe
141
+ // mutation that the row is meant to record -- otherwise a client retry with
142
+ // the same idempotency_key sees { ok:true, duplicate:true } for a
143
+ // cancellation that never happened. No-op for dry runs, which never insert
144
+ // the row in the first place.
145
+ const releaseAuditRow = async () => {
146
+ if (dryRun)
147
+ return;
148
+ try {
149
+ const { error } = await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
150
+ if (error) {
151
+ await logOps(admin, 'membership_admin_action_release_failed', {
152
+ message: error.message, idempotency_key: idempotencyKey,
153
+ }, { severity: 'warning' });
154
+ }
155
+ }
156
+ catch (e) {
157
+ const msg = e instanceof Error ? e.message : String(e);
158
+ await logOps(admin, 'membership_admin_action_release_failed', {
159
+ message: msg, idempotency_key: idempotencyKey,
160
+ }, { severity: 'warning' });
161
+ }
162
+ };
119
163
  // 1. Live state re-check (concurrency guard).
120
164
  const { data: membership, error: mErr } = await admin
121
165
  .from('memberships')
@@ -156,8 +200,10 @@ export async function handle(req, operator = {}) {
156
200
  }
157
201
  }
158
202
  const stripeKey = Deno.env.get('STRIPE_SECRET_KEY');
159
- if (!stripeKey)
203
+ if (!stripeKey) {
204
+ await releaseAuditRow();
160
205
  return json(500, { ok: false, error: 'stripe_not_configured' });
206
+ }
161
207
  const stripe = new Stripe(stripeKey, { apiVersion: '2024-11-20.acacia' });
162
208
  // 4. Retrieve subscription.
163
209
  let sub;
@@ -166,14 +212,40 @@ export async function handle(req, operator = {}) {
166
212
  }
167
213
  catch (e) {
168
214
  const msg = e instanceof Error ? e.message : String(e);
215
+ await releaseAuditRow();
169
216
  return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
170
217
  }
171
- if (sub.items.data.length !== 1) {
172
- return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
218
+ const subForItems = sub;
219
+ const baseItem = findBaseItem(subForItems);
220
+ if (!baseItem) {
221
+ const nonAddonCount = countBaseItems(subForItems);
222
+ await releaseAuditRow();
223
+ return json(400, { ok: false, error: 'unexpected_item_count', detail: `${nonAddonCount} non-addon items` });
224
+ }
225
+ // Add-on items carry their own pricing that the base-item period-fraction
226
+ // refund math below does not account for, so an automated refund on a
227
+ // subscription with add-ons can under-refund the member. Block it (even on
228
+ // a dry run, so staff see this instead of a misleading estimate) and leave
229
+ // cancellation-without-refund untouched.
230
+ if (issueRefund && hasAddonItems(subForItems)) {
231
+ await releaseAuditRow();
232
+ return json(400, {
233
+ ok: false,
234
+ error: 'refund_blocked_with_addons',
235
+ detail: 'This subscription has add-ons; staff must refund manually in Stripe.',
236
+ });
237
+ }
238
+ const item = baseItem;
239
+ // Item-level current_period_start/end were only added to Stripe's API in
240
+ // 2025-03-31.basil; this function pins 2024-11-20.acacia, where an item may
241
+ // not carry them. Fall back to the subscription-level period (which acacia
242
+ // always returns) rather than silently computing refund math on undefined.
243
+ const periodStart = item.current_period_start ?? sub.current_period_start;
244
+ const periodEnd = item.current_period_end ?? sub.current_period_end;
245
+ if (typeof periodStart !== 'number' || typeof periodEnd !== 'number') {
246
+ await releaseAuditRow();
247
+ return json(400, { ok: false, error: 'period_unavailable' });
173
248
  }
174
- const item = sub.items.data[0];
175
- const periodStart = item.current_period_start;
176
- const periodEnd = item.current_period_end;
177
249
  // 5. Compute the timestamp to send to Stripe. This MUST always be strictly
178
250
  // future or Stripe rejects the cancel_at update — the safety floor below is
179
251
  // the fix for the bug where "today" (midnight) or a clamp to periodStart
@@ -203,17 +275,41 @@ export async function handle(req, operator = {}) {
203
275
  }
204
276
  catch (e) {
205
277
  const msg = e instanceof Error ? e.message : String(e);
278
+ await releaseAuditRow();
206
279
  return json(500, { ok: false, error: 'stripe_invoice_lookup_failed', detail: msg });
207
280
  }
208
281
  if (!invoice) {
209
- if (!dryRun) {
210
- try {
211
- await admin.from('membership_admin_actions').delete().eq('idempotency_key', idempotencyKey);
212
- }
213
- catch { /* non-fatal */ }
214
- }
282
+ await releaseAuditRow();
215
283
  return json(400, { ok: false, error: 'no_refundable_invoice' });
216
284
  }
285
+ // The refund math below prorates this invoice's amount_paid using the
286
+ // base item's full-period bounds. That is only valid when this invoice
287
+ // IS that full-period charge -- a renewal or the original subscription
288
+ // creation. Any other latest-paid invoice (e.g. a mid-cycle add-on
289
+ // charge) would under-refund the member, so refuse rather than guess.
290
+ if (!isRenewalInvoice(invoice)) {
291
+ await releaseAuditRow();
292
+ return json(400, {
293
+ ok: false,
294
+ error: 'refund_invoice_ambiguous',
295
+ detail: `latest paid invoice billing_reason is '${invoice.billing_reason ?? 'unknown'}', not a renewal invoice`,
296
+ });
297
+ }
298
+ // isRenewalInvoice only confirms the invoice is SHAPED like a full-period
299
+ // charge -- it says nothing about WHICH period. A past_due subscription
300
+ // (CANCELLABLE allows it) or the brief draft window right after a renewal
301
+ // can leave the latest PAID invoice as last period's while the current
302
+ // period is still unpaid. Prorating that stale invoice against the
303
+ // current period's bounds would over-refund the member, so also require
304
+ // one of its lines to actually cover the current period.
305
+ if (!invoiceCoversPeriod(invoice, periodStart)) {
306
+ await releaseAuditRow();
307
+ return json(400, {
308
+ ok: false,
309
+ error: 'refund_invoice_ambiguous',
310
+ detail: 'latest paid invoice has no line covering the current billing period',
311
+ });
312
+ }
217
313
  paymentIntent = invoice.payment_intent;
218
314
  const charge = paymentIntent?.latest_charge ?? null;
219
315
  const refundableCents = (invoice.amount_paid ?? 0) - (charge?.amount_refunded ?? 0);
@@ -265,7 +361,7 @@ export async function handle(req, operator = {}) {
265
361
  amount: refundCents,
266
362
  reason: 'requested_by_customer',
267
363
  metadata: { membership_id: membershipId, actor: callerEmail },
268
- }, { idempotencyKey });
364
+ }, { idempotencyKey: `${idempotencyKey}:refund` });
269
365
  stripeRefundId = refund.id;
270
366
  }
271
367
  catch (e) {
@@ -4,6 +4,7 @@ import { jwtVerify, createRemoteJWKSet } from 'jose';
4
4
  import { clientIp, checkRateLimit } from '../rateLimit.js';
5
5
  import { logOps } from '../ops.js';
6
6
  import { hasEntitlement } from '../entitlements.js';
7
+ import { findBaseItem, countBaseItems, hasAddonItems, matchesPlanPrice } from '../membershipSubscriptionItems.js';
7
8
  const corsHeaders = {
8
9
  'Access-Control-Allow-Origin': '*',
9
10
  'Access-Control-Allow-Headers': 'authorization, x-client-info, apikey, content-type',
@@ -186,12 +187,34 @@ export async function handle(req, operator = {}) {
186
187
  const msg = e instanceof Error ? e.message : String(e);
187
188
  return json(500, { ok: false, error: 'stripe_retrieve_failed', detail: msg });
188
189
  }
189
- if (sub.items.data.length !== 1) {
190
- return json(400, { ok: false, error: 'unexpected_item_count', detail: `${sub.items.data.length} items` });
190
+ const subForItems = sub;
191
+ const baseItem = findBaseItem(subForItems);
192
+ if (!baseItem) {
193
+ const nonAddonCount = countBaseItems(subForItems);
194
+ return json(400, { ok: false, error: 'unexpected_item_count', detail: `${nonAddonCount} non-addon items` });
195
+ }
196
+ // Item metadata is editable in the Stripe Dashboard (and by any future
197
+ // add-on writer), so once add-ons exist, findBaseItem's "only untagged
198
+ // item" rule is not enough on its own -- confirm the resolved item is
199
+ // actually still priced at the member's current plan before swapping its
200
+ // price. matchesPlanPrice checks price id first, falling back to product id
201
+ // (for inline price_data plans or a rotated catalog price), and fails
202
+ // closed if the plan has neither id stored. Subscriptions with no add-on
203
+ // items keep today's behavior exactly; this check only engages once a
204
+ // gc_addon-tagged item is present.
205
+ if (hasAddonItems(subForItems) && !matchesPlanPrice(baseItem, currentPlan)) {
206
+ return json(400, { ok: false, error: 'base_item_mismatch' });
207
+ }
208
+ const item = baseItem;
209
+ // Item-level current_period_start/end were only added to Stripe's API in
210
+ // 2025-03-31.basil; this function pins 2024-11-20.acacia, where an item may
211
+ // not carry them. Fall back to the subscription-level period (which acacia
212
+ // always returns) rather than silently computing estimates on undefined.
213
+ const periodStart = item.current_period_start ?? sub.current_period_start;
214
+ const periodEnd = item.current_period_end ?? sub.current_period_end;
215
+ if (typeof periodStart !== 'number' || typeof periodEnd !== 'number') {
216
+ return json(400, { ok: false, error: 'period_unavailable' });
191
217
  }
192
- const item = sub.items.data[0];
193
- const periodStart = item.current_period_start;
194
- const periodEnd = item.current_period_end;
195
218
  const nowUnix = Math.floor(Date.now() / 1000);
196
219
  // 6. Estimate-only proration math (same time-remaining-fraction approach as
197
220
  // admin-cancel-membership's refund estimate) — a heads-up for the admin.
@@ -250,21 +273,54 @@ export async function handle(req, operator = {}) {
250
273
  let invoiceId = null;
251
274
  let invoiceAmountCents = null;
252
275
  let invoiceStatus = null;
253
- try {
254
- const invoices = await stripe.invoices.list({ subscription: subscriptionId, limit: 1 });
255
- const latest = invoices.data[0];
256
- if (latest) {
257
- invoiceId = latest.id ?? null;
258
- invoiceAmountCents = latest.amount_due ?? latest.total ?? null;
259
- invoiceStatus = latest.status ?? null;
260
- }
261
- }
262
- catch (e) {
263
- const msg = e instanceof Error ? e.message : String(e);
264
- await logOps(admin, 'membership_plan_change_invoice_lookup_failed', {
265
- message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
276
+ const priorLatestInvoiceRef = sub.latest_invoice;
277
+ const priorLatestInvoiceId = priorLatestInvoiceRef
278
+ ? (typeof priorLatestInvoiceRef === 'string' ? priorLatestInvoiceRef : priorLatestInvoiceRef.id)
279
+ : null;
280
+ const latestInvoiceRef = updatedSub.latest_invoice;
281
+ const updatedLatestInvoiceId = latestInvoiceRef
282
+ ? (typeof latestInvoiceRef === 'string' ? latestInvoiceRef : latestInvoiceRef.id)
283
+ : null;
284
+ if (updatedLatestInvoiceId && updatedLatestInvoiceId === priorLatestInvoiceId) {
285
+ // always_invoice swept no pending proration into a new invoice, so
286
+ // latest_invoice still points at the pre-update (renewal) invoice. That
287
+ // invoice is not the authoritative record of this plan change -- report
288
+ // nothing rather than a misleading unrelated amount.
289
+ await logOps(admin, 'membership_plan_change_no_new_invoice', {
290
+ membership_id: membershipId, idempotency_key: idempotencyKey, invoice_id: updatedLatestInvoiceId,
266
291
  }, { severity: 'warning' });
267
292
  }
293
+ else {
294
+ try {
295
+ let latest = null;
296
+ if (updatedLatestInvoiceId) {
297
+ try {
298
+ latest = await stripe.invoices.retrieve(updatedLatestInvoiceId);
299
+ }
300
+ catch (e) {
301
+ const msg = e instanceof Error ? e.message : String(e);
302
+ await logOps(admin, 'membership_plan_change_invoice_retrieve_failed', {
303
+ message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
304
+ }, { severity: 'warning' });
305
+ }
306
+ }
307
+ if (!latest) {
308
+ const invoices = await stripe.invoices.list({ subscription: subscriptionId, limit: 1 });
309
+ latest = invoices.data[0];
310
+ }
311
+ if (latest) {
312
+ invoiceId = latest.id ?? null;
313
+ invoiceAmountCents = latest.amount_due ?? latest.total ?? null;
314
+ invoiceStatus = latest.status ?? null;
315
+ }
316
+ }
317
+ catch (e) {
318
+ const msg = e instanceof Error ? e.message : String(e);
319
+ await logOps(admin, 'membership_plan_change_invoice_lookup_failed', {
320
+ message: msg, membership_id: membershipId, idempotency_key: idempotencyKey,
321
+ }, { severity: 'warning' });
322
+ }
323
+ }
268
324
  // 10. Authoritative membership write, done immediately after the Stripe
269
325
  // mutation that produced it.
270
326
  const { error: updErr } = await admin
@@ -10,6 +10,7 @@
10
10
  // fallback). Uses the operator's own STRIPE_SECRET_KEY only.
11
11
  import { createClient } from '@supabase/supabase-js';
12
12
  import Stripe from 'stripe';
13
+ import { findBaseItem } from '../membershipSubscriptionItems.js';
13
14
  const WINDOW_DAYS = 7;
14
15
  const STRIPE_LIVE = new Set(['active', 'trialing', 'past_due', 'unpaid', 'incomplete']);
15
16
  const DB_ENTITLED = new Set(['active', 'trialing', 'past_due']);
@@ -48,6 +49,12 @@ function subCurrentPeriodEndISO(sub) {
48
49
  const top = sub.current_period_end;
49
50
  if (typeof top === 'number')
50
51
  return new Date(top * 1000).toISOString();
52
+ // Prefer the base (non-addon) item; fall back to the old items.data[0]
53
+ // behavior when findBaseItem can't resolve exactly one, so this never
54
+ // regresses for a shape it used to handle.
55
+ const baseItemCpe = findBaseItem(sub)?.current_period_end;
56
+ if (typeof baseItemCpe === 'number')
57
+ return new Date(baseItemCpe * 1000).toISOString();
51
58
  const itemCpe = sub.items?.data?.[0]?.current_period_end;
52
59
  if (typeof itemCpe === 'number')
53
60
  return new Date(itemCpe * 1000).toISOString();
@@ -7,6 +7,7 @@ import { extractDoorAccess } from '../busClient.js';
7
7
  import { logWelcomeSkipped, WELCOME_OK_STATUSES, } from '../membershipWelcome.js';
8
8
  import { sendDunningEmail } from '../dunningEmails.js';
9
9
  import { recordReferralFailure, maybeGrantReferralCredit } from '../referralGrant.js';
10
+ import { findBaseItem } from '../membershipSubscriptionItems.js';
10
11
  export function createStripeWebhookHandler(config) {
11
12
  const { systemActorEmail, dayPassPortalRedirectUrl, teamSeatSlug, virtualOfficeSlug, siteConfig, busProvision, busCancel, notifyGhl, createCalendarEvent, handleCommonsDepositSession, sendVirtualOfficeWelcome, sendMembershipWelcome, sendPrivateOfficeWelcome, loadPrivateOfficeBilling, sendTeamSeatWelcome, maybeActivateAgreement, pacificMidnightUtc, maybeConvertTrialGrant, provisionDayPass, cancelDayPass, } = config;
12
13
  // No CORS — this is called by Stripe, not the browser.
@@ -287,7 +288,14 @@ export function createStripeWebhookHandler(config) {
287
288
  const top = anySub.current_period_end;
288
289
  if (typeof top === 'number')
289
290
  return new Date(top * 1000).toISOString();
290
- // Recent Stripe API versions expose the billing period on the subscription item.
291
+ // Recent Stripe API versions expose the billing period on the subscription
292
+ // item instead. Prefer the base (non-addon) item; fall back to the old
293
+ // items.data[0] behavior when findBaseItem can't resolve exactly one
294
+ // (e.g. an addon-only or unexpectedly-shaped subscription) so this never
295
+ // regresses for a shape it used to handle.
296
+ const baseItemCpe = findBaseItem(anySub)?.current_period_end;
297
+ if (typeof baseItemCpe === 'number')
298
+ return new Date(baseItemCpe * 1000).toISOString();
291
299
  const itemCpe = anySub.items?.data?.[0]?.current_period_end;
292
300
  if (typeof itemCpe === 'number')
293
301
  return new Date(itemCpe * 1000).toISOString();
@@ -0,0 +1,87 @@
1
+ /**
2
+ * Deliberately not the full Stripe.SubscriptionItem type: every existing call
3
+ * site already narrows to this shape via `as unknown as {...}` because the
4
+ * installed Stripe SDK's types lag the API's per-item billing-period fields.
5
+ * Keeping the helper's own shape this small also means test fixtures don't
6
+ * need to satisfy Stripe's full item type.
7
+ */
8
+ export interface BaseSubscriptionItem {
9
+ id: string;
10
+ current_period_start: number;
11
+ current_period_end: number;
12
+ metadata?: Record<string, string> | null;
13
+ }
14
+ export interface SubscriptionWithItems<T extends BaseSubscriptionItem = BaseSubscriptionItem> {
15
+ items: {
16
+ data: T[];
17
+ };
18
+ }
19
+ /**
20
+ * Resolve the single non-addon item on a subscription. Returns null unless
21
+ * exactly one item remains after add-on-tagged items are filtered out --
22
+ * including when every item is an add-on, or when more than one untagged
23
+ * item is present (an unexpected configuration, same as the old
24
+ * items.data.length !== 1 guard it replaces). A subscription with no
25
+ * gc_addon-tagged items at all (every subscription before add-ons existed)
26
+ * still resolves to its single item, unchanged.
27
+ */
28
+ export declare function findBaseItem<T extends BaseSubscriptionItem>(sub: SubscriptionWithItems<T>): T | null;
29
+ /** Count of non-addon items, for error details when findBaseItem returns null. */
30
+ export declare function countBaseItems<T extends BaseSubscriptionItem>(sub: SubscriptionWithItems<T>): number;
31
+ /**
32
+ * True if the subscription carries at least one gc_addon-tagged item. Used to
33
+ * gate add-on-aware guards (refund-with-addons block, base-price mismatch
34
+ * check) so subscriptions with no add-ons keep their pre-add-on behavior
35
+ * exactly.
36
+ */
37
+ export declare function hasAddonItems<T extends BaseSubscriptionItem>(sub: SubscriptionWithItems<T>): boolean;
38
+ export interface PricedSubscriptionItem {
39
+ price?: {
40
+ id?: string | null;
41
+ product?: string | null;
42
+ } | null;
43
+ }
44
+ export interface PlanPriceIdentity {
45
+ stripe_price_id?: string | null;
46
+ stripe_product_id?: string | null;
47
+ }
48
+ /**
49
+ * True if baseItem's Stripe price identifies the same plan as currentPlan:
50
+ * first by price id, falling back to product id when the plan has no stored
51
+ * price id or the ids differ. Fails closed -- returns false, meaning
52
+ * "reject" to the caller -- when neither identifies a match, including when
53
+ * the plan has neither id stored.
54
+ */
55
+ export declare function matchesPlanPrice(baseItem: PricedSubscriptionItem, plan: PlanPriceIdentity): boolean;
56
+ export interface InvoiceBillingReason {
57
+ billing_reason?: string | null;
58
+ }
59
+ /**
60
+ * True only for the invoice Stripe creates for a normal subscription renewal
61
+ * or the original subscription creation -- the one invoice whose amount
62
+ * actually corresponds to a full billing period, which the cancel-refund
63
+ * proration math assumes. Any other billing_reason (e.g. an add-on's
64
+ * always_invoice charge, or a manual/one-off invoice) is not safe to prorate
65
+ * as if it were the base-period invoice.
66
+ */
67
+ export declare function isRenewalInvoice(invoice: InvoiceBillingReason | null | undefined): boolean;
68
+ export interface InvoiceWithLines {
69
+ lines?: {
70
+ data?: Array<{
71
+ period?: {
72
+ start?: number | null;
73
+ } | null;
74
+ }> | null;
75
+ } | null;
76
+ }
77
+ /**
78
+ * True only if at least one of the invoice's line items has period.start
79
+ * equal to periodStart -- i.e. the invoice actually covers the CURRENT
80
+ * billing period, not a past or future one. isRenewalInvoice() confirms the
81
+ * invoice is SHAPED like a full-period charge; it says nothing about WHICH
82
+ * period. A past_due subscription or the brief draft window right after a
83
+ * renewal can leave the latest PAID invoice as last period's while the
84
+ * current period is still unpaid, and prorating that stale invoice against
85
+ * the current period's bounds would over-refund the member.
86
+ */
87
+ export declare function invoiceCoversPeriod(invoice: InvoiceWithLines | null | undefined, periodStart: number): boolean;
@@ -0,0 +1,71 @@
1
+ // Membership add-ons (membership add-ons phase) give a subscription a second
2
+ // Stripe subscription item alongside the base membership item, tagged with
3
+ // item-level metadata.gc_addon === '1'. Every admin path that used to assume
4
+ // "a membership subscription has exactly one item" -- plan changes,
5
+ // cancellation, and the period-bounds reads in the webhook/reconciler --
6
+ // must instead resolve the ONE remaining non-addon ("base") item and ignore
7
+ // add-on items entirely.
8
+ /**
9
+ * Resolve the single non-addon item on a subscription. Returns null unless
10
+ * exactly one item remains after add-on-tagged items are filtered out --
11
+ * including when every item is an add-on, or when more than one untagged
12
+ * item is present (an unexpected configuration, same as the old
13
+ * items.data.length !== 1 guard it replaces). A subscription with no
14
+ * gc_addon-tagged items at all (every subscription before add-ons existed)
15
+ * still resolves to its single item, unchanged.
16
+ */
17
+ export function findBaseItem(sub) {
18
+ const baseItems = (sub.items?.data ?? []).filter((item) => item.metadata?.gc_addon !== '1');
19
+ return baseItems.length === 1 ? baseItems[0] : null;
20
+ }
21
+ /** Count of non-addon items, for error details when findBaseItem returns null. */
22
+ export function countBaseItems(sub) {
23
+ return (sub.items?.data ?? []).filter((item) => item.metadata?.gc_addon !== '1').length;
24
+ }
25
+ /**
26
+ * True if the subscription carries at least one gc_addon-tagged item. Used to
27
+ * gate add-on-aware guards (refund-with-addons block, base-price mismatch
28
+ * check) so subscriptions with no add-ons keep their pre-add-on behavior
29
+ * exactly.
30
+ */
31
+ export function hasAddonItems(sub) {
32
+ return (sub.items?.data ?? []).some((item) => item.metadata?.gc_addon === '1');
33
+ }
34
+ /**
35
+ * True if baseItem's Stripe price identifies the same plan as currentPlan:
36
+ * first by price id, falling back to product id when the plan has no stored
37
+ * price id or the ids differ. Fails closed -- returns false, meaning
38
+ * "reject" to the caller -- when neither identifies a match, including when
39
+ * the plan has neither id stored.
40
+ */
41
+ export function matchesPlanPrice(baseItem, plan) {
42
+ if (plan.stripe_price_id && baseItem.price?.id === plan.stripe_price_id)
43
+ return true;
44
+ if (plan.stripe_product_id && baseItem.price?.product === plan.stripe_product_id)
45
+ return true;
46
+ return false;
47
+ }
48
+ /**
49
+ * True only for the invoice Stripe creates for a normal subscription renewal
50
+ * or the original subscription creation -- the one invoice whose amount
51
+ * actually corresponds to a full billing period, which the cancel-refund
52
+ * proration math assumes. Any other billing_reason (e.g. an add-on's
53
+ * always_invoice charge, or a manual/one-off invoice) is not safe to prorate
54
+ * as if it were the base-period invoice.
55
+ */
56
+ export function isRenewalInvoice(invoice) {
57
+ return invoice?.billing_reason === 'subscription_cycle' || invoice?.billing_reason === 'subscription_create';
58
+ }
59
+ /**
60
+ * True only if at least one of the invoice's line items has period.start
61
+ * equal to periodStart -- i.e. the invoice actually covers the CURRENT
62
+ * billing period, not a past or future one. isRenewalInvoice() confirms the
63
+ * invoice is SHAPED like a full-period charge; it says nothing about WHICH
64
+ * period. A past_due subscription or the brief draft window right after a
65
+ * renewal can leave the latest PAID invoice as last period's while the
66
+ * current period is still unpaid, and prorating that stale invoice against
67
+ * the current period's bounds would over-refund the member.
68
+ */
69
+ export function invoiceCoversPeriod(invoice, periodStart) {
70
+ return (invoice?.lines?.data ?? []).some((line) => line?.period?.start === periodStart);
71
+ }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@simplelayer/graniteer-core",
3
- "version": "0.3.14",
3
+ "version": "0.3.15",
4
4
  "description": "Shared platform core for Graniteer",
5
5
  "main": "./dist/index.js",
6
6
  "types": "./dist/index.d.ts",
@@ -53,6 +53,10 @@
53
53
  "types": "./dist/membershipBusClient.d.ts",
54
54
  "default": "./dist/membershipBusClient.js"
55
55
  },
56
+ "./membershipSubscriptionItems": {
57
+ "types": "./dist/membershipSubscriptionItems.d.ts",
58
+ "default": "./dist/membershipSubscriptionItems.js"
59
+ },
56
60
  "./membershipWelcome": {
57
61
  "types": "./dist/membershipWelcome.d.ts",
58
62
  "default": "./dist/membershipWelcome.js"