Files
pn-new-crm/tests/integration/api/tenancies.test.ts
Matt dd25ccfb53 fix(tenancies-audit): resolve findings from 7-agent system-wide rename audit
MUST-FIX:
- src/app/api/v1/admin/users/[id]/permission-overrides/route.ts:70 — the
  PUT allowlist still gated `reservations: {view,create,activate,cancel}`.
  Stale: would reject valid `tenancies.{view,manage,cancel}` writes and
  silently accept ghost `reservations.*` writes that never land. Replaced.
- src/lib/services/alert-rules.ts:68 — `reservation.no_agreement` alert
  emitted `entityType: 'reservation'`. Every other tenancy-related
  audit/socket/dashboard label is `'berth_tenancy'`. Inconsistent dedupe
  + activity-feed label miss.
- tests/e2e/exhaustive/08-portal.spec.ts:6 — hardcoded /portal/my-reservations
  navigates to a 404 every run.
- tests/e2e/exhaustive/03-reservations.spec.ts — entire spec renamed to
  03-tenancies.spec.ts; tab + button locators updated to match renamed UI.

SHOULD-FIX (consistency):
- src/components/clients/client-detail.tsx — useRealtimeInvalidation only
  caught 3 of the 4 berth_tenancy:* events; added the `:created` listener.
- src/lib/services/client-merge.service.ts — MergeResult.movedRows.reservations
  + snapshot.reservations + local loserReservations / movedReservations
  renamed to tenancies / loserTenancies / movedTenancies. No external
  consumers grep-confirmed.
- src/lib/services/gdpr-bundle-builder.ts — GdprBundle.reservations field
  renamed to .tenancies; user-facing HTML section "Reservations" → "Tenancies";
  local reservationRows → tenancyRows.
- 6 UI copy strings: gdpr-export-button, bulk-archive-wizard,
  bulk-hard-delete-dialog, hard-delete-dialog, admin-sections-browser ×2,
  admin/import/page, won-status-panel — all "reservations" prose updated
  to "tenancies" (occupancy-record sense).
- tests/integration/api/tenancies.test.ts — handler import aliases
  `createReservationHandler` etc renamed to `createTenancyHandler` etc.
- tests/unit/services/berth-tenancies.test.ts — local helper makeReservation
  → makeTenancyLocal (avoids shadow of the renamed factory).
- scripts/audit-permissions.ts — stale allowlist entry for
  /berth-reservations/[id]/route.ts removed (path no longer exists).
- docs/runbooks/permission-audit.md — stale row for same path removed.
- docs/tenancies-design.md — fixed factual error
  ("tenancies.service.ts" → "berth-tenancies.service.ts").

Verified: tsc clean, 1493/1493 vitest.

Dev-server note: the running `next dev` process started before P2 and
shows Turbopack cached compile errors against the renamed schema files.
Source is correct (./tenancies); restart `next dev` to clear the cache.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-25 16:03:14 +02:00

