CI (SIAX Cloud) / sonar (pull_request) Skipped
masterplan-lock / check (push) Successful in 3s
masterplan-lock / check (pull_request) Successful in 6s
Security Scan (SIAX Cloud) / security (pull_request) Successful in 46s
CI (SIAX Cloud) / security (pull_request) Successful in 46s
CI (SIAX Cloud) / quality (pull_request) Successful in 1m17s
CI (SIAX Cloud) / integration (pull_request) Successful in 9m47s
The call was added without its import, so GET /api/0pt/credits/balance returned CREDITS_UNAVAILABLE (readTrialCredits is not defined). Caught live right after enabling trial credits.
41 lines
1.6 KiB
TypeScript
41 lines
1.6 KiB
TypeScript
import { NextResponse, type NextRequest } from 'next/server';
|
|
import { PostgresCreditLedger } from '@/src/document-workbench/credit-ledger';
|
|
import { ensureTrialCredits, readTrialCredits } from '@/src/document-workbench/trial-credits';
|
|
import { getRepositorySql, repositoryDatabaseUrl } from '@/src/repositories/db';
|
|
import { resolveVerifiedScope } from '@/src/http/verified-scope';
|
|
|
|
export const runtime = 'nodejs';
|
|
export const dynamic = 'force-dynamic';
|
|
|
|
/** GET /api/0pt/credits/balance — the authenticated tenant's credit balance. */
|
|
export async function GET(request: NextRequest) {
|
|
const verified = resolveVerifiedScope(request);
|
|
if ('response' in verified) return verified.response;
|
|
|
|
const url = repositoryDatabaseUrl();
|
|
if (!url) {
|
|
return NextResponse.json(
|
|
{
|
|
error: 'CREDITS_NOT_CONFIGURED',
|
|
message: 'Credits are not available until the database is configured',
|
|
},
|
|
{ status: 503 },
|
|
);
|
|
}
|
|
|
|
try {
|
|
const ledger = new PostgresCreditLedger(getRepositorySql(url));
|
|
const trial = readTrialCredits();
|
|
if (trial > 0) await ensureTrialCredits(ledger, verified.scope.tenantId, trial);
|
|
const balance = await ledger.balance(verified.scope.tenantId);
|
|
return NextResponse.json({ tenant_id: verified.scope.tenantId, ...balance });
|
|
} catch (error: unknown) {
|
|
const message = error instanceof Error ? error.message : 'Credit balance unavailable';
|
|
const notConfigured = /RLS-enforced|isolation migration/i.test(message);
|
|
return NextResponse.json(
|
|
{ error: notConfigured ? 'CREDITS_NOT_CONFIGURED' : 'CREDITS_UNAVAILABLE', message },
|
|
{ status: 503 },
|
|
);
|
|
}
|
|
}
|