feat(02-04): billing API routes and comprehensive tests (38 passing)

- Fix shouldBillToday() month-wrapping logic for PREPAID lead days
- POST /api/billing/generate — triggers monthly invoice generation cycle
- GET /api/invoices — paginated list with status/subscriber/date filters
- GET /api/invoices/[id] — invoice detail with lines and subscriber
- POST /api/invoices/[id]/void — void with JE reversal

Test coverage (38 tests):
- computeBillingPeriod pure function
- shouldBillToday: postpaid, prepaid, and month-wrapping edge case
- Invoice number sequencing per tenant/year
- Invoice generation: amounts, InvoiceLine, period dates
- Journal entries: DR AR (1100), CR Revenue (4010), balanced
- Idempotency: duplicate prevention via unique(subscriberId, periodStart)
- Credit auto-application: full, partial, zero credit, JE (DR 1150, CR 1100)
- Billing cycle: active-only, suspended/cancelled excluded, prepaid lead days
- Overdue detection: bulk update of DRAFT/SENT/PARTIAL past due date
- Void: JE reversal, already-voided guard, PAID guard
- getInvoice, listInvoices, status filtering
- Tenant isolation: Tenant B cannot see Tenant A invoices
This commit is contained in:
kevin-asprec
2026-03-04 23:38:43 +08:00
parent 7cb7a9099c
commit 902587683f
6 changed files with 1310 additions and 8 deletions

View File

