Files
pn-new-crm/tests/unit/services/berth-tenancies.test.ts
Matt ccc775dc66 feat(tenancies-p2): rename berth_reservations → berth_tenancies (schema + perms + UI)
73-file atomic rename per docs/tenancies-design.md:

- Migration 0085: rename table + indexes + FK constraints; rename
  documents.reservation_id → tenancy_id; migrate jsonb permission maps
  (reservations resource → tenancies; collapse create+activate → manage);
  rewrite historical audit_logs.entity_type='berth_reservation' →
  'berth_tenancy'. FK renames wrapped in DO blocks so dev DBs that pre-date
  the FK additions don't abort.
- Schema: berthReservations → berthTenancies; BerthReservation type →
  BerthTenancy; indexes idx_br_* / idx_brr_* → idx_bt_*.
- RolePermissions: resource { view, create, activate, cancel } collapses to
  { view, manage, cancel }; all 8 default seed bundles + role-form + matrix
  updated.
- Service: berth-reservations.service.ts → berth-tenancies.service.ts;
  endReservation → endTenancy; listReservations → listTenancies.
- API: /api/v1/berth-reservations → /api/v1/tenancies (+ nested [id]);
  /api/v1/berths/[id]/reservations → /api/v1/berths/[id]/tenancies.
- Validators: reservations.ts → tenancies.ts; RESERVATION_STATUSES →
  TENANCY_STATUSES; endReservationSchema → endTenancySchema.
- Routes: /{portSlug}/berth-reservations → /{portSlug}/tenancies;
  /portal/my-reservations → /portal/my-tenancies.
