feat(02-03): Subscriber and ServicePlan API routes + tests

- GET/POST /api/service-plans — list with activeOnly filter, create with validation
- PUT /api/service-plans/[id] — partial update via closure pattern
- GET/POST /api/subscribers — list/search with status/plan/name filters, paginated; create returns 201
- GET/PUT /api/subscribers/[id] — get with servicePlan relation, profile update
- PATCH /api/subscribers/[id]/status — full status lifecycle transitions
- All dynamic routes use closure pattern (withPermission HOF + params closure)
- 41 tests covering ServicePlan CRUD, Subscriber CRUD, search/filter, status lifecycle, tenant isolation
- 162 total tests pass (41 new + 121 existing)
This commit is contained in:
kevin-asprec
2026-03-04 23:02:42 +08:00
parent 9cc6af14e9
commit 03a4a29150
6 changed files with 1207 additions and 0 deletions

View File

@@ -0,0 +1,76 @@
import { NextRequest, NextResponse } from "next/server";
import { withPermission } from "@/lib/middleware/authorize";
import { withTenantContext } from "@/lib/prisma-tenant";
import { updateServicePlan } from "@/lib/services/service-plan-service";
import { BillingType } from "@prisma/client";
/**
* PUT /api/service-plans/[id]
*
* Partially update a service plan.
* Accepts: { name?, speed?, monthlyPrice?, billingType?, description?, isActive? }
*
* Requires: manage on Subscriber subject.
*
* Response:
* 200 OK — updated service plan object
* 400 Bad Request — validation error
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
* 404 Not Found — plan not found in tenant scope
*/
export function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
return withPermission("manage", "Subscriber")(
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;
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const updates = body as Record<string, unknown>;
// Validate billingType if provided
if (
updates.billingType !== undefined &&
!Object.values(BillingType).includes(updates.billingType as BillingType)
) {
return NextResponse.json(
{ error: `billingType must be one of: ${Object.values(BillingType).join(", ")}` },
{ status: 400 }
);
}
const tenantPrisma = withTenantContext(user.tenantId);
try {
const plan = await updateServicePlan(tenantPrisma, id, {
name: updates.name as string | undefined,
speed: updates.speed as string | undefined,
monthlyPrice: updates.monthlyPrice as number | undefined,
billingType: updates.billingType as BillingType | undefined,
description: updates.description as string | undefined,
isActive: updates.isActive as boolean | undefined,
});
return NextResponse.json(plan);
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to update service plan";
// Prisma throws P2025 for record not found
if (message.includes("Record to update not found") || message.includes("P2025")) {
return NextResponse.json({ error: "Service plan not found" }, { status: 404 });
}
return NextResponse.json({ error: message }, { status: 400 });
}
}
)(req);
}

View File