@@ -0,0 +1,71 @@
import { NextRequest, NextResponse } from "next/server";
import { withPermission } from "@/lib/middleware/authorize";
import { withTenantContext } from "@/lib/prisma-tenant";
import { generateMonthlyInvoices } from "@/lib/services/billing-service";
/**
* POST /api/billing/generate
*
* Trigger the monthly invoice generation cycle for the authenticated tenant.
* Accepts: { targetDate?: string (ISO date) }
*
* If targetDate is omitted, defaults to today.
*
* Requires: manage on Invoice subject.
*
* Response:
* 200 OK — { generated: number, skipped: number, errors: Array<{subscriberId, error}> }
* 400 Bad Request — invalid date
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export const POST = withPermission("manage", "Invoice")(
async (req: NextRequest, { user }) => {
if (!user.tenantId) {
return NextResponse.json(
{ error: "No tenant context — super-admins must use the admin API" },
{ status: 400 }
);
}
let body: Record<string, unknown> = {};
try {
const text = await req.text();
if (text) {
body = JSON.parse(text);
}
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
let targetDate: Date;
if (body.targetDate) {
targetDate = new Date(body.targetDate as string);
if (isNaN(targetDate.getTime())) {
return NextResponse.json({ error: "Invalid targetDate — must be a valid ISO date" }, { status: 400 });
}
} else {
targetDate = new Date();
}
const tenantPrisma = withTenantContext(user.tenantId);
try {
const result = await generateMonthlyInvoices(
tenantPrisma,
user.tenantId,
targetDate,
user.id
);
return NextResponse.json({
generated: result.generated.length,
skipped: result.skipped.length,
errors: result.errors,
});
} catch (err) {
const message = err instanceof Error ? err.message : "Invoice generation failed";
return NextResponse.json({ error: message }, { status: 500 });
}
}
);

View File

@@ -0,0 +1,45 @@
import { NextRequest, NextResponse } from "next/server";
import { withPermission } from "@/lib/middleware/authorize";
import { withTenantContext } from "@/lib/prisma-tenant";
import { getInvoice } from "@/lib/services/invoice-service";
/**
* GET /api/invoices/[id]
*
* Get a single invoice by ID with line items.
*
* Requires: read on Invoice subject.
*
* Response:
* 200 OK — Invoice with lines and subscriber details
* 400 Bad Request — no tenant context
* 404 Not Found — invoice not found
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
return withPermission("read", "Invoice")(
async (_req: NextRequest, { user }) => {
if (!user.tenantId) {
return NextResponse.json(
{ error: "No tenant context — super-admins must use the admin API" },
{ status: 400 }
);
}
const { id } = await params;
if (!id) {
return NextResponse.json({ error: "Invoice ID is required" }, { status: 400 });
}
const tenantPrisma = withTenantContext(user.tenantId);
const invoice = await getInvoice(tenantPrisma, id);
if (!invoice) {
return NextResponse.json({ error: "Invoice not found" }, { status: 404 });
}
return NextResponse.json(invoice);
}
)(req);
}

View File

@@ -0,0 +1,54 @@
import { NextRequest, NextResponse } from "next/server";
import { withPermission } from "@/lib/middleware/authorize";
import { withTenantContext } from "@/lib/prisma-tenant";
import { voidInvoice } from "@/lib/services/invoice-service";
/**
* POST /api/invoices/[id]/void
*
* Void an invoice and create a reversing journal entry.
*
* Cannot void invoices with status PAID or already VOID.
*
* Requires: manage on Invoice subject.
*
* Response:
* 200 OK — { invoice, reversingEntry }
* 400 Bad Request — cannot void (paid/already voided)
* 404 Not Found — invoice not found
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
return withPermission("manage", "Invoice")(
async (_req: NextRequest, { user }) => {
if (!user.tenantId) {
return NextResponse.json(
{ error: "No tenant context — super-admins must use the admin API" },
{ status: 400 }
);
}
const { id } = await params;
if (!id) {
return NextResponse.json({ error: "Invoice ID is required" }, { status: 400 });
}
const tenantPrisma = withTenantContext(user.tenantId);
try {
const result = await voidInvoice(tenantPrisma, user.tenantId, id, user.id);
return NextResponse.json(result);
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to void invoice";
// Differentiate between not found vs business rule violation
if (message.includes("not found")) {
return NextResponse.json({ error: message }, { status: 404 });
}
return NextResponse.json({ error: message }, { status: 400 });
}
}
)(req);
}

View File

@@ -0,0 +1,58 @@
import { NextRequest, NextResponse } from "next/server";
import { withPermission } from "@/lib/middleware/authorize";
import { withTenantContext } from "@/lib/prisma-tenant";
import { listInvoices } from "@/lib/services/invoice-service";
import { InvoiceStatus } from "@prisma/client";
/**
* GET /api/invoices
*
* List invoices for the authenticated tenant.
* Accepts: ?status=&subscriberId=&dueDateFrom=&dueDateTo=&page=&pageSize=
*
* Requires: read on Invoice subject.
*
* Response:
* 200 OK — { invoices, total, page, pageSize }
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export const GET = withPermission("read", "Invoice")(
async (req: NextRequest, { user }) => {
if (!user.tenantId) {
return NextResponse.json(
{ error: "No tenant context — super-admins must use the admin API" },
{ status: 400 }
);
}
const { searchParams } = new URL(req.url);
const status = searchParams.get("status") as InvoiceStatus | null;
const subscriberId = searchParams.get("subscriberId") ?? undefined;
const dueDateFrom = searchParams.get("dueDateFrom");
const dueDateTo = searchParams.get("dueDateTo");
const page = parseInt(searchParams.get("page") ?? "1", 10);
const pageSize = parseInt(searchParams.get("pageSize") ?? "20", 10);
// Validate status if provided
if (status && !Object.values(InvoiceStatus).includes(status)) {
return NextResponse.json(
{ error: `status must be one of: ${Object.values(InvoiceStatus).join(", ")}` },
{ status: 400 }
);
}
const tenantPrisma = withTenantContext(user.tenantId);
const result = await listInvoices(tenantPrisma, {
status: status ?? undefined,
subscriberId,
dueDateFrom: dueDateFrom ? new Date(dueDateFrom) : undefined,
dueDateTo: dueDateTo ? new Date(dueDateTo) : undefined,
page: isNaN(page) ? 1 : page,
pageSize: isNaN(pageSize) ? 20 : pageSize,
});
return NextResponse.json(result);
}
);