feat(03-01): Zone service, API routes, and 25 integration tests
- zone-service.ts: createZone, updateZone, listZones, getZone, assignSubscriberToZone, removeSubscriberFromZone, assignCollectorToZone, removeCollectorFromZone, getCollectorZones, getCollectorSubscribers - API routes: GET/POST /api/zones, GET/PUT /api/zones/[id], POST/DELETE /api/zones/[id]/subscribers, GET /api/collectors/[id]/subscribers - 25 integration tests: zone CRUD, subscriber assignment, collector scoping, no-zone-assignment security boundary, cross-tenant isolation - Fix subscriber-service.ts: zone String? -> zoneId FK (deviation Rule 1) - Fix subscriber API routes: zone -> zoneId (deviation Rule 1)
This commit is contained in:
61
src/app/api/collectors/[id]/subscribers/route.ts
Normal file
61
src/app/api/collectors/[id]/subscribers/route.ts
Normal file
@@ -0,0 +1,61 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { withPermission } from "@/lib/middleware/authorize";
|
||||
import { withTenantContext } from "@/lib/prisma-tenant";
|
||||
import { getCollectorSubscribers } from "@/lib/services/zone-service";
|
||||
import { Role } from "@prisma/client";
|
||||
|
||||
/**
|
||||
* GET /api/collectors/[id]/subscribers
|
||||
*
|
||||
* Get all subscribers in the zones assigned to a collector.
|
||||
*
|
||||
* SECURITY:
|
||||
* - A COLLECTOR can only query their own subscriber list (id must match their userId).
|
||||
* - An ADMIN or OFFICE_STAFF can query any collector's subscriber list.
|
||||
* - If the collector has no zone assignments, an error is returned (security boundary).
|
||||
*
|
||||
* Requires: read on Subscriber subject.
|
||||
*
|
||||
* Response:
|
||||
* 200 OK — array of subscribers with zone info
|
||||
* 400 Bad Request — collector has no zone assignments
|
||||
* 403 Forbidden — collector trying to query another collector's list
|
||||
* 404 Not Found — collector user not found
|
||||
* 401 Unauthorized — no session
|
||||
*/
|
||||
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: collectorId } = await params;
|
||||
|
||||
// Collectors can only query their own subscriber list
|
||||
const isAdmin = user.roles?.includes(Role.ADMIN) || user.roles?.includes(Role.OFFICE_STAFF);
|
||||
if (!isAdmin && user.id !== collectorId) {
|
||||
return NextResponse.json(
|
||||
{ error: "Collectors can only query their own subscriber list" },
|
||||
{ status: 403 }
|
||||
);
|
||||
}
|
||||
|
||||
const tenantPrisma = withTenantContext(user.tenantId);
|
||||
|
||||
try {
|
||||
const subscribers = await getCollectorSubscribers(tenantPrisma, user.tenantId, collectorId);
|
||||
return NextResponse.json(subscribers);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Failed to get collector subscribers";
|
||||
if (message.includes("no zone assignments")) {
|
||||
return NextResponse.json({ error: message }, { status: 400 });
|
||||
}
|
||||
return NextResponse.json({ error: message }, { status: 500 });
|
||||
}
|
||||
}
|
||||
)(req);
|
||||
}
|
||||
@@ -48,7 +48,7 @@ export function GET(req: NextRequest, { params }: { params: Promise<{ id: string
|
||||
*
|
||||
* Update subscriber profile fields.
|
||||
* Status changes must use PATCH /api/subscribers/[id]/status.
|
||||
* Accepts: { firstName?, lastName?, email?, phone?, address?, zone?, servicePlanId?, notes? }
|
||||
* Accepts: { firstName?, lastName?, email?, phone?, address?, zoneId?, servicePlanId?, notes? }
|
||||
*
|
||||
* Requires: manage on Subscriber subject.
|
||||
*
|
||||
@@ -89,7 +89,7 @@ export function PUT(req: NextRequest, { params }: { params: Promise<{ id: string
|
||||
email: updates.email as string | undefined,
|
||||
phone: updates.phone as string | undefined,
|
||||
address: updates.address as string | undefined,
|
||||
zone: updates.zone as string | undefined,
|
||||
zoneId: updates.zoneId as string | undefined,
|
||||
servicePlanId: updates.servicePlanId as string | undefined,
|
||||
notes: updates.notes as string | undefined,
|
||||
autoSuspendDays: updates.autoSuspendDays as number | null | undefined,
|
||||
|
||||
@@ -61,7 +61,7 @@ export const GET = withPermission("read", "Subscriber")(
|
||||
* POST /api/subscribers
|
||||
*
|
||||
* Register a new subscriber.
|
||||
* Accepts: { firstName, lastName, email?, phone?, address, zone?, servicePlanId, notes? }
|
||||
* Accepts: { firstName, lastName, email?, phone?, address, zoneId?, servicePlanId, notes? }
|
||||
*
|
||||
* Requires: manage on Subscriber subject.
|
||||
*
|
||||
@@ -93,7 +93,7 @@ export const POST = withPermission("manage", "Subscriber")(
|
||||
email,
|
||||
phone,
|
||||
address,
|
||||
zone,
|
||||
zoneId,
|
||||
servicePlanId,
|
||||
notes,
|
||||
} = body as Record<string, unknown>;
|
||||
@@ -120,7 +120,7 @@ export const POST = withPermission("manage", "Subscriber")(
|
||||
email: email as string | undefined,
|
||||
phone: phone as string | undefined,
|
||||
address,
|
||||
zone: zone as string | undefined,
|
||||
zoneId: zoneId as string | undefined,
|
||||
servicePlanId,
|
||||
notes: notes as string | undefined,
|
||||
});
|
||||
|
||||
97
src/app/api/zones/[id]/route.ts
Normal file
97
src/app/api/zones/[id]/route.ts
Normal file
@@ -0,0 +1,97 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { withPermission } from "@/lib/middleware/authorize";
|
||||
import { withTenantContext } from "@/lib/prisma-tenant";
|
||||
import { getZone, updateZone } from "@/lib/services/zone-service";
|
||||
|
||||
/**
|
||||
* GET /api/zones/[id]
|
||||
*
|
||||
* Get a single zone with its subscribers and assigned collectors.
|
||||
*
|
||||
* Requires: read on Zone subject.
|
||||
*
|
||||
* Response:
|
||||
* 200 OK — zone with relations
|
||||
* 404 Not Found — zone 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", "Zone")(
|
||||
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 zone = await getZone(tenantPrisma, id);
|
||||
|
||||
if (!zone) {
|
||||
return NextResponse.json({ error: "Zone not found" }, { status: 404 });
|
||||
}
|
||||
|
||||
return NextResponse.json(zone);
|
||||
}
|
||||
)(req);
|
||||
}
|
||||
|
||||
/**
|
||||
* PUT /api/zones/[id]
|
||||
*
|
||||
* Update a zone's name, description, or isActive flag.
|
||||
* Accepts: { name?, description?, isActive? }
|
||||
*
|
||||
* Requires: update on Zone subject.
|
||||
*
|
||||
* Response:
|
||||
* 200 OK — updated zone
|
||||
* 400 Bad Request — validation error
|
||||
* 404 Not Found — zone not found
|
||||
* 401 Unauthorized — no session
|
||||
* 403 Forbidden — insufficient role
|
||||
*/
|
||||
export function PUT(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
return withPermission("update", "Zone")(
|
||||
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 zone = await updateZone(tenantPrisma, id, {
|
||||
name: updates.name as string | undefined,
|
||||
description: updates.description as string | undefined,
|
||||
isActive: updates.isActive as boolean | undefined,
|
||||
});
|
||||
return NextResponse.json(zone);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Failed to update zone";
|
||||
if (message.includes("Record to update not found") || message.includes("P2025")) {
|
||||
return NextResponse.json({ error: "Zone not found" }, { status: 404 });
|
||||
}
|
||||
return NextResponse.json({ error: message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
)(req);
|
||||
}
|
||||
115
src/app/api/zones/[id]/subscribers/route.ts
Normal file
115
src/app/api/zones/[id]/subscribers/route.ts
Normal file
@@ -0,0 +1,115 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { withPermission } from "@/lib/middleware/authorize";
|
||||
import { withTenantContext } from "@/lib/prisma-tenant";
|
||||
import { assignSubscriberToZone, removeSubscriberFromZone } from "@/lib/services/zone-service";
|
||||
|
||||
/**
|
||||
* POST /api/zones/[id]/subscribers
|
||||
*
|
||||
* Assign a subscriber to this zone.
|
||||
* Accepts: { subscriberId }
|
||||
*
|
||||
* Requires: update on Zone subject (managing zone membership).
|
||||
*
|
||||
* Response:
|
||||
* 200 OK — updated subscriber with zoneId
|
||||
* 400 Bad Request — missing subscriberId or zone not found
|
||||
* 401 Unauthorized — no session
|
||||
* 403 Forbidden — insufficient role
|
||||
*/
|
||||
export function POST(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
return withPermission("update", "Zone")(
|
||||
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: zoneId } = await params;
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { subscriberId } = body as Record<string, unknown>;
|
||||
|
||||
if (!subscriberId || typeof subscriberId !== "string") {
|
||||
return NextResponse.json({ error: "subscriberId is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
const tenantPrisma = withTenantContext(user.tenantId);
|
||||
|
||||
try {
|
||||
const subscriber = await assignSubscriberToZone(tenantPrisma, subscriberId, zoneId);
|
||||
return NextResponse.json(subscriber);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Failed to assign subscriber to zone";
|
||||
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);
|
||||
}
|
||||
|
||||
/**
|
||||
* DELETE /api/zones/[id]/subscribers
|
||||
*
|
||||
* Remove a subscriber from this zone (set zoneId to null).
|
||||
* Accepts: { subscriberId }
|
||||
*
|
||||
* Requires: update on Zone subject (managing zone membership).
|
||||
*
|
||||
* Response:
|
||||
* 200 OK — updated subscriber with zoneId null
|
||||
* 400 Bad Request — missing subscriberId
|
||||
* 401 Unauthorized — no session
|
||||
* 403 Forbidden — insufficient role
|
||||
*/
|
||||
export function DELETE(req: NextRequest, { params }: { params: Promise<{ id: string }> }) {
|
||||
return withPermission("update", "Zone")(
|
||||
async (req: NextRequest, { user }) => {
|
||||
if (!user.tenantId) {
|
||||
return NextResponse.json(
|
||||
{ error: "No tenant context — super-admins must use the admin API" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
// params not used here (removing from any zone, not just this one)
|
||||
await params;
|
||||
|
||||
let body: unknown;
|
||||
try {
|
||||
body = await req.json();
|
||||
} catch {
|
||||
return NextResponse.json({ error: "Invalid JSON body" }, { status: 400 });
|
||||
}
|
||||
|
||||
const { subscriberId } = body as Record<string, unknown>;
|
||||
|
||||
if (!subscriberId || typeof subscriberId !== "string") {
|
||||
return NextResponse.json({ error: "subscriberId is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
const tenantPrisma = withTenantContext(user.tenantId);
|
||||
|
||||
try {
|
||||
const subscriber = await removeSubscriberFromZone(tenantPrisma, subscriberId);
|
||||
return NextResponse.json(subscriber);
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Failed to remove subscriber from zone";
|
||||
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);
|
||||
}
|
||||
83
src/app/api/zones/route.ts
Normal file
83
src/app/api/zones/route.ts
Normal file
@@ -0,0 +1,83 @@
|
||||
import { NextRequest, NextResponse } from "next/server";
|
||||
import { withPermission } from "@/lib/middleware/authorize";
|
||||
import { withTenantContext } from "@/lib/prisma-tenant";
|
||||
import { createZone, listZones } from "@/lib/services/zone-service";
|
||||
|
||||
/**
|
||||
* GET /api/zones
|
||||
*
|
||||
* List all zones for the authenticated tenant.
|
||||
* Returns zones with subscriber count and collector count.
|
||||
*
|
||||
* Requires: read on Zone subject.
|
||||
*
|
||||
* Response:
|
||||
* 200 OK — array of zones with counts
|
||||
* 401 Unauthorized — no session
|
||||
* 403 Forbidden — insufficient role
|
||||
*/
|
||||
export const GET = withPermission("read", "Zone")(
|
||||
async (_req: NextRequest, { user }) => {
|
||||
if (!user.tenantId) {
|
||||
return NextResponse.json(
|
||||
{ error: "No tenant context — super-admins must use the admin API" },
|
||||
{ status: 400 }
|
||||
);
|
||||
}
|
||||
|
||||
const tenantPrisma = withTenantContext(user.tenantId);
|
||||
const zones = await listZones(tenantPrisma);
|
||||
return NextResponse.json(zones);
|
||||
}
|
||||
);
|
||||
|
||||
/**
|
||||
* POST /api/zones
|
||||
*
|
||||
* Create a new zone.
|
||||
* Accepts: { name, description? }
|
||||
*
|
||||
* Requires: create on Zone subject.
|
||||
*
|
||||
* Response:
|
||||
* 201 Created — created zone
|
||||
* 400 Bad Request — validation error or duplicate name
|
||||
* 401 Unauthorized — no session
|
||||
* 403 Forbidden — insufficient role
|
||||
*/
|
||||
export const POST = withPermission("create", "Zone")(
|
||||
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, description } = body as Record<string, unknown>;
|
||||
|
||||
if (!name || typeof name !== "string") {
|
||||
return NextResponse.json({ error: "name is required" }, { status: 400 });
|
||||
}
|
||||
|
||||
const tenantPrisma = withTenantContext(user.tenantId);
|
||||
|
||||
try {
|
||||
const zone = await createZone(tenantPrisma, user.tenantId, {
|
||||
name: name as string,
|
||||
description: description as string | undefined,
|
||||
});
|
||||
return NextResponse.json(zone, { status: 201 });
|
||||
} catch (err) {
|
||||
const message = err instanceof Error ? err.message : "Failed to create zone";
|
||||
return NextResponse.json({ error: message }, { status: 400 });
|
||||
}
|
||||
}
|
||||
);
|
||||
Reference in New Issue
Block a user