Files
0pt/app/api/0pt/credits/checkout/route.ts
T
admin a0dd6b7653
CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (pull_request) Successful in 3s
masterplan-lock / check (push) Successful in 14s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 18s
CI (SIAX Cloud) / security (pull_request) Successful in 23s
CI (SIAX Cloud) / quality (pull_request) Successful in 54s
CI (SIAX Cloud) / integration (pull_request) Successful in 1m2s
fix(live): refuse billing in pilot mode and explain unparsed documents
- Checkout returns 503 CREDITS_DISABLED while OPT_CREDITS_MODE=off, so a
  customer can never pay for credits that the pipeline will not consume.
- Packs expose purchases_enabled; the portal hides Buy and says billing is off.
- Structuring an unparsed document (e.g. a scanned PDF with no text layer) now
  answers 422 DOCUMENT_NOT_PARSED instead of a generic INVALID_REQUEST.
2026-11-02 20:14:12 +01:00

156 lines
4.9 KiB
TypeScript

import { NextResponse, type NextRequest } from 'next/server';
import { getStripe } from '@/lib/stripe';
import { PostgresCreditPurchaseStore } from '@/src/document-workbench/credit-purchase-store';
import { findPack, readCreditPriceBook } from '@/src/document-workbench/price-book';
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
import { isValidScopeId, resolveVerifiedScope } from '@/src/http/verified-scope';
export const runtime = 'nodejs';
export const dynamic = 'force-dynamic';
function appBaseUrl(request: NextRequest): string {
const configured = process.env.NEXT_PUBLIC_APP_URL;
if (configured && /^https:\/\//.test(configured)) return configured.replace(/\/+$/, '');
return request.nextUrl.origin;
}
/**
* POST /api/0pt/credits/checkout { pack_id }
*
* Creates a Stripe Checkout Session and stores the server-owned price snapshot
* BEFORE any credit exists. Credits are granted only when the Stripe webhook
* re-reads the session and its payment intent and the ledger accepts the
* idempotent verified-payment command.
*/
export async function POST(request: NextRequest) {
const verified = resolveVerifiedScope(request);
if ('response' in verified) return verified.response;
const { tenantId } = verified.scope;
if (process.env.OPT_CREDITS_MODE === 'off') {
return NextResponse.json(
{
error: 'CREDITS_DISABLED',
message: 'Billing is not active yet (pilot mode). No payment can be taken.',
},
{ status: 503 },
);
}
const book = readCreditPriceBook();
if (!book) {
return NextResponse.json(
{ error: 'PRICE_BOOK_NOT_CONFIGURED', message: 'Credit purchases are not available yet' },
{ status: 503 },
);
}
const stripe = getStripe();
if (!stripe) {
return NextResponse.json(
{ error: 'STRIPE_NOT_CONFIGURED', message: 'Payments are not available yet' },
{ status: 503 },
);
}
const databaseUrl = repositoryDatabaseUrl();
if (!databaseUrl) {
return NextResponse.json(
{
error: 'CREDITS_NOT_CONFIGURED',
message: 'Credits are not available until the database is configured',
},
{ status: 503 },
);
}
let body: unknown;
try {
body = await request.json();
} catch {
return NextResponse.json({ error: 'INVALID_BODY', message: 'JSON body required' }, { status: 400 });
}
const packId = (body as { pack_id?: unknown } | null)?.pack_id;
if (typeof packId !== 'string' || !isValidScopeId(packId)) {
return NextResponse.json(
{ error: 'INVALID_PACK', message: 'A valid pack_id is required' },
{ status: 400 },
);
}
const pack = findPack(book, packId);
if (!pack) {
return NextResponse.json({ error: 'UNKNOWN_PACK', message: 'Unknown credit pack' }, { status: 404 });
}
const purchaseId = crypto.randomUUID();
const base = appBaseUrl(request);
const metadata = {
kind: '0pt_credit_purchase',
tenant_id: tenantId,
purchase_id: purchaseId,
price_book_version: book.version,
};
let session;
try {
session = await stripe.checkout.sessions.create({
mode: 'payment',
client_reference_id: tenantId,
line_items: [
{
quantity: 1,
price_data: {
currency: book.currency.toLowerCase(),
unit_amount: pack.amountMinor,
product_data: { name: `${pack.credits} 0pt credits` },
},
},
],
metadata,
payment_intent_data: { metadata },
success_url: `${base}/portal/krediter?status=success&purchase=${encodeURIComponent(purchaseId)}`,
cancel_url: `${base}/portal/krediter?status=cancelled`,
});
} catch {
return NextResponse.json(
{ error: 'CHECKOUT_UNAVAILABLE', message: 'The payment provider could not start a checkout' },
{ status: 502 },
);
}
try {
await new PostgresCreditPurchaseStore(getRepositorySql(databaseUrl)).create({
tenantId,
purchaseId,
checkoutSessionId: session.id,
amountMinor: pack.amountMinor,
currency: book.currency,
credits: pack.credits,
});
} catch (error: unknown) {
// Never leave a payable session with no server-side snapshot behind it.
try {
await stripe.checkout.sessions.expire(session.id);
} catch {
/* best effort; the webhook will refuse the unmatched session */
}
const message = error instanceof Error ? error.message : 'Credit purchase could not be stored';
return NextResponse.json({ error: 'CREDITS_NOT_CONFIGURED', message }, { status: 503 });
}
if (!session.url) {
return NextResponse.json(
{ error: 'CHECKOUT_UNAVAILABLE', message: 'The payment provider returned no checkout URL' },
{ status: 502 },
);
}
return NextResponse.json(
{
purchase_id: purchaseId,
checkout_url: session.url,
credits: pack.credits,
amount_minor: pack.amountMinor,
currency: book.currency,
},
{ status: 201 },
);
}