488 lines
16 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import { eq } from 'drizzle-orm';
import {
createHandler as createTenancyHandler,
listHandler as listTenanciesHandler,
} from '@/app/api/v1/berths/[id]/tenancies/handlers';
import {
getHandler as getTenancyHandler,
patchHandler as patchTenancyHandler,
deleteHandler as deleteTenancyHandler,
} from '@/app/api/v1/tenancies/[id]/handlers';
import { db } from '@/lib/db';
import { berthTenancies } from '@/lib/db/schema/tenancies';
import { enableTenanciesModule } from '@/lib/services/tenancies-module.service';
import { makeMockCtx, makeMockRequest } from '../../helpers/route-tester';
import {
makeBerth,
makeClient,
makeFullPermissions,
makePort,
makeSalesAgentPermissions,
makeYacht,
} from '../../helpers/factories';
/** Wrap makePort so every test in this file operates against a port that
* has the tenancies module enabled — the API handlers assertModuleEnabled
* up front (P5 design) and would otherwise 404 every call. */
async function makePortWithTenancies(): Promise<Awaited<ReturnType<typeof makePort>>> {
const port = await makePort();
await enableTenanciesModule(port.id);
return port;
}
// ─── POST /api/v1/berths/[id]/tenancies ───────────────────────────────────
describe('POST /api/v1/berths/[id]/tenancies', () => {
it('creates pending reservation (201)', async () => {
const port = await makePortWithTenancies();
const berth = await makeBerth({ portId: port.id });
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
});
const res = await createTenancyHandler(req, ctx, { id: berth.id });
expect(res.status).toBe(201);
const body = (await res.json()) as any;
expect(body.data.berthId).toBe(berth.id);
expect(body.data.clientId).toBe(client.id);
expect(body.data.yachtId).toBe(yacht.id);
expect(body.data.status).toBe('pending');
});
it('returns 400 when yacht does not belong to reservation client', async () => {
const port = await makePortWithTenancies();
const berth = await makeBerth({ portId: port.id });
const ownerClient = await makeClient({ portId: port.id });
const otherClient = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: ownerClient.id,
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: otherClient.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
});
const res = await createTenancyHandler(req, ctx, { id: berth.id });
expect(res.status).toBe(400);
});
it('returns 404 when berth is cross-tenant', async () => {
const portA = await makePortWithTenancies();
const portB = await makePortWithTenancies();
const berthA = await makeBerth({ portId: portA.id });
const client = await makeClient({ portId: portB.id });
const yacht = await makeYacht({
portId: portB.id,
ownerType: 'client',
ownerId: client.id,
});
// Caller is scoped to portB but the URL berth lives in portA.
const ctxB = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berthA.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
});
const res = await createTenancyHandler(req, ctxB, { id: berthA.id });
expect(res.status).toBe(404);
});
it('ignores berthId from body, uses URL param instead', async () => {
const port = await makePortWithTenancies();
const urlBerth = await makeBerth({ portId: port.id });
const bodyBerth = await makeBerth({ portId: port.id });
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${urlBerth.id}/tenancies`, {
body: {
berthId: bodyBerth.id,
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
});
const res = await createTenancyHandler(req, ctx, { id: urlBerth.id });
expect(res.status).toBe(201);
const body = (await res.json()) as any;
expect(body.data.berthId).toBe(urlBerth.id);
expect(body.data.berthId).not.toBe(bodyBerth.id);
});
});
// ─── GET /api/v1/berths/[id]/tenancies ────────────────────────────────────
describe('GET /api/v1/berths/[id]/tenancies', () => {
it('returns reservations filtered by that berth', async () => {
const port = await makePortWithTenancies();
const berthA = await makeBerth({ portId: port.id });
const berthB = await makeBerth({ portId: port.id });
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
// Create a reservation for berthA.
await createTenancyHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berthA.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
}),
ctx,
{ id: berthA.id },
);
// Create a reservation for berthB.
await createTenancyHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berthB.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
}),
ctx,
{ id: berthB.id },
);
const res = await listTenanciesHandler(
makeMockRequest('GET', `http://localhost/api/v1/berths/${berthA.id}/tenancies`),
ctx,
{ id: berthA.id },
);
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data.length).toBe(1);
expect(body.data[0].berthId).toBe(berthA.id);
});
});
// ─── GET /api/v1/tenancies/[id] ─────────────────────────────────────
describe('GET /api/v1/tenancies/[id]', () => {
it('returns the reservation', async () => {
const port = await makePortWithTenancies();
const berth = await makeBerth({ portId: port.id });
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const createRes = await createTenancyHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
}),
ctx,
{ id: berth.id },
);
const reservation = ((await createRes.json()) as any).data;
const res = await getTenancyHandler(
makeMockRequest('GET', `http://localhost/api/v1/tenancies/${reservation.id}`),
ctx,
{ id: reservation.id },
);
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data.id).toBe(reservation.id);
});
it('returns 404 for cross-tenant', async () => {
const portA = await makePortWithTenancies();
const portB = await makePortWithTenancies();
const berth = await makeBerth({ portId: portA.id });
const client = await makeClient({ portId: portA.id });
const yacht = await makeYacht({
portId: portA.id,
ownerType: 'client',
ownerId: client.id,
});
const ctxA = makeMockCtx({ portId: portA.id, permissions: makeFullPermissions() });
const createRes = await createTenancyHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
}),
ctxA,
{ id: berth.id },
);
const reservation = ((await createRes.json()) as any).data;
const ctxB = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const res = await getTenancyHandler(
makeMockRequest('GET', `http://localhost/api/v1/tenancies/${reservation.id}`),
ctxB,
{ id: reservation.id },
);
expect(res.status).toBe(404);
});
});
// ─── PATCH /api/v1/tenancies/[id] ───────────────────────────────────
describe('PATCH /api/v1/tenancies/[id]', () => {
async function seedReservation() {
const port = await makePortWithTenancies();
const berth = await makeBerth({ portId: port.id });
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const createRes = await createTenancyHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
}),
ctx,
{ id: berth.id },
);
const reservation = ((await createRes.json()) as any).data;
return { port, berth, client, yacht, ctx, reservation };
}
it('activate: pending → active (200)', async () => {
const { ctx, reservation } = await seedReservation();
const res = await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' },
}),
ctx,
{ id: reservation.id },
);
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data.status).toBe('active');
});
it('end: active → ended (200)', async () => {
const { ctx, reservation } = await seedReservation();
// First activate.
await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' },
}),
ctx,
{ id: reservation.id },
);
// Then end.
const endDate = new Date('2027-01-01T00:00:00.000Z');
const res = await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: {
action: 'end',
endDate: endDate.toISOString(),
notes: 'tenant moved',
},
}),
ctx,
{ id: reservation.id },
);
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data.status).toBe('ended');
expect(new Date(body.data.endDate).toISOString()).toBe(endDate.toISOString());
});
it('cancel: pending → cancelled (200)', async () => {
const { ctx, reservation } = await seedReservation();
const res = await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'cancel', reason: 'client changed mind' },
}),
ctx,
{ id: reservation.id },
);
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data.status).toBe('cancelled');
});
it('returns 400 on invalid transition (ended → activate)', async () => {
const { ctx, reservation } = await seedReservation();
// pending → active.
await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' },
}),
ctx,
{ id: reservation.id },
);
// active → ended.
await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: {
action: 'end',
endDate: new Date().toISOString(),
},
}),
ctx,
{ id: reservation.id },
);
// ended → activate should fail.
const res = await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' },
}),
ctx,
{ id: reservation.id },
);
expect(res.status).toBe(400);
});
it('returns 400 on invalid body shape (action missing)', async () => {
const { ctx, reservation } = await seedReservation();
const res = await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { notes: 'noop' },
}),
ctx,
{ id: reservation.id },
);
expect(res.status).toBe(400);
});
it('returns 403 when caller lacks tenancies.manage for activate action', async () => {
const { port, reservation } = await seedReservation();
// Viewer-like permissions: no manage.
const ctx = makeMockCtx({
portId: port.id,
permissions: {
...makeSalesAgentPermissions(),
tenancies: { view: true, manage: false, cancel: true },
},
});
const res = await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' },
}),
ctx,
{ id: reservation.id },
);
expect(res.status).toBe(403);
});
it('returns 403 when caller lacks tenancies.cancel for cancel action', async () => {
const { port, reservation } = await seedReservation();
// Sales agent - has manage but NOT cancel.
const ctx = makeMockCtx({
portId: port.id,
permissions: makeSalesAgentPermissions(),
});
const res = await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'cancel', reason: 'test' },
}),
ctx,
{ id: reservation.id },
);
expect(res.status).toBe(403);
// But activate succeeds with the same permissions set.
const activateRes = await patchTenancyHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' },
}),
ctx,
{ id: reservation.id },
);
expect(activateRes.status).toBe(200);
});
});
// ─── DELETE /api/v1/tenancies/[id] ──────────────────────────────────
describe('DELETE /api/v1/tenancies/[id]', () => {
it('cancels the reservation (204)', async () => {
const port = await makePortWithTenancies();
const berth = await makeBerth({ portId: port.id });
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const createRes = await createTenancyHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
}),
ctx,
{ id: berth.id },
);
const reservation = ((await createRes.json()) as any).data;
const delRes = await deleteTenancyHandler(
makeMockRequest('DELETE', `http://localhost/api/v1/tenancies/${reservation.id}`),
ctx,
{ id: reservation.id },
);
expect(delRes.status).toBe(204);
const [row] = await db
.select()
.from(berthTenancies)
.where(eq(berthTenancies.id, reservation.id));
expect(row?.status).toBe('cancelled');
});
});