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>
This commit is contained in:
2026-05-25 15:09:35 +02:00
parent 4f350d1fbd
commit ccc775dc66
77 changed files with 818 additions and 742 deletions

View File

@@ -1,10 +0,0 @@
import { ReservationDetail } from '@/components/reservations/reservation-detail';
interface PageProps {
params: Promise<{ portSlug: string; id: string }>;
}
export default async function ReservationDetailPage({ params }: PageProps) {
const { portSlug, id } = await params;
return <ReservationDetail reservationId={id} portSlug={portSlug} />;
}

View File

@@ -1,5 +0,0 @@
import { BerthReservationsList } from '@/components/reservations/berth-reservations-list';
export default function BerthReservationsPage() {
return <BerthReservationsList />;
}

View File

@@ -0,0 +1,10 @@
import { TenancyDetail } from '@/components/tenancies/tenancy-detail';
interface PageProps {
params: Promise<{ portSlug: string; id: string }>;
}
export default async function TenancyDetailPage({ params }: PageProps) {
const { portSlug, id } = await params;
return <TenancyDetail tenancyId={id} portSlug={portSlug} />;
}

View File

@@ -0,0 +1,5 @@
import { TenanciesListPage } from '@/components/tenancies/tenancies-list-page';
export default function BerthTenanciesPage() {
return <TenanciesListPage />;
}

View File

@@ -59,11 +59,11 @@ export default async function PortalDashboardPage() {
route). Hidden until a memberships page ships. The count is still route). Hidden until a memberships page ships. The count is still
available in the underlying dashboard data when needed. */} available in the underlying dashboard data when needed. */}
<PortalCard <PortalCard
title="My Active Reservations" title="My Active Tenancies"
value={dashboard.counts.activeReservations} value={dashboard.counts.activeTenancies}
description="Current and pending berth reservations" description="Current and pending berth tenancies"
icon={CalendarCheck} icon={CalendarCheck}
href="/portal/my-reservations" href="/portal/my-tenancies"
/> />
</div> </div>

View File

