Files
pn-new-crm/tests/integration/api/yachts-detail.test.ts
Matt 221ae5784e chore(autonomous-session): consolidate uncommitted work from prior session
Bundles the prior autonomous-session output that was sitting unstaged:

- Em-dash sweep across src/ + tests/ (en-dash/em-dash to hyphen, ~2280 instances)
- country-flag-icons rollout (CountryFlag component, replaces emoji glyphs that
  never rendered on Windows; lazy-loads the 3x2 SVG index as a single chunk
  after the per-subpath dynamic-import approach silently failed in webpack)
- Admin IA Phase 1+2: 7-domain regroup, 41 to 38 pages, /admin/berths index,
  redirects (ocr to ai, reports to dashboard, invitations to users),
  docs/admin-ia-proposal.md
- Per-template email tester (registry + endpoint + UI on Email admin page)
- Cancel-document mode picker (delete-from-Documenso vs keep-for-audit)
- Dashboard PDF report: 25 widgets, SVG charts, date-range picker, 11 resolvers
- Customize-widgets per-region sortables at xl+ (charts/rails/feed); single
  flat sortable below xl when the layout stacks; per-viewport saved orders
- Audit doc updates capturing each shipped item
- Lint fixes: react-compiler immutability in DonutChart (reduce instead of
  let-reassign), set-state-in-effect disables in CountryFlag and
  UploadForSigning preview-bytes effect, unused 'confirm' destructures in
  interest contract + reservation tabs, unescaped apostrophe in test-template
  card copy
2026-05-23 00:52:59 +02:00

