Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 10 additions & 0 deletions modules/billing/billing.init.js
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
/**
* Module dependencies
*/
import config from '../../config/index.js';
import AnalyticsService from '../../lib/services/analytics.js';
import billingEvents from './lib/events.js';

Expand All @@ -13,6 +14,15 @@ import billingEvents from './lib/events.js';
*/
// eslint-disable-next-line no-unused-vars
export default async (app) => {
// Warn at startup if any pack is missing a valid priceUsd — refundPartial fallback will be inaccurate
if (config.billing?.packs?.length) {
for (const pack of config.billing.packs) {
if (typeof pack.priceUsd !== 'number' || pack.priceUsd <= 0) {
console.warn(`[billing] pack '${pack.packId}' missing valid priceUsd; refundPartial fallback will be inaccurate`);
}
}
}

// Update analytics group properties when a subscription plan changes
billingEvents.on('plan.changed', ({ organizationId, newPlan }) => {
try {
Expand Down
3 changes: 3 additions & 0 deletions modules/billing/controllers/billing.controller.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,9 @@ import BillingUsageService from '../services/billing.usage.service.js';
import BillingExtraService from '../services/billing.extra.service.js';
import BillingExtraBalanceRepository from '../repositories/billing.extraBalance.repository.js';

// NOTE: BillingExtraBalance uses field name 'organization', BillingUsage uses 'organizationId' — both are Schema.ObjectId refs to Organization.
// Only the field name differs (historical reasons) — keep queries consistent with each model's own convention.

/**
* @desc Endpoint to create a Stripe Checkout session
* @param {Object} req - Express request object
Expand Down
6 changes: 6 additions & 0 deletions modules/billing/models/billing.usage.model.mongoose.js
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,12 @@ const Schema = mongoose.Schema;
* Meter fields (weekKey, meterUsed, etc.) are sparse/optional — only
* populated when config.billing.meterMode is true. This ensures full
* backward compatibility for non-meter downstream projects.
*
* NOTE — Mixed type caveats (applies to 'counters' and 'meterBreakdown' fields):
* Mongoose validators are NOT executed for in-place mutations on Mixed fields
* (doc.field.x = y; doc.save() silently skips validators).
* Always use atomic MongoDB operators ($inc, $set via findOneAndUpdate)
* or Model.create() which runs validators on the full document.
*/
const UsageMongoose = new Schema(
{
Expand Down
6 changes: 4 additions & 2 deletions modules/billing/services/billing.extra.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -87,10 +87,12 @@ const refundPartial = async (orgId, stripeSessionId, amountRefundedCents) => {
return { doc, applied: false, refundUnits: 0 };
}

// Find the pack config to compute proportion.
// Find the pack config to compute proportion using the topup entry's meterUnits.
// Ambiguity guard: if 0 or >1 packs share the same meterUnits, fall back to
// applied=false rather than using a wrong priceUsd.
// TODO PR-N3: webhook handler will pass packId from session metadata, removing the need for this heuristic.
// NOTE: packId is not passed to refundPartial — charge.refunded carries it in
// charge.metadata but the webhook call-site only passes (orgId, stripeSessionId, amountCents).
// This heuristic is therefore intentionally retained; the ambiguity guard is the safety net.
const packs = config?.billing?.packs ?? [];
const matchingPacks = packs.filter(
(p) => (p.meterUnits ?? p.computeUnits) === topupEntry.amount,
Expand Down
27 changes: 26 additions & 1 deletion modules/billing/services/billing.webhook.service.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
import mongoose from 'mongoose';

import config from '../../../config/index.js';
import getStripe from '../lib/stripe.js';
import SubscriptionRepository from '../repositories/billing.subscription.repository.js';
import ProcessedStripeEventRepository from '../repositories/billing.processedStripeEvent.repository.js';
import OrganizationRepository from '../../organizations/repositories/organizations.repository.js';
Expand Down Expand Up @@ -152,14 +153,38 @@ const handleCheckoutCompleted = async (session) => {
const handleCheckoutPaymentCompleted = async (session) => {
if (session.payment_status !== 'paid') return;

const { metadata, id: stripeSessionId } = session;
const { metadata, id: stripeSessionId, payment_intent: paymentIntentId } = session;
const { organizationId, packId, kind } = metadata ?? {};

if (kind !== 'extras') return;
if (!organizationId || !mongoose.Types.ObjectId.isValid(organizationId)) return;
if (!packId) return;

await BillingExtraService.creditPack(organizationId, packId, stripeSessionId);

// Backfill PaymentIntent metadata with the real session ID so that charge.refunded
// events can correlate the charge back to this ledger entry.
// At session.create time stripeSessionId was set to '__pending__' (Stripe forbids
// self-reference). Propagating the real cs_* ID here ensures charge.metadata carries
// it when a refund is issued later.
if (paymentIntentId) {
const stripe = getStripe();
if (stripe) {
try {
await stripe.paymentIntents.update(paymentIntentId, {
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🟡 MEDIUM RISK

Suggestion: This metadata backfill is a robust solution for the 'correlation' problem. By propagating the 'stripeSessionId' and 'packId' to the PaymentIntent, you ensure future events (like refunds) can be mapped back to internal ledger entries. Suggestion: Consider if additional metadata like 'userId' or 'environment' should also be propagated to improve long-term auditability.

metadata: {
organizationId,
packId,
kind: 'extras',
stripeSessionId, // real cs_* ID
},
Comment on lines +165 to +180
});
} catch (err) {
// Log but don't fail — refund correlation may need fallback path
console.warn('[billing.webhook] PaymentIntent metadata update failed:', err.message);
}
}
}
};

/**
Expand Down
64 changes: 64 additions & 0 deletions modules/billing/tests/billing.webhook.checkout.unit.tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ describe('Billing webhook checkout unit tests:', () => {
let mockSubscriptionRepository;
let mockOrganizationRepository;
let mockExtraService;
let mockStripeInstance;

const orgId = '507f1f77bcf86cd799439011';
const subId = '607f1f77bcf86cd799439022';
Expand All @@ -39,6 +40,12 @@ describe('Billing webhook checkout unit tests:', () => {
refundPartial: jest.fn(),
};

mockStripeInstance = {
paymentIntents: {
update: jest.fn().mockResolvedValue({}),
},
};

jest.unstable_mockModule('../repositories/billing.subscription.repository.js', () => ({
Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

⚪ LOW RISK

Nitpick: Duplicated mock setups identified. Extracting these into a shared utility would improve maintainability.

default: mockSubscriptionRepository,
}));
Expand Down Expand Up @@ -66,6 +73,10 @@ describe('Billing webhook checkout unit tests:', () => {
default: { emit: jest.fn() },
}));

jest.unstable_mockModule('../lib/stripe.js', () => ({
default: jest.fn(() => mockStripeInstance),
}));

jest.unstable_mockModule('../../../config/index.js', () => ({
default: {
billing: { plans: ['free', 'starter', 'pro', 'enterprise'] },
Expand Down Expand Up @@ -220,6 +231,59 @@ describe('Billing webhook checkout unit tests:', () => {

expect(mockExtraService.creditPack).not.toHaveBeenCalled();
});

test('should call stripe.paymentIntents.update with real sessionId after creditPack succeeds (CRITICAL: refund correlation)', async () => {
const paymentIntentId = 'pi_test_abc123';

await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
payment_intent: paymentIntentId,
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'extras' },
});

expect(mockExtraService.creditPack).toHaveBeenCalledWith(orgId, 'pack_500k', stripeSessionId);
expect(mockStripeInstance.paymentIntents.update).toHaveBeenCalledWith(
paymentIntentId,
{
metadata: {
organizationId: orgId,
packId: 'pack_500k',
kind: 'extras',
stripeSessionId, // real cs_* ID (not '__pending__')
},
},
);
});

test('should skip paymentIntents.update when payment_intent is absent', async () => {
await BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
// payment_intent omitted — e.g. in test fixtures without PI
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'extras' },
});

expect(mockExtraService.creditPack).toHaveBeenCalled();
expect(mockStripeInstance.paymentIntents.update).not.toHaveBeenCalled();
});

test('should not throw when paymentIntents.update fails (non-fatal fallback)', async () => {
const paymentIntentId = 'pi_test_failing';
mockStripeInstance.paymentIntents.update.mockRejectedValue(new Error('Stripe API error'));

await expect(
BillingWebhookService.handleCheckoutPaymentCompleted({
id: stripeSessionId,
payment_status: 'paid',
payment_intent: paymentIntentId,
metadata: { organizationId: orgId, packId: 'pack_500k', kind: 'extras' },
}),
).resolves.toBeUndefined();

// creditPack should still have run despite the PI update failure
expect(mockExtraService.creditPack).toHaveBeenCalledWith(orgId, 'pack_500k', stripeSessionId);
});
});

describe('handleCheckoutCompleted (mode=subscription)', () => {
Expand Down
Loading