- Components: src/components/reservations/* → src/components/tenancies/*;
  BerthReservationsTab → BerthTenanciesTab; ClientReservationsTab →
  ClientTenanciesTab; ReservationList → TenancyList.
- Socket events: berth_reservation:* → berth_tenancy:*; payload
  reservationId → tenancyId.
- Webhook events: berth_reservation.* → berth_tenancy.*.
- Portal: getPortalUserReservations → getPortalUserTenancies;
  PortalReservation → PortalTenancy; PortalDashboard.counts.activeReservations
  → activeTenancies; PortalNav label "Reservations" → "Tenancies".
- Dossier: DossierReservation → DossierTenancy; reservationDecisions →
  tenancyDecisions across smart-archive-dialog + bulk-archive routes.
- Documents schema: documents.reservationId → documents.tenancyId
  (TS + DB column + index + FK constraint).
- Activity feed label berth_reservation → berth_tenancy (matched against
  migrated historical audit rows).

KEPT (separate concepts):
- Reservation Agreement document type (the contract sent to clients).
- "Reservation" pipeline stage name.
- {{reservation.*}} merge tokens in template authoring.
- interest.reservationStatus / reservationDocStatus / dateReservationSent
  fields (track agreement signing on the deal).
- reservation-agreement-context.ts service (builds merge context for the
  Reservation Agreement doc; only its DB imports were renamed).

Verified: tsc clean, 1480/1480 vitest passing, migration applied.

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

439 lines
14 KiB
TypeScript

import { describe, it, expect } from 'vitest';
import { eq } from 'drizzle-orm';
import {
createPending,
activate,
endTenancy,
cancel,
listTenancies,
} from '@/lib/services/berth-tenancies.service';
import {
makePort,
makeClient,
makeBerth,
makeYacht,
makeCompany,
makeAuditMeta,
} from '../../helpers/factories';
import { db } from '@/lib/db';
import { companyMemberships } from '@/lib/db/schema/companies';
// ─── createPending ───────────────────────────────────────────────────────────
describe('berth-tenancies.service - createPending', () => {
it('creates pending reservation for client-owned yacht', async () => {
const port = await makePort();
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 reservation = await createPending(
port.id,
{
berthId: berth.id,
clientId: client.id,
yachtId: yacht.id,
startDate: new Date(),
tenureType: 'permanent',
},
makeAuditMeta({ portId: port.id }),
);
expect(reservation.status).toBe('pending');
expect(reservation.berthId).toBe(berth.id);
expect(reservation.clientId).toBe(client.id);
expect(reservation.yachtId).toBe(yacht.id);
expect(reservation.portId).toBe(port.id);
expect(reservation.tenureType).toBe('permanent');
});
it('creates pending for company-owned yacht when client is a company member', async () => {
const port = await makePort();
const berth = await makeBerth({ portId: port.id });
const company = await makeCompany({ portId: port.id });
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'company',
ownerId: company.id,
});
// Active membership (no endDate).
await db.insert(companyMemberships).values({
companyId: company.id,
clientId: client.id,
role: 'director',
startDate: new Date(),
});
const reservation = await createPending(
port.id,
{
berthId: berth.id,
clientId: client.id,
yachtId: yacht.id,
startDate: new Date(),
tenureType: 'permanent',
},
makeAuditMeta({ portId: port.id }),
);
expect(reservation.status).toBe('pending');
expect(reservation.clientId).toBe(client.id);
});
it('rejects when yacht does not belong to client (no membership)', async () => {
const port = await makePort();
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,
});
await expect(
createPending(
port.id,
{
berthId: berth.id,
clientId: otherClient.id,
yachtId: yacht.id,
startDate: new Date(),
tenureType: 'permanent',
},
makeAuditMeta({ portId: port.id }),
),
).rejects.toThrow(/yacht does not belong/i);
});
it('rejects when company-owned yacht client has an ended membership', async () => {
const port = await makePort();
const berth = await makeBerth({ portId: port.id });
const company = await makeCompany({ portId: port.id });
const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({
portId: port.id,
ownerType: 'company',
ownerId: company.id,
});
// Membership ended → should not authorise.
await db.insert(companyMemberships).values({
companyId: company.id,
clientId: client.id,
role: 'director',
startDate: new Date('2024-01-01'),
endDate: new Date('2024-12-31'),
});
await expect(
createPending(
port.id,
{
berthId: berth.id,
clientId: client.id,
yachtId: yacht.id,
startDate: new Date(),
tenureType: 'permanent',
},
makeAuditMeta({ portId: port.id }),
),
).rejects.toThrow(/yacht does not belong/i);
});
it('rejects berth from a different port (tenant)', async () => {
const portA = await makePort();
const portB = await makePort();
const berthInB = await makeBerth({ portId: portB.id });
const clientInA = await makeClient({ portId: portA.id });
const yachtInA = await makeYacht({
portId: portA.id,
ownerType: 'client',
ownerId: clientInA.id,
});
await expect(
createPending(
portA.id,
{
berthId: berthInB.id,
clientId: clientInA.id,
yachtId: yachtInA.id,
startDate: new Date(),
tenureType: 'permanent',
},
makeAuditMeta({ portId: portA.id }),
),
).rejects.toThrow(/berth not found/i);
});
it('rejects yacht from a different port (tenant)', async () => {
const portA = await makePort();
const portB = await makePort();
const berthInA = await makeBerth({ portId: portA.id });
const clientInA = await makeClient({ portId: portA.id });
const clientInB = await makeClient({ portId: portB.id });
const yachtInB = await makeYacht({
portId: portB.id,
ownerType: 'client',
ownerId: clientInB.id,
});
await expect(
createPending(
portA.id,
{
berthId: berthInA.id,
clientId: clientInA.id,
yachtId: yachtInB.id,
startDate: new Date(),
tenureType: 'permanent',
},
makeAuditMeta({ portId: portA.id }),
),
).rejects.toThrow(/yacht not found/i);
});
});
// ─── Lifecycle transitions ───────────────────────────────────────────────────
describe('berth-tenancies.service - lifecycle transitions', () => {
async function setup() {
const port = await makePort();
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 reservation = await createPending(
port.id,
{
berthId: berth.id,
clientId: client.id,
yachtId: yacht.id,
startDate: new Date(),
tenureType: 'permanent',
},
makeAuditMeta({ portId: port.id }),
);
return { port, berth, client, yacht, reservation };
}
it('pending → active (activate)', async () => {
const { port, reservation } = await setup();
const activated = await activate(
reservation.id,
port.id,
{},
makeAuditMeta({ portId: port.id }),
);
expect(activated.status).toBe('active');
});
it('active → ended (endTenancy)', async () => {
const { port, reservation } = await setup();
await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
const ended = await endTenancy(
reservation.id,
port.id,
{ endDate: new Date() },
makeAuditMeta({ portId: port.id }),
);
expect(ended.status).toBe('ended');
expect(ended.endDate).not.toBeNull();
});
it('pending → cancelled (cancel)', async () => {
const { port, reservation } = await setup();
const cancelled = await cancel(
reservation.id,
port.id,
{ reason: 'client withdrew' },
makeAuditMeta({ portId: port.id }),
);
expect(cancelled.status).toBe('cancelled');
});
it('active → cancelled (cancel)', async () => {
const { port, reservation } = await setup();
await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
const cancelled = await cancel(
reservation.id,
port.id,
{ reason: 'contract terminated' },
makeAuditMeta({ portId: port.id }),
);
expect(cancelled.status).toBe('cancelled');
});
it('rejects ended → active (invalid transition)', async () => {
const { port, reservation } = await setup();
await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
await endTenancy(
reservation.id,
port.id,
{ endDate: new Date() },
makeAuditMeta({ portId: port.id }),
);
await expect(
activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id })),
).rejects.toThrow(/invalid transition/i);
});
it('rejects cancelled → active (invalid transition)', async () => {
const { port, reservation } = await setup();
await cancel(
reservation.id,
port.id,
{ reason: 'changed mind' },
makeAuditMeta({ portId: port.id }),
);
await expect(
activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id })),
).rejects.toThrow(/invalid transition/i);
});
it('rejects cancel from ended state', async () => {
const { port, reservation } = await setup();
await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
await endTenancy(
reservation.id,
port.id,
{ endDate: new Date() },
makeAuditMeta({ portId: port.id }),
);
await expect(
cancel(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id })),
).rejects.toThrow(/invalid transition/i);
});
it('rejects endTenancy on a pending reservation', async () => {
const { port, reservation } = await setup();
await expect(
endTenancy(
reservation.id,
port.id,
{ endDate: new Date() },
makeAuditMeta({ portId: port.id }),
),
).rejects.toThrow(/invalid transition/i);
});
});
// ─── listTenancies ────────────────────────────────────────────────────────
describe('berth-tenancies.service - listTenancies', () => {
async function makeReservation(portId: string, opts?: { berthId?: string }) {
const berth = opts?.berthId ? { id: opts.berthId } : await makeBerth({ portId });
const client = await makeClient({ portId });
const yacht = await makeYacht({ portId, ownerType: 'client', ownerId: client.id });
return createPending(
portId,
{
berthId: berth.id,
clientId: client.id,
yachtId: yacht.id,
startDate: new Date(),
tenureType: 'permanent',
},
makeAuditMeta({ portId }),
);
}
it('is tenant-scoped', async () => {
const portA = await makePort();
const portB = await makePort();
const resA = await makeReservation(portA.id);
await makeReservation(portB.id);
const result = await listTenancies(portA.id, {
page: 1,
limit: 50,
order: 'desc',
includeArchived: false,
});
const ids = result.data.map((r) => r.id);
expect(ids).toContain(resA.id);
expect(result.data.every((r) => r.portId === portA.id)).toBe(true);
});
it('filters by status', async () => {
const port = await makePort();
const resPending = await makeReservation(port.id);
const resActive = await makeReservation(port.id);
await activate(resActive.id, port.id, {}, makeAuditMeta({ portId: port.id }));
const activeList = await listTenancies(port.id, {
page: 1,
limit: 50,
order: 'desc',
includeArchived: false,
status: 'active',
});
expect(activeList.data.map((r) => r.id)).toContain(resActive.id);
expect(activeList.data.map((r) => r.id)).not.toContain(resPending.id);
});
it('filters by berthId', async () => {
const port = await makePort();
const berth1 = await makeBerth({ portId: port.id });
const berth2 = await makeBerth({ portId: port.id });
const client1 = await makeClient({ portId: port.id });
const yacht1 = await makeYacht({ portId: port.id, ownerType: 'client', ownerId: client1.id });
const res1 = await createPending(
port.id,
{ berthId: berth1.id, clientId: client1.id, yachtId: yacht1.id, startDate: new Date() },
makeAuditMeta({ portId: port.id }),
);
const client2 = await makeClient({ portId: port.id });
const yacht2 = await makeYacht({ portId: port.id, ownerType: 'client', ownerId: client2.id });
const res2 = await createPending(
port.id,
{ berthId: berth2.id, clientId: client2.id, yachtId: yacht2.id, startDate: new Date() },
makeAuditMeta({ portId: port.id }),
);
const result = await listTenancies(port.id, {
page: 1,
limit: 50,
order: 'desc',
includeArchived: false,
berthId: berth1.id,
});
const ids = result.data.map((r) => r.id);
expect(ids).toContain(res1.id);
expect(ids).not.toContain(res2.id);
});
});
// ─── Self-check: DB state is as expected after cancel ────────────────────────
describe('berth-tenancies.service - DB state', () => {
it('cancel persists status=cancelled in the database', async () => {
const port = await makePort();
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 res = await createPending(
port.id,
{ berthId: berth.id, clientId: client.id, yachtId: yacht.id, startDate: new Date() },
makeAuditMeta({ portId: port.id }),
);
await cancel(res.id, port.id, {}, makeAuditMeta({ portId: port.id }));
const { berthTenancies } = await import('@/lib/db/schema');
const [row] = await db.select().from(berthTenancies).where(eq(berthTenancies.id, res.id));
expect(row!.status).toBe('cancelled');
});
});