353 lines
13 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import { getHandler, patchHandler, deleteHandler } from '@/app/api/v1/yachts/[id]/handlers';
import { transferHandler } from '@/app/api/v1/yachts/[id]/transfer/handlers';
import { historyHandler } from '@/app/api/v1/yachts/[id]/ownership-history/handlers';
import { autocompleteHandler } from '@/app/api/v1/yachts/autocomplete/handlers';
import { withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { yachts } from '@/lib/db/schema';
import { eq } from 'drizzle-orm';
import { makeMockCtx, makeMockRequest } from '../../helpers/route-tester';
import {
makePort,
makeClient,
makeCompany,
makeYacht,
makeFullPermissions,
makeSalesAgentPermissions,
} from '../../helpers/factories';
describe('GET /api/v1/yachts/[id]', () => {
it('returns the yacht for valid id + port', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
name: 'Detail Yacht',
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest('GET', `http://localhost/api/v1/yachts/${yacht.id}`);
const res = await getHandler(req, ctx, { id: yacht.id });
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data.id).toBe(yacht.id);
expect(body.data.name).toBe('Detail Yacht');
});
it('returns 404 for wrong port (tenant isolation)', async () => {
const portA = await makePort();
const portB = await makePort();
const client = await makeClient({ portId: portA.id });
const yacht = await makeYacht({
portId: portA.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const req = makeMockRequest('GET', `http://localhost/api/v1/yachts/${yacht.id}`);
const res = await getHandler(req, ctx, { id: yacht.id });
expect(res.status).toBe(404);
});
it('returns 404 for non-existent id', async () => {
const port = await makePort();
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest('GET', 'http://localhost/api/v1/yachts/does-not-exist');
const res = await getHandler(req, ctx, { id: 'does-not-exist' });
expect(res.status).toBe(404);
});
});
describe('PATCH /api/v1/yachts/[id]', () => {
it('updates allowed fields', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
name: 'Before',
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest('PATCH', `http://localhost/api/v1/yachts/${yacht.id}`, {
body: { name: 'After', notes: 'updated notes' },
});
const res = await patchHandler(req, ctx, { id: yacht.id });
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data.name).toBe('After');
expect(body.data.notes).toBe('updated notes');
});
it('returns 400 when attempting to set currentOwnerId (defensive guard)', async () => {
const port = await makePort();
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() });
// Validator strips owner fields, so we need to bypass it to reach the service's defensive guard.
// Test the service layer defense by calling the handler with a payload that the validator
// would accept but which also contains an unknown field that matches the forbidden keys.
// Actually the validator just omits `owner` - additional keys `currentOwnerId` etc. pass
// through Zod's .partial() (which still omits unknown keys by default).
// Zod .strip() is default, so unknown keys are dropped: we assert on the service directly.
const { updateYacht } = await import('@/lib/services/yachts.service');
await expect(
updateYacht(
yacht.id,
port.id,
{ currentOwnerId: 'evil' } as unknown as Parameters<typeof updateYacht>[2],
{
userId: ctx.userId,
portId: port.id,
ipAddress: ctx.ipAddress,
userAgent: ctx.userAgent,
},
),
).rejects.toMatchObject({ statusCode: 400 });
});
it('returns 404 for cross-tenant', async () => {
const portA = await makePort();
const portB = await makePort();
const client = await makeClient({ portId: portA.id });
const yacht = await makeYacht({
portId: portA.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const req = makeMockRequest('PATCH', `http://localhost/api/v1/yachts/${yacht.id}`, {
body: { name: 'hijack' },
});
const res = await patchHandler(req, ctx, { id: yacht.id });
expect(res.status).toBe(404);
});
});
describe('DELETE /api/v1/yachts/[id]', () => {
it('archives the yacht (returns 204)', async () => {
const port = await makePort();
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('DELETE', `http://localhost/api/v1/yachts/${yacht.id}`);
const res = await deleteHandler(req, ctx, { id: yacht.id });
expect(res.status).toBe(204);
const [row] = await db.select().from(yachts).where(eq(yachts.id, yacht.id));
expect(row?.archivedAt).not.toBeNull();
});
it('returns 404 for cross-tenant', async () => {
const portA = await makePort();
const portB = await makePort();
const client = await makeClient({ portId: portA.id });
const yacht = await makeYacht({
portId: portA.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const req = makeMockRequest('DELETE', `http://localhost/api/v1/yachts/${yacht.id}`);
const res = await deleteHandler(req, ctx, { id: yacht.id });
expect(res.status).toBe(404);
});
});
describe('POST /api/v1/yachts/[id]/transfer', () => {
it('transfers ownership (200) when caller has yachts.transfer', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
const company = await makeCompany({ 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/yachts/${yacht.id}/transfer`, {
body: {
newOwner: { type: 'company', id: company.id },
effectiveDate: new Date().toISOString(),
transferReason: 'sale',
},
});
const res = await transferHandler(req, ctx, { id: yacht.id });
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data.currentOwnerType).toBe('company');
expect(body.data.currentOwnerId).toBe(company.id);
});
it('returns 403 when caller lacks yachts.transfer (only has yachts.edit)', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
const company = await makeCompany({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
});
const gated = withPermission('yachts', 'transfer', transferHandler);
const ctx = makeMockCtx({ portId: port.id, permissions: makeSalesAgentPermissions() });
const req = makeMockRequest('POST', `http://localhost/api/v1/yachts/${yacht.id}/transfer`, {
body: {
newOwner: { type: 'company', id: company.id },
effectiveDate: new Date().toISOString(),
},
});
const res = await gated(req, ctx, { id: yacht.id });
expect(res.status).toBe(403);
});
it('returns 400 when newOwner === currentOwner', async () => {
const port = await makePort();
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/yachts/${yacht.id}/transfer`, {
body: {
newOwner: { type: 'client', id: client.id },
effectiveDate: new Date().toISOString(),
},
});
const res = await transferHandler(req, ctx, { id: yacht.id });
expect(res.status).toBe(400);
});
});
describe('GET /api/v1/yachts/[id]/ownership-history', () => {
it('returns full history sorted by startDate DESC', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
const company = await makeCompany({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
});
// Transfer to create a second history row
const ctxFull = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const transferReq = makeMockRequest(
'POST',
`http://localhost/api/v1/yachts/${yacht.id}/transfer`,
{
body: {
newOwner: { type: 'company', id: company.id },
effectiveDate: new Date().toISOString(),
transferReason: 'sale',
},
},
);
const transferRes = await transferHandler(transferReq, ctxFull, { id: yacht.id });
expect(transferRes.status).toBe(200);
const req = makeMockRequest(
'GET',
`http://localhost/api/v1/yachts/${yacht.id}/ownership-history`,
);
const res = await historyHandler(req, ctxFull, { id: yacht.id });
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data).toHaveLength(2);
// Sorted DESC by startDate - newest first
const firstStart = new Date(body.data[0].startDate).getTime();
const secondStart = new Date(body.data[1].startDate).getTime();
expect(firstStart).toBeGreaterThanOrEqual(secondStart);
});
it('returns 404 for cross-tenant yacht', async () => {
const portA = await makePort();
const portB = await makePort();
const client = await makeClient({ portId: portA.id });
const yacht = await makeYacht({
portId: portA.id,
ownerType: 'client',
ownerId: client.id,
});
const ctx = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const req = makeMockRequest(
'GET',
`http://localhost/api/v1/yachts/${yacht.id}/ownership-history`,
);
const res = await historyHandler(req, ctx, { id: yacht.id });
expect(res.status).toBe(404);
});
});
describe('GET /api/v1/yachts/autocomplete', () => {
it('returns matching yachts by name', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
name: 'AutoCompleteMatch One',
});
await makeYacht({
portId: port.id,
ownerType: 'client',
ownerId: client.id,
name: 'OtherName',
});
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest(
'GET',
'http://localhost/api/v1/yachts/autocomplete?q=AutoCompleteMatch',
);
const res = await autocompleteHandler(req, ctx, {});
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data.length).toBeGreaterThanOrEqual(1);
expect(body.data.every((y: { name: string }) => y.name.includes('AutoCompleteMatch'))).toBe(
true,
);
});
it('returns empty array when q is missing', async () => {
const port = await makePort();
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest('GET', 'http://localhost/api/v1/yachts/autocomplete');
const res = await autocompleteHandler(req, ctx, {});
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data).toEqual([]);
});
it('is tenant-scoped', async () => {
const portA = await makePort();
const portB = await makePort();
const clientA = await makeClient({ portId: portA.id });
await makeYacht({
portId: portA.id,
ownerType: 'client',
ownerId: clientA.id,
name: 'TenantScopedYachtXYZ',
});
const ctx = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const req = makeMockRequest(
'GET',
'http://localhost/api/v1/yachts/autocomplete?q=TenantScopedYachtXYZ',
);
const res = await autocompleteHandler(req, ctx, {});
expect(res.status).toBe(200);
const body = (await res.json()) as any;
expect(body.data).toEqual([]);
});
});