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);
}
);

File diff suppressed because it is too large Load Diff

View File

@@ -91,8 +91,14 @@ export function computeBillingPeriod(targetDate: Date, billingDay: number): Bill
* Determine if a subscriber should be billed on targetDate. * Determine if a subscriber should be billed on targetDate.
* *
* POSTPAID: billingDay === targetDate's day-of-month * POSTPAID: billingDay === targetDate's day-of-month
* PREPAID: (billingDay - prepaidLeadDays) matches targetDate's day-of-month * PREPAID: billingDay - prepaidLeadDays matches targetDate's day-of-month,
* with month wrapping (e.g., billingDay=5, leadDays=7 -> bill on day 28/29 of previous month) * with month wrapping when the lead day falls into the previous month.
* e.g., billingDay=5, leadDays=7 -> lead day = -2 (spills into prev month)
* -> if next billing date is March 5, lead day is Feb 26 (28-2)
*
* Implementation: compute the "theoretical billing date" as the billingDay of
* the NEXT calendar month relative to targetDate, then subtract prepaidLeadDays
* and compare to targetDate.
*/ */
export function shouldBillToday( export function shouldBillToday(
billingType: BillingType, billingType: BillingType,
@@ -101,23 +107,32 @@ export function shouldBillToday(
prepaidLeadDays: number prepaidLeadDays: number
): boolean { ): boolean {
const targetDay = targetDate.getUTCDate(); const targetDay = targetDate.getUTCDate();
const targetMonth = targetDate.getUTCMonth();
const targetYear = targetDate.getUTCFullYear();
if (billingType === BillingType.POSTPAID) { if (billingType === BillingType.POSTPAID) {
return billingDay === targetDay; return billingDay === targetDay;
} }
// PREPAID: determine the lead-up day // PREPAID: determine the lead-up day
// If billingDay - leadDays <= 0, we spill into the previous month // If billingDay - leadDays > 0, the lead day is in the same month as billingDay
const leadDay = billingDay - prepaidLeadDays; const leadDay = billingDay - prepaidLeadDays;
if (leadDay > 0) { if (leadDay > 0) {
// Lead day is in the same month as the billing day
// Check if targetDate's day matches the lead day in the same month
return leadDay === targetDay; return leadDay === targetDay;
} else { } else {
// Spills into previous month — compute last N days of previous month // leadDay <= 0: the lead day spills into the month BEFORE the billing month
const prevMonthLastDay = new Date(Date.UTC(targetYear, targetMonth, 0)).getUTCDate(); // The billing month's "previous month" from the perspective of the leadDay is the
const actualLeadDay = prevMonthLastDay + leadDay; // leadDay is negative here // month AFTER targetDate (since targetDate is in the lead month, billing is next month).
//
// Strategy: compute what billing date would be for next month, then work backwards.
// The lead day's actual calendar day = (last day of targetDate's month) + leadDay
// because leadDay is negative and the billing date is in the next month.
const targetMonth = targetDate.getUTCMonth();
const targetYear = targetDate.getUTCFullYear();
// Last day of the current month (targetDate's month)
const lastDayOfCurrentMonth = new Date(Date.UTC(targetYear, targetMonth + 1, 0)).getUTCDate();
const actualLeadDay = lastDayOfCurrentMonth + leadDay; // leadDay is ≤ 0
return actualLeadDay === targetDay; return actualLeadDay === targetDay;
} }
} }