@@ -3,10 +3,10 @@ import { CalendarCheck } from 'lucide-react';
import type { Metadata } from 'next'; import type { Metadata } from 'next';
import { getPortalSession } from '@/lib/portal/auth'; import { getPortalSession } from '@/lib/portal/auth';
import { getPortalUserReservations } from '@/lib/services/portal.service'; import { getPortalUserTenancies } from '@/lib/services/portal.service';
import { Badge } from '@/components/ui/badge'; import { Badge } from '@/components/ui/badge';
export const metadata: Metadata = { title: 'My Reservations' }; export const metadata: Metadata = { title: 'My Tenancies' };
const STATUS_COLORS: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = { const STATUS_COLORS: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
pending: 'secondary', pending: 'secondary',
@@ -29,30 +29,30 @@ function formatDate(d: Date | string): string {
}); });
} }
export default async function PortalMyReservationsPage() { export default async function PortalMyTenanciesPage() {
const session = await getPortalSession(); const session = await getPortalSession();
if (!session) redirect('/portal/login'); if (!session) redirect('/portal/login');
const reservations = await getPortalUserReservations(session.clientId, session.portId); const tenancies = await getPortalUserTenancies(session.clientId, session.portId);
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div> <div>
<h1 className="text-2xl font-semibold text-gray-900">My Reservations</h1> <h1 className="text-2xl font-semibold text-gray-900">My Tenancies</h1>
<p className="text-sm text-gray-500 mt-1">Your current and pending berth reservations</p> <p className="text-sm text-gray-500 mt-1">Your current and pending berth tenancies</p>
</div> </div>
{reservations.length === 0 ? ( {tenancies.length === 0 ? (
<div className="bg-white rounded-lg border p-12 text-center"> <div className="bg-white rounded-lg border p-12 text-center">
<CalendarCheck className="h-10 w-10 text-gray-300 mx-auto mb-3" /> <CalendarCheck className="h-10 w-10 text-gray-300 mx-auto mb-3" />
<p className="text-gray-500 font-medium">No active reservations</p> <p className="text-gray-500 font-medium">No active tenancies</p>
<p className="text-sm text-gray-400 mt-1"> <p className="text-sm text-gray-400 mt-1">
Contact your port representative to discuss reservations. Contact your port representative to discuss tenancies.
</p> </p>
</div> </div>
) : ( ) : (
<div className="space-y-3"> <div className="space-y-3">
{reservations.map((r) => ( {tenancies.map((r) => (
<div key={r.id} className="bg-white rounded-lg border p-5"> <div key={r.id} className="bg-white rounded-lg border p-5">
<div className="flex items-start justify-between gap-4"> <div className="flex items-start justify-between gap-4">
<div className="flex-1 min-w-0"> <div className="flex-1 min-w-0">

View File

@@ -1,6 +0,0 @@
import { withAuth, withPermission } from '@/lib/api/helpers';
import { listHandler, createHandler } from './handlers';
export const GET = withAuth(withPermission('reservations', 'view', listHandler));
export const POST = withAuth(withPermission('reservations', 'create', createHandler));

View File

@@ -6,8 +6,8 @@ import { parseBody, parseQuery } from '@/lib/api/route-helpers';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { NotFoundError, errorResponse } from '@/lib/errors'; import { NotFoundError, errorResponse } from '@/lib/errors';
import { createPending, listReservations } from '@/lib/services/berth-reservations.service'; import { createPending, listTenancies } from '@/lib/services/berth-tenancies.service';
import { createPendingSchema, listReservationsSchema } from '@/lib/validators/reservations'; import { createPendingSchema, listTenanciesSchema } from '@/lib/validators/tenancies';
// URL berthId is authoritative; make body berthId optional (ignored anyway). // URL berthId is authoritative; make body berthId optional (ignored anyway).
const createPendingBodySchema = createPendingSchema const createPendingBodySchema = createPendingSchema
@@ -24,8 +24,8 @@ async function assertBerthInPort(berthId: string, portId: string): Promise<void>
export const listHandler: RouteHandler = async (req, ctx, params) => { export const listHandler: RouteHandler = async (req, ctx, params) => {
try { try {
await assertBerthInPort(params.id!, ctx.portId); await assertBerthInPort(params.id!, ctx.portId);
const query = parseQuery(req, listReservationsSchema); const query = parseQuery(req, listTenanciesSchema);
const result = await listReservations(ctx.portId, { ...query, berthId: params.id! }); const result = await listTenancies(ctx.portId, { ...query, berthId: params.id! });
const { page, limit } = query; const { page, limit } = query;
const totalPages = Math.ceil(result.total / limit); const totalPages = Math.ceil(result.total / limit);
return NextResponse.json({ return NextResponse.json({
@@ -48,7 +48,7 @@ export const createHandler: RouteHandler = async (req, ctx, params) => {
try { try {
await assertBerthInPort(params.id!, ctx.portId); await assertBerthInPort(params.id!, ctx.portId);
const body = await parseBody(req, createPendingBodySchema); const body = await parseBody(req, createPendingBodySchema);
const reservation = await createPending( const tenancy = await createPending(
ctx.portId, ctx.portId,
{ ...body, berthId: params.id! }, { ...body, berthId: params.id! },
{ {
@@ -58,7 +58,7 @@ export const createHandler: RouteHandler = async (req, ctx, params) => {
userAgent: ctx.userAgent, userAgent: ctx.userAgent,
}, },
); );
return NextResponse.json({ data: reservation }, { status: 201 }); return NextResponse.json({ data: tenancy }, { status: 201 });
} catch (error) { } catch (error) {
return errorResponse(error); return errorResponse(error);
} }

View File

@@ -0,0 +1,6 @@
import { withAuth, withPermission } from '@/lib/api/helpers';
import { listHandler, createHandler } from './handlers';
export const GET = withAuth(withPermission('tenancies', 'view', listHandler));
export const POST = withAuth(withPermission('tenancies', 'manage', createHandler));

View File

@@ -35,10 +35,10 @@ const decisionsSchema = z.object({
}), }),
) )
.default([]), .default([]),
reservationDecisions: z tenancyDecisions: z
.array( .array(
z.object({ z.object({
reservationId: z.string().min(1), tenancyId: z.string().min(1),
action: z.enum(['cancel', 'transfer']), action: z.enum(['cancel', 'transfer']),
transferToClientId: z.string().min(1).optional(), transferToClientId: z.string().min(1).optional(),
}), }),

View File

@@ -16,7 +16,7 @@ interface PreflightItem {
stakeLevel: 'low' | 'high'; stakeLevel: 'low' | 'high';
highStakesStage: string | null; highStakesStage: string | null;
blockers: string[]; blockers: string[];
summary: { berths: number; yachts: number; reservations: number; signedDocs: number }; summary: { berths: number; yachts: number; tenancies: number; signedDocs: number };
} }
/** /**
@@ -43,7 +43,7 @@ export const POST = withAuth(
summary: { summary: {
berths: d.berths.length, berths: d.berths.length,
yachts: d.yachts.length, yachts: d.yachts.length,
reservations: d.reservations.length, tenancies: d.tenancies.length,
signedDocs: d.documents.filter( signedDocs: d.documents.filter(
(doc) => doc.status === 'completed' || doc.status === 'signed', (doc) => doc.status === 'completed' || doc.status === 'signed',
).length, ).length,
@@ -60,7 +60,7 @@ export const POST = withAuth(
stakeLevel: 'low', stakeLevel: 'low',
highStakesStage: null, highStakesStage: null,
blockers: ['Could not load dossier - client may have been removed'], blockers: ['Could not load dossier - client may have been removed'],
summary: { berths: 0, yachts: 0, reservations: 0, signedDocs: 0 }, summary: { berths: 0, yachts: 0, tenancies: 0, signedDocs: 0 },
}); });
} }
} }

View File

@@ -135,8 +135,8 @@ export const POST = withAuth(async (req, ctx) => {
acknowledgedSignedDocuments: hasSignedDocs, acknowledgedSignedDocuments: hasSignedDocs,
berthDecisions, berthDecisions,
yachtDecisions: dossier.yachts.map((y) => ({ yachtId: y.yachtId, action: 'retain' })), yachtDecisions: dossier.yachts.map((y) => ({ yachtId: y.yachtId, action: 'retain' })),
reservationDecisions: dossier.reservations.map((r) => ({ tenancyDecisions: dossier.tenancies.map((r) => ({
reservationId: r.reservationId, tenancyId: r.tenancyId,
action: 'cancel', action: 'cancel',
})), })),
invoiceDecisions: dossier.invoices.map((i) => ({ invoiceDecisions: dossier.invoices.map((i) => ({

View File

@@ -5,12 +5,7 @@ import { type RouteHandler } from '@/lib/api/helpers';
import { parseBody } from '@/lib/api/route-helpers'; import { parseBody } from '@/lib/api/route-helpers';
import { requirePermission } from '@/lib/auth/permissions'; import { requirePermission } from '@/lib/auth/permissions';
import { errorResponse } from '@/lib/errors'; import { errorResponse } from '@/lib/errors';
import { import { activate, cancel, endTenancy, getById } from '@/lib/services/berth-tenancies.service';
activate,
cancel,
endReservation,
getById,
} from '@/lib/services/berth-reservations.service';
// ─── PATCH body schema (action-based discriminated union) ──────────────────── // ─── PATCH body schema (action-based discriminated union) ────────────────────
@@ -35,8 +30,8 @@ const patchBodySchema = z.discriminatedUnion('action', [
export const getHandler: RouteHandler = async (_req, ctx, params) => { export const getHandler: RouteHandler = async (_req, ctx, params) => {
try { try {
const reservation = await getById(params.id!, ctx.portId); const tenancy = await getById(params.id!, ctx.portId);
return NextResponse.json({ data: reservation }); return NextResponse.json({ data: tenancy });
} catch (error) { } catch (error) {
return errorResponse(error); return errorResponse(error);
} }
@@ -53,7 +48,7 @@ export const patchHandler: RouteHandler = async (req, ctx, params) => {
}; };
if (body.action === 'activate') { if (body.action === 'activate') {
requirePermission(ctx, 'reservations', 'activate'); requirePermission(ctx, 'tenancies', 'manage');
const result = await activate( const result = await activate(
params.id!, params.id!,
ctx.portId, ctx.portId,
@@ -68,8 +63,8 @@ export const patchHandler: RouteHandler = async (req, ctx, params) => {
if (body.action === 'end') { if (body.action === 'end') {
// `end` is lifecycle progression; same privilege as activate. // `end` is lifecycle progression; same privilege as activate.
requirePermission(ctx, 'reservations', 'activate'); requirePermission(ctx, 'tenancies', 'manage');
const result = await endReservation( const result = await endTenancy(
params.id!, params.id!,
ctx.portId, ctx.portId,
{ endDate: body.endDate, notes: body.notes }, { endDate: body.endDate, notes: body.notes },
@@ -79,7 +74,7 @@ export const patchHandler: RouteHandler = async (req, ctx, params) => {
} }
// action === 'cancel' // action === 'cancel'
requirePermission(ctx, 'reservations', 'cancel'); requirePermission(ctx, 'tenancies', 'cancel');
const result = await cancel(params.id!, ctx.portId, { reason: body.reason }, meta); const result = await cancel(params.id!, ctx.portId, { reason: body.reason }, meta);
return NextResponse.json({ data: result }); return NextResponse.json({ data: result });
} catch (error) { } catch (error) {

View File

@@ -2,9 +2,9 @@ import { withAuth, withPermission } from '@/lib/api/helpers';
import { getHandler, patchHandler, deleteHandler } from './handlers'; import { getHandler, patchHandler, deleteHandler } from './handlers';
export const GET = withAuth(withPermission('reservations', 'view', getHandler)); export const GET = withAuth(withPermission('tenancies', 'view', getHandler));
// PATCH cannot use `withPermission` wrapper - the required permission depends // PATCH cannot use `withPermission` wrapper - the required permission depends
// on the `action` field in the body. `requirePermission` is called inside the // on the `action` field in the body. `requirePermission` is called inside the
// handler after the body is parsed. // handler after the body is parsed.
export const PATCH = withAuth(patchHandler); export const PATCH = withAuth(patchHandler);
export const DELETE = withAuth(withPermission('reservations', 'cancel', deleteHandler)); export const DELETE = withAuth(withPermission('tenancies', 'cancel', deleteHandler));

View File

@@ -3,19 +3,19 @@ import { NextResponse } from 'next/server';
import type { AuthContext } from '@/lib/api/helpers'; import type { AuthContext } from '@/lib/api/helpers';
import { parseQuery } from '@/lib/api/route-helpers'; import { parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors'; import { errorResponse } from '@/lib/errors';
import { listReservations } from '@/lib/services/berth-reservations.service'; import { listTenancies } from '@/lib/services/berth-tenancies.service';
import { listReservationsSchema } from '@/lib/validators/reservations'; import { listTenanciesSchema } from '@/lib/validators/tenancies';
/** /**
* Port-scoped global list of reservations across all berths. Inner handler * Port-scoped global list of tenancies across all berths. Inner handler
* lives here so it can be invoked directly from integration tests without * lives here so it can be invoked directly from integration tests without
* the `withAuth(withPermission(...))` wrappers (matches the convention * the `withAuth(withPermission(...))` wrappers (matches the convention
* used throughout `src/app/api/v1/*`). * used throughout `src/app/api/v1/*`).
*/ */
export async function listHandler(req: Request, ctx: AuthContext): Promise<NextResponse> { export async function listHandler(req: Request, ctx: AuthContext): Promise<NextResponse> {
try { try {
const query = parseQuery(req as never, listReservationsSchema); const query = parseQuery(req as never, listTenanciesSchema);
const result = await listReservations(ctx.portId, query); const result = await listTenancies(ctx.portId, query);
const { page, limit } = query; const { page, limit } = query;
const totalPages = Math.ceil(result.total / limit); const totalPages = Math.ceil(result.total / limit);
return NextResponse.json({ return NextResponse.json({

View File

@@ -1,4 +1,4 @@
import { withAuth, withPermission } from '@/lib/api/helpers'; import { withAuth, withPermission } from '@/lib/api/helpers';
import { listHandler } from './handlers'; import { listHandler } from './handlers';
export const GET = withAuth(withPermission('reservations', 'view', listHandler)); export const GET = withAuth(withPermission('tenancies', 'view', listHandler));

View File

@@ -82,7 +82,7 @@ const DEFAULT_PERMISSIONS: Record<string, Record<string, boolean>> = {
yachts: { view: false, create: false, edit: false, delete: false, transfer: false }, yachts: { view: false, create: false, edit: false, delete: false, transfer: false },
companies: { view: false, create: false, edit: false, delete: false }, companies: { view: false, create: false, edit: false, delete: false },
memberships: { view: false, manage: false }, memberships: { view: false, manage: false },
reservations: { view: false, create: false, activate: false, cancel: false }, tenancies: { view: false, manage: false, cancel: false },
admin: { admin: {
manage_users: false, manage_users: false,
view_audit_log: false, view_audit_log: false,
@@ -122,7 +122,7 @@ const GROUP_LABELS: Record<string, string> = {
yachts: 'Yachts', yachts: 'Yachts',
companies: 'Companies', companies: 'Companies',
memberships: 'Company Memberships', memberships: 'Company Memberships',
reservations: 'Reservations', tenancies: 'Tenancies',
admin: 'Administration', admin: 'Administration',
residential_clients: 'Residential Clients', residential_clients: 'Residential Clients',
residential_interests: 'Residential Interests', residential_interests: 'Residential Interests',

View File

@@ -46,7 +46,7 @@ const GROUP_LABELS: Record<string, string> = {
yachts: 'Yachts', yachts: 'Yachts',
companies: 'Companies', companies: 'Companies',
memberships: 'Company Memberships', memberships: 'Company Memberships',
reservations: 'Reservations', tenancies: 'Tenancies',
admin: 'Administration', admin: 'Administration',
residential_clients: 'Residential Clients', residential_clients: 'Residential Clients',
residential_interests: 'Residential Interests', residential_interests: 'Residential Interests',
@@ -89,7 +89,7 @@ const PERMISSION_LEAVES: Record<string, string[]> = {
yachts: ['view', 'create', 'edit', 'delete', 'transfer'], yachts: ['view', 'create', 'edit', 'delete', 'transfer'],
companies: ['view', 'create', 'edit', 'delete'], companies: ['view', 'create', 'edit', 'delete'],
memberships: ['view', 'manage'], memberships: ['view', 'manage'],
reservations: ['view', 'create', 'activate', 'cancel'], tenancies: ['view', 'manage', 'cancel'],
admin: [ admin: [
'manage_users', 'manage_users',
'view_audit_log', 'view_audit_log',

View File

@@ -23,7 +23,7 @@ import {
BERTH_SIDE_PONTOON_OPTIONS, BERTH_SIDE_PONTOON_OPTIONS,
toSelectOptions, toSelectOptions,
} from '@/lib/constants'; } from '@/lib/constants';
import { BerthReservationsTab } from './berth-reservations-tab'; import { BerthTenanciesTab } from './berth-tenancies-tab';
import { BerthInterestsTab } from './berth-interests-tab'; import { BerthInterestsTab } from './berth-interests-tab';
import { BerthInterestPulse } from './berth-interest-pulse'; import { BerthInterestPulse } from './berth-interest-pulse';
import { BerthDocumentsTab } from './berth-documents-tab'; import { BerthDocumentsTab } from './berth-documents-tab';
@@ -432,9 +432,9 @@ export function buildBerthTabs(berth: BerthData): DetailTab[] {
content: <BerthInterestsTab berthId={berth.id} />, content: <BerthInterestsTab berthId={berth.id} />,
}, },
{ {
id: 'reservations', id: 'tenancies',
label: 'Reservations', label: 'Tenancies',
content: <BerthReservationsTab berthId={berth.id} />, content: <BerthTenanciesTab berthId={berth.id} />,
}, },
{ {
id: 'spec', id: 'spec',

View File

@@ -9,61 +9,61 @@ import { Button } from '@/components/ui/button';
import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card'; import { Card, CardContent, CardHeader, CardTitle } from '@/components/ui/card';
import { PermissionGate } from '@/components/shared/permission-gate'; import { PermissionGate } from '@/components/shared/permission-gate';
import { EmptyState } from '@/components/shared/empty-state'; import { EmptyState } from '@/components/shared/empty-state';
import { ReservationList, type ReservationRow } from '@/components/reservations/reservation-list'; import { TenancyList, type TenancyRow } from '@/components/tenancies/tenancy-list';
import { BerthReserveDialog } from '@/components/reservations/berth-reserve-dialog'; import { BerthReserveDialog } from '@/components/tenancies/berth-reserve-dialog';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation'; import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
interface BerthReservationsTabProps { interface BerthTenanciesTabProps {
berthId: string; berthId: string;
} }
export function BerthReservationsTab({ berthId }: BerthReservationsTabProps) { export function BerthTenanciesTab({ berthId }: BerthTenanciesTabProps) {
const routeParams = useParams<{ portSlug: string }>(); const routeParams = useParams<{ portSlug: string }>();
const portSlug = routeParams?.portSlug ?? ''; const portSlug = routeParams?.portSlug ?? '';
const [reserveOpen, setReserveOpen] = useState(false); const [reserveOpen, setReserveOpen] = useState(false);
const { data, isLoading } = useQuery<{ data: ReservationRow[]; pagination?: unknown }>({ const { data, isLoading } = useQuery<{ data: TenancyRow[]; pagination?: unknown }>({
queryKey: ['berths', berthId, 'reservations'], queryKey: ['berths', berthId, 'tenancies'],
queryFn: () => queryFn: () =>
apiFetch( apiFetch(
`/api/v1/berths/${berthId}/reservations?page=1&limit=50&order=desc&includeArchived=false`, `/api/v1/berths/${berthId}/tenancies?page=1&limit=50&order=desc&includeArchived=false`,
), ),
}); });
useRealtimeInvalidation({ useRealtimeInvalidation({
'berth_reservation:created': [['berths', berthId, 'reservations']], 'berth_tenancy:created': [['berths', berthId, 'tenancies']],
'berth_reservation:activated': [['berths', berthId, 'reservations']], 'berth_tenancy:activated': [['berths', berthId, 'tenancies']],
'berth_reservation:ended': [['berths', berthId, 'reservations']], 'berth_tenancy:ended': [['berths', berthId, 'tenancies']],
'berth_reservation:cancelled': [['berths', berthId, 'reservations']], 'berth_tenancy:cancelled': [['berths', berthId, 'tenancies']],
}); });
const reservations = data?.data ?? []; const tenancies = data?.data ?? [];
const active = reservations.find((r) => r.status === 'active'); const active = tenancies.find((r) => r.status === 'active');
const history = reservations.filter((r) => r.status !== 'active'); const history = tenancies.filter((r) => r.status !== 'active');
return ( return (
<div className="space-y-6"> <div className="space-y-6">
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h3 className="text-lg font-semibold">Reservations</h3> <h3 className="text-lg font-semibold">Tenancies</h3>
<PermissionGate resource="reservations" action="create"> <PermissionGate resource="tenancies" action="manage">
<Button size="sm" onClick={() => setReserveOpen(true)}> <Button size="sm" onClick={() => setReserveOpen(true)}>
<Plus className="mr-1.5 h-4 w-4" aria-hidden /> <Plus className="mr-1.5 h-4 w-4" aria-hidden />
Reserve this berth Create tenancy
</Button> </Button>
</PermissionGate> </PermissionGate>
</div> </div>
{/* Active reservation card */} {/* Active tenancy card */}
<Card> <Card>
<CardHeader className="pb-3"> <CardHeader className="pb-3">
<CardTitle className="text-sm font-medium">Active reservation</CardTitle> <CardTitle className="text-sm font-medium">Active tenancy</CardTitle>
</CardHeader> </CardHeader>
<CardContent> <CardContent>
{active ? ( {active ? (
<ReservationList reservations={[active]} portSlug={portSlug} /> <TenancyList tenancies={[active]} portSlug={portSlug} />
) : ( ) : (
<p className="text-sm text-muted-foreground">No active reservation.</p> <p className="text-sm text-muted-foreground">No active tenancy.</p>
)} )}
</CardContent> </CardContent>
</Card> </Card>
@@ -77,9 +77,9 @@ export function BerthReservationsTab({ berthId }: BerthReservationsTabProps) {
{isLoading ? ( {isLoading ? (
<p className="text-sm text-muted-foreground">Loading</p> <p className="text-sm text-muted-foreground">Loading</p>
) : history.length === 0 ? ( ) : history.length === 0 ? (
<EmptyState title="No past reservations" description="Nothing here yet." /> <EmptyState title="No past tenancies" description="Nothing here yet." />
) : ( ) : (
<ReservationList reservations={history} portSlug={portSlug} /> <TenancyList tenancies={history} portSlug={portSlug} />
)} )}
</CardContent> </CardContent>
</Card> </Card>

View File

@@ -26,7 +26,7 @@ interface PreflightItem {
stakeLevel: 'low' | 'high'; stakeLevel: 'low' | 'high';
highStakesStage: string | null; highStakesStage: string | null;
blockers: string[]; blockers: string[];
summary: { berths: number; yachts: number; reservations: number; signedDocs: number }; summary: { berths: number; yachts: number; tenancies: number; signedDocs: number };
} }
interface Props { interface Props {
@@ -215,8 +215,8 @@ function BulkArchiveWizardBody({ open, onOpenChange, clientIds, onSuccess }: Pro
{currentHighStakes.summary.signedDocs > 0 {currentHighStakes.summary.signedDocs > 0
? `${currentHighStakes.summary.signedDocs} signed doc(s), ` ? `${currentHighStakes.summary.signedDocs} signed doc(s), `
: ''} : ''}
{currentHighStakes.summary.reservations > 0 {currentHighStakes.summary.tenancies > 0
? `${currentHighStakes.summary.reservations} reservation(s)` ? `${currentHighStakes.summary.tenancies} tenancy(ies)`
: ''} : ''}
</span> </span>
</WarningCallout> </WarningCallout>

View File

@@ -64,7 +64,7 @@ interface ClientData {
status: string; status: string;
}; };
}>; }>;
activeReservations: Array<{ activeTenancies: Array<{
id: string; id: string;
berthId: string; berthId: string;
yachtId: string; yachtId: string;
@@ -113,9 +113,9 @@ export function ClientDetail({ clientId, currentUserId }: ClientDetailProps) {
'yacht:ownership_transferred': [['clients', clientId]], 'yacht:ownership_transferred': [['clients', clientId]],
'company_membership:added': [['clients', clientId]], 'company_membership:added': [['clients', clientId]],
'company_membership:ended': [['clients', clientId]], 'company_membership:ended': [['clients', clientId]],
'berth_reservation:activated': [['clients', clientId]], 'berth_tenancy:activated': [['clients', clientId]],
'berth_reservation:ended': [['clients', clientId]], 'berth_tenancy:ended': [['clients', clientId]],
'berth_reservation:cancelled': [['clients', clientId]], 'berth_tenancy:cancelled': [['clients', clientId]],
}); });
if (error && !isLoading) { if (error && !isLoading) {

View File

@@ -16,7 +16,7 @@ import { ClientInterestsTab } from '@/components/clients/client-interests-tab';
import { ClientPipelineSummary } from '@/components/clients/client-pipeline-summary'; import { ClientPipelineSummary } from '@/components/clients/client-pipeline-summary';
import { ClientYachtsTab } from '@/components/clients/client-yachts-tab'; import { ClientYachtsTab } from '@/components/clients/client-yachts-tab';
import { ClientCompaniesTab } from '@/components/clients/client-companies-tab'; import { ClientCompaniesTab } from '@/components/clients/client-companies-tab';
import { ClientReservationsTab } from '@/components/clients/client-reservations-tab'; import { ClientTenanciesTab } from '@/components/clients/client-tenancies-tab';
import { ClientFilesTab } from '@/components/clients/client-files-tab'; import { ClientFilesTab } from '@/components/clients/client-files-tab';
import { ContactsEditor } from '@/components/clients/contacts-editor'; import { ContactsEditor } from '@/components/clients/contacts-editor';
import { AddressesEditor, type Address } from '@/components/shared/addresses-editor'; import { AddressesEditor, type Address } from '@/components/shared/addresses-editor';
@@ -123,7 +123,7 @@ interface ClientTabsOptions {
status: string; status: string;
}; };
}>; }>;
activeReservations: Array<{ activeTenancies: Array<{
id: string; id: string;
berthId: string; berthId: string;
yachtId: string; yachtId: string;
@@ -276,12 +276,10 @@ export function getClientTabs({ clientId, currentUserId, client }: ClientTabsOpt
content: <ClientCompaniesTab clientId={clientId} companies={client.companies} />, content: <ClientCompaniesTab clientId={clientId} companies={client.companies} />,
}, },
{ {
id: 'reservations', id: 'tenancies',
label: 'Reservations', label: 'Tenancies',
badge: client.activeReservations.length, badge: client.activeTenancies.length,
content: ( content: <ClientTenanciesTab clientId={clientId} activeTenancies={client.activeTenancies} />,
<ClientReservationsTab clientId={clientId} activeReservations={client.activeReservations} />
),
}, },
{ {
id: 'addresses', id: 'addresses',

View File

@@ -3,13 +3,13 @@
import { useState } from 'react'; import { useState } from 'react';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { ReservationList, type ReservationRow } from '@/components/reservations/reservation-list'; import { TenancyList, type TenancyRow } from '@/components/tenancies/tenancy-list';
import { Button } from '@/components/ui/button'; import { Button } from '@/components/ui/button';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
interface ClientReservationsTabProps { interface ClientTenanciesTabProps {
clientId: string; clientId: string;
activeReservations: Array<{ activeTenancies: Array<{
id: string; id: string;
berthId: string; berthId: string;
yachtId: string; yachtId: string;
@@ -19,24 +19,21 @@ interface ClientReservationsTabProps {
}>; }>;
} }
interface ReservationListResponse { interface TenancyListResponse {
data: ReservationRow[]; data: TenancyRow[];
pagination?: { total: number }; pagination?: { total: number };
} }
export function ClientReservationsTab({ export function ClientTenanciesTab({ clientId, activeTenancies }: ClientTenanciesTabProps) {
clientId,
activeReservations,
}: ClientReservationsTabProps) {
const [showHistory, setShowHistory] = useState(false); const [showHistory, setShowHistory] = useState(false);
const activeRows: ReservationRow[] = activeReservations.map((r) => ({ const activeRows: TenancyRow[] = activeTenancies.map((r) => ({
id: r.id, id: r.id,
berthId: r.berthId, berthId: r.berthId,
portId: '', portId: '',
clientId, clientId,
yachtId: r.yachtId, yachtId: r.yachtId,
status: r.status as ReservationRow['status'], status: r.status as TenancyRow['status'],
startDate: typeof r.startDate === 'string' ? r.startDate : r.startDate.toISOString(), startDate: typeof r.startDate === 'string' ? r.startDate : r.startDate.toISOString(),
endDate: null, endDate: null,
tenureType: r.tenureType, tenureType: r.tenureType,
@@ -48,23 +45,23 @@ export function ClientReservationsTab({
// Lazy-load history (ended + cancelled). Two parallel queries because // Lazy-load history (ended + cancelled). Two parallel queries because
// the API takes one status at a time; combining once both resolve. // the API takes one status at a time; combining once both resolve.
const endedQuery = useQuery({ const endedQuery = useQuery({
queryKey: ['reservations', { clientId, status: 'ended' }], queryKey: ['tenancies', { clientId, status: 'ended' }],
queryFn: () => queryFn: () =>
apiFetch<ReservationListResponse>( apiFetch<TenancyListResponse>(
`/api/v1/berth-reservations?clientId=${encodeURIComponent(clientId)}&status=ended&pageSize=50`, `/api/v1/tenancies?clientId=${encodeURIComponent(clientId)}&status=ended&pageSize=50`,
), ),
enabled: showHistory, enabled: showHistory,
}); });
const cancelledQuery = useQuery({ const cancelledQuery = useQuery({
queryKey: ['reservations', { clientId, status: 'cancelled' }], queryKey: ['tenancies', { clientId, status: 'cancelled' }],
queryFn: () => queryFn: () =>
apiFetch<ReservationListResponse>( apiFetch<TenancyListResponse>(
`/api/v1/berth-reservations?clientId=${encodeURIComponent(clientId)}&status=cancelled&pageSize=50`, `/api/v1/tenancies?clientId=${encodeURIComponent(clientId)}&status=cancelled&pageSize=50`,
), ),
enabled: showHistory, enabled: showHistory,
}); });
const historyRows: ReservationRow[] = [ const historyRows: TenancyRow[] = [
...(endedQuery.data?.data ?? []), ...(endedQuery.data?.data ?? []),
...(cancelledQuery.data?.data ?? []), ...(cancelledQuery.data?.data ?? []),
].sort((a, b) => (a.startDate < b.startDate ? 1 : -1)); ].sort((a, b) => (a.startDate < b.startDate ? 1 : -1));
@@ -75,12 +72,12 @@ export function ClientReservationsTab({
<div className="space-y-6"> <div className="space-y-6">
<div> <div>
<div className="flex items-center justify-between"> <div className="flex items-center justify-between">
<h3 className="text-sm font-medium">Active reservations</h3> <h3 className="text-sm font-medium">Active tenancies</h3>
</div> </div>
<ReservationList <TenancyList
reservations={activeRows} tenancies={activeRows}
showBerth showBerth
emptyMessage="This client has no active reservations." emptyMessage="This client has no active tenancies."
/> />
</div> </div>
@@ -100,15 +97,15 @@ export function ClientReservationsTab({
isHistoryLoading ? ( isHistoryLoading ? (
<p className="text-xs text-muted-foreground">Loading</p> <p className="text-xs text-muted-foreground">Loading</p>
) : ( ) : (
<ReservationList <TenancyList
reservations={historyRows} tenancies={historyRows}
showBerth showBerth
emptyMessage="No ended or cancelled reservations." emptyMessage="No ended or cancelled tenancies."
/> />
) )
) : ( ) : (
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">
Click &ldquo;Show history&rdquo; to load ended and cancelled reservations. Click &ldquo;Show history&rdquo; to load ended and cancelled tenancies.
</p> </p>
)} )}
</div> </div>

View File

@@ -47,8 +47,8 @@ interface DossierYacht {
hullNumber: string | null; hullNumber: string | null;
status: string; status: string;
} }
interface DossierReservation { interface DossierTenancy {
reservationId: string; tenancyId: string;
berthId: string; berthId: string;
mooringNumber: string; mooringNumber: string;
status: string; status: string;
@@ -75,7 +75,7 @@ interface ArchiveDossier {
berths: DossierBerth[]; berths: DossierBerth[];
yachts: DossierYacht[]; yachts: DossierYacht[];
companies: Array<{ companyId: string; name: string; membershipRole: string | null }>; companies: Array<{ companyId: string; name: string; membershipRole: string | null }>;
reservations: DossierReservation[]; tenancies: DossierTenancy[];
invoices: DossierInvoice[]; invoices: DossierInvoice[];
documents: DossierDocument[]; documents: DossierDocument[];
hasPortalUser: boolean; hasPortalUser: boolean;
@@ -84,7 +84,7 @@ interface ArchiveDossier {
type BerthAction = 'release' | 'retain'; type BerthAction = 'release' | 'retain';
type YachtAction = 'transfer' | 'mark_sold_away' | 'retain'; type YachtAction = 'transfer' | 'mark_sold_away' | 'retain';
type ReservationAction = 'cancel' | 'transfer'; type TenancyAction = 'cancel' | 'transfer';
type InvoiceAction = 'void' | 'write_off' | 'leave'; type InvoiceAction = 'void' | 'write_off' | 'leave';
type DocumentAction = 'void_documenso' | 'leave'; type DocumentAction = 'void_documenso' | 'leave';
@@ -168,13 +168,9 @@ function SmartArchiveDialogBody({
? Object.fromEntries(dossier.yachts.map((y) => [y.yachtId, 'retain' as YachtAction])) ? Object.fromEntries(dossier.yachts.map((y) => [y.yachtId, 'retain' as YachtAction]))
: {}, : {},
); );
const [reservationDecisions, setReservationDecisions] = useState< const [tenancyDecisions, setTenancyDecisions] = useState<Record<string, TenancyAction>>(() =>
Record<string, ReservationAction>
>(() =>
dossier dossier
? Object.fromEntries( ? Object.fromEntries(dossier.tenancies.map((r) => [r.tenancyId, 'cancel' as TenancyAction]))
dossier.reservations.map((r) => [r.reservationId, 'cancel' as ReservationAction]),
)
: {}, : {},
); );
const [invoiceDecisions, setInvoiceDecisions] = useState<Record<string, InvoiceAction>>(() => const [invoiceDecisions, setInvoiceDecisions] = useState<Record<string, InvoiceAction>>(() =>
@@ -233,9 +229,9 @@ function SmartArchiveDialogBody({
yachtId: y.yachtId, yachtId: y.yachtId,
action: yachtDecisions[y.yachtId] ?? 'retain', action: yachtDecisions[y.yachtId] ?? 'retain',
})), })),
reservationDecisions: dossier.reservations.map((r) => ({ tenancyDecisions: dossier.tenancies.map((r) => ({
reservationId: r.reservationId, tenancyId: r.tenancyId,
action: reservationDecisions[r.reservationId] ?? 'cancel', action: tenancyDecisions[r.tenancyId] ?? 'cancel',
})), })),
invoiceDecisions: dossier.invoices.map((i) => ({ invoiceDecisions: dossier.invoices.map((i) => ({
invoiceId: i.invoiceId, invoiceId: i.invoiceId,
@@ -459,33 +455,30 @@ function SmartArchiveDialogBody({
</Card> </Card>
)} )}
{/* Reservations */} {/* Tenancies */}
{dossier.reservations.length > 0 && ( {dossier.tenancies.length > 0 && (
<Card> <Card>
<CardHeader className="pb-2"> <CardHeader className="pb-2">
<CardTitle className="text-sm font-medium flex items-center gap-2"> <CardTitle className="text-sm font-medium flex items-center gap-2">
<Anchor className="h-4 w-4" aria-hidden /> Active reservations ( <Anchor className="h-4 w-4" aria-hidden /> Active tenancies (
{dossier.reservations.length}) {dossier.tenancies.length})
</CardTitle> </CardTitle>
</CardHeader> </CardHeader>
<CardContent className="space-y-2"> <CardContent className="space-y-2">
{dossier.reservations.map((r) => ( {dossier.tenancies.map((r) => (
<div <div key={r.tenancyId} className="flex items-center justify-between text-xs">
key={r.reservationId}
className="flex items-center justify-between text-xs"
>
<span>Berth {r.mooringNumber}</span> <span>Berth {r.mooringNumber}</span>
<select <select
className="rounded border bg-background px-2 py-1 text-xs" className="rounded border bg-background px-2 py-1 text-xs"
value={reservationDecisions[r.reservationId] ?? 'cancel'} value={tenancyDecisions[r.tenancyId] ?? 'cancel'}
onChange={(e) => onChange={(e) =>
setReservationDecisions((prev) => ({ setTenancyDecisions((prev) => ({
...prev, ...prev,
[r.reservationId]: e.target.value as ReservationAction, [r.tenancyId]: e.target.value as TenancyAction,
})) }))
} }
> >
<option value="cancel">Cancel reservation</option> <option value="cancel">Cancel tenancy</option>
</select> </select>
</div> </div>
))} ))}

View File

@@ -58,7 +58,7 @@ function humanizeFieldName(name: string): string {
const ENTITY_TYPE_LABELS: Record<string, string> = { const ENTITY_TYPE_LABELS: Record<string, string> = {
residential_client: 'Residential client', residential_client: 'Residential client',
residential_interest: 'Residential interest', residential_interest: 'Residential interest',
berth_reservation: 'Berth reservation', berth_tenancy: 'Berth tenancy',
berth_maintenance_log: 'Berth maintenance', berth_maintenance_log: 'Berth maintenance',
berth_recommendation: 'Berth recommendation', berth_recommendation: 'Berth recommendation',
client_note: 'Client note', client_note: 'Client note',

View File

@@ -45,7 +45,7 @@ const SIGNER_ROLES = ['client', 'sales', 'approver', 'developer', 'other'] as co
const SUBJECT_TYPES = [ const SUBJECT_TYPES = [
{ key: 'interest', label: 'Interest', field: 'interestId' as const }, { key: 'interest', label: 'Interest', field: 'interestId' as const },
{ key: 'reservation', label: 'Reservation', field: 'reservationId' as const }, { key: 'tenancy', label: 'Tenancy', field: 'tenancyId' as const },
{ key: 'client', label: 'Client', field: 'clientId' as const }, { key: 'client', label: 'Client', field: 'clientId' as const },
{ key: 'company', label: 'Company', field: 'companyId' as const }, { key: 'company', label: 'Company', field: 'companyId' as const },
{ key: 'yacht', label: 'Yacht', field: 'yachtId' as const }, { key: 'yacht', label: 'Yacht', field: 'yachtId' as const },
@@ -364,7 +364,7 @@ export function CreateDocumentWizard({ portSlug }: CreateDocumentWizardProps) {
<Input <Input
value={subjectId} value={subjectId}
onChange={(e) => setSubjectId(e.target.value)} onChange={(e) => setSubjectId(e.target.value)}
placeholder="Reservation id" placeholder="Tenancy id"
/> />
)} )}
</div> </div>

View File

@@ -57,7 +57,7 @@ interface DetailDoc {
documentType: string; documentType: string;
documensoId: string | null; documensoId: string | null;
signedFileId: string | null; signedFileId: string | null;
reservationId: string | null; tenancyId: string | null;
interestId: string | null; interestId: string | null;
clientId: string | null; clientId: string | null;
yachtId: string | null; yachtId: string | null;
@@ -232,10 +232,10 @@ export function DocumentDetail({ documentId, portSlug }: DocumentDetailProps) {
// render as a chip row; nothing renders when there's nothing to // render as a chip row; nothing renders when there's nothing to
// link. // link.
const linkedRows: Array<{ href: string; label: string; sub: string | null }> = []; const linkedRows: Array<{ href: string; label: string; sub: string | null }> = [];
if (doc.reservationId) { if (doc.tenancyId) {
linkedRows.push({ linkedRows.push({
href: `/${portSlug}/berth-reservations/${doc.reservationId}`, href: `/${portSlug}/tenancies/${doc.tenancyId}`,
label: 'Reservation', label: 'Tenancy',
sub: null, sub: null,
}); });
} }

View File

@@ -75,7 +75,7 @@ interface InterestData {
reminderDays: number | null; reminderDays: number | null;
reminderLastFired: string | null; reminderLastFired: string | null;
/** Phase 2 risk-signal dates derived in getInterestById from event /** Phase 2 risk-signal dates derived in getInterestById from event
* tables (document_events, berth_reservations, conflicting won * tables (document_events, berth_tenancies, conflicting won
* interests). Feed DealPulseChip; null when no matching event. */ * interests). Feed DealPulseChip; null when no matching event. */
dateDocumentDeclined: string | null; dateDocumentDeclined: string | null;
dateReservationCancelled: string | null; dateReservationCancelled: string | null;

View File

@@ -17,7 +17,7 @@ const navItems = [
{ label: 'Dashboard', href: '/portal/dashboard', icon: LayoutDashboard }, { label: 'Dashboard', href: '/portal/dashboard', icon: LayoutDashboard },
{ label: 'Interests', href: '/portal/interests', icon: Anchor }, { label: 'Interests', href: '/portal/interests', icon: Anchor },
{ label: 'My Yachts', href: '/portal/my-yachts', icon: Sailboat }, { label: 'My Yachts', href: '/portal/my-yachts', icon: Sailboat },
{ label: 'Reservations', href: '/portal/my-reservations', icon: CalendarCheck }, { label: 'Tenancies', href: '/portal/my-tenancies', icon: CalendarCheck },
{ label: 'Documents', href: '/portal/documents', icon: FileText }, { label: 'Documents', href: '/portal/documents', icon: FileText },
{ label: 'Invoices', href: '/portal/invoices', icon: Receipt }, { label: 'Invoices', href: '/portal/invoices', icon: Receipt },
{ label: 'Profile', href: '/portal/profile', icon: User }, { label: 'Profile', href: '/portal/profile', icon: User },

View File

@@ -102,7 +102,7 @@ export function BerthReserveDialog({ open, onOpenChange, berthId }: BerthReserve
} }
async function createPending(data: FormValues): Promise<{ id: string }> { async function createPending(data: FormValues): Promise<{ id: string }> {
const res = await apiFetch<{ data: { id: string } }>(`/api/v1/berths/${berthId}/reservations`, { const res = await apiFetch<{ data: { id: string } }>(`/api/v1/berths/${berthId}/tenancies`, {
method: 'POST', method: 'POST',
body: { body: {
clientId: data.clientId!, clientId: data.clientId!,
@@ -122,9 +122,9 @@ export function BerthReserveDialog({ open, onOpenChange, berthId }: BerthReserve
await createPending(data); await createPending(data);
}, },
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['berths', berthId, 'reservations'] }); queryClient.invalidateQueries({ queryKey: ['berths', berthId, 'tenancies'] });
queryClient.invalidateQueries({ queryKey: ['berth-reservations'] }); queryClient.invalidateQueries({ queryKey: ['tenancies'] });
toast.success('Reservation created'); toast.success('Tenancy created');
onOpenChange(false); onOpenChange(false);
}, },
onError: (err: unknown) => { onError: (err: unknown) => {
@@ -139,22 +139,22 @@ export function BerthReserveDialog({ open, onOpenChange, berthId }: BerthReserve
if (err) throw new Error(err); if (err) throw new Error(err);
const pending = await createPending(data); const pending = await createPending(data);
// Immediately activate // Immediately activate
await apiFetch(`/api/v1/berth-reservations/${pending.id}`, { await apiFetch(`/api/v1/tenancies/${pending.id}`, {
method: 'PATCH', method: 'PATCH',
body: { action: 'activate' }, body: { action: 'activate' },
}); });
}, },
onSuccess: () => { onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['berths', berthId, 'reservations'] }); queryClient.invalidateQueries({ queryKey: ['berths', berthId, 'tenancies'] });
queryClient.invalidateQueries({ queryKey: ['berth-reservations'] }); queryClient.invalidateQueries({ queryKey: ['tenancies'] });
toast.success('Reservation created and activated'); toast.success('Tenancy created and activated');
onOpenChange(false); onOpenChange(false);
}, },
onError: (err: unknown) => { onError: (err: unknown) => {
const msg = err instanceof Error ? err.message : 'Failed to activate'; const msg = err instanceof Error ? err.message : 'Failed to activate';
if (/active reservation|conflict|409/i.test(msg)) { if (/active tenancy|active reservation|conflict|409/i.test(msg)) {
setFormError( setFormError(
'This berth already has an active reservation. The pending record was created - activate it manually once the other reservation ends.', 'This berth already has an active tenancy. The pending record was created - activate it manually once the other tenancy ends.',
); );
} else { } else {
setFormError(msg); setFormError(msg);

View File

@@ -5,30 +5,30 @@ import { useParams } from 'next/navigation';
import { useQuery } from '@tanstack/react-query'; import { useQuery } from '@tanstack/react-query';
import { PageHeader } from '@/components/shared/page-header'; import { PageHeader } from '@/components/shared/page-header';
import { ReservationList, type ReservationRow } from '@/components/reservations/reservation-list'; import { TenancyList, type TenancyRow } from '@/components/tenancies/tenancy-list';
import { TableSkeleton } from '@/components/shared/loading-skeleton'; import { TableSkeleton } from '@/components/shared/loading-skeleton';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
interface ReservationsApiResponse { interface TenanciesApiResponse {
data: ReservationRow[]; data: TenancyRow[];
pagination: { total: number; page: number; pageSize: number }; pagination: { total: number; page: number; pageSize: number };
} }
export function BerthReservationsList() { export function TenanciesListPage() {
const params = useParams<{ portSlug: string }>(); const params = useParams<{ portSlug: string }>();
const portSlug = params?.portSlug ?? ''; const portSlug = params?.portSlug ?? '';
const { data, isLoading } = useQuery<ReservationsApiResponse>({ const { data, isLoading } = useQuery<TenanciesApiResponse>({
queryKey: ['berth-reservations', 'list'], queryKey: ['tenancies', 'list'],
queryFn: () => apiFetch('/api/v1/berth-reservations?page=1&limit=100&order=desc'), queryFn: () => apiFetch('/api/v1/tenancies?page=1&limit=100&order=desc'),
}); });
return ( return (
<div className="flex flex-col gap-6"> <div className="flex flex-col gap-6">
<PageHeader <PageHeader
eyebrow="Marina" eyebrow="Marina"
title="Berth Reservations" title="Tenancies"
description="All reservations across all berths" description="All tenancies across all berths"
actions={ actions={
<Link <Link
href={`/${portSlug}/berths`} href={`/${portSlug}/berths`}
@@ -42,11 +42,11 @@ export function BerthReservationsList() {
{isLoading ? ( {isLoading ? (
<TableSkeleton /> <TableSkeleton />
) : ( ) : (
<ReservationList <TenancyList
reservations={data?.data ?? []} tenancies={data?.data ?? []}
showBerth showBerth
portSlug={portSlug} portSlug={portSlug}
emptyMessage="No reservations found." emptyMessage="No tenancies found."
/> />
)} )}
</div> </div>

View File

@@ -23,9 +23,9 @@ import { EmptyState } from '@/components/ui/empty-state';
import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation'; import { useRealtimeInvalidation } from '@/hooks/use-realtime-invalidation';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
import { toastError } from '@/lib/api/toast-error'; import { toastError } from '@/lib/api/toast-error';
import { ClientLink, YachtLink, BerthLink } from '@/components/reservations/reservation-list'; import { ClientLink, YachtLink, BerthLink } from '@/components/tenancies/tenancy-list';
interface ReservationDoc { interface TenancyDoc {
id: string; id: string;
title: string; title: string;
status: string; status: string;
@@ -34,7 +34,7 @@ interface ReservationDoc {
signers: Array<{ id: string; status: string; signerName: string }>; signers: Array<{ id: string; status: string; signerName: string }>;
} }
interface ReservationData { interface TenancyData {
id: string; id: string;
status: string; status: string;
startDate: string; startDate: string;
@@ -47,7 +47,7 @@ interface ReservationData {
notes: string | null; notes: string | null;
} }
const RESERVATION_PILL: Record<string, StatusPillStatus> = { const TENANCY_PILL: Record<string, StatusPillStatus> = {
pending: 'pending', pending: 'pending',
active: 'active', active: 'active',
ended: 'archived', ended: 'archived',
@@ -58,13 +58,13 @@ function todayIso(): string {
return new Date().toISOString().slice(0, 10); return new Date().toISOString().slice(0, 10);
} }
interface EndReservationDialogProps { interface EndTenancyDialogProps {
reservationId: string; tenancyId: string;
open: boolean; open: boolean;
onOpenChange: (open: boolean) => void; onOpenChange: (open: boolean) => void;
} }
function EndReservationDialog({ reservationId, open, onOpenChange }: EndReservationDialogProps) { function EndTenancyDialog({ tenancyId, open, onOpenChange }: EndTenancyDialogProps) {
const qc = useQueryClient(); const qc = useQueryClient();
const [endDate, setEndDate] = useState(todayIso); const [endDate, setEndDate] = useState(todayIso);
const [submitting, setSubmitting] = useState(false); const [submitting, setSubmitting] = useState(false);
@@ -73,12 +73,12 @@ function EndReservationDialog({ reservationId, open, onOpenChange }: EndReservat
e.preventDefault(); e.preventDefault();
setSubmitting(true); setSubmitting(true);
try { try {
await apiFetch(`/api/v1/berth-reservations/${reservationId}`, { await apiFetch(`/api/v1/tenancies/${tenancyId}`, {
method: 'PATCH', method: 'PATCH',
body: { action: 'end', endDate }, body: { action: 'end', endDate },
}); });
qc.invalidateQueries({ queryKey: ['reservation', reservationId] }); qc.invalidateQueries({ queryKey: ['tenancy', tenancyId] });
toast.success('Reservation ended'); toast.success('Tenancy ended');
onOpenChange(false); onOpenChange(false);
} catch (err) { } catch (err) {
toastError(err); toastError(err);
@@ -91,7 +91,7 @@ function EndReservationDialog({ reservationId, open, onOpenChange }: EndReservat
<Dialog open={open} onOpenChange={onOpenChange}> <Dialog open={open} onOpenChange={onOpenChange}>
<DialogContent className="sm:max-w-sm"> <DialogContent className="sm:max-w-sm">
<DialogHeader> <DialogHeader>
<DialogTitle>End reservation</DialogTitle> <DialogTitle>End tenancy</DialogTitle>
</DialogHeader> </DialogHeader>
<form onSubmit={handleSubmit} className="space-y-4 pt-2"> <form onSubmit={handleSubmit} className="space-y-4 pt-2">
<div className="space-y-1.5"> <div className="space-y-1.5">
@@ -103,7 +103,7 @@ function EndReservationDialog({ reservationId, open, onOpenChange }: EndReservat
Cancel Cancel
</Button> </Button>
<Button type="submit" variant="destructive" disabled={submitting}> <Button type="submit" variant="destructive" disabled={submitting}>
{submitting ? 'Ending…' : 'End reservation'} {submitting ? 'Ending…' : 'End tenancy'}
</Button> </Button>
</DialogFooter> </DialogFooter>
</form> </form>
@@ -112,50 +112,50 @@ function EndReservationDialog({ reservationId, open, onOpenChange }: EndReservat
); );
} }
interface ReservationDetailProps { interface TenancyDetailProps {
reservationId: string; tenancyId: string;
portSlug: string; portSlug: string;
} }
export function ReservationDetail({ reservationId, portSlug }: ReservationDetailProps) { export function TenancyDetail({ tenancyId, portSlug }: TenancyDetailProps) {
const [endDialogOpen, setEndDialogOpen] = useState(false); const [endDialogOpen, setEndDialogOpen] = useState(false);
const reservation = useQuery<{ data: ReservationData }>({ const tenancy = useQuery<{ data: TenancyData }>({
queryKey: ['reservation', reservationId], queryKey: ['tenancy', tenancyId],
queryFn: () => apiFetch(`/api/v1/berth-reservations/${reservationId}`), queryFn: () => apiFetch(`/api/v1/tenancies/${tenancyId}`),
}); });
const documentsForRes = useQuery<{ data: ReservationDoc[] }>({ const documentsForTenancy = useQuery<{ data: TenancyDoc[] }>({
queryKey: ['documents', 'by-reservation', reservationId], queryKey: ['documents', 'by-tenancy', tenancyId],
queryFn: () => queryFn: () =>
apiFetch( apiFetch(
`/api/v1/documents?documentType=reservation_agreement&signatureOnly=true&limit=10`, `/api/v1/documents?documentType=reservation_agreement&signatureOnly=true&limit=10`,
).then((res) => { ).then((res) => {
const r = res as { data: ReservationDoc[] & Array<{ reservationId?: string }> }; const r = res as { data: TenancyDoc[] & Array<{ tenancyId?: string }> };
return { return {
data: r.data.filter( data: r.data.filter(
(d: ReservationDoc & { reservationId?: string }) => d.reservationId === reservationId, (d: TenancyDoc & { tenancyId?: string }) => d.tenancyId === tenancyId,
), ),
} as { data: ReservationDoc[] }; } as { data: TenancyDoc[] };
}), }),
}); });
useRealtimeInvalidation({ useRealtimeInvalidation({
'document:created': [['documents', 'by-reservation', reservationId]], 'document:created': [['documents', 'by-tenancy', tenancyId]],
'document:completed': [ 'document:completed': [
['documents', 'by-reservation', reservationId], ['documents', 'by-tenancy', tenancyId],
['reservation', reservationId], ['tenancy', tenancyId],
], ],
'document:cancelled': [['documents', 'by-reservation', reservationId]], 'document:cancelled': [['documents', 'by-tenancy', tenancyId]],
}); });
if (reservation.isLoading) { if (tenancy.isLoading) {
return <div className="h-32 animate-pulse rounded-md bg-muted/40" />; return <div className="h-32 animate-pulse rounded-md bg-muted/40" />;
} }
if (reservation.error || !reservation.data) { if (tenancy.error || !tenancy.data) {
return ( return (
<PageHeader <PageHeader
title="Reservation not found" title="Tenancy not found"
actions={ actions={
<Button asChild variant="outline"> <Button asChild variant="outline">
<Link href={`/${portSlug}/berths`}> <Link href={`/${portSlug}/berths`}>
@@ -167,8 +167,8 @@ export function ReservationDetail({ reservationId, portSlug }: ReservationDetail
); );
} }
const res = reservation.data.data; const res = tenancy.data.data;
const docs = documentsForRes.data?.data ?? []; const docs = documentsForTenancy.data?.data ?? [];
const activeAgreement = docs.find((d) => ['sent', 'partially_signed'].includes(d.status)); const activeAgreement = docs.find((d) => ['sent', 'partially_signed'].includes(d.status));
const completedAgreement = docs.find((d) => ['completed', 'signed'].includes(d.status)); const completedAgreement = docs.find((d) => ['completed', 'signed'].includes(d.status));
@@ -199,9 +199,7 @@ export function ReservationDetail({ reservationId, portSlug }: ReservationDetail
</Link> </Link>
</Button> </Button>
</div> </div>
<p className="text-xs text-muted-foreground"> <p className="text-xs text-muted-foreground">Signed contract attached to this tenancy.</p>
Signed contract attached to this reservation.
</p>
</div> </div>
); );
} }
@@ -254,13 +252,13 @@ export function ReservationDetail({ reservationId, portSlug }: ReservationDetail
return ( return (
<EmptyState <EmptyState
icon={<FileSignature className="h-7 w-7" aria-hidden />} icon={<FileSignature className="h-7 w-7" aria-hidden />}
title="No reservation agreement yet" title="No tenancy agreement yet"
body="Generate an agreement for the parties to sign before activation." body="Generate an agreement for the parties to sign before activation."
actions={ actions={
<Button asChild> <Button asChild>
<Link <Link
href={ href={
`/${portSlug}/documents/new?reservationId=${reservationId}&documentType=reservation_agreement` as Route `/${portSlug}/documents/new?tenancyId=${tenancyId}&documentType=reservation_agreement` as Route
} }
> >
Generate agreement Generate agreement
@@ -274,12 +272,12 @@ export function ReservationDetail({ reservationId, portSlug }: ReservationDetail
return ( return (
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<PageHeader <PageHeader
eyebrow="Berth reservation" eyebrow="Berth tenancy"
title={`Reservation #${res.id.slice(0, 8)}`} title={`Tenancy #${res.id.slice(0, 8)}`}
description={`${res.tenureType.replace(/_/g, ' ')} · ${new Date(res.startDate).toLocaleDateString(undefined)}${res.endDate ? `${new Date(res.endDate).toLocaleDateString(undefined)}` : ''}`} description={`${res.tenureType.replace(/_/g, ' ')} · ${new Date(res.startDate).toLocaleDateString(undefined)}${res.endDate ? `${new Date(res.endDate).toLocaleDateString(undefined)}` : ''}`}
kpiLine={ kpiLine={
<> <>
<StatusPill status={RESERVATION_PILL[res.status] ?? 'pending'} withDot> <StatusPill status={TENANCY_PILL[res.status] ?? 'pending'} withDot>
{res.status} {res.status}
</StatusPill> </StatusPill>
{res.contractFileId ? <span>Contract attached</span> : <span>No contract</span>} {res.contractFileId ? <span>Contract attached</span> : <span>No contract</span>}
@@ -290,7 +288,7 @@ export function ReservationDetail({ reservationId, portSlug }: ReservationDetail
{res.status === 'active' && ( {res.status === 'active' && (
<Button variant="outline" size="sm" onClick={() => setEndDialogOpen(true)}> <Button variant="outline" size="sm" onClick={() => setEndDialogOpen(true)}>
<StopCircle className="mr-1.5 h-4 w-4" aria-hidden /> <StopCircle className="mr-1.5 h-4 w-4" aria-hidden />
End reservation End tenancy
</Button> </Button>
)} )}
<Button asChild variant="outline"> <Button asChild variant="outline">
@@ -307,7 +305,7 @@ export function ReservationDetail({ reservationId, portSlug }: ReservationDetail
<div className="flex flex-col gap-4"> <div className="flex flex-col gap-4">
<section className="rounded-md border bg-white p-4"> <section className="rounded-md border bg-white p-4">
<h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground"> <h2 className="mb-2 text-sm font-semibold uppercase tracking-wide text-muted-foreground">
Reservation details Tenancy details
</h2> </h2>
<dl className="grid grid-cols-2 gap-3 text-sm"> <dl className="grid grid-cols-2 gap-3 text-sm">
<div> <div>
@@ -352,8 +350,8 @@ export function ReservationDetail({ reservationId, portSlug }: ReservationDetail
</div> </div>
</div> </div>
<EndReservationDialog <EndTenancyDialog
reservationId={reservationId} tenancyId={tenancyId}
open={endDialogOpen} open={endDialogOpen}
onOpenChange={setEndDialogOpen} onOpenChange={setEndDialogOpen}
/> />

View File

@@ -15,7 +15,7 @@ import {
import { EmptyState } from '@/components/shared/empty-state'; import { EmptyState } from '@/components/shared/empty-state';
import { apiFetch } from '@/lib/api/client'; import { apiFetch } from '@/lib/api/client';
export interface ReservationRow { export interface TenancyRow {
id: string; id: string;
berthId: string; berthId: string;
portId: string; portId: string;
@@ -30,8 +30,8 @@ export interface ReservationRow {
createdAt: string; createdAt: string;
} }
export interface ReservationListProps { export interface TenancyListProps {
reservations: ReservationRow[]; tenancies: TenancyRow[];
showBerth?: boolean; showBerth?: boolean;
portSlug?: string; portSlug?: string;
emptyMessage?: string; emptyMessage?: string;
@@ -106,8 +106,8 @@ export function BerthLink({ berthId, portSlug }: { berthId: string; portSlug: st
/** /**
* Renders a status badge with appropriate color coding. * Renders a status badge with appropriate color coding.
*/ */
function StatusBadge({ status }: { status: ReservationRow['status'] }) { function StatusBadge({ status }: { status: TenancyRow['status'] }) {
const colorMap: Record<ReservationRow['status'], string> = { const colorMap: Record<TenancyRow['status'], string> = {
pending: 'bg-gray-100 text-gray-800', pending: 'bg-gray-100 text-gray-800',
active: 'bg-green-100 text-green-800', active: 'bg-green-100 text-green-800',
ended: 'bg-blue-100 text-blue-800', ended: 'bg-blue-100 text-blue-800',
@@ -145,19 +145,17 @@ function formatDateRange(startDate: string, endDate: string | null): string {
return `${start}${end}`; return `${start}${end}`;
} }
export function ReservationList({ export function TenancyList({
reservations, tenancies,
showBerth = false, showBerth = false,
portSlug: portSlugProp, portSlug: portSlugProp,
emptyMessage, emptyMessage,
}: ReservationListProps) { }: TenancyListProps) {
const routeParams = useParams<{ portSlug: string }>(); const routeParams = useParams<{ portSlug: string }>();
const portSlug = portSlugProp ?? routeParams?.portSlug ?? ''; const portSlug = portSlugProp ?? routeParams?.portSlug ?? '';
if (reservations.length === 0) { if (tenancies.length === 0) {
return ( return <EmptyState title="No tenancies" description={emptyMessage ?? 'No tenancies yet.'} />;
<EmptyState title="No reservations" description={emptyMessage ?? 'No reservations yet.'} />
);
} }
return ( return (
@@ -175,7 +173,7 @@ export function ReservationList({
</TableRow> </TableRow>
</TableHeader> </TableHeader>
<TableBody> <TableBody>
{reservations.map((r) => ( {tenancies.map((r) => (
<TableRow key={r.id}> <TableRow key={r.id}>
{showBerth && ( {showBerth && (
<TableCell> <TableCell>

View File

@@ -9,7 +9,7 @@ import { FieldHistoryProvider, FieldHistoryIcon } from '@/components/shared/fiel
import { InlineTagEditor } from '@/components/shared/inline-tag-editor'; import { InlineTagEditor } from '@/components/shared/inline-tag-editor';
import { NotesList } from '@/components/shared/notes-list'; import { NotesList } from '@/components/shared/notes-list';
import { EntityActivityFeed } from '@/components/shared/entity-activity-feed'; import { EntityActivityFeed } from '@/components/shared/entity-activity-feed';
import { ReservationList, type ReservationRow } from '@/components/reservations/reservation-list'; import { TenancyList, type TenancyRow } from '@/components/tenancies/tenancy-list';
import { RemindersInline } from '@/components/reminders/reminders-inline'; import { RemindersInline } from '@/components/reminders/reminders-inline';
import { YachtOwnershipHistory } from '@/components/yachts/yacht-ownership-history'; import { YachtOwnershipHistory } from '@/components/yachts/yacht-ownership-history';
import { feetToMeters, metersToFeet } from '@/components/yachts/yacht-dimensions'; import { feetToMeters, metersToFeet } from '@/components/yachts/yacht-dimensions';
@@ -334,23 +334,23 @@ function YachtInterestsTab({ yachtId }: { yachtId: string }) {
); );
} }
function YachtReservationsTab({ yachtId }: { yachtId: string }) { function YachtTenanciesTab({ yachtId }: { yachtId: string }) {
const routeParams = useParams<{ portSlug: string }>(); const routeParams = useParams<{ portSlug: string }>();
const portSlug = routeParams?.portSlug ?? ''; const portSlug = routeParams?.portSlug ?? '';
const { data, isLoading } = useQuery<{ data: ReservationRow[] }>({ const { data, isLoading } = useQuery<{ data: TenancyRow[] }>({
queryKey: ['berth-reservations', 'by-yacht', yachtId], queryKey: ['tenancies', 'by-yacht', yachtId],
queryFn: () => apiFetch(`/api/v1/berth-reservations?yachtId=${yachtId}&limit=50&order=desc`), queryFn: () => apiFetch(`/api/v1/tenancies?yachtId=${yachtId}&limit=50&order=desc`),
}); });
if (isLoading) return <p className="text-sm text-muted-foreground">Loading</p>; if (isLoading) return <p className="text-sm text-muted-foreground">Loading</p>;
return ( return (
<ReservationList <TenancyList
reservations={data?.data ?? []} tenancies={data?.data ?? []}
showBerth showBerth
portSlug={portSlug} portSlug={portSlug}
emptyMessage="No reservations for this yacht." emptyMessage="No tenancies for this yacht."
/> />
); );
} }
@@ -373,9 +373,9 @@ export function getYachtTabs({ yachtId, currentUserId, yacht }: YachtTabsOptions
content: <YachtInterestsTab yachtId={yachtId} />, content: <YachtInterestsTab yachtId={yachtId} />,
}, },
{ {
id: 'reservations', id: 'tenancies',
label: 'Reservations', label: 'Tenancies',
content: <YachtReservationsTab yachtId={yachtId} />, content: <YachtTenanciesTab yachtId={yachtId} />,
}, },
{ {
id: 'notes', id: 'notes',

View File

@@ -0,0 +1,129 @@
-- 0085_rename_reservations_to_tenancies.sql
-- Rename berth_reservations → berth_tenancies (table + indexes + FK constraints +
-- documents.reservation_id column) and migrate jsonb permission maps (rename
-- the `reservations` resource key → `tenancies`, collapse the create/activate
-- actions into a single `manage`). See docs/tenancies-design.md.
--
-- The data is preserved verbatim; this is a pure rename at the storage
-- layer. Permission shape change: { view, create, activate, cancel }
-- collapses to { view, manage, cancel } (manage = old create OR activate).
-- 1. Rename the table.
ALTER TABLE berth_reservations RENAME TO berth_tenancies;
-- 2. Rename indexes (idx_br_* / idx_brr_* → idx_bt_*).
ALTER INDEX idx_br_berth RENAME TO idx_bt_berth;
ALTER INDEX idx_br_client RENAME TO idx_bt_client;
ALTER INDEX idx_br_yacht RENAME TO idx_bt_yacht;
ALTER INDEX idx_br_port RENAME TO idx_bt_port;
ALTER INDEX idx_brr_interest RENAME TO idx_bt_interest;
ALTER INDEX idx_brr_contract_file RENAME TO idx_bt_contract_file;
ALTER INDEX idx_br_active RENAME TO idx_bt_active;
-- 3. Rename FK constraints so Drizzle-derived names match the new table.
-- Wrapped in DO-blocks so dev DBs that pre-date 0042 (and therefore
-- are missing some FKs) don't abort the migration.
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_berth_id_berths_id_fk') THEN
ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_berth_id_berths_id_fk TO berth_tenancies_berth_id_berths_id_fk;
END IF;
END $$;
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_port_id_ports_id_fk') THEN
ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_port_id_ports_id_fk TO berth_tenancies_port_id_ports_id_fk;
END IF;
END $$;
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_client_id_clients_id_fk') THEN
ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_client_id_clients_id_fk TO berth_tenancies_client_id_clients_id_fk;
END IF;
END $$;
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_yacht_id_yachts_id_fk') THEN
ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_yacht_id_yachts_id_fk TO berth_tenancies_yacht_id_yachts_id_fk;
END IF;
END $$;
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_interest_id_interests_id_fk') THEN
ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_interest_id_interests_id_fk TO berth_tenancies_interest_id_interests_id_fk;
END IF;
END $$;
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM pg_constraint WHERE conrelid='berth_tenancies'::regclass AND conname='berth_reservations_contract_file_id_files_id_fk') THEN
ALTER TABLE berth_tenancies RENAME CONSTRAINT berth_reservations_contract_file_id_files_id_fk TO berth_tenancies_contract_file_id_files_id_fk;
END IF;
END $$;
-- 4. Rename the FK column on documents from reservation_id → tenancy_id.
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM information_schema.columns WHERE table_name='documents' AND column_name='reservation_id') THEN
ALTER TABLE documents RENAME COLUMN reservation_id TO tenancy_id;
END IF;
END $$;
DO $$ BEGIN
IF EXISTS (SELECT 1 FROM pg_indexes WHERE tablename='documents' AND indexname='idx_docs_reservation') THEN
ALTER INDEX idx_docs_reservation RENAME TO idx_docs_tenancy;
END IF;
END $$;
DO $$ BEGIN
IF EXISTS (
SELECT 1 FROM pg_constraint
WHERE conrelid = 'documents'::regclass
AND conname = 'documents_reservation_id_berth_reservations_id_fk'
) THEN
ALTER TABLE documents RENAME CONSTRAINT documents_reservation_id_berth_reservations_id_fk TO documents_tenancy_id_berth_tenancies_id_fk;
END IF;
END $$;
-- 5. Migrate jsonb permission maps: rename the resource key + collapse actions.
UPDATE roles
SET permissions = (
(permissions - 'reservations') ||
jsonb_build_object(
'tenancies',
jsonb_build_object(
'view', COALESCE((permissions -> 'reservations' ->> 'view')::boolean, false),
'manage', (COALESCE((permissions -> 'reservations' ->> 'create')::boolean, false)
OR COALESCE((permissions -> 'reservations' ->> 'activate')::boolean, false)),
'cancel', COALESCE((permissions -> 'reservations' ->> 'cancel')::boolean, false)
)
)
)
WHERE permissions ? 'reservations';
UPDATE port_role_overrides
SET permission_overrides = (
(permission_overrides - 'reservations') ||
jsonb_build_object(
'tenancies',
jsonb_build_object(
'view', COALESCE((permission_overrides -> 'reservations' ->> 'view')::boolean, false),
'manage', (COALESCE((permission_overrides -> 'reservations' ->> 'create')::boolean, false)
OR COALESCE((permission_overrides -> 'reservations' ->> 'activate')::boolean, false)),
'cancel', COALESCE((permission_overrides -> 'reservations' ->> 'cancel')::boolean, false)
)
)
)
WHERE permission_overrides ? 'reservations';
UPDATE user_permission_overrides
SET permission_overrides = (
(permission_overrides - 'reservations') ||
jsonb_build_object(
'tenancies',
jsonb_build_object(
'view', COALESCE((permission_overrides -> 'reservations' ->> 'view')::boolean, false),
'manage', (COALESCE((permission_overrides -> 'reservations' ->> 'create')::boolean, false)
OR COALESCE((permission_overrides -> 'reservations' ->> 'activate')::boolean, false)),
'cancel', COALESCE((permission_overrides -> 'reservations' ->> 'cancel')::boolean, false)
)
)
)
WHERE permission_overrides ? 'reservations';
-- 6. Migrate historical audit-log entity_type strings so the dashboard
-- activity feed groups old + new events under the same label.
UPDATE audit_logs SET entity_type = 'berth_tenancy'
WHERE entity_type = 'berth_reservation';

View File

@@ -17,7 +17,7 @@ import { clients } from './clients';
import { yachts } from './yachts'; import { yachts } from './yachts';
import { companies } from './companies'; import { companies } from './companies';
import { interests } from './interests'; import { interests } from './interests';
import { berthReservations } from './reservations'; import { berthTenancies } from './tenancies';
export const files = pgTable( export const files = pgTable(
'files', 'files',
@@ -90,7 +90,7 @@ export const documents = pgTable(
clientId: text('client_id').references(() => clients.id, { onDelete: 'set null' }), clientId: text('client_id').references(() => clients.id, { onDelete: 'set null' }),
yachtId: text('yacht_id').references(() => yachts.id, { onDelete: 'set null' }), yachtId: text('yacht_id').references(() => yachts.id, { onDelete: 'set null' }),
companyId: text('company_id').references(() => companies.id, { onDelete: 'set null' }), companyId: text('company_id').references(() => companies.id, { onDelete: 'set null' }),
reservationId: text('reservation_id').references(() => berthReservations.id, { tenancyId: text('tenancy_id').references(() => berthTenancies.id, {
onDelete: 'set null', onDelete: 'set null',
}), }),
folderId: text('folder_id').references((): AnyPgColumn => documentFolders.id, { folderId: text('folder_id').references((): AnyPgColumn => documentFolders.id, {
@@ -155,7 +155,7 @@ export const documents = pgTable(
index('idx_docs_client').on(table.clientId), index('idx_docs_client').on(table.clientId),
index('idx_documents_yacht').on(table.yachtId), index('idx_documents_yacht').on(table.yachtId),
index('idx_documents_company').on(table.companyId), index('idx_documents_company').on(table.companyId),
index('idx_docs_reservation').on(table.reservationId), index('idx_docs_tenancy').on(table.tenancyId),
index('idx_docs_type').on(table.portId, table.documentType), index('idx_docs_type').on(table.portId, table.documentType),
index('idx_docs_status_port').on(table.portId, table.status), index('idx_docs_status_port').on(table.portId, table.status),
// Cover the file FKs Postgres doesn't auto-index. Without these, // Cover the file FKs Postgres doesn't auto-index. Without these,

View File

@@ -19,8 +19,8 @@ export * from './interests';
// Berths // Berths
export * from './berths'; export * from './berths';
// Reservations // Tenancies (formerly berth_reservations)
export * from './reservations'; export * from './tenancies';
// Documents & Files // Documents & Files
export * from './documents'; export * from './documents';

View File

@@ -43,8 +43,8 @@ import {
berthPdfVersions, berthPdfVersions,
} from './berths'; } from './berths';
// Reservations // Tenancies (formerly berth_reservations)
import { berthReservations } from './reservations'; import { berthTenancies } from './tenancies';
// Documents // Documents
import { import {
@@ -104,7 +104,7 @@ export const portsRelations = relations(ports, ({ many }) => ({
yachts: many(yachts), yachts: many(yachts),
companies: many(companies), companies: many(companies),
berths: many(berths), berths: many(berths),
berthReservations: many(berthReservations), berthTenancies: many(berthTenancies),
documents: many(documents), documents: many(documents),
documentTemplates: many(documentTemplates), documentTemplates: many(documentTemplates),
formTemplates: many(formTemplates), formTemplates: many(formTemplates),
@@ -187,7 +187,7 @@ export const clientsRelations = relations(clients, ({ one, many }) => ({
formSubmissions: many(formSubmissions), formSubmissions: many(formSubmissions),
addresses: many(clientAddresses), addresses: many(clientAddresses),
companyMemberships: many(companyMemberships), companyMemberships: many(companyMemberships),
berthReservations: many(berthReservations), berthTenancies: many(berthTenancies),
})); }));
export const clientContactsRelations = relations(clientContacts, ({ one }) => ({ export const clientContactsRelations = relations(clientContacts, ({ one }) => ({
@@ -318,7 +318,7 @@ export const yachtsRelations = relations(yachts, ({ one, many }) => ({
notes: many(yachtNotes), notes: many(yachtNotes),
tags: many(yachtTags), tags: many(yachtTags),
interests: many(interests), interests: many(interests),
reservations: many(berthReservations), tenancies: many(berthTenancies),
documents: many(documents), documents: many(documents),
})); }));
@@ -482,31 +482,31 @@ export const berthTagsRelations = relations(berthTags, ({ one }) => ({
}), }),
})); }));
// ─── Berth Reservations ─────────────────────────────────────────────────────── // ─── Berth Tenancies ──────────────────────────────────────────────────────────
export const berthReservationsRelations = relations(berthReservations, ({ one, many }) => ({ export const berthTenanciesRelations = relations(berthTenancies, ({ one, many }) => ({
berth: one(berths, { berth: one(berths, {
fields: [berthReservations.berthId], fields: [berthTenancies.berthId],
references: [berths.id], references: [berths.id],
}), }),
port: one(ports, { port: one(ports, {
fields: [berthReservations.portId], fields: [berthTenancies.portId],
references: [ports.id], references: [ports.id],
}), }),
client: one(clients, { client: one(clients, {
fields: [berthReservations.clientId], fields: [berthTenancies.clientId],
references: [clients.id], references: [clients.id],
}), }),
yacht: one(yachts, { yacht: one(yachts, {
fields: [berthReservations.yachtId], fields: [berthTenancies.yachtId],
references: [yachts.id], references: [yachts.id],
}), }),
interest: one(interests, { interest: one(interests, {
fields: [berthReservations.interestId], fields: [berthTenancies.interestId],
references: [interests.id], references: [interests.id],
}), }),
contractFile: one(files, { contractFile: one(files, {
fields: [berthReservations.contractFileId], fields: [berthTenancies.contractFileId],
references: [files.id], references: [files.id],
}), }),
documents: many(documents), documents: many(documents),
@@ -566,9 +566,9 @@ export const documentsRelations = relations(documents, ({ one, many }) => ({
fields: [documents.companyId], fields: [documents.companyId],
references: [companies.id], references: [companies.id],
}), }),
reservation: one(berthReservations, { tenancy: one(berthTenancies, {
fields: [documents.reservationId], fields: [documents.tenancyId],
references: [berthReservations.id], references: [berthTenancies.id],
}), }),
folder: one(documentFolders, { folder: one(documentFolders, {
fields: [documents.folderId], fields: [documents.folderId],

View File

@@ -7,17 +7,17 @@ import { yachts } from './yachts';
import { interests } from './interests'; import { interests } from './interests';
import { files } from './documents'; import { files } from './documents';
export const berthReservations = pgTable( export const berthTenancies = pgTable(
'berth_reservations', 'berth_tenancies',
{ {
id: text('id') id: text('id')
.primaryKey() .primaryKey()
.$defaultFn(() => crypto.randomUUID()), .$defaultFn(() => crypto.randomUUID()),
// H-01: reservations are the canonical "who occupies a berth right // H-01: tenancies are the canonical "who occupies a berth right
// now" record; RESTRICT on every parent FK keeps an ad-hoc DB-side // now" record; RESTRICT on every parent FK keeps an ad-hoc DB-side
// hard-delete from leaving a reservation pointing at a missing // hard-delete from leaving a tenancy pointing at a missing
// berth/client/yacht. Interest is nullable + SET NULL because a // berth/client/yacht. Interest is nullable + SET NULL because a
// reservation legitimately outlives the originating deal. // tenancy legitimately outlives the originating deal.
berthId: text('berth_id') berthId: text('berth_id')
.notNull() .notNull()
.references(() => berths.id, { onDelete: 'restrict' }), .references(() => berths.id, { onDelete: 'restrict' }),
@@ -36,7 +36,7 @@ export const berthReservations = pgTable(
endDate: timestamp('end_date', { withTimezone: true, mode: 'date' }), endDate: timestamp('end_date', { withTimezone: true, mode: 'date' }),
// M-L01: canonical tenure_type union is // M-L01: canonical tenure_type union is
// `permanent | fixed_term | fee_simple | strata_lot | seasonal` // `permanent | fixed_term | fee_simple | strata_lot | seasonal`
// (kept in sync with berths.tenure_type). 'seasonal' is reservation- // (kept in sync with berths.tenure_type). 'seasonal' is tenancy-
// specific (winter haul-out etc.); the others mirror the berth's // specific (winter haul-out etc.); the others mirror the berth's
// own tenure shape. Configurable via the per-port vocabulary at // own tenure shape. Configurable via the per-port vocabulary at
// /admin/vocabularies (key: berth_tenure_types). // /admin/vocabularies (key: berth_tenure_types).
@@ -48,21 +48,17 @@ export const berthReservations = pgTable(
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(), updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
}, },
(table) => [ (table) => [
index('idx_br_berth').on(table.berthId), index('idx_bt_berth').on(table.berthId),
index('idx_br_client').on(table.clientId), index('idx_bt_client').on(table.clientId),
index('idx_br_yacht').on(table.yachtId), index('idx_bt_yacht').on(table.yachtId),
index('idx_br_port').on(table.portId), index('idx_bt_port').on(table.portId),
// Cover the FKs Postgres doesn't auto-index. Without these, deleting index('idx_bt_interest').on(table.interestId),
// (or restrict-checking) the parent interest / contract file row index('idx_bt_contract_file').on(table.contractFileId),
// requires a full scan of berth_reservations. (idx_br_interest is uniqueIndex('idx_bt_active')
// already used by berth_recommendations - namespace this one.)
index('idx_brr_interest').on(table.interestId),
index('idx_brr_contract_file').on(table.contractFileId),
uniqueIndex('idx_br_active')
.on(table.berthId) .on(table.berthId)
.where(sql`${table.status} = 'active'`), .where(sql`${table.status} = 'active'`),
], ],
); );
export type BerthReservation = typeof berthReservations.$inferSelect; export type BerthTenancy = typeof berthTenancies.$inferSelect;
export type NewBerthReservation = typeof berthReservations.$inferInsert; export type NewBerthTenancy = typeof berthTenancies.$inferInsert;

View File

@@ -130,10 +130,9 @@ export type RolePermissions = {
view: boolean; view: boolean;
manage: boolean; manage: boolean;
}; };
reservations: { tenancies: {
view: boolean; view: boolean;
create: boolean; manage: boolean;
activate: boolean;
cancel: boolean; cancel: boolean;
}; };
admin: { admin: {

View File

@@ -37,7 +37,7 @@ import {
yachts, yachts,
yachtOwnershipHistory, yachtOwnershipHistory,
berths, berths,
berthReservations, berthTenancies,
interests, interests,
interestBerths, interestBerths,
documentTemplates, documentTemplates,
@@ -115,7 +115,7 @@ export interface SeedSummary {
companies: number; companies: number;
yachts: number; yachts: number;
interests: number; interests: number;
reservations: number; tenancies: number;
} }
// ─── Main ──────────────────────────────────────────────────────────────────── // ─── Main ────────────────────────────────────────────────────────────────────
@@ -1049,7 +1049,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
const cancelledAssignment = { berthIdx: 0, clientIdx: 2, yachtIdx: 2, startDaysAgo: 30 }; const cancelledAssignment = { berthIdx: 0, clientIdx: 2, yachtIdx: 2, startDaysAgo: 30 };
const reservationValues: Array<typeof berthReservations.$inferInsert> = []; const reservationValues: Array<typeof berthTenancies.$inferInsert> = [];
for (const a of activeAssignments) { for (const a of activeAssignments) {
reservationValues.push({ reservationValues.push({
@@ -1090,7 +1090,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
notes: 'Cancelled by client before activation.', notes: 'Cancelled by client before activation.',
}); });
await tx.insert(berthReservations).values(reservationValues); await tx.insert(berthTenancies).values(reservationValues);
return { return {
berths: berthRows.length, berths: berthRows.length,
@@ -1098,7 +1098,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
companies: companyRows.length, companies: companyRows.length,
yachts: yachtRows.length, yachts: yachtRows.length,
interests: interestPlan.length, interests: interestPlan.length,
reservations: reservationValues.length, tenancies: reservationValues.length,
}; };
}); });
} }

View File

@@ -67,7 +67,7 @@ export const ALL_PERMISSIONS: RolePermissions = {
yachts: { view: true, create: true, edit: true, delete: true, transfer: true }, yachts: { view: true, create: true, edit: true, delete: true, transfer: true },
companies: { view: true, create: true, edit: true, delete: true }, companies: { view: true, create: true, edit: true, delete: true },
memberships: { view: true, manage: true }, memberships: { view: true, manage: true },
reservations: { view: true, create: true, activate: true, cancel: true }, tenancies: { view: true, manage: true, cancel: true },
admin: { admin: {
manage_users: true, manage_users: true,
view_audit_log: true, view_audit_log: true,
@@ -146,7 +146,7 @@ export const DIRECTOR_PERMISSIONS: RolePermissions = {
yachts: { view: true, create: true, edit: true, delete: true, transfer: true }, yachts: { view: true, create: true, edit: true, delete: true, transfer: true },
companies: { view: true, create: true, edit: true, delete: true }, companies: { view: true, create: true, edit: true, delete: true },
memberships: { view: true, manage: true }, memberships: { view: true, manage: true },
reservations: { view: true, create: true, activate: true, cancel: true }, tenancies: { view: true, manage: true, cancel: true },
admin: { admin: {
manage_users: true, manage_users: true,
view_audit_log: true, view_audit_log: true,
@@ -225,7 +225,7 @@ export const SALES_MANAGER_PERMISSIONS: RolePermissions = {
yachts: { view: true, create: true, edit: true, delete: false, transfer: true }, yachts: { view: true, create: true, edit: true, delete: false, transfer: true },
companies: { view: true, create: true, edit: true, delete: false }, companies: { view: true, create: true, edit: true, delete: false },
memberships: { view: true, manage: true }, memberships: { view: true, manage: true },
reservations: { view: true, create: true, activate: true, cancel: true }, tenancies: { view: true, manage: true, cancel: true },
admin: { admin: {
manage_users: false, manage_users: false,
view_audit_log: false, view_audit_log: false,
@@ -304,7 +304,7 @@ export const SALES_AGENT_PERMISSIONS: RolePermissions = {
yachts: { view: true, create: true, edit: true, delete: false, transfer: false }, yachts: { view: true, create: true, edit: true, delete: false, transfer: false },
companies: { view: true, create: true, edit: false, delete: false }, companies: { view: true, create: true, edit: false, delete: false },
memberships: { view: true, manage: false }, memberships: { view: true, manage: false },
reservations: { view: true, create: true, activate: true, cancel: false }, tenancies: { view: true, manage: true, cancel: false },
admin: { admin: {
manage_users: false, manage_users: false,
view_audit_log: false, view_audit_log: false,
@@ -389,7 +389,7 @@ export const VIEWER_PERMISSIONS: RolePermissions = {
yachts: { view: true, create: false, edit: false, delete: false, transfer: false }, yachts: { view: true, create: false, edit: false, delete: false, transfer: false },
companies: { view: true, create: false, edit: false, delete: false }, companies: { view: true, create: false, edit: false, delete: false },
memberships: { view: true, manage: false }, memberships: { view: true, manage: false },
reservations: { view: true, create: false, activate: false, cancel: false }, tenancies: { view: true, manage: false, cancel: false },
admin: { admin: {
manage_users: false, manage_users: false,
view_audit_log: false, view_audit_log: false,
@@ -477,7 +477,7 @@ export const RESIDENTIAL_PARTNER_PERMISSIONS: RolePermissions = {
yachts: { view: false, create: false, edit: false, delete: false, transfer: false }, yachts: { view: false, create: false, edit: false, delete: false, transfer: false },
companies: { view: false, create: false, edit: false, delete: false }, companies: { view: false, create: false, edit: false, delete: false },
memberships: { view: false, manage: false }, memberships: { view: false, manage: false },
reservations: { view: false, create: false, activate: false, cancel: false }, tenancies: { view: false, manage: false, cancel: false },
admin: { admin: {
manage_users: false, manage_users: false,
view_audit_log: false, view_audit_log: false,

View File

@@ -30,7 +30,7 @@ import {
yachts, yachts,
yachtOwnershipHistory, yachtOwnershipHistory,
berths, berths,
berthReservations, berthTenancies,
interests, interests,
interestBerths, interestBerths,
} from './schema'; } from './schema';
@@ -700,10 +700,10 @@ export async function seedSyntheticPortData(
// ── 9. Reservations ───────────────────────────────────────────────────── // ── 9. Reservations ─────────────────────────────────────────────────────
// One active reservation on the under_offer berth held by Carla, // One active reservation on the under_offer berth held by Carla,
// one cancelled on an available berth. // one cancelled on an available berth.
// berthReservations requires a yacht - wire both to the charter co. // berthTenancies requires a yacht - wire both to the charter co.
// flagship since Carla / Olivia don't own yachts yet. // flagship since Carla / Olivia don't own yachts yet.
const sharedYachtId = charterYachtRow[1]!.id; const sharedYachtId = charterYachtRow[1]!.id;
await tx.insert(berthReservations).values([ await tx.insert(berthTenancies).values([
{ {
portId, portId,
berthId: berthRows[5]!.id, berthId: berthRows[5]!.id,

View File

@@ -39,7 +39,7 @@ async function seed() {
} else { } else {
const x = s.summary; const x = s.summary;
console.log( console.log(
` ✓ Port "${s.name}" - ${x.berths} berths, ${x.clients} clients, ${x.companies} companies, ${x.yachts} yachts, ${x.interests} interests, ${x.reservations} reservations`, ` ✓ Port "${s.name}" - ${x.berths} berths, ${x.clients} clients, ${x.companies} companies, ${x.yachts} yachts, ${x.interests} interests, ${x.tenancies} tenancies`,
); );
} }
} }

View File

@@ -15,7 +15,7 @@ import { and, eq, isNull, isNotNull, lt, sql, inArray, or } from 'drizzle-orm';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { interests } from '@/lib/db/schema/interests'; import { interests } from '@/lib/db/schema/interests';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { documents, documentSigners } from '@/lib/db/schema/documents'; import { documents, documentSigners } from '@/lib/db/schema/documents';
import { expenses } from '@/lib/db/schema/financial'; import { expenses } from '@/lib/db/schema/financial';
@@ -39,20 +39,20 @@ function daysAgo(n: number): Date {
async function reservationNoAgreement(portId: string): Promise<AlertCandidate[]> { async function reservationNoAgreement(portId: string): Promise<AlertCandidate[]> {
const rows = await db const rows = await db
.select({ .select({
id: berthReservations.id, id: berthTenancies.id,
startDate: berthReservations.startDate, startDate: berthTenancies.startDate,
clientName: sql<string>`coalesce((SELECT full_name FROM clients WHERE id = ${berthReservations.clientId}), 'unknown')`, clientName: sql<string>`coalesce((SELECT full_name FROM clients WHERE id = ${berthTenancies.clientId}), 'unknown')`,
yachtName: sql<string>`coalesce((SELECT name FROM yachts WHERE id = ${berthReservations.yachtId}), 'unknown')`, yachtName: sql<string>`coalesce((SELECT name FROM yachts WHERE id = ${berthTenancies.yachtId}), 'unknown')`,
}) })
.from(berthReservations) .from(berthTenancies)
.where( .where(
and( and(
eq(berthReservations.portId, portId), eq(berthTenancies.portId, portId),
eq(berthReservations.status, 'active'), eq(berthTenancies.status, 'active'),
lt(berthReservations.createdAt, daysAgo(3)), lt(berthTenancies.createdAt, daysAgo(3)),
sql`NOT EXISTS ( sql`NOT EXISTS (
SELECT 1 FROM ${documents} SELECT 1 FROM ${documents}
WHERE ${documents.reservationId} = ${berthReservations.id} WHERE ${documents.tenancyId} = ${berthTenancies.id}
AND ${documents.documentType} = 'reservation_agreement' AND ${documents.documentType} = 'reservation_agreement'
AND ${documents.status} NOT IN ('cancelled', 'expired') AND ${documents.status} NOT IN ('cancelled', 'expired')
)`, )`,
@@ -64,7 +64,7 @@ async function reservationNoAgreement(portId: string): Promise<AlertCandidate[]>
severity: 'warning', severity: 'warning',
title: `Reservation needs an agreement`, title: `Reservation needs an agreement`,
body: `Active reservation for ${r.yachtName} (${r.clientName}) has no signed agreement yet.`, body: `Active reservation for ${r.yachtName} (${r.clientName}) has no signed agreement yet.`,
link: `/[port]/berth-reservations/${r.id}`, link: `/[port]/tenancies/${r.id}`,
entityType: 'reservation', entityType: 'reservation',
entityId: r.id, entityId: r.id,
})); }));

View File

@@ -1,6 +1,6 @@
import { and, eq, isNull } from 'drizzle-orm'; import { and, eq, isNull } from 'drizzle-orm';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { berthReservations, type BerthReservation } from '@/lib/db/schema/reservations'; import { berthTenancies, type BerthTenancy } from '@/lib/db/schema/tenancies';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { clients } from '@/lib/db/schema/clients'; import { clients } from '@/lib/db/schema/clients';
import { files } from '@/lib/db/schema/documents'; import { files } from '@/lib/db/schema/documents';
@@ -11,26 +11,26 @@ import { createAuditLog, type AuditMeta } from '@/lib/audit';
import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors'; import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
import { emitToRoom } from '@/lib/socket/server'; import { emitToRoom } from '@/lib/socket/server';
import type { z } from 'zod'; import type { z } from 'zod';
import { createPendingSchema } from '@/lib/validators/reservations'; import { createPendingSchema } from '@/lib/validators/tenancies';
import type { import type {
ActivateInput, ActivateInput,
EndReservationInput, EndTenancyInput,
CancelInput, CancelInput,
ListReservationsInput, ListTenanciesInput,
} from '@/lib/validators/reservations'; } from '@/lib/validators/tenancies';
// Use z.input so callers (including tests) can omit fields with // Use z.input so callers (including tests) can omit fields with
// `.default()` like `tenureType`. The service re-parses below to get // `.default()` like `tenureType`. The service re-parses below to get
// the post-coercion shape Drizzle expects (Date, defaulted tenureType). // the post-coercion shape Drizzle expects (Date, defaulted tenureType).
type CreatePendingInput = z.input<typeof createPendingSchema>; type CreatePendingInput = z.input<typeof createPendingSchema>;
export type { BerthReservation }; export type { BerthTenancy };
// ─── Helpers ───────────────────────────────────────────────────────────────── // ─── Helpers ─────────────────────────────────────────────────────────────────
/** /**
* Returns true if the error is a Postgres unique-violation (SQLSTATE 23505) * Returns true if the error is a Postgres unique-violation (SQLSTATE 23505)
* raised specifically on the `idx_br_active` partial unique index. Narrowing * raised specifically on the `idx_bt_active` partial unique index. Narrowing
* to this constraint name prevents us from swallowing unrelated unique * to this constraint name prevents us from swallowing unrelated unique
* violations. * violations.
*/ */
@@ -46,11 +46,11 @@ function isBerthActiveConflict(err: unknown): boolean {
if (code !== '23505') return false; if (code !== '23505') return false;
const constraint = const constraint =
e.constraint_name ?? e.constraint ?? e.cause?.constraint_name ?? e.cause?.constraint; e.constraint_name ?? e.constraint ?? e.cause?.constraint_name ?? e.cause?.constraint;
return constraint === 'idx_br_active'; return constraint === 'idx_bt_active';
} }
/** /**
* Cross-references the reservation's client against the yacht's current owner. * Cross-references the tenancy's client against the yacht's current owner.
* Either the yacht is directly owned by the client, OR the client has an * Either the yacht is directly owned by the client, OR the client has an
* active (endDate IS NULL) company_membership on the owning company. * active (endDate IS NULL) company_membership on the owning company.
*/ */
@@ -73,14 +73,14 @@ async function assertClientOwnsOrRepresentsYacht(
if (membership) return; if (membership) return;
} }
throw new ValidationError('yacht does not belong to reservation client'); throw new ValidationError('yacht does not belong to tenancy client');
} }
async function loadScoped(id: string, portId: string): Promise<BerthReservation> { async function loadScoped(id: string, portId: string): Promise<BerthTenancy> {
const row = await db.query.berthReservations.findFirst({ const row = await db.query.berthTenancies.findFirst({
where: and(eq(berthReservations.id, id), eq(berthReservations.portId, portId)), where: and(eq(berthTenancies.id, id), eq(berthTenancies.portId, portId)),
}); });
if (!row) throw new NotFoundError('Reservation'); if (!row) throw new NotFoundError('Tenancy');
return row; return row;
} }
@@ -90,7 +90,7 @@ export async function createPending(
portId: string, portId: string,
data: CreatePendingInput, data: CreatePendingInput,
meta: AuditMeta, meta: AuditMeta,
): Promise<BerthReservation> { ): Promise<BerthTenancy> {
// Tenant-scoped existence checks (berth, client, yacht). // Tenant-scoped existence checks (berth, client, yacht).
const berth = await db.query.berths.findFirst({ const berth = await db.query.berths.findFirst({
where: and(eq(berths.id, data.berthId), eq(berths.portId, portId)), where: and(eq(berths.id, data.berthId), eq(berths.portId, portId)),
@@ -118,8 +118,8 @@ export async function createPending(
// z.input is too loose to satisfy that. // z.input is too loose to satisfy that.
const parsed = createPendingSchema.parse(data); const parsed = createPendingSchema.parse(data);
const [reservation] = await db const [tenancy] = await db
.insert(berthReservations) .insert(berthTenancies)
.values({ .values({
portId, portId,
berthId: parsed.berthId, berthId: parsed.berthId,
@@ -138,48 +138,48 @@ export async function createPending(
userId: meta.userId, userId: meta.userId,
portId, portId,
action: 'create', action: 'create',
entityType: 'berth_reservation', entityType: 'berth_tenancy',
entityId: reservation!.id, entityId: tenancy!.id,
newValue: { newValue: {
berthId: reservation!.berthId, berthId: tenancy!.berthId,
clientId: reservation!.clientId, clientId: tenancy!.clientId,
yachtId: reservation!.yachtId, yachtId: tenancy!.yachtId,
status: reservation!.status, status: tenancy!.status,
startDate: reservation!.startDate, startDate: tenancy!.startDate,
}, },
ipAddress: meta.ipAddress, ipAddress: meta.ipAddress,
userAgent: meta.userAgent, userAgent: meta.userAgent,
}); });
emitToRoom(`port:${portId}`, 'berth_reservation:created', { emitToRoom(`port:${portId}`, 'berth_tenancy:created', {
reservationId: reservation!.id, tenancyId: tenancy!.id,
berthId: reservation!.berthId, berthId: tenancy!.berthId,
}); });
return reservation!; return tenancy!;
} }
// ─── Activate (pending → active) ───────────────────────────────────────────── // ─── Activate (pending → active) ─────────────────────────────────────────────
export async function activate( export async function activate(
reservationId: string, tenancyId: string,
portId: string, portId: string,
data: ActivateInput, data: ActivateInput,
meta: AuditMeta, meta: AuditMeta,
): Promise<BerthReservation> { ): Promise<BerthTenancy> {
const existing = await loadScoped(reservationId, portId); const existing = await loadScoped(tenancyId, portId);
if (existing.status !== 'pending') { if (existing.status !== 'pending') {
throw new ValidationError(`invalid transition: ${existing.status} → active`); throw new ValidationError(`invalid transition: ${existing.status} → active`);
} }
const patch: Partial<typeof berthReservations.$inferInsert> = { const patch: Partial<typeof berthTenancies.$inferInsert> = {
status: 'active', status: 'active',
updatedAt: new Date(), updatedAt: new Date(),
}; };
if (data.contractFileId !== undefined) { if (data.contractFileId !== undefined) {
// Verify the contract file lives in the caller's port. Without this, // Verify the contract file lives in the caller's port. Without this,
// a port-A user activating a port-A reservation could attach a // a port-A user activating a port-A tenancy could attach a
// port-B file id and downstream presigned-download paths (admin // port-B file id and downstream presigned-download paths (admin
// export, portal contract download) would otherwise leak that // export, portal contract download) would otherwise leak that
// foreign-port content. // foreign-port content.
@@ -197,27 +197,27 @@ export async function activate(
patch.startDate = data.effectiveDate; patch.startDate = data.effectiveDate;
} }
let updated: BerthReservation | undefined; let updated: BerthTenancy | undefined;
try { try {
const rows = await db const rows = await db
.update(berthReservations) .update(berthTenancies)
.set(patch) .set(patch)
.where(and(eq(berthReservations.id, reservationId), eq(berthReservations.portId, portId))) .where(and(eq(berthTenancies.id, tenancyId), eq(berthTenancies.portId, portId)))
.returning(); .returning();
updated = rows[0]; updated = rows[0];
} catch (err) { } catch (err) {
if (isBerthActiveConflict(err)) { if (isBerthActiveConflict(err)) {
const conflicting = await db.query.berthReservations.findFirst({ const conflicting = await db.query.berthTenancies.findFirst({
where: and( where: and(
eq(berthReservations.berthId, existing.berthId), eq(berthTenancies.berthId, existing.berthId),
eq(berthReservations.status, 'active'), eq(berthTenancies.status, 'active'),
eq(berthReservations.portId, portId), eq(berthTenancies.portId, portId),
), ),
}); });
throw new ConflictError( throw new ConflictError(
conflicting conflicting
? `berth already has active reservation (conflictingReservationId: ${conflicting.id})` ? `berth already has active tenancy (conflictingTenancyId: ${conflicting.id})`
: 'berth already has active reservation', : 'berth already has active tenancy',
); );
} }
throw err; throw err;
@@ -227,16 +227,16 @@ export async function activate(
userId: meta.userId, userId: meta.userId,
portId, portId,
action: 'update', action: 'update',
entityType: 'berth_reservation', entityType: 'berth_tenancy',
entityId: reservationId, entityId: tenancyId,
oldValue: { status: existing.status }, oldValue: { status: existing.status },
newValue: { status: 'active', contractFileId: updated!.contractFileId }, newValue: { status: 'active', contractFileId: updated!.contractFileId },
ipAddress: meta.ipAddress, ipAddress: meta.ipAddress,
userAgent: meta.userAgent, userAgent: meta.userAgent,
}); });
emitToRoom(`port:${portId}`, 'berth_reservation:activated', { emitToRoom(`port:${portId}`, 'berth_tenancy:activated', {
reservationId, tenancyId,
berthId: updated!.berthId, berthId: updated!.berthId,
}); });
@@ -245,27 +245,27 @@ export async function activate(
// ─── End (active → ended) ──────────────────────────────────────────────────── // ─── End (active → ended) ────────────────────────────────────────────────────
export async function endReservation( export async function endTenancy(
reservationId: string, tenancyId: string,
portId: string, portId: string,
data: EndReservationInput, data: EndTenancyInput,
meta: AuditMeta, meta: AuditMeta,
): Promise<BerthReservation> { ): Promise<BerthTenancy> {
const existing = await loadScoped(reservationId, portId); const existing = await loadScoped(tenancyId, portId);
if (existing.status !== 'active') { if (existing.status !== 'active') {
throw new ValidationError(`invalid transition: ${existing.status} → ended`); throw new ValidationError(`invalid transition: ${existing.status} → ended`);
} }
const rows = await db const rows = await db
.update(berthReservations) .update(berthTenancies)
.set({ .set({
status: 'ended', status: 'ended',
endDate: data.endDate, endDate: data.endDate,
notes: data.notes ?? existing.notes, notes: data.notes ?? existing.notes,
updatedAt: new Date(), updatedAt: new Date(),
}) })
.where(and(eq(berthReservations.id, reservationId), eq(berthReservations.portId, portId))) .where(and(eq(berthTenancies.id, tenancyId), eq(berthTenancies.portId, portId)))
.returning(); .returning();
const updated = rows[0]!; const updated = rows[0]!;
@@ -274,16 +274,16 @@ export async function endReservation(
userId: meta.userId, userId: meta.userId,
portId, portId,
action: 'update', action: 'update',
entityType: 'berth_reservation', entityType: 'berth_tenancy',
entityId: reservationId, entityId: tenancyId,
oldValue: { status: existing.status }, oldValue: { status: existing.status },
newValue: { status: 'ended', endDate: updated.endDate }, newValue: { status: 'ended', endDate: updated.endDate },
ipAddress: meta.ipAddress, ipAddress: meta.ipAddress,
userAgent: meta.userAgent, userAgent: meta.userAgent,
}); });
emitToRoom(`port:${portId}`, 'berth_reservation:ended', { emitToRoom(`port:${portId}`, 'berth_tenancy:ended', {
reservationId, tenancyId,
berthId: updated.berthId, berthId: updated.berthId,
}); });
@@ -293,19 +293,19 @@ export async function endReservation(
// ─── Cancel (pending|active → cancelled) ───────────────────────────────────── // ─── Cancel (pending|active → cancelled) ─────────────────────────────────────
export async function cancel( export async function cancel(
reservationId: string, tenancyId: string,
portId: string, portId: string,
data: CancelInput, data: CancelInput,
meta: AuditMeta, meta: AuditMeta,
): Promise<BerthReservation> { ): Promise<BerthTenancy> {
const existing = await loadScoped(reservationId, portId); const existing = await loadScoped(tenancyId, portId);
if (existing.status !== 'pending' && existing.status !== 'active') { if (existing.status !== 'pending' && existing.status !== 'active') {
throw new ValidationError(`invalid transition: ${existing.status} → cancelled`); throw new ValidationError(`invalid transition: ${existing.status} → cancelled`);
} }
const rows = await db const rows = await db
.update(berthReservations) .update(berthTenancies)
.set({ .set({
status: 'cancelled', status: 'cancelled',
notes: data.reason notes: data.reason
@@ -313,7 +313,7 @@ export async function cancel(
: existing.notes, : existing.notes,
updatedAt: new Date(), updatedAt: new Date(),
}) })
.where(and(eq(berthReservations.id, reservationId), eq(berthReservations.portId, portId))) .where(and(eq(berthTenancies.id, tenancyId), eq(berthTenancies.portId, portId)))
.returning(); .returning();
const updated = rows[0]!; const updated = rows[0]!;
@@ -322,16 +322,16 @@ export async function cancel(
userId: meta.userId, userId: meta.userId,
portId, portId,
action: 'update', action: 'update',
entityType: 'berth_reservation', entityType: 'berth_tenancy',
entityId: reservationId, entityId: tenancyId,
oldValue: { status: existing.status }, oldValue: { status: existing.status },
newValue: { status: 'cancelled', reason: data.reason ?? null }, newValue: { status: 'cancelled', reason: data.reason ?? null },
ipAddress: meta.ipAddress, ipAddress: meta.ipAddress,
userAgent: meta.userAgent, userAgent: meta.userAgent,
}); });
emitToRoom(`port:${portId}`, 'berth_reservation:cancelled', { emitToRoom(`port:${portId}`, 'berth_tenancy:cancelled', {
reservationId, tenancyId,
berthId: updated.berthId, berthId: updated.berthId,
}); });
@@ -340,38 +340,38 @@ export async function cancel(
// ─── Get ───────────────────────────────────────────────────────────────────── // ─── Get ─────────────────────────────────────────────────────────────────────
export async function getById(id: string, portId: string): Promise<BerthReservation> { export async function getById(id: string, portId: string): Promise<BerthTenancy> {
return loadScoped(id, portId); return loadScoped(id, portId);
} }
// ─── List ──────────────────────────────────────────────────────────────────── // ─── List ────────────────────────────────────────────────────────────────────
export async function listReservations( export async function listTenancies(
portId: string, portId: string,
query: ListReservationsInput, query: ListTenanciesInput,
): Promise<{ data: BerthReservation[]; total: number }> { ): Promise<{ data: BerthTenancy[]; total: number }> {
const { page, limit, sort, order, search, status, berthId, clientId, yachtId } = query; const { page, limit, sort, order, search, status, berthId, clientId, yachtId } = query;
const filters = []; const filters = [];
if (status) filters.push(eq(berthReservations.status, status)); if (status) filters.push(eq(berthTenancies.status, status));
if (berthId) filters.push(eq(berthReservations.berthId, berthId)); if (berthId) filters.push(eq(berthTenancies.berthId, berthId));
if (clientId) filters.push(eq(berthReservations.clientId, clientId)); if (clientId) filters.push(eq(berthTenancies.clientId, clientId));
if (yachtId) filters.push(eq(berthReservations.yachtId, yachtId)); if (yachtId) filters.push(eq(berthTenancies.yachtId, yachtId));
let sortColumn: let sortColumn:
| typeof berthReservations.startDate | typeof berthTenancies.startDate
| typeof berthReservations.createdAt | typeof berthTenancies.createdAt
| typeof berthReservations.updatedAt = berthReservations.updatedAt; | typeof berthTenancies.updatedAt = berthTenancies.updatedAt;
if (sort === 'startDate') sortColumn = berthReservations.startDate; if (sort === 'startDate') sortColumn = berthTenancies.startDate;
else if (sort === 'createdAt') sortColumn = berthReservations.createdAt; else if (sort === 'createdAt') sortColumn = berthTenancies.createdAt;
const result = await buildListQuery<BerthReservation>({ const result = await buildListQuery<BerthTenancy>({
table: berthReservations, table: berthTenancies,
portIdColumn: berthReservations.portId, portIdColumn: berthTenancies.portId,
portId, portId,
idColumn: berthReservations.id, idColumn: berthTenancies.id,
updatedAtColumn: berthReservations.updatedAt, updatedAtColumn: berthTenancies.updatedAt,
searchColumns: search ? [berthReservations.notes] : [], searchColumns: search ? [berthTenancies.notes] : [],
searchTerm: search, searchTerm: search,
filters, filters,
sort: sort ? { column: sortColumn, direction: order } : undefined, sort: sort ? { column: sortColumn, direction: order } : undefined,

View File

@@ -18,7 +18,7 @@ import { yachts } from '@/lib/db/schema/yachts';
import { companies, companyMemberships } from '@/lib/db/schema/companies'; import { companies, companyMemberships } from '@/lib/db/schema/companies';
import { interests, interestBerths } from '@/lib/db/schema/interests'; import { interests, interestBerths } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { invoices } from '@/lib/db/schema/financial'; import { invoices } from '@/lib/db/schema/financial';
import { documents } from '@/lib/db/schema/documents'; import { documents } from '@/lib/db/schema/documents';
import { activeInterestsWhere } from '@/lib/services/active-interest'; import { activeInterestsWhere } from '@/lib/services/active-interest';
@@ -84,8 +84,8 @@ export interface DossierCompany {
membershipRole: string | null; membershipRole: string | null;
} }
export interface DossierReservation { export interface DossierTenancy {
reservationId: string; tenancyId: string;
berthId: string; berthId: string;
mooringNumber: string; mooringNumber: string;
status: string; // typically 'active' status: string; // typically 'active'
@@ -128,13 +128,13 @@ export interface ClientArchiveDossier {
berths: DossierBerth[]; berths: DossierBerth[];
yachts: DossierYacht[]; yachts: DossierYacht[];
companies: DossierCompany[]; companies: DossierCompany[];
reservations: DossierReservation[]; tenancies: DossierTenancy[];
invoices: DossierInvoice[]; invoices: DossierInvoice[];
documents: DossierDocument[]; documents: DossierDocument[];
hasPortalUser: boolean; hasPortalUser: boolean;
/** Hard blockers - cannot proceed with archive at all until these are /** Hard blockers - cannot proceed with archive at all until these are
* resolved manually. Currently the only one is "active reservation * resolved manually. Currently the only one is "active tenancy
* on a sold berth" (since you can't unsell a berth from this flow). */ * on a sold berth" (since you can't unsell a berth from this flow). */
blockers: string[]; blockers: string[];
} }
@@ -327,23 +327,23 @@ export async function getClientArchiveDossier(
), ),
); );
// ─── Active reservations ───────────────────────────────────────────────── // ─── Active tenancies ────────────────────────────────────────────────────
const activeReservations = await db const activeTenancies = await db
.select({ .select({
id: berthReservations.id, id: berthTenancies.id,
berthId: berthReservations.berthId, berthId: berthTenancies.berthId,
mooringNumber: berths.mooringNumber, mooringNumber: berths.mooringNumber,
status: berthReservations.status, status: berthTenancies.status,
startDate: berthReservations.startDate, startDate: berthTenancies.startDate,
berthStatus: berths.status, berthStatus: berths.status,
}) })
.from(berthReservations) .from(berthTenancies)
.innerJoin(berths, eq(berthReservations.berthId, berths.id)) .innerJoin(berths, eq(berthTenancies.berthId, berths.id))
.where( .where(
and( and(
eq(berthReservations.clientId, clientId), eq(berthTenancies.clientId, clientId),
eq(berthReservations.portId, portId), eq(berthTenancies.portId, portId),
eq(berthReservations.status, 'active'), eq(berthTenancies.status, 'active'),
), ),
); );
@@ -376,14 +376,14 @@ export async function getClientArchiveDossier(
.limit(1); .limit(1);
// ─── Hard blockers ─────────────────────────────────────────────────────── // ─── Hard blockers ───────────────────────────────────────────────────────
// The only true blocker is an active reservation on a SOLD berth - we // The only true blocker is an active tenancy on a SOLD berth - we
// can't auto-handle this without crossing into refund territory. Force // can't auto-handle this without crossing into refund territory. Force
// the operator to handle it via the existing reservation UI first. // the operator to handle it via the existing tenancy UI first.
const blockers: string[] = []; const blockers: string[] = [];
for (const r of activeReservations) { for (const r of activeTenancies) {
if (r.berthStatus === 'sold') { if (r.berthStatus === 'sold') {
blockers.push( blockers.push(
`Active reservation on sold berth ${r.mooringNumber} (#${r.id.slice(0, 8)}). Process the refund or transfer the reservation before archiving.`, `Active tenancy on sold berth ${r.mooringNumber} (#${r.id.slice(0, 8)}). Process the refund or transfer the tenancy before archiving.`,
); );
} }
} }
@@ -410,8 +410,8 @@ export async function getClientArchiveDossier(
name: m.name, name: m.name,
membershipRole: m.role, membershipRole: m.role,
})), })),
reservations: activeReservations.map((r) => ({ tenancies: activeTenancies.map((r) => ({
reservationId: r.id, tenancyId: r.id,
berthId: r.berthId, berthId: r.berthId,
mooringNumber: r.mooringNumber, mooringNumber: r.mooringNumber,
status: r.status, status: r.status,

View File

@@ -17,7 +17,7 @@ import { db } from '@/lib/db';
import { clients } from '@/lib/db/schema/clients'; import { clients } from '@/lib/db/schema/clients';
import { interests, interestBerths } from '@/lib/db/schema/interests'; import { interests, interestBerths } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { invoices } from '@/lib/db/schema/financial'; import { invoices } from '@/lib/db/schema/financial';
import { yachts } from '@/lib/db/schema/yachts'; import { yachts } from '@/lib/db/schema/yachts';
import { companyMemberships } from '@/lib/db/schema/companies'; import { companyMemberships } from '@/lib/db/schema/companies';
@@ -49,8 +49,8 @@ export type YachtDecision = {
newOwnerId?: string; newOwnerId?: string;
}; };
export type ReservationDecision = { export type TenancyDecision = {
reservationId: string; tenancyId: string;
action: 'cancel' | 'transfer'; action: 'cancel' | 'transfer';
/** Required when action='transfer' - the new client id. */ /** Required when action='transfer' - the new client id. */
transferToClientId?: string; transferToClientId?: string;
@@ -73,7 +73,7 @@ export interface ArchiveDecisions {
acknowledgedSignedDocuments: boolean; acknowledgedSignedDocuments: boolean;
berthDecisions: BerthDecision[]; berthDecisions: BerthDecision[];
yachtDecisions: YachtDecision[]; yachtDecisions: YachtDecision[];
reservationDecisions: ReservationDecision[]; tenancyDecisions: TenancyDecision[];
invoiceDecisions: InvoiceDecision[]; invoiceDecisions: InvoiceDecision[];
documentDecisions: DocumentDecision[]; documentDecisions: DocumentDecision[];
} }
@@ -87,8 +87,8 @@ interface PersistedDecision {
| 'yacht_transferred' | 'yacht_transferred'
| 'yacht_marked_sold_away' | 'yacht_marked_sold_away'
| 'yacht_retained' | 'yacht_retained'
| 'reservation_cancelled' | 'tenancy_cancelled'
| 'reservation_transferred' | 'tenancy_transferred'
| 'invoice_voided' | 'invoice_voided'
| 'invoice_written_off' | 'invoice_written_off'
| 'invoice_left' | 'invoice_left'
@@ -268,27 +268,25 @@ export async function archiveClientWithDecisions(args: {
} }
} }
// ─── Reservation decisions ─────────────────────────────────────────── // ─── Tenancy decisions ───────────────────────────────────────────────
for (const d of decisions.reservationDecisions) { for (const d of decisions.tenancyDecisions) {
if (d.action === 'cancel') { if (d.action === 'cancel') {
await tx await tx
.update(berthReservations) .update(berthTenancies)
.set({ status: 'cancelled', updatedAt: new Date() }) .set({ status: 'cancelled', updatedAt: new Date() })
.where(eq(berthReservations.id, d.reservationId)); .where(eq(berthTenancies.id, d.tenancyId));
persistedDecisions.push({ kind: 'reservation_cancelled', refId: d.reservationId }); persistedDecisions.push({ kind: 'tenancy_cancelled', refId: d.tenancyId });
} else if (d.action === 'transfer') { } else if (d.action === 'transfer') {
if (!d.transferToClientId) { if (!d.transferToClientId) {
throw new ValidationError( throw new ValidationError(`Tenancy ${d.tenancyId}: transfer requires transferToClientId`);
`Reservation ${d.reservationId}: transfer requires transferToClientId`,
);
} }
await tx await tx
.update(berthReservations) .update(berthTenancies)
.set({ clientId: d.transferToClientId, updatedAt: new Date() }) .set({ clientId: d.transferToClientId, updatedAt: new Date() })
.where(eq(berthReservations.id, d.reservationId)); .where(eq(berthTenancies.id, d.tenancyId));
persistedDecisions.push({ persistedDecisions.push({
kind: 'reservation_transferred', kind: 'tenancy_transferred',
refId: d.reservationId, refId: d.tenancyId,
detail: { previousClientId: clientId, newClientId: d.transferToClientId }, detail: { previousClientId: clientId, newClientId: d.transferToClientId },
}); });
} }

View File

@@ -34,7 +34,7 @@ import { and, eq, inArray, sql } from 'drizzle-orm';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { clients, clientContacts, clientMergeLog } from '@/lib/db/schema/clients'; import { clients, clientContacts, clientMergeLog } from '@/lib/db/schema/clients';
import { interests } from '@/lib/db/schema/interests'; import { interests } from '@/lib/db/schema/interests';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { files, documents, formSubmissions } from '@/lib/db/schema/documents'; import { files, documents, formSubmissions } from '@/lib/db/schema/documents';
import { documentSends } from '@/lib/db/schema/brochures'; import { documentSends } from '@/lib/db/schema/brochures';
import { emailThreads, emailMessages } from '@/lib/db/schema/email'; import { emailThreads, emailMessages } from '@/lib/db/schema/email';
@@ -311,7 +311,7 @@ export async function hardDeleteClient(args: {
// Delete non-nullable-FK children explicitly (cascade chains // Delete non-nullable-FK children explicitly (cascade chains
// pick up their own children in turn). // pick up their own children in turn).
await tx.delete(interests).where(eq(interests.clientId, args.clientId)); await tx.delete(interests).where(eq(interests.clientId, args.clientId));
await tx.delete(berthReservations).where(eq(berthReservations.clientId, args.clientId)); await tx.delete(berthTenancies).where(eq(berthTenancies.clientId, args.clientId));
// Finally, the client itself. // Finally, the client itself.
await tx.delete(clients).where(eq(clients.id, args.clientId)); await tx.delete(clients).where(eq(clients.id, args.clientId));

View File

@@ -31,7 +31,7 @@ import {
clientMergeCandidates, clientMergeCandidates,
} from '@/lib/db/schema/clients'; } from '@/lib/db/schema/clients';
import { interests } from '@/lib/db/schema/interests'; import { interests } from '@/lib/db/schema/interests';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { auditLogs } from '@/lib/db/schema/system'; import { auditLogs } from '@/lib/db/schema/system';
import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors'; import { ConflictError, NotFoundError, ValidationError } from '@/lib/errors';
@@ -153,9 +153,9 @@ export async function mergeClients(opts: MergeOptions): Promise<MergeResult> {
.from(interests) .from(interests)
.where(eq(interests.clientId, opts.loserId)); .where(eq(interests.clientId, opts.loserId));
const loserReservations = await tx const loserReservations = await tx
.select({ id: berthReservations.id }) .select({ id: berthTenancies.id })
.from(berthReservations) .from(berthTenancies)
.where(eq(berthReservations.clientId, opts.loserId)); .where(eq(berthTenancies.clientId, opts.loserId));
const loserRelationshipsAsA = await tx const loserRelationshipsAsA = await tx
.select() .select()
.from(clientRelationships) .from(clientRelationships)
@@ -215,10 +215,10 @@ export async function mergeClients(opts: MergeOptions): Promise<MergeResult> {
const movedReservations = ( const movedReservations = (
await tx await tx
.update(berthReservations) .update(berthTenancies)
.set({ clientId: opts.winnerId, updatedAt: new Date() }) .set({ clientId: opts.winnerId, updatedAt: new Date() })
.where(eq(berthReservations.clientId, opts.loserId)) .where(eq(berthTenancies.clientId, opts.loserId))
.returning({ id: berthReservations.id }) .returning({ id: berthTenancies.id })
).length; ).length;
// Contacts: move loser's contacts to winner, but DON'T duplicate any // Contacts: move loser's contacts to winner, but DON'T duplicate any

View File

@@ -11,7 +11,7 @@ import {
} from '@/lib/db/schema/clients'; } from '@/lib/db/schema/clients';
import { companies, companyMemberships } from '@/lib/db/schema/companies'; import { companies, companyMemberships } from '@/lib/db/schema/companies';
import { yachts } from '@/lib/db/schema/yachts'; import { yachts } from '@/lib/db/schema/yachts';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { interests, interestBerths } from '@/lib/db/schema/interests'; import { interests, interestBerths } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { tags } from '@/lib/db/schema/system'; import { tags } from '@/lib/db/schema/system';
@@ -412,11 +412,11 @@ export async function getClientById(id: string, portId: string) {
), ),
); );
const activeReservations = await db.query.berthReservations.findMany({ const activeTenancies = await db.query.berthTenancies.findMany({
where: and( where: and(
eq(berthReservations.clientId, id), eq(berthTenancies.clientId, id),
eq(berthReservations.portId, portId), eq(berthTenancies.portId, portId),
eq(berthReservations.status, 'active'), eq(berthTenancies.status, 'active'),
), ),
columns: { columns: {
id: true, id: true,
@@ -450,7 +450,7 @@ export async function getClientById(id: string, portId: string) {
tags: clientTagRows.map((r) => r.tag), tags: clientTagRows.map((r) => r.tag),
yachts: yachtRows, yachts: yachtRows,
companies: membershipRows, companies: membershipRows,
activeReservations, activeTenancies,
interestCount: interestCountRow?.count ?? 0, interestCount: interestCountRow?.count ?? 0,
noteCount: noteCountRow?.count ?? 0, noteCount: noteCountRow?.count ?? 0,
clientPortalEnabled: portalEnabled, clientPortalEnabled: portalEnabled,

View File

@@ -6,7 +6,7 @@ import { yachts, yachtNotes } from '@/lib/db/schema/yachts';
import { companies, companyNotes } from '@/lib/db/schema/companies'; import { companies, companyNotes } from '@/lib/db/schema/companies';
import { interests, interestBerths, interestNotes } from '@/lib/db/schema/interests'; import { interests, interestBerths, interestNotes } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { invoices, expenses } from '@/lib/db/schema/financial'; import { invoices, expenses } from '@/lib/db/schema/financial';
import { payments } from '@/lib/db/schema/pipeline'; import { payments } from '@/lib/db/schema/pipeline';
import { documents } from '@/lib/db/schema/documents'; import { documents } from '@/lib/db/schema/documents';
@@ -508,18 +508,18 @@ export async function getRecentActivity(portId: string, limit = 20) {
(r) => r.clientName, (r) => r.clientName,
), ),
loadLabels( loadLabels(
'berth_reservation', 'berth_tenancy',
(ids) => (ids) =>
db db
.select({ .select({
id: berthReservations.id, id: berthTenancies.id,
mooring: berths.mooringNumber, mooring: berths.mooringNumber,
clientName: clients.fullName, clientName: clients.fullName,
}) })
.from(berthReservations) .from(berthTenancies)
.innerJoin(berths, eq(berthReservations.berthId, berths.id)) .innerJoin(berths, eq(berthTenancies.berthId, berths.id))
.leftJoin(clients, eq(berthReservations.clientId, clients.id)) .leftJoin(clients, eq(berthTenancies.clientId, clients.id))
.where(and(eq(berthReservations.portId, portId), inArray(berthReservations.id, ids))), .where(and(eq(berthTenancies.portId, portId), inArray(berthTenancies.id, ids))),
(r) => `Berth ${r.mooring}${r.clientName ? ` · ${r.clientName}` : ''}`, (r) => `Berth ${r.mooring}${r.clientName ? ` · ${r.clientName}` : ''}`,
), ),
loadLabels( loadLabels(

View File

@@ -14,7 +14,7 @@ import { companies } from '@/lib/db/schema/companies';
import { yachts } from '@/lib/db/schema/yachts'; import { yachts } from '@/lib/db/schema/yachts';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { formatBerthRange } from '@/lib/templates/berth-range'; import { formatBerthRange } from '@/lib/templates/berth-range';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { ports } from '@/lib/db/schema/ports'; import { ports } from '@/lib/db/schema/ports';
import { userProfiles, userPortRoles } from '@/lib/db/schema/users'; import { userProfiles, userPortRoles } from '@/lib/db/schema/users';
import { buildListQuery } from '@/lib/db/query-builder'; import { buildListQuery } from '@/lib/db/query-builder';
@@ -428,7 +428,7 @@ export async function getDocumentById(id: string, portId: string) {
/** /**
* Reject any subject FK (clientId / interestId / companyId / yachtId / * Reject any subject FK (clientId / interestId / companyId / yachtId /
* reservationId) that points at a row outside the caller's port. Without * tenancyId) that points at a row outside the caller's port. Without
* this guard, a port-A user could create a document whose subject is a * this guard, a port-A user could create a document whose subject is a
* port-B client and then exfiltrate the foreign client's name + email * port-B client and then exfiltrate the foreign client's name + email
* via sendForSigning's Documenso payload, or via the local watcher / * via sendForSigning's Documenso payload, or via the local watcher /
@@ -441,7 +441,7 @@ async function assertSubjectFksInPort(
interestId?: string | null; interestId?: string | null;
companyId?: string | null; companyId?: string | null;
yachtId?: string | null; yachtId?: string | null;
reservationId?: string | null; tenancyId?: string | null;
}, },
): Promise<void> { ): Promise<void> {
const checks: Array<Promise<void>> = []; const checks: Array<Promise<void>> = [];
@@ -485,17 +485,14 @@ async function assertSubjectFksInPort(
}), }),
); );
} }
if (fks.reservationId) { if (fks.tenancyId) {
checks.push( checks.push(
db.query.berthReservations db.query.berthTenancies
.findFirst({ .findFirst({
where: and( where: and(eq(berthTenancies.id, fks.tenancyId), eq(berthTenancies.portId, portId)),
eq(berthReservations.id, fks.reservationId),
eq(berthReservations.portId, portId),
),
}) })
.then((row) => { .then((row) => {
if (!row) throw new ValidationError('reservationId not found in this port'); if (!row) throw new ValidationError('tenancyId not found in this port');
}), }),
); );
} }
@@ -1494,14 +1491,14 @@ export async function handleDocumentCompleted(eventData: { documentId: string; p
.where(eq(documents.id, doc.id)); .where(eq(documents.id, doc.id));
// Reservation agreements mirror their signed PDF onto // Reservation agreements mirror their signed PDF onto
// berth_reservations.contractFileId so the portal "My Reservations" view // berth_tenancies.contractFileId so the portal "My Tenancies" view
// can resolve the contract without joining through documents. // can resolve the contract without joining through documents.
if (doc.documentType === 'reservation_agreement' && doc.reservationId) { if (doc.documentType === 'reservation_agreement' && doc.tenancyId) {
const { berthReservations } = await import('@/lib/db/schema/reservations'); const { berthTenancies } = await import('@/lib/db/schema/tenancies');
await tx await tx
.update(berthReservations) .update(berthTenancies)
.set({ contractFileId: inserted.id, updatedAt: new Date() }) .set({ contractFileId: inserted.id, updatedAt: new Date() })
.where(eq(berthReservations.id, doc.reservationId)); .where(eq(berthTenancies.id, doc.tenancyId));
} }
return inserted; return inserted;
@@ -2427,7 +2424,7 @@ export async function createFromWizard(
interestId: data.interestId, interestId: data.interestId,
companyId: data.companyId, companyId: data.companyId,
yachtId: data.yachtId, yachtId: data.yachtId,
reservationId: data.reservationId, tenancyId: data.tenancyId,
}); });
const [doc] = await db const [doc] = await db
@@ -2435,7 +2432,7 @@ export async function createFromWizard(
.values({ .values({
portId, portId,
interestId: data.interestId ?? null, interestId: data.interestId ?? null,
reservationId: data.reservationId ?? null, tenancyId: data.tenancyId ?? null,
clientId: data.clientId ?? null, clientId: data.clientId ?? null,
companyId: data.companyId ?? null, companyId: data.companyId ?? null,
yachtId: data.yachtId ?? null, yachtId: data.yachtId ?? null,
@@ -2516,7 +2513,7 @@ export async function createFromUpload(
interestId: data.interestId, interestId: data.interestId,
companyId: data.companyId, companyId: data.companyId,
yachtId: data.yachtId, yachtId: data.yachtId,
reservationId: data.reservationId, tenancyId: data.tenancyId,
}); });
const [doc] = await db const [doc] = await db
@@ -2524,7 +2521,7 @@ export async function createFromUpload(
.values({ .values({
portId, portId,
interestId: data.interestId ?? null, interestId: data.interestId ?? null,
reservationId: data.reservationId ?? null, tenancyId: data.tenancyId ?? null,
clientId: data.clientId ?? null, clientId: data.clientId ?? null,
companyId: data.companyId ?? null, companyId: data.companyId ?? null,
yachtId: data.yachtId ?? null, yachtId: data.yachtId ?? null,

View File

@@ -26,7 +26,7 @@ import { tags, scratchpadNotes } from '@/lib/db/schema/system';
import { companies, companyMemberships } from '@/lib/db/schema/companies'; import { companies, companyMemberships } from '@/lib/db/schema/companies';
import { yachts } from '@/lib/db/schema/yachts'; import { yachts } from '@/lib/db/schema/yachts';
import { interests } from '@/lib/db/schema/interests'; import { interests } from '@/lib/db/schema/interests';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { invoices } from '@/lib/db/schema/financial'; import { invoices } from '@/lib/db/schema/financial';
import { documents, files, formSubmissions } from '@/lib/db/schema/documents'; import { documents, files, formSubmissions } from '@/lib/db/schema/documents';
import { auditLogs } from '@/lib/db/schema/system'; import { auditLogs } from '@/lib/db/schema/system';
@@ -141,8 +141,8 @@ export async function buildClientBundle(clientId: string, portId: string): Promi
db.query.interests.findMany({ db.query.interests.findMany({
where: and(eq(interests.clientId, clientId), eq(interests.portId, portId)), where: and(eq(interests.clientId, clientId), eq(interests.portId, portId)),
}), }),
db.query.berthReservations.findMany({ db.query.berthTenancies.findMany({
where: and(eq(berthReservations.clientId, clientId), eq(berthReservations.portId, portId)), where: and(eq(berthTenancies.clientId, clientId), eq(berthTenancies.portId, portId)),
}), }),
db.query.invoices.findMany({ db.query.invoices.findMany({
where: and( where: and(

View File

@@ -6,7 +6,7 @@ import { reminders, interestContactLog } from '@/lib/db/schema/operations';
import { clients, clientAddresses, clientContacts } from '@/lib/db/schema/clients'; import { clients, clientAddresses, clientContacts } from '@/lib/db/schema/clients';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { documents, documentEvents } from '@/lib/db/schema/documents'; import { documents, documentEvents } from '@/lib/db/schema/documents';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { yachts } from '@/lib/db/schema/yachts'; import { yachts } from '@/lib/db/schema/yachts';
import { companyMemberships } from '@/lib/db/schema/companies'; import { companyMemberships } from '@/lib/db/schema/companies';
import { tags } from '@/lib/db/schema/system'; import { tags } from '@/lib/db/schema/system';
@@ -622,14 +622,14 @@ export async function getInterestById(id: string, portId: string) {
) )
.orderBy(desc(documentEvents.createdAt)) .orderBy(desc(documentEvents.createdAt))
.limit(1), .limit(1),
// Latest cancelled berth_reservation row pointing at this interest. // Latest cancelled berth_tenancy row pointing at this interest.
// berth_reservations has no cancelled_at column; updatedAt is set when // berth_tenancies has no cancelled_at column; updatedAt is set when
// the row flips to status='cancelled', so it tracks the same moment. // the row flips to status='cancelled', so it tracks the same moment.
db db
.select({ at: berthReservations.updatedAt }) .select({ at: berthTenancies.updatedAt })
.from(berthReservations) .from(berthTenancies)
.where(and(eq(berthReservations.interestId, id), eq(berthReservations.status, 'cancelled'))) .where(and(eq(berthTenancies.interestId, id), eq(berthTenancies.status, 'cancelled')))
.orderBy(desc(berthReservations.updatedAt)) .orderBy(desc(berthTenancies.updatedAt))
.limit(1), .limit(1),
// "Berth sold to another deal" - any of this interest's linked berths // "Berth sold to another deal" - any of this interest's linked berths
// has at least one OTHER interest with a `won` outcome. Take the // has at least one OTHER interest with a `won` outcome. Take the

View File

@@ -10,7 +10,7 @@ import { berths } from '@/lib/db/schema/berths';
import { ports } from '@/lib/db/schema/ports'; import { ports } from '@/lib/db/schema/ports';
import { yachts } from '@/lib/db/schema/yachts'; import { yachts } from '@/lib/db/schema/yachts';
import { companies, companyMemberships } from '@/lib/db/schema/companies'; import { companies, companyMemberships } from '@/lib/db/schema/companies';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { presignDownloadUrl } from '@/lib/storage'; import { presignDownloadUrl } from '@/lib/storage';
import { getCountryName } from '@/lib/i18n/countries'; import { getCountryName } from '@/lib/i18n/countries';
@@ -32,7 +32,7 @@ export interface PortalDashboard {
invoices: number; invoices: number;
yachts: number; yachts: number;
memberships: number; memberships: number;
activeReservations: number; activeTenancies: number;
}; };
} }
@@ -40,7 +40,7 @@ export async function getPortalDashboard(
clientId: string, clientId: string,
portId: string, portId: string,
): Promise<PortalDashboard | null> { ): Promise<PortalDashboard | null> {
const [client, port, interestCount, documentCount, yachtList, membershipList, reservationList] = const [client, port, interestCount, documentCount, yachtList, membershipList, tenancyList] =
await Promise.all([ await Promise.all([
db.query.clients.findFirst({ db.query.clients.findFirst({
where: and(eq(clients.id, clientId), eq(clients.portId, portId)), where: and(eq(clients.id, clientId), eq(clients.portId, portId)),
@@ -59,7 +59,7 @@ export async function getPortalDashboard(
.where(and(eq(documents.clientId, clientId), eq(documents.portId, portId))), .where(and(eq(documents.clientId, clientId), eq(documents.portId, portId))),
getPortalUserYachts(clientId, portId), getPortalUserYachts(clientId, portId),
getPortalUserMemberships(clientId, portId), getPortalUserMemberships(clientId, portId),
getPortalUserReservations(clientId, portId), getPortalUserTenancies(clientId, portId),
]); ]);
if (!client || !port) return null; if (!client || !port) return null;
@@ -96,7 +96,7 @@ export async function getPortalDashboard(
invoices: invoiceCount, invoices: invoiceCount,
yachts: yachtList.length, yachts: yachtList.length,
memberships: membershipList.length, memberships: membershipList.length,
activeReservations: reservationList.length, activeTenancies: tenancyList.length,
}, },
}; };
} }
@@ -515,9 +515,9 @@ export async function getPortalUserMemberships(
return rows; return rows;
} }
// ─── Reservations ───────────────────────────────────────────────────────────── // ─── Tenancies ────────────────────────────────────────────────────────────────
export interface PortalReservation { export interface PortalTenancy {
id: string; id: string;
berthId: string; berthId: string;
berthMooringNumber: string | null; berthMooringNumber: string | null;
@@ -529,32 +529,32 @@ export interface PortalReservation {
tenureType: string; tenureType: string;
} }
export async function getPortalUserReservations( export async function getPortalUserTenancies(
clientId: string, clientId: string,
portId: string, portId: string,
): Promise<PortalReservation[]> { ): Promise<PortalTenancy[]> {
const rows = await db const rows = await db
.select({ .select({
id: berthReservations.id, id: berthTenancies.id,
berthId: berthReservations.berthId, berthId: berthTenancies.berthId,
berthMooringNumber: berths.mooringNumber, berthMooringNumber: berths.mooringNumber,
yachtId: berthReservations.yachtId, yachtId: berthTenancies.yachtId,
yachtName: yachts.name, yachtName: yachts.name,
status: berthReservations.status, status: berthTenancies.status,
startDate: berthReservations.startDate, startDate: berthTenancies.startDate,
endDate: berthReservations.endDate, endDate: berthTenancies.endDate,
tenureType: berthReservations.tenureType, tenureType: berthTenancies.tenureType,
}) })
.from(berthReservations) .from(berthTenancies)
.innerJoin(berths, eq(berthReservations.berthId, berths.id)) .innerJoin(berths, eq(berthTenancies.berthId, berths.id))
.innerJoin(yachts, eq(berthReservations.yachtId, yachts.id)) .innerJoin(yachts, eq(berthTenancies.yachtId, yachts.id))
.where( .where(
and( and(
eq(berthReservations.clientId, clientId), eq(berthTenancies.clientId, clientId),
eq(berthReservations.portId, portId), eq(berthTenancies.portId, portId),
inArray(berthReservations.status, ['pending', 'active']), inArray(berthTenancies.status, ['pending', 'active']),
), ),
) )
.orderBy(desc(berthReservations.createdAt)); .orderBy(desc(berthTenancies.createdAt));
return rows as PortalReservation[]; return rows as PortalTenancy[];
} }

View File

@@ -2,7 +2,7 @@ import { and, eq } from 'drizzle-orm';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { berths } from '@/lib/db/schema/berths'; import { berths } from '@/lib/db/schema/berths';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { clients } from '@/lib/db/schema/clients'; import { clients } from '@/lib/db/schema/clients';
import { ports } from '@/lib/db/schema/ports'; import { ports } from '@/lib/db/schema/ports';
import { yachts } from '@/lib/db/schema/yachts'; import { yachts } from '@/lib/db/schema/yachts';
@@ -57,13 +57,13 @@ export type ReservationAgreementContext = {
* formatting helpers in the template language. * formatting helpers in the template language.
*/ */
export async function buildReservationAgreementContext( export async function buildReservationAgreementContext(
reservationId: string, tenancyId: string,
portId: string, portId: string,
): Promise<ReservationAgreementContext> { ): Promise<ReservationAgreementContext> {
const reservation = await db.query.berthReservations.findFirst({ const reservation = await db.query.berthTenancies.findFirst({
where: and(eq(berthReservations.id, reservationId), eq(berthReservations.portId, portId)), where: and(eq(berthTenancies.id, tenancyId), eq(berthTenancies.portId, portId)),
}); });
if (!reservation) throw new NotFoundError('Reservation'); if (!reservation) throw new NotFoundError('Tenancy');
const [client, yacht, berth, port] = await Promise.all([ const [client, yacht, berth, port] = await Promise.all([
db.query.clients.findFirst({ db.query.clients.findFirst({

View File

@@ -3,7 +3,7 @@
* entity tabs, top-level page, dashboard widgets, webhook auto-create * entity tabs, top-level page, dashboard widgets, webhook auto-create
* branch) is hidden by default and only surfaces when EITHER: * branch) is hidden by default and only surfaces when EITHER:
* *
* (a) at least one `berth_reservations` row exists for the port * (a) at least one `berth_tenancies` row exists for the port
* (lazy auto-enable on first creation), OR * (lazy auto-enable on first creation), OR
* (b) an admin has explicitly enabled the module via * (b) an admin has explicitly enabled the module via
* `system_settings.tenancies_module_enabled` (default false). * `system_settings.tenancies_module_enabled` (default false).
@@ -20,7 +20,7 @@ import { and, eq, isNull, or } from 'drizzle-orm';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { systemSettings } from '@/lib/db/schema/system'; import { systemSettings } from '@/lib/db/schema/system';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { NotFoundError } from '@/lib/errors'; import { NotFoundError } from '@/lib/errors';
/** /**
@@ -50,9 +50,9 @@ export async function isTenanciesModuleEnabled(portId: string): Promise<boolean>
// the rest of the app, even when the admin setting is still false. // the rest of the app, even when the admin setting is still false.
// Once any port has a tenancy, the module's UX is justified. // Once any port has a tenancy, the module's UX is justified.
const rowCheck = await db const rowCheck = await db
.select({ id: berthReservations.id }) .select({ id: berthTenancies.id })
.from(berthReservations) .from(berthTenancies)
.where(eq(berthReservations.portId, portId)) .where(eq(berthTenancies.portId, portId))
.limit(1); .limit(1);
return rowCheck.length > 0; return rowCheck.length > 0;
} }

View File

@@ -36,10 +36,10 @@ export const WEBHOOK_EVENTS = [
'company_membership.added', 'company_membership.added',
'company_membership.updated', 'company_membership.updated',
'company_membership.ended', 'company_membership.ended',
'berth_reservation.created', 'berth_tenancy.created',
'berth_reservation.activated', 'berth_tenancy.activated',
'berth_reservation.ended', 'berth_tenancy.ended',
'berth_reservation.cancelled', 'berth_tenancy.cancelled',
] as const; ] as const;
export type WebhookEvent = (typeof WEBHOOK_EVENTS)[number]; export type WebhookEvent = (typeof WEBHOOK_EVENTS)[number];
@@ -78,8 +78,8 @@ export const INTERNAL_TO_WEBHOOK_MAP: Record<string, WebhookEvent> = {
'company_membership:added': 'company_membership.added', 'company_membership:added': 'company_membership.added',
'company_membership:updated': 'company_membership.updated', 'company_membership:updated': 'company_membership.updated',
'company_membership:ended': 'company_membership.ended', 'company_membership:ended': 'company_membership.ended',
'berth_reservation:created': 'berth_reservation.created', 'berth_tenancy:created': 'berth_tenancy.created',
'berth_reservation:activated': 'berth_reservation.activated', 'berth_tenancy:activated': 'berth_tenancy.activated',
'berth_reservation:ended': 'berth_reservation.ended', 'berth_tenancy:ended': 'berth_tenancy.ended',
'berth_reservation:cancelled': 'berth_reservation.cancelled', 'berth_tenancy:cancelled': 'berth_tenancy.cancelled',
}; };

View File

@@ -132,11 +132,11 @@ export interface ServerToClientEvents {
clientId: string; clientId: string;
}) => void; }) => void;
// Berth reservation events // Berth tenancy events
'berth_reservation:created': (payload: { reservationId: string; berthId: string }) => void; 'berth_tenancy:created': (payload: { tenancyId: string; berthId: string }) => void;
'berth_reservation:activated': (payload: { reservationId: string; berthId: string }) => void; 'berth_tenancy:activated': (payload: { tenancyId: string; berthId: string }) => void;
'berth_reservation:ended': (payload: { reservationId: string; berthId: string }) => void; 'berth_tenancy:ended': (payload: { tenancyId: string; berthId: string }) => void;
'berth_reservation:cancelled': (payload: { reservationId: string; berthId: string }) => void; 'berth_tenancy:cancelled': (payload: { tenancyId: string; berthId: string }) => void;
// Document events // Document events
'document:created': (payload: { documentId: string; type?: string; interestId?: string }) => void; 'document:created': (payload: { documentId: string; type?: string; interestId?: string }) => void;

View File

@@ -36,7 +36,7 @@ export const createDocumentWizardSchema = z
notes: z.string().optional(), notes: z.string().optional(),
interestId: z.string().optional(), interestId: z.string().optional(),
reservationId: z.string().optional(), tenancyId: z.string().optional(),
clientId: z.string().optional(), clientId: z.string().optional(),
companyId: z.string().optional(), companyId: z.string().optional(),
yachtId: z.string().optional(), yachtId: z.string().optional(),
@@ -55,9 +55,8 @@ export const createDocumentWizardSchema = z
}) })
.refine( .refine(
(d) => (d) =>
[d.interestId, d.reservationId, d.clientId, d.companyId, d.yachtId].filter(Boolean).length === [d.interestId, d.tenancyId, d.clientId, d.companyId, d.yachtId].filter(Boolean).length === 1,
1, { message: 'Exactly one subject (interest/tenancy/client/company/yacht) is required' },
{ message: 'Exactly one subject (interest/reservation/client/company/yacht) is required' },
) )
.refine((d) => d.source !== 'template' || Boolean(d.templateId), { .refine((d) => d.source !== 'template' || Boolean(d.templateId), {
path: ['templateId'], path: ['templateId'],

View File

@@ -1,7 +1,7 @@
import { z } from 'zod'; import { z } from 'zod';
import { baseListQuerySchema } from '@/lib/api/list-query'; import { baseListQuerySchema } from '@/lib/api/list-query';
export const RESERVATION_STATUSES = ['pending', 'active', 'ended', 'cancelled'] as const; export const TENANCY_STATUSES = ['pending', 'active', 'ended', 'cancelled'] as const;
export const TENURE_TYPES = ['permanent', 'fixed_term', 'seasonal'] as const; export const TENURE_TYPES = ['permanent', 'fixed_term', 'seasonal'] as const;
export const createPendingSchema = z.object({ export const createPendingSchema = z.object({
@@ -19,7 +19,7 @@ export const activateSchema = z.object({
effectiveDate: z.coerce.date().optional(), effectiveDate: z.coerce.date().optional(),
}); });
export const endReservationSchema = z.object({ export const endTenancySchema = z.object({
endDate: z.coerce.date(), endDate: z.coerce.date(),
notes: z.string().optional(), notes: z.string().optional(),
}); });
@@ -28,8 +28,8 @@ export const cancelSchema = z.object({
reason: z.string().optional(), reason: z.string().optional(),
}); });
export const listReservationsSchema = baseListQuerySchema.extend({ export const listTenanciesSchema = baseListQuerySchema.extend({
status: z.enum(RESERVATION_STATUSES).optional(), status: z.enum(TENANCY_STATUSES).optional(),
berthId: z.string().optional(), berthId: z.string().optional(),
clientId: z.string().optional(), clientId: z.string().optional(),
yachtId: z.string().optional(), yachtId: z.string().optional(),
@@ -37,6 +37,6 @@ export const listReservationsSchema = baseListQuerySchema.extend({
export type CreatePendingInput = z.infer<typeof createPendingSchema>; export type CreatePendingInput = z.infer<typeof createPendingSchema>;
export type ActivateInput = z.infer<typeof activateSchema>; export type ActivateInput = z.infer<typeof activateSchema>;
export type EndReservationInput = z.infer<typeof endReservationSchema>; export type EndTenancyInput = z.infer<typeof endTenancySchema>;
export type CancelInput = z.infer<typeof cancelSchema>; export type CancelInput = z.infer<typeof cancelSchema>;
export type ListReservationsInput = z.infer<typeof listReservationsSchema>; export type ListTenanciesInput = z.infer<typeof listTenanciesSchema>;

View File

@@ -93,7 +93,7 @@ test.describe('destructive: client smart-archive + smart-restore', () => {
acknowledgedSignedDocuments: false, acknowledgedSignedDocuments: false,
berthDecisions: [], berthDecisions: [],
yachtDecisions: [], yachtDecisions: [],
reservationDecisions: [], tenancyDecisions: [],
invoiceDecisions: [], invoiceDecisions: [],
documentDecisions: [], documentDecisions: [],
}, },

View File

@@ -31,7 +31,7 @@ export async function teardown() {
-- Cascade-delete dependent rows. Order respects FK chains. -- Cascade-delete dependent rows. Order respects FK chains.
, del_audit AS (DELETE FROM audit_logs WHERE port_id IN (SELECT id FROM doomed) RETURNING 1) , del_audit AS (DELETE FROM audit_logs WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_bml AS (DELETE FROM berth_maintenance_log WHERE port_id IN (SELECT id FROM doomed) RETURNING 1) , del_bml AS (DELETE FROM berth_maintenance_log WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_resv AS (DELETE FROM berth_reservations WHERE port_id IN (SELECT id FROM doomed) RETURNING 1) , del_resv AS (DELETE FROM berth_tenancies WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_caddr AS (DELETE FROM client_addresses WHERE port_id IN (SELECT id FROM doomed) RETURNING 1) , del_caddr AS (DELETE FROM client_addresses WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_cmlog AS (DELETE FROM client_merge_log WHERE port_id IN (SELECT id FROM doomed) RETURNING 1) , del_cmlog AS (DELETE FROM client_merge_log WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_crel AS (DELETE FROM client_relationships WHERE port_id IN (SELECT id FROM doomed) RETURNING 1) , del_crel AS (DELETE FROM client_relationships WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)

View File

@@ -22,7 +22,7 @@ import {
type NewCompany, type NewCompany,
type Company, type Company,
} from '@/lib/db/schema/companies'; } from '@/lib/db/schema/companies';
import { berthReservations, type BerthReservation } from '@/lib/db/schema/reservations'; import { berthTenancies, type BerthTenancy } from '@/lib/db/schema/tenancies';
// ─── Port ──────────────────────────────────────────────────────────────────── // ─── Port ────────────────────────────────────────────────────────────────────
@@ -157,7 +157,7 @@ export async function makeMembership(args: {
// ─── Berth Reservation ─────────────────────────────────────────────────────── // ─── Berth Reservation ───────────────────────────────────────────────────────
export async function makeReservation(args: { export async function makeTenancy(args: {
berthId: string; berthId: string;
portId: string; portId: string;
clientId: string; clientId: string;
@@ -169,9 +169,9 @@ export async function makeReservation(args: {
interestId?: string; interestId?: string;
createdBy?: string; createdBy?: string;
notes?: string; notes?: string;
}): Promise<BerthReservation> { }): Promise<BerthTenancy> {
const [row] = await db const [row] = await db
.insert(berthReservations) .insert(berthTenancies)
.values({ .values({
berthId: args.berthId, berthId: args.berthId,
portId: args.portId, portId: args.portId,
@@ -363,7 +363,7 @@ export function makeFullPermissions(): RolePermissions {
yachts: { view: true, create: true, edit: true, delete: true, transfer: true }, yachts: { view: true, create: true, edit: true, delete: true, transfer: true },
companies: { view: true, create: true, edit: true, delete: true }, companies: { view: true, create: true, edit: true, delete: true },
memberships: { view: true, manage: true }, memberships: { view: true, manage: true },
reservations: { view: true, create: true, activate: true, cancel: true }, tenancies: { view: true, manage: true, cancel: true },
admin: { admin: {
manage_users: true, manage_users: true,
view_audit_log: true, view_audit_log: true,
@@ -451,7 +451,7 @@ export function makeViewerPermissions(): RolePermissions {
yachts: { view: true, create: false, edit: false, delete: false, transfer: false }, yachts: { view: true, create: false, edit: false, delete: false, transfer: false },
companies: { view: true, create: false, edit: false, delete: false }, companies: { view: true, create: false, edit: false, delete: false },
memberships: { view: true, manage: false }, memberships: { view: true, manage: false },
reservations: { view: true, create: false, activate: false, cancel: false }, tenancies: { view: true, manage: false, cancel: false },
admin: { admin: {
manage_users: false, manage_users: false,
view_audit_log: false, view_audit_log: false,
@@ -539,7 +539,7 @@ export function makeSalesAgentPermissions(): RolePermissions {
yachts: { view: true, create: true, edit: true, delete: false, transfer: false }, yachts: { view: true, create: true, edit: true, delete: false, transfer: false },
companies: { view: true, create: true, edit: false, delete: false }, companies: { view: true, create: true, edit: false, delete: false },
memberships: { view: true, manage: false }, memberships: { view: true, manage: false },
reservations: { view: true, create: true, activate: true, cancel: false }, tenancies: { view: true, manage: true, cancel: false },
admin: { admin: {
manage_users: false, manage_users: false,
view_audit_log: false, view_audit_log: false,
@@ -627,7 +627,7 @@ export function makeSalesManagerPermissions(): RolePermissions {
yachts: { view: true, create: true, edit: true, delete: false, transfer: true }, yachts: { view: true, create: true, edit: true, delete: false, transfer: true },
companies: { view: true, create: true, edit: true, delete: false }, companies: { view: true, create: true, edit: true, delete: false },
memberships: { view: true, manage: true }, memberships: { view: true, manage: true },
reservations: { view: true, create: true, activate: true, cancel: true }, tenancies: { view: true, manage: true, cancel: true },
admin: { admin: {
manage_users: false, manage_users: false,
view_audit_log: true, view_audit_log: true,

View File

@@ -16,7 +16,7 @@ vi.mock('@/lib/socket/server', () => ({
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { alerts } from '@/lib/db/schema/insights'; import { alerts } from '@/lib/db/schema/insights';
import { interests } from '@/lib/db/schema/interests'; import { interests } from '@/lib/db/schema/interests';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { documents } from '@/lib/db/schema/documents'; import { documents } from '@/lib/db/schema/documents';
import { runAlertEngineForPorts } from '@/lib/services/alert-engine'; import { runAlertEngineForPorts } from '@/lib/services/alert-engine';
import { makePort, makeClient, makeBerth, makeYacht } from '../helpers/factories'; import { makePort, makeClient, makeBerth, makeYacht } from '../helpers/factories';
@@ -49,7 +49,7 @@ describe('alert engine', () => {
}); });
const fourDaysAgo = new Date(Date.now() - 4 * 86_400_000); const fourDaysAgo = new Date(Date.now() - 4 * 86_400_000);
const [resv] = await db const [resv] = await db
.insert(berthReservations) .insert(berthTenancies)
.values({ .values({
portId: port.id, portId: port.id,
berthId: berth.id, berthId: berth.id,
@@ -82,7 +82,7 @@ describe('alert engine', () => {
ownerId: client.id, ownerId: client.id,
}); });
const stale = new Date(Date.now() - 10 * 86_400_000); const stale = new Date(Date.now() - 10 * 86_400_000);
await db.insert(berthReservations).values({ await db.insert(berthTenancies).values({
portId: port.id, portId: port.id,
berthId: berth.id, berthId: berth.id,
clientId: client.id, clientId: client.id,
@@ -112,7 +112,7 @@ describe('alert engine', () => {
}); });
const tenDaysAgo = new Date(Date.now() - 10 * 86_400_000); const tenDaysAgo = new Date(Date.now() - 10 * 86_400_000);
const [resv] = await db const [resv] = await db
.insert(berthReservations) .insert(berthTenancies)
.values({ .values({
portId: port.id, portId: port.id,
berthId: berth.id, berthId: berth.id,
@@ -132,7 +132,7 @@ describe('alert engine', () => {
// Add an agreement document - condition no longer fires. // Add an agreement document - condition no longer fires.
await db.insert(documents).values({ await db.insert(documents).values({
portId: port.id, portId: port.id,
reservationId: resv!.id, tenancyId: resv!.id,
documentType: 'reservation_agreement', documentType: 'reservation_agreement',
title: 'Reservation Agreement', title: 'Reservation Agreement',
status: 'sent', status: 'sent',

View File

@@ -1,15 +1,15 @@
/** /**
* Port-scoped global reservations list - locks in feat(marina): the new * Port-scoped global tenancies list - locks in feat(marina): the
* `GET /api/v1/berth-reservations` endpoint that powers the * `GET /api/v1/tenancies` endpoint that powers the
* `[portSlug]/berth-reservations` page. The route is thin (parseQuery * `[portSlug]/tenancies` page. The route is thin (parseQuery
* listReservations); the test guarantees port scoping at the handler * listTenancies); the test guarantees port scoping at the handler
* boundary so a future refactor of the service can't accidentally leak * boundary so a future refactor of the service can't accidentally leak
* cross-port rows. * cross-port rows.
*/ */
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { listHandler } from '@/app/api/v1/berth-reservations/handlers'; import { listHandler } from '@/app/api/v1/tenancies/handlers';
import { createHandler as createReservationHandler } from '@/app/api/v1/berths/[id]/reservations/handlers'; import { createHandler as createTenancyHandler } from '@/app/api/v1/berths/[id]/tenancies/handlers';
import { makeMockCtx, makeMockRequest } from '../../helpers/route-tester'; import { makeMockCtx, makeMockRequest } from '../../helpers/route-tester';
import { import {
makeBerth, makeBerth,
@@ -19,13 +19,13 @@ import {
makeYacht, makeYacht,
} from '../../helpers/factories'; } from '../../helpers/factories';
async function seedReservation(portId: string) { async function seedTenancy(portId: string) {
const berth = await makeBerth({ portId }); const berth = await makeBerth({ portId });
const client = await makeClient({ portId }); const client = await makeClient({ portId });
const yacht = await makeYacht({ portId, ownerType: 'client', ownerId: client.id }); const yacht = await makeYacht({ portId, ownerType: 'client', ownerId: client.id });
const ctx = makeMockCtx({ portId, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId, permissions: makeFullPermissions() });
const res = await createReservationHandler( const res = await createTenancyHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, { makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: { body: {
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
@@ -38,17 +38,14 @@ async function seedReservation(portId: string) {
return ((await res.json()) as any).data as { id: string; berthId: string }; return ((await res.json()) as any).data as { id: string; berthId: string };
} }
describe('GET /api/v1/berth-reservations', () => { describe('GET /api/v1/tenancies', () => {
it('returns all reservations for the requesting port', async () => { it('returns all tenancies for the requesting port', async () => {
const port = await makePort(); const port = await makePort();
const r1 = await seedReservation(port.id); const r1 = await seedTenancy(port.id);
const r2 = await seedReservation(port.id); const r2 = await seedTenancy(port.id);
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const res = await listHandler( const res = await listHandler(makeMockRequest('GET', 'http://localhost/api/v1/tenancies'), ctx);
makeMockRequest('GET', 'http://localhost/api/v1/berth-reservations'),
ctx,
);
expect(res.status).toBe(200); expect(res.status).toBe(200);
const body = (await res.json()) as any; const body = (await res.json()) as any;
@@ -57,33 +54,30 @@ describe('GET /api/v1/berth-reservations', () => {
expect(body.pagination).toMatchObject({ page: 1, total: 2 }); expect(body.pagination).toMatchObject({ page: 1, total: 2 });
}); });
it('does not leak reservations from a different port', async () => { it('does not leak tenancies from a different port', async () => {
const portA = await makePort(); const portA = await makePort();
const portB = await makePort(); const portB = await makePort();
const reservationInB = await seedReservation(portB.id); const tenancyInB = await seedTenancy(portB.id);
// Caller is operating in portA; portB's reservation must not appear. // Caller is operating in portA; portB's tenancy must not appear.
const ctx = makeMockCtx({ portId: portA.id, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId: portA.id, permissions: makeFullPermissions() });
const res = await listHandler( const res = await listHandler(makeMockRequest('GET', 'http://localhost/api/v1/tenancies'), ctx);
makeMockRequest('GET', 'http://localhost/api/v1/berth-reservations'),
ctx,
);
expect(res.status).toBe(200); expect(res.status).toBe(200);
const body = (await res.json()) as any; const body = (await res.json()) as any;
const ids = (body.data as Array<{ id: string }>).map((r) => r.id); const ids = (body.data as Array<{ id: string }>).map((r) => r.id);
expect(ids).not.toContain(reservationInB.id); expect(ids).not.toContain(tenancyInB.id);
}); });
it('honors pagination via query params', async () => { it('honors pagination via query params', async () => {
const port = await makePort(); const port = await makePort();
await seedReservation(port.id); await seedTenancy(port.id);
await seedReservation(port.id); await seedTenancy(port.id);
await seedReservation(port.id); await seedTenancy(port.id);
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const res = await listHandler( const res = await listHandler(
makeMockRequest('GET', 'http://localhost/api/v1/berth-reservations?page=1&limit=2'), makeMockRequest('GET', 'http://localhost/api/v1/tenancies?page=1&limit=2'),
ctx, ctx,
); );
expect(res.status).toBe(200); expect(res.status).toBe(200);

View File

@@ -4,14 +4,14 @@ import { eq } from 'drizzle-orm';
import { import {
createHandler as createReservationHandler, createHandler as createReservationHandler,
listHandler as listReservationsHandler, listHandler as listReservationsHandler,
} from '@/app/api/v1/berths/[id]/reservations/handlers'; } from '@/app/api/v1/berths/[id]/tenancies/handlers';
import { import {
getHandler as getReservationHandler, getHandler as getReservationHandler,
patchHandler as patchReservationHandler, patchHandler as patchReservationHandler,
deleteHandler as deleteReservationHandler, deleteHandler as deleteReservationHandler,
} from '@/app/api/v1/berth-reservations/[id]/handlers'; } from '@/app/api/v1/tenancies/[id]/handlers';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { makeMockCtx, makeMockRequest } from '../../helpers/route-tester'; import { makeMockCtx, makeMockRequest } from '../../helpers/route-tester';
import { import {
makeBerth, makeBerth,
@@ -22,9 +22,9 @@ import {
makeYacht, makeYacht,
} from '../../helpers/factories'; } from '../../helpers/factories';
// ─── POST /api/v1/berths/[id]/reservations ─────────────────────────────────── // ─── POST /api/v1/berths/[id]/tenancies ───────────────────────────────────
describe('POST /api/v1/berths/[id]/reservations', () => { describe('POST /api/v1/berths/[id]/tenancies', () => {
it('creates pending reservation (201)', async () => { it('creates pending reservation (201)', async () => {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
@@ -36,7 +36,7 @@ describe('POST /api/v1/berths/[id]/reservations', () => {
}); });
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, { const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: { body: {
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
@@ -64,7 +64,7 @@ describe('POST /api/v1/berths/[id]/reservations', () => {
}); });
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, { const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: { body: {
clientId: otherClient.id, clientId: otherClient.id,
yachtId: yacht.id, yachtId: yacht.id,
@@ -88,17 +88,13 @@ describe('POST /api/v1/berths/[id]/reservations', () => {
// Caller is scoped to portB but the URL berth lives in portA. // Caller is scoped to portB but the URL berth lives in portA.
const ctxB = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() }); const ctxB = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const req = makeMockRequest( const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berthA.id}/tenancies`, {
'POST', body: {
`http://localhost/api/v1/berths/${berthA.id}/reservations`, clientId: client.id,
{ yachtId: yacht.id,
body: { startDate: new Date().toISOString(),
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
}, },
); });
const res = await createReservationHandler(req, ctxB, { id: berthA.id }); const res = await createReservationHandler(req, ctxB, { id: berthA.id });
expect(res.status).toBe(404); expect(res.status).toBe(404);
}); });
@@ -115,18 +111,14 @@ describe('POST /api/v1/berths/[id]/reservations', () => {
}); });
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const req = makeMockRequest( const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${urlBerth.id}/tenancies`, {
'POST', body: {
`http://localhost/api/v1/berths/${urlBerth.id}/reservations`, berthId: bodyBerth.id,
{ clientId: client.id,
body: { yachtId: yacht.id,
berthId: bodyBerth.id, startDate: new Date().toISOString(),
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
}, },
); });
const res = await createReservationHandler(req, ctx, { id: urlBerth.id }); const res = await createReservationHandler(req, ctx, { id: urlBerth.id });
expect(res.status).toBe(201); expect(res.status).toBe(201);
const body = (await res.json()) as any; const body = (await res.json()) as any;
@@ -135,9 +127,9 @@ describe('POST /api/v1/berths/[id]/reservations', () => {
}); });
}); });
// ─── GET /api/v1/berths/[id]/reservations ──────────────────────────────────── // ─── GET /api/v1/berths/[id]/tenancies ────────────────────────────────────
describe('GET /api/v1/berths/[id]/reservations', () => { describe('GET /api/v1/berths/[id]/tenancies', () => {
it('returns reservations filtered by that berth', async () => { it('returns reservations filtered by that berth', async () => {
const port = await makePort(); const port = await makePort();
const berthA = await makeBerth({ portId: port.id }); const berthA = await makeBerth({ portId: port.id });
@@ -152,7 +144,7 @@ describe('GET /api/v1/berths/[id]/reservations', () => {
// Create a reservation for berthA. // Create a reservation for berthA.
await createReservationHandler( await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berthA.id}/reservations`, { makeMockRequest('POST', `http://localhost/api/v1/berths/${berthA.id}/tenancies`, {
body: { body: {
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
@@ -165,7 +157,7 @@ describe('GET /api/v1/berths/[id]/reservations', () => {
// Create a reservation for berthB. // Create a reservation for berthB.
await createReservationHandler( await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berthB.id}/reservations`, { makeMockRequest('POST', `http://localhost/api/v1/berths/${berthB.id}/tenancies`, {
body: { body: {
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
@@ -177,7 +169,7 @@ describe('GET /api/v1/berths/[id]/reservations', () => {
); );
const res = await listReservationsHandler( const res = await listReservationsHandler(
makeMockRequest('GET', `http://localhost/api/v1/berths/${berthA.id}/reservations`), makeMockRequest('GET', `http://localhost/api/v1/berths/${berthA.id}/tenancies`),
ctx, ctx,
{ id: berthA.id }, { id: berthA.id },
); );
@@ -188,9 +180,9 @@ describe('GET /api/v1/berths/[id]/reservations', () => {
}); });
}); });
// ─── GET /api/v1/berth-reservations/[id] ───────────────────────────────────── // ─── GET /api/v1/tenancies/[id] ─────────────────────────────────────
describe('GET /api/v1/berth-reservations/[id]', () => { describe('GET /api/v1/tenancies/[id]', () => {
it('returns the reservation', async () => { it('returns the reservation', async () => {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
@@ -203,7 +195,7 @@ describe('GET /api/v1/berth-reservations/[id]', () => {
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const createRes = await createReservationHandler( const createRes = await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, { makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: { body: {
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
@@ -216,7 +208,7 @@ describe('GET /api/v1/berth-reservations/[id]', () => {
const reservation = ((await createRes.json()) as any).data; const reservation = ((await createRes.json()) as any).data;
const res = await getReservationHandler( const res = await getReservationHandler(
makeMockRequest('GET', `http://localhost/api/v1/berth-reservations/${reservation.id}`), makeMockRequest('GET', `http://localhost/api/v1/tenancies/${reservation.id}`),
ctx, ctx,
{ id: reservation.id }, { id: reservation.id },
); );
@@ -238,7 +230,7 @@ describe('GET /api/v1/berth-reservations/[id]', () => {
const ctxA = makeMockCtx({ portId: portA.id, permissions: makeFullPermissions() }); const ctxA = makeMockCtx({ portId: portA.id, permissions: makeFullPermissions() });
const createRes = await createReservationHandler( const createRes = await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, { makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: { body: {
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
@@ -252,7 +244,7 @@ describe('GET /api/v1/berth-reservations/[id]', () => {
const ctxB = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() }); const ctxB = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const res = await getReservationHandler( const res = await getReservationHandler(
makeMockRequest('GET', `http://localhost/api/v1/berth-reservations/${reservation.id}`), makeMockRequest('GET', `http://localhost/api/v1/tenancies/${reservation.id}`),
ctxB, ctxB,
{ id: reservation.id }, { id: reservation.id },
); );
@@ -260,9 +252,9 @@ describe('GET /api/v1/berth-reservations/[id]', () => {
}); });
}); });
// ─── PATCH /api/v1/berth-reservations/[id] ─────────────────────────────────── // ─── PATCH /api/v1/tenancies/[id] ───────────────────────────────────
describe('PATCH /api/v1/berth-reservations/[id]', () => { describe('PATCH /api/v1/tenancies/[id]', () => {
async function seedReservation() { async function seedReservation() {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
@@ -275,7 +267,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const createRes = await createReservationHandler( const createRes = await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, { makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: { body: {
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
@@ -292,7 +284,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
it('activate: pending → active (200)', async () => { it('activate: pending → active (200)', async () => {
const { ctx, reservation } = await seedReservation(); const { ctx, reservation } = await seedReservation();
const res = await patchReservationHandler( const res = await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' }, body: { action: 'activate' },
}), }),
ctx, ctx,
@@ -308,7 +300,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// First activate. // First activate.
await patchReservationHandler( await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' }, body: { action: 'activate' },
}), }),
ctx, ctx,
@@ -318,7 +310,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// Then end. // Then end.
const endDate = new Date('2027-01-01T00:00:00.000Z'); const endDate = new Date('2027-01-01T00:00:00.000Z');
const res = await patchReservationHandler( const res = await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { body: {
action: 'end', action: 'end',
endDate: endDate.toISOString(), endDate: endDate.toISOString(),
@@ -337,7 +329,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
it('cancel: pending → cancelled (200)', async () => { it('cancel: pending → cancelled (200)', async () => {
const { ctx, reservation } = await seedReservation(); const { ctx, reservation } = await seedReservation();
const res = await patchReservationHandler( const res = await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'cancel', reason: 'client changed mind' }, body: { action: 'cancel', reason: 'client changed mind' },
}), }),
ctx, ctx,
@@ -353,7 +345,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// pending → active. // pending → active.
await patchReservationHandler( await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' }, body: { action: 'activate' },
}), }),
ctx, ctx,
@@ -361,7 +353,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
); );
// active → ended. // active → ended.
await patchReservationHandler( await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { body: {
action: 'end', action: 'end',
endDate: new Date().toISOString(), endDate: new Date().toISOString(),
@@ -373,7 +365,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// ended → activate should fail. // ended → activate should fail.
const res = await patchReservationHandler( const res = await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' }, body: { action: 'activate' },
}), }),
ctx, ctx,
@@ -385,7 +377,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
it('returns 400 on invalid body shape (action missing)', async () => { it('returns 400 on invalid body shape (action missing)', async () => {
const { ctx, reservation } = await seedReservation(); const { ctx, reservation } = await seedReservation();
const res = await patchReservationHandler( const res = await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { notes: 'noop' }, body: { notes: 'noop' },
}), }),
ctx, ctx,
@@ -394,18 +386,18 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
expect(res.status).toBe(400); expect(res.status).toBe(400);
}); });
it('returns 403 when caller lacks reservations.activate for activate action', async () => { it('returns 403 when caller lacks tenancies.manage for activate action', async () => {
const { port, reservation } = await seedReservation(); const { port, reservation } = await seedReservation();
// Viewer-like permissions: no activate. // Viewer-like permissions: no manage.
const ctx = makeMockCtx({ const ctx = makeMockCtx({
portId: port.id, portId: port.id,
permissions: { permissions: {
...makeSalesAgentPermissions(), ...makeSalesAgentPermissions(),
reservations: { view: true, create: true, activate: false, cancel: true }, tenancies: { view: true, manage: false, cancel: true },
}, },
}); });
const res = await patchReservationHandler( const res = await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' }, body: { action: 'activate' },
}), }),
ctx, ctx,
@@ -414,15 +406,15 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
expect(res.status).toBe(403); expect(res.status).toBe(403);
}); });
it('returns 403 when caller lacks reservations.cancel for cancel action', async () => { it('returns 403 when caller lacks tenancies.cancel for cancel action', async () => {
const { port, reservation } = await seedReservation(); const { port, reservation } = await seedReservation();
// Sales agent - has activate but NOT cancel. // Sales agent - has manage but NOT cancel.
const ctx = makeMockCtx({ const ctx = makeMockCtx({
portId: port.id, portId: port.id,
permissions: makeSalesAgentPermissions(), permissions: makeSalesAgentPermissions(),
}); });
const res = await patchReservationHandler( const res = await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'cancel', reason: 'test' }, body: { action: 'cancel', reason: 'test' },
}), }),
ctx, ctx,
@@ -432,7 +424,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// But activate succeeds with the same permissions set. // But activate succeeds with the same permissions set.
const activateRes = await patchReservationHandler( const activateRes = await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, { makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' }, body: { action: 'activate' },
}), }),
ctx, ctx,
@@ -442,9 +434,9 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
}); });
}); });
// ─── DELETE /api/v1/berth-reservations/[id] ────────────────────────────────── // ─── DELETE /api/v1/tenancies/[id] ──────────────────────────────────
describe('DELETE /api/v1/berth-reservations/[id]', () => { describe('DELETE /api/v1/tenancies/[id]', () => {
it('cancels the reservation (204)', async () => { it('cancels the reservation (204)', async () => {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
@@ -457,7 +449,7 @@ describe('DELETE /api/v1/berth-reservations/[id]', () => {
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() }); const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const createRes = await createReservationHandler( const createRes = await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, { makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: { body: {
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
@@ -470,7 +462,7 @@ describe('DELETE /api/v1/berth-reservations/[id]', () => {
const reservation = ((await createRes.json()) as any).data; const reservation = ((await createRes.json()) as any).data;
const delRes = await deleteReservationHandler( const delRes = await deleteReservationHandler(
makeMockRequest('DELETE', `http://localhost/api/v1/berth-reservations/${reservation.id}`), makeMockRequest('DELETE', `http://localhost/api/v1/tenancies/${reservation.id}`),
ctx, ctx,
{ id: reservation.id }, { id: reservation.id },
); );
@@ -478,8 +470,8 @@ describe('DELETE /api/v1/berth-reservations/[id]', () => {
const [row] = await db const [row] = await db
.select() .select()
.from(berthReservations) .from(berthTenancies)
.where(eq(berthReservations.id, reservation.id)); .where(eq(berthTenancies.id, reservation.id));
expect(row?.status).toBe('cancelled'); expect(row?.status).toBe('cancelled');
}); });
}); });

View File

@@ -6,7 +6,7 @@ import {
makeBerth, makeBerth,
makeYacht, makeYacht,
makeMembership, makeMembership,
makeReservation, makeTenancy,
makeOwnershipTransfer, makeOwnershipTransfer,
} from '../helpers/factories'; } from '../helpers/factories';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
@@ -23,7 +23,7 @@ describe('factory helpers smoke', () => {
expect(m.endDate).toBeNull(); expect(m.endDate).toBeNull();
}); });
it('makeReservation inserts a row in any status', async () => { it('makeTenancy inserts a row in any status', async () => {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
const client = await makeClient({ portId: port.id }); const client = await makeClient({ portId: port.id });
@@ -32,7 +32,7 @@ describe('factory helpers smoke', () => {
ownerType: 'client', ownerType: 'client',
ownerId: client.id, ownerId: client.id,
}); });
const r = await makeReservation({ const r = await makeTenancy({
berthId: berth.id, berthId: berth.id,
portId: port.id, portId: port.id,
clientId: client.id, clientId: client.id,

View File

@@ -252,9 +252,9 @@ describe('deepMerge - permission override merging', () => {
}); });
}); });
// ─── new resources (yachts, companies, memberships, reservations) ──────────── // ─── new resources (yachts, companies, memberships, tenancies) ──────────────
describe('new resources (yachts, companies, memberships, reservations)', () => { describe('new resources (yachts, companies, memberships, tenancies)', () => {
it('super_admin bypasses all new resource permissions', async () => { it('super_admin bypasses all new resource permissions', async () => {
const ctx = makeCtx({ isSuperAdmin: true, permissions: null }); const ctx = makeCtx({ isSuperAdmin: true, permissions: null });
const handler = vi.fn(okHandler()); const handler = vi.fn(okHandler());
@@ -295,15 +295,15 @@ describe('new resources (yachts, companies, memberships, reservations)', () => {
expect(manageRes.status).toBe(200); expect(manageRes.status).toBe(200);
}); });
it('sales_agent can reservations.activate but not reservations.cancel', async () => { it('sales_agent can tenancies.manage but not tenancies.cancel', async () => {
const ctx = makeCtx({ permissions: makeSalesAgentPermissions() }); const ctx = makeCtx({ permissions: makeSalesAgentPermissions() });
const activateRes = await withPermission('reservations', 'activate', vi.fn(okHandler()))( const manageRes = await withPermission('tenancies', 'manage', vi.fn(okHandler()))(
makeRequest(), makeRequest(),
ctx, ctx,
{}, {},
); );
expect(activateRes.status).toBe(200); expect(manageRes.status).toBe(200);
const cancelRes = await withPermission('reservations', 'cancel', vi.fn(okHandler()))( const cancelRes = await withPermission('tenancies', 'cancel', vi.fn(okHandler()))(
makeRequest(), makeRequest(),
ctx, ctx,
{}, {},

View File

@@ -12,7 +12,7 @@ import { describe, it, expect, beforeAll } from 'vitest';
import { db } from '@/lib/db'; import { db } from '@/lib/db';
import { yachtOwnershipHistory } from '@/lib/db/schema/yachts'; import { yachtOwnershipHistory } from '@/lib/db/schema/yachts';
import { berthReservations } from '@/lib/db/schema/reservations'; import { berthTenancies } from '@/lib/db/schema/tenancies';
import { companies } from '@/lib/db/schema/companies'; import { companies } from '@/lib/db/schema/companies';
import { makeBerth, makeClient, makeCompany, makePort, makeYacht } from '../helpers/factories'; import { makeBerth, makeClient, makeCompany, makePort, makeYacht } from '../helpers/factories';
@@ -86,7 +86,7 @@ describe('schema constraints', () => {
}); });
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
await db.insert(berthReservations).values({ await db.insert(berthTenancies).values({
berthId: berth.id, berthId: berth.id,
portId: port.id, portId: port.id,
clientId: clientA.id, clientId: clientA.id,
@@ -97,7 +97,7 @@ describe('schema constraints', () => {
}); });
await expect( await expect(
db.insert(berthReservations).values({ db.insert(berthTenancies).values({
berthId: berth.id, berthId: berth.id,
portId: port.id, portId: port.id,
clientId: clientB.id, clientId: clientB.id,
@@ -126,7 +126,7 @@ describe('schema constraints', () => {
// Two ended reservations on same berth - both should succeed // Two ended reservations on same berth - both should succeed
// (partial index only constrains status='active'). // (partial index only constrains status='active').
await expect( await expect(
db.insert(berthReservations).values([ db.insert(berthTenancies).values([
{ {
berthId: berth.id, berthId: berth.id,
portId: port.id, portId: port.id,

View File

@@ -1,9 +1,9 @@
import { describe, it, expect } from 'vitest'; import { describe, it, expect } from 'vitest';
import { createPending, activate, endReservation } from '@/lib/services/berth-reservations.service'; import { createPending, activate, endTenancy } from '@/lib/services/berth-tenancies.service';
import { makeBerth, makeClient, makePort, makeYacht, makeAuditMeta } from '../helpers/factories'; import { makeBerth, makeClient, makePort, makeYacht, makeAuditMeta } from '../helpers/factories';
import { ConflictError } from '@/lib/errors'; import { ConflictError } from '@/lib/errors';
describe('reservation exclusivity', () => { describe('tenancy exclusivity', () => {
it('two concurrent activates on same berth: one succeeds, one throws ConflictError', async () => { it('two concurrent activates on same berth: one succeeds, one throws ConflictError', async () => {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
@@ -52,7 +52,7 @@ describe('reservation exclusivity', () => {
expect((failures[0] as PromiseRejectedResult).reason).toBeInstanceOf(ConflictError); expect((failures[0] as PromiseRejectedResult).reason).toBeInstanceOf(ConflictError);
}); });
it('activating a second reservation after first is ended succeeds', async () => { it('activating a second tenancy after first is ended succeeds', async () => {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
const clientA = await makeClient({ portId: port.id }); const clientA = await makeClient({ portId: port.id });
@@ -74,12 +74,7 @@ describe('reservation exclusivity', () => {
makeAuditMeta({ portId: port.id }), makeAuditMeta({ portId: port.id }),
); );
await activate(resA.id, port.id, {}, makeAuditMeta({ portId: port.id })); await activate(resA.id, port.id, {}, makeAuditMeta({ portId: port.id }));
await endReservation( await endTenancy(resA.id, port.id, { endDate: new Date() }, makeAuditMeta({ portId: port.id }));
resA.id,
port.id,
{ endDate: new Date() },
makeAuditMeta({ portId: port.id }),
);
const resB = await createPending( const resB = await createPending(
port.id, port.id,

View File

@@ -3,10 +3,10 @@ import { eq } from 'drizzle-orm';
import { import {
createPending, createPending,
activate, activate,
endReservation, endTenancy,
cancel, cancel,
listReservations, listTenancies,
} from '@/lib/services/berth-reservations.service'; } from '@/lib/services/berth-tenancies.service';
import { import {
makePort, makePort,
makeClient, makeClient,
@@ -20,7 +20,7 @@ import { companyMemberships } from '@/lib/db/schema/companies';
// ─── createPending ─────────────────────────────────────────────────────────── // ─── createPending ───────────────────────────────────────────────────────────
describe('berth-reservations.service - createPending', () => { describe('berth-tenancies.service - createPending', () => {
it('creates pending reservation for client-owned yacht', async () => { it('creates pending reservation for client-owned yacht', async () => {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
@@ -203,7 +203,7 @@ describe('berth-reservations.service - createPending', () => {
// ─── Lifecycle transitions ─────────────────────────────────────────────────── // ─── Lifecycle transitions ───────────────────────────────────────────────────
describe('berth-reservations.service - lifecycle transitions', () => { describe('berth-tenancies.service - lifecycle transitions', () => {
async function setup() { async function setup() {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
@@ -238,10 +238,10 @@ describe('berth-reservations.service - lifecycle transitions', () => {
expect(activated.status).toBe('active'); expect(activated.status).toBe('active');
}); });
it('active → ended (endReservation)', async () => { it('active → ended (endTenancy)', async () => {
const { port, reservation } = await setup(); const { port, reservation } = await setup();
await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id })); await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
const ended = await endReservation( const ended = await endTenancy(
reservation.id, reservation.id,
port.id, port.id,
{ endDate: new Date() }, { endDate: new Date() },
@@ -277,7 +277,7 @@ describe('berth-reservations.service - lifecycle transitions', () => {
it('rejects ended → active (invalid transition)', async () => { it('rejects ended → active (invalid transition)', async () => {
const { port, reservation } = await setup(); const { port, reservation } = await setup();
await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id })); await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
await endReservation( await endTenancy(
reservation.id, reservation.id,
port.id, port.id,
{ endDate: new Date() }, { endDate: new Date() },
@@ -304,7 +304,7 @@ describe('berth-reservations.service - lifecycle transitions', () => {
it('rejects cancel from ended state', async () => { it('rejects cancel from ended state', async () => {
const { port, reservation } = await setup(); const { port, reservation } = await setup();
await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id })); await activate(reservation.id, port.id, {}, makeAuditMeta({ portId: port.id }));
await endReservation( await endTenancy(
reservation.id, reservation.id,
port.id, port.id,
{ endDate: new Date() }, { endDate: new Date() },
@@ -315,10 +315,10 @@ describe('berth-reservations.service - lifecycle transitions', () => {
).rejects.toThrow(/invalid transition/i); ).rejects.toThrow(/invalid transition/i);
}); });
it('rejects endReservation on a pending reservation', async () => { it('rejects endTenancy on a pending reservation', async () => {
const { port, reservation } = await setup(); const { port, reservation } = await setup();
await expect( await expect(
endReservation( endTenancy(
reservation.id, reservation.id,
port.id, port.id,
{ endDate: new Date() }, { endDate: new Date() },
@@ -328,9 +328,9 @@ describe('berth-reservations.service - lifecycle transitions', () => {
}); });
}); });
// ─── listReservations ──────────────────────────────────────────────────────── // ─── listTenancies ────────────────────────────────────────────────────────
describe('berth-reservations.service - listReservations', () => { describe('berth-tenancies.service - listTenancies', () => {
async function makeReservation(portId: string, opts?: { berthId?: string }) { async function makeReservation(portId: string, opts?: { berthId?: string }) {
const berth = opts?.berthId ? { id: opts.berthId } : await makeBerth({ portId }); const berth = opts?.berthId ? { id: opts.berthId } : await makeBerth({ portId });
const client = await makeClient({ portId }); const client = await makeClient({ portId });
@@ -354,7 +354,7 @@ describe('berth-reservations.service - listReservations', () => {
const resA = await makeReservation(portA.id); const resA = await makeReservation(portA.id);
await makeReservation(portB.id); await makeReservation(portB.id);
const result = await listReservations(portA.id, { const result = await listTenancies(portA.id, {
page: 1, page: 1,
limit: 50, limit: 50,
order: 'desc', order: 'desc',
@@ -371,7 +371,7 @@ describe('berth-reservations.service - listReservations', () => {
const resActive = await makeReservation(port.id); const resActive = await makeReservation(port.id);
await activate(resActive.id, port.id, {}, makeAuditMeta({ portId: port.id })); await activate(resActive.id, port.id, {}, makeAuditMeta({ portId: port.id }));
const activeList = await listReservations(port.id, { const activeList = await listTenancies(port.id, {
page: 1, page: 1,
limit: 50, limit: 50,
order: 'desc', order: 'desc',
@@ -403,7 +403,7 @@ describe('berth-reservations.service - listReservations', () => {
makeAuditMeta({ portId: port.id }), makeAuditMeta({ portId: port.id }),
); );
const result = await listReservations(port.id, { const result = await listTenancies(port.id, {
page: 1, page: 1,
limit: 50, limit: 50,
order: 'desc', order: 'desc',
@@ -418,7 +418,7 @@ describe('berth-reservations.service - listReservations', () => {
// ─── Self-check: DB state is as expected after cancel ──────────────────────── // ─── Self-check: DB state is as expected after cancel ────────────────────────
describe('berth-reservations.service - DB state', () => { describe('berth-tenancies.service - DB state', () => {
it('cancel persists status=cancelled in the database', async () => { it('cancel persists status=cancelled in the database', async () => {
const port = await makePort(); const port = await makePort();
const berth = await makeBerth({ portId: port.id }); const berth = await makeBerth({ portId: port.id });
@@ -431,8 +431,8 @@ describe('berth-reservations.service - DB state', () => {
); );
await cancel(res.id, port.id, {}, makeAuditMeta({ portId: port.id })); await cancel(res.id, port.id, {}, makeAuditMeta({ portId: port.id }));
const { berthReservations } = await import('@/lib/db/schema'); const { berthTenancies } = await import('@/lib/db/schema');
const [row] = await db.select().from(berthReservations).where(eq(berthReservations.id, res.id)); const [row] = await db.select().from(berthTenancies).where(eq(berthTenancies.id, res.id));
expect(row!.status).toBe('cancelled'); expect(row!.status).toBe('cancelled');
}); });
}); });

View File

@@ -238,8 +238,8 @@ describe('portal.service - getPortalUserMemberships', () => {
}); });
}); });
describe('portal.service - getPortalUserReservations', () => { describe('portal.service - getPortalUserTenancies', () => {
let getPortalUserReservations: (clientId: string, portId: string) => Promise<Array<any>>; let getPortalUserTenancies: (clientId: string, portId: string) => Promise<Array<any>>;
let makeClient: typeof import('../../helpers/factories').makeClient; let makeClient: typeof import('../../helpers/factories').makeClient;
@@ -249,20 +249,20 @@ describe('portal.service - getPortalUserReservations', () => {
let makeBerth: typeof import('../../helpers/factories').makeBerth; let makeBerth: typeof import('../../helpers/factories').makeBerth;
let makeReservation: typeof import('../../helpers/factories').makeReservation; let makeTenancy: typeof import('../../helpers/factories').makeTenancy;
beforeAll(async () => { beforeAll(async () => {
const portalMod = await import('@/lib/services/portal.service'); const portalMod = await import('@/lib/services/portal.service');
getPortalUserReservations = portalMod.getPortalUserReservations; getPortalUserTenancies = portalMod.getPortalUserTenancies;
const factoriesMod = await import('../../helpers/factories'); const factoriesMod = await import('../../helpers/factories');
makeClient = factoriesMod.makeClient; makeClient = factoriesMod.makeClient;
makePort = factoriesMod.makePort; makePort = factoriesMod.makePort;
makeYacht = factoriesMod.makeYacht; makeYacht = factoriesMod.makeYacht;
makeBerth = factoriesMod.makeBerth; makeBerth = factoriesMod.makeBerth;
makeReservation = factoriesMod.makeReservation; makeTenancy = factoriesMod.makeTenancy;
}); });
it('returns active + pending reservations', async () => { it('returns active + pending tenancies', async () => {
const port = await makePort(); const port = await makePort();
const client = await makeClient({ portId: port.id }); const client = await makeClient({ portId: port.id });
const yacht = await makeYacht({ const yacht = await makeYacht({
@@ -272,14 +272,14 @@ describe('portal.service - getPortalUserReservations', () => {
}); });
const berth1 = await makeBerth({ portId: port.id }); const berth1 = await makeBerth({ portId: port.id });
const berth2 = await makeBerth({ portId: port.id }); const berth2 = await makeBerth({ portId: port.id });
await makeReservation({ await makeTenancy({
berthId: berth1.id, berthId: berth1.id,
portId: port.id, portId: port.id,
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
status: 'active', status: 'active',
}); });
await makeReservation({ await makeTenancy({
berthId: berth2.id, berthId: berth2.id,
portId: port.id, portId: port.id,
clientId: client.id, clientId: client.id,
@@ -287,7 +287,7 @@ describe('portal.service - getPortalUserReservations', () => {
status: 'pending', status: 'pending',
}); });
const result = await getPortalUserReservations(client.id, port.id); const result = await getPortalUserTenancies(client.id, port.id);
expect(result).toHaveLength(2); expect(result).toHaveLength(2);
const statuses = result.map((r) => r.status).sort(); const statuses = result.map((r) => r.status).sort();
expect(statuses).toEqual(['active', 'pending']); expect(statuses).toEqual(['active', 'pending']);
@@ -303,14 +303,14 @@ describe('portal.service - getPortalUserReservations', () => {
}); });
const berth1 = await makeBerth({ portId: port.id }); const berth1 = await makeBerth({ portId: port.id });
const berth2 = await makeBerth({ portId: port.id }); const berth2 = await makeBerth({ portId: port.id });
await makeReservation({ await makeTenancy({
berthId: berth1.id, berthId: berth1.id,
portId: port.id, portId: port.id,
clientId: client.id, clientId: client.id,
yachtId: yacht.id, yachtId: yacht.id,
status: 'ended', status: 'ended',
}); });
await makeReservation({ await makeTenancy({
berthId: berth2.id, berthId: berth2.id,
portId: port.id, portId: port.id,
clientId: client.id, clientId: client.id,
@@ -318,7 +318,7 @@ describe('portal.service - getPortalUserReservations', () => {
status: 'cancelled', status: 'cancelled',
}); });
const result = await getPortalUserReservations(client.id, port.id); const result = await getPortalUserTenancies(client.id, port.id);
expect(result).toHaveLength(0); expect(result).toHaveLength(0);
}); });
@@ -332,7 +332,7 @@ describe('portal.service - getPortalUserReservations', () => {
ownerId: client.id, ownerId: client.id,
}); });
const berthB = await makeBerth({ portId: portB.id }); const berthB = await makeBerth({ portId: portB.id });
await makeReservation({ await makeTenancy({
berthId: berthB.id, berthId: berthB.id,
portId: portB.id, portId: portB.id,
clientId: client.id, clientId: client.id,
@@ -340,7 +340,7 @@ describe('portal.service - getPortalUserReservations', () => {
status: 'active', status: 'active',
}); });
const resultA = await getPortalUserReservations(client.id, portA.id); const resultA = await getPortalUserTenancies(client.id, portA.id);
expect(resultA).toHaveLength(0); expect(resultA).toHaveLength(0);
}); });
@@ -357,7 +357,7 @@ describe('portal.service - getPortalUserReservations', () => {
portId: port.id, portId: port.id,
overrides: { mooringNumber: 'M-42' }, overrides: { mooringNumber: 'M-42' },
}); });
await makeReservation({ await makeTenancy({
berthId: berth.id, berthId: berth.id,
portId: port.id, portId: port.id,
clientId: client.id, clientId: client.id,
@@ -365,7 +365,7 @@ describe('portal.service - getPortalUserReservations', () => {
status: 'active', status: 'active',
}); });
const result = await getPortalUserReservations(client.id, port.id); const result = await getPortalUserTenancies(client.id, port.id);
expect(result).toHaveLength(1); expect(result).toHaveLength(1);
expect(result[0]!.yachtName).toBe('Test Vessel'); expect(result[0]!.yachtName).toBe('Test Vessel');
expect(result[0]!.berthMooringNumber).toBe('M-42'); expect(result[0]!.berthMooringNumber).toBe('M-42');

View File

@@ -8,7 +8,7 @@ import { createFieldSchema, updateFieldSchema } from '@/lib/validators/custom-fi
import { createYachtSchema, transferOwnershipSchema } from '@/lib/validators/yachts'; import { createYachtSchema, transferOwnershipSchema } from '@/lib/validators/yachts';
import { createCompanySchema } from '@/lib/validators/companies'; import { createCompanySchema } from '@/lib/validators/companies';
import { addMembershipSchema } from '@/lib/validators/company-memberships'; import { addMembershipSchema } from '@/lib/validators/company-memberships';
import { createPendingSchema } from '@/lib/validators/reservations'; import { createPendingSchema } from '@/lib/validators/tenancies';
// ─── Client schemas ─────────────────────────────────────────────────────────── // ─── Client schemas ───────────────────────────────────────────────────────────

View File

@@ -103,13 +103,13 @@ describe('new resource events (yachts, companies, memberships, reservations)', (
); );
}); });
it('includes all berth reservation lifecycle events', () => { it('includes all berth tenancy lifecycle events', () => {
const events = new Set<string>(WEBHOOK_EVENTS); const events = new Set<string>(WEBHOOK_EVENTS);
[ [
'berth_reservation.created', 'berth_tenancy.created',
'berth_reservation.activated', 'berth_tenancy.activated',
'berth_reservation.ended', 'berth_tenancy.ended',
'berth_reservation.cancelled', 'berth_tenancy.cancelled',
].forEach((e) => { ].forEach((e) => {
expect(events.has(e)).toBe(true); expect(events.has(e)).toBe(true);
}); });
@@ -121,9 +121,7 @@ describe('new resource events (yachts, companies, memberships, reservations)', (
); );
}); });
it('berth_reservation:activated maps to berth_reservation.activated', () => { it('berth_tenancy:activated maps to berth_tenancy.activated', () => {
expect(INTERNAL_TO_WEBHOOK_MAP['berth_reservation:activated']).toBe( expect(INTERNAL_TO_WEBHOOK_MAP['berth_tenancy:activated']).toBe('berth_tenancy.activated');
'berth_reservation.activated',
);
}); });
}); });