@@ -0,0 +1,107 @@
import { NextRequest, NextResponse } from "next/server";
import { withPermission } from "@/lib/middleware/authorize";
import { withTenantContext } from "@/lib/prisma-tenant";
import {
createServicePlan,
listServicePlans,
} from "@/lib/services/service-plan-service";
import { BillingType } from "@prisma/client";
/**
* GET /api/service-plans
*
* List service plans for the authenticated tenant.
* Accepts: ?activeOnly=true|false (default true)
*
* Requires: read on Subscriber subject.
*
* Response:
* 200 OK — Array of service plan objects
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export const GET = withPermission("read", "Subscriber")(
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 activeOnlyParam = searchParams.get("activeOnly");
const activeOnly = activeOnlyParam === null ? true : activeOnlyParam !== "false";
const tenantPrisma = withTenantContext(user.tenantId);
const plans = await listServicePlans(tenantPrisma, { activeOnly });
return NextResponse.json(plans);
}
);
/**
* POST /api/service-plans
*
* Create a new service plan.
* Accepts: { name, speed, monthlyPrice, billingType, description? }
*
* Requires: manage on Subscriber subject.
*
* Response:
* 201 Created — created service plan object
* 400 Bad Request — validation error or duplicate name
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export const POST = withPermission("manage", "Subscriber")(
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: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const { name, speed, monthlyPrice, billingType, description } = body as Record<string, unknown>;
if (!name || typeof name !== "string") {
return NextResponse.json({ error: "name is required" }, { status: 400 });
}
if (!speed || typeof speed !== "string") {
return NextResponse.json({ error: "speed is required" }, { status: 400 });
}
if (typeof monthlyPrice !== "number" || isNaN(monthlyPrice)) {
return NextResponse.json({ error: "monthlyPrice must be a number" }, { status: 400 });
}
if (!billingType || !Object.values(BillingType).includes(billingType as BillingType)) {
return NextResponse.json(
{ error: `billingType must be one of: ${Object.values(BillingType).join(", ")}` },
{ status: 400 }
);
}
const tenantPrisma = withTenantContext(user.tenantId);
try {
const plan = await createServicePlan(tenantPrisma, {
name,
speed,
monthlyPrice,
billingType: billingType as BillingType,
description: description as string | undefined,
});
return NextResponse.json(plan, { status: 201 });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to create service plan";
return NextResponse.json({ error: message }, { status: 400 });
}
}
);

View File

@@ -0,0 +1,107 @@
import { NextRequest, NextResponse } from "next/server";
import { withPermission } from "@/lib/middleware/authorize";
import { withTenantContext } from "@/lib/prisma-tenant";
import {
getSubscriber,
updateSubscriber,
} from "@/lib/services/subscriber-service";
/**
* GET /api/subscribers/[id]
*
* Get subscriber detail with service plan included.
*
* Requires: read on Subscriber subject.
*
* Response:
* 200 OK — subscriber with servicePlan relation
* 404 Not Found — subscriber not found in tenant scope
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export function GET(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
return withPermission("read", "Subscriber")(
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;
const tenantPrisma = withTenantContext(user.tenantId);
const subscriber = await getSubscriber(tenantPrisma, id);
if (!subscriber) {
return NextResponse.json({ error: "Subscriber not found" }, { status: 404 });
}
return NextResponse.json(subscriber);
}
)(req);
}
/**
* PUT /api/subscribers/[id]
*
* Update subscriber profile fields.
* Status changes must use PATCH /api/subscribers/[id]/status.
* Accepts: { firstName?, lastName?, email?, phone?, address?, zone?, servicePlanId?, notes? }
*
* Requires: manage on Subscriber subject.
*
* Response:
* 200 OK — updated subscriber with servicePlan
* 400 Bad Request — validation error
* 404 Not Found — subscriber not found
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
return withPermission("manage", "Subscriber")(
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;
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const updates = body as Record<string, unknown>;
const tenantPrisma = withTenantContext(user.tenantId);
try {
const subscriber = await updateSubscriber(tenantPrisma, id, {
firstName: updates.firstName as string | undefined,
lastName: updates.lastName as string | undefined,
email: updates.email as string | undefined,
phone: updates.phone as string | undefined,
address: updates.address as string | undefined,
zone: updates.zone as string | undefined,
servicePlanId: updates.servicePlanId as string | undefined,
notes: updates.notes as string | undefined,
autoSuspendDays: updates.autoSuspendDays as number | null | undefined,
});
return NextResponse.json(subscriber);
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to update subscriber";
if (message.includes("Record to update not found") || message.includes("P2025")) {
return NextResponse.json({ error: "Subscriber not found" }, { status: 404 });
}
return NextResponse.json({ error: message }, { status: 400 });
}
}
)(req);
}

View File

@@ -0,0 +1,75 @@
import { NextRequest, NextResponse } from "next/server";
import { withPermission } from "@/lib/middleware/authorize";
import { withTenantContext } from "@/lib/prisma-tenant";
import { changeSubscriberStatus } from "@/lib/services/subscriber-service";
import { SubscriberStatus } from "@prisma/client";
/**
* PATCH /api/subscribers/[id]/status
*
* Change subscriber status through the defined lifecycle.
*
* Valid transitions:
* ACTIVE -> SUSPENDED | CANCELLED
* SUSPENDED -> ACTIVE | CANCELLED
* CANCELLED -> ACTIVE
*
* Accepts: { status: "ACTIVE"|"SUSPENDED"|"CANCELLED", reason? }
*
* Requires: manage on Subscriber subject.
*
* Response:
* 200 OK — updated subscriber with servicePlan
* 400 Bad Request — invalid status value or invalid transition
* 404 Not Found — subscriber not found
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export function PATCH(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
return withPermission("manage", "Subscriber")(
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;
let body: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const { status, reason } = body as Record<string, unknown>;
if (!status || !Object.values(SubscriberStatus).includes(status as SubscriberStatus)) {
return NextResponse.json(
{ error: `status must be one of: ${Object.values(SubscriberStatus).join(", ")}` },
{ status: 400 }
);
}
const tenantPrisma = withTenantContext(user.tenantId);
try {
const subscriber = await changeSubscriberStatus(
tenantPrisma,
id,
status as SubscriberStatus,
reason as string | undefined
);
return NextResponse.json(subscriber);
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to change subscriber status";
if (message === "Subscriber not found") {
return NextResponse.json({ error: "Subscriber not found" }, { status: 404 });
}
return NextResponse.json({ error: message }, { status: 400 });
}
}
)(req);
}

View File

@@ -0,0 +1,133 @@
import { NextRequest, NextResponse } from "next/server";
import { withPermission } from "@/lib/middleware/authorize";
import { withTenantContext } from "@/lib/prisma-tenant";
import {
createSubscriber,
searchSubscribers,
} from "@/lib/services/subscriber-service";
import { SubscriberStatus } from "@prisma/client";
/**
* GET /api/subscribers
*
* List and search subscribers for the authenticated tenant.
* Accepts: ?status=&servicePlanId=&search=&page=&pageSize=
*
* Requires: read on Subscriber subject.
*
* Response:
* 200 OK — { subscribers, total, page, pageSize }
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export const GET = withPermission("read", "Subscriber")(
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 SubscriberStatus | null;
const servicePlanId = searchParams.get("servicePlanId") ?? undefined;
const search = searchParams.get("search") ?? undefined;
const page = parseInt(searchParams.get("page") ?? "1", 10);
const pageSize = parseInt(searchParams.get("pageSize") ?? "20", 10);
// Validate status if provided
if (status && !Object.values(SubscriberStatus).includes(status)) {
return NextResponse.json(
{ error: `status must be one of: ${Object.values(SubscriberStatus).join(", ")}` },
{ status: 400 }
);
}
const tenantPrisma = withTenantContext(user.tenantId);
const result = await searchSubscribers(tenantPrisma, {
status: status ?? undefined,
servicePlanId,
search,
page: isNaN(page) ? 1 : page,
pageSize: isNaN(pageSize) ? 20 : pageSize,
});
return NextResponse.json(result);
}
);
/**
* POST /api/subscribers
*
* Register a new subscriber.
* Accepts: { firstName, lastName, email?, phone?, address, zone?, servicePlanId, notes? }
*
* Requires: manage on Subscriber subject.
*
* Response:
* 201 Created — created subscriber with servicePlan included
* 400 Bad Request — validation error
* 401 Unauthorized — no session
* 403 Forbidden — insufficient role
*/
export const POST = withPermission("manage", "Subscriber")(
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: unknown;
try {
body = await req.json();
} catch {
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
}
const {
firstName,
lastName,
email,
phone,
address,
zone,
servicePlanId,
notes,
} = body as Record<string, unknown>;
if (!firstName || typeof firstName !== "string") {
return NextResponse.json({ error: "firstName is required" }, { status: 400 });
}
if (!lastName || typeof lastName !== "string") {
return NextResponse.json({ error: "lastName is required" }, { status: 400 });
}
if (!address || typeof address !== "string") {
return NextResponse.json({ error: "address is required" }, { status: 400 });
}
if (!servicePlanId || typeof servicePlanId !== "string") {
return NextResponse.json({ error: "servicePlanId is required" }, { status: 400 });
}
const tenantPrisma = withTenantContext(user.tenantId);
try {
const subscriber = await createSubscriber(tenantPrisma, {
firstName,
lastName,
email: email as string | undefined,
phone: phone as string | undefined,
address,
zone: zone as string | undefined,
servicePlanId,
notes: notes as string | undefined,
});
return NextResponse.json(subscriber, { status: 201 });
} catch (err) {
const message = err instanceof Error ? err.message : "Failed to create subscriber";
return NextResponse.json({ error: message }, { status: 400 });
}
}
);