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
available in the underlying dashboard data when needed. */}
<PortalCard
title="My Active Reservations"
value={dashboard.counts.activeReservations}
description="Current and pending berth reservations"
title="My Active Tenancies"
value={dashboard.counts.activeTenancies}
description="Current and pending berth tenancies"
icon={CalendarCheck}
href="/portal/my-reservations"
href="/portal/my-tenancies"
/>
</div>

View File

@@ -3,10 +3,10 @@ import { CalendarCheck } from 'lucide-react';
import type { Metadata } from 'next';
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';
export const metadata: Metadata = { title: 'My Reservations' };
export const metadata: Metadata = { title: 'My Tenancies' };
const STATUS_COLORS: Record<string, 'default' | 'secondary' | 'destructive' | 'outline'> = {
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();
if (!session) redirect('/portal/login');
const reservations = await getPortalUserReservations(session.clientId, session.portId);
const tenancies = await getPortalUserTenancies(session.clientId, session.portId);
return (
<div className="space-y-6">
<div>
<h1 className="text-2xl font-semibold text-gray-900">My Reservations</h1>
<p className="text-sm text-gray-500 mt-1">Your current and pending berth reservations</p>
<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 tenancies</p>
</div>
{reservations.length === 0 ? (
{tenancies.length === 0 ? (
<div className="bg-white rounded-lg border p-12 text-center">
<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">
Contact your port representative to discuss reservations.
Contact your port representative to discuss tenancies.
</p>
</div>
) : (
<div className="space-y-3">
{reservations.map((r) => (
{tenancies.map((r) => (
<div key={r.id} className="bg-white rounded-lg border p-5">
<div className="flex items-start justify-between gap-4">
<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 { berths } from '@/lib/db/schema/berths';
import { NotFoundError, errorResponse } from '@/lib/errors';
import { createPending, listReservations } from '@/lib/services/berth-reservations.service';
import { createPendingSchema, listReservationsSchema } from '@/lib/validators/reservations';
import { createPending, listTenancies } from '@/lib/services/berth-tenancies.service';
import { createPendingSchema, listTenanciesSchema } from '@/lib/validators/tenancies';
// URL berthId is authoritative; make body berthId optional (ignored anyway).
const createPendingBodySchema = createPendingSchema
@@ -24,8 +24,8 @@ async function assertBerthInPort(berthId: string, portId: string): Promise<void>
export const listHandler: RouteHandler = async (req, ctx, params) => {
try {
await assertBerthInPort(params.id!, ctx.portId);
const query = parseQuery(req, listReservationsSchema);
const result = await listReservations(ctx.portId, { ...query, berthId: params.id! });
const query = parseQuery(req, listTenanciesSchema);
const result = await listTenancies(ctx.portId, { ...query, berthId: params.id! });
const { page, limit } = query;
const totalPages = Math.ceil(result.total / limit);
return NextResponse.json({
@@ -48,7 +48,7 @@ export const createHandler: RouteHandler = async (req, ctx, params) => {
try {
await assertBerthInPort(params.id!, ctx.portId);
const body = await parseBody(req, createPendingBodySchema);
const reservation = await createPending(
const tenancy = await createPending(
ctx.portId,
{ ...body, berthId: params.id! },
{
@@ -58,7 +58,7 @@ export const createHandler: RouteHandler = async (req, ctx, params) => {
userAgent: ctx.userAgent,
},
);
return NextResponse.json({ data: reservation }, { status: 201 });
return NextResponse.json({ data: tenancy }, { status: 201 });
} catch (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([]),
reservationDecisions: z
tenancyDecisions: z
.array(
z.object({
reservationId: z.string().min(1),
tenancyId: z.string().min(1),
action: z.enum(['cancel', 'transfer']),
transferToClientId: z.string().min(1).optional(),
}),

View File

@@ -16,7 +16,7 @@ interface PreflightItem {
stakeLevel: 'low' | 'high';
highStakesStage: string | null;
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: {
berths: d.berths.length,
yachts: d.yachts.length,
reservations: d.reservations.length,
tenancies: d.tenancies.length,
signedDocs: d.documents.filter(
(doc) => doc.status === 'completed' || doc.status === 'signed',
).length,
@@ -60,7 +60,7 @@ export const POST = withAuth(
stakeLevel: 'low',
highStakesStage: null,
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,
berthDecisions,
yachtDecisions: dossier.yachts.map((y) => ({ yachtId: y.yachtId, action: 'retain' })),
reservationDecisions: dossier.reservations.map((r) => ({
reservationId: r.reservationId,
tenancyDecisions: dossier.tenancies.map((r) => ({
tenancyId: r.tenancyId,
action: 'cancel',
})),
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 { requirePermission } from '@/lib/auth/permissions';
import { errorResponse } from '@/lib/errors';
import {
activate,
cancel,
endReservation,
getById,
} from '@/lib/services/berth-reservations.service';
import { activate, cancel, endTenancy, getById } from '@/lib/services/berth-tenancies.service';
// ─── PATCH body schema (action-based discriminated union) ────────────────────
@@ -35,8 +30,8 @@ const patchBodySchema = z.discriminatedUnion('action', [
export const getHandler: RouteHandler = async (_req, ctx, params) => {
try {
const reservation = await getById(params.id!, ctx.portId);
return NextResponse.json({ data: reservation });
const tenancy = await getById(params.id!, ctx.portId);
return NextResponse.json({ data: tenancy });
} catch (error) {
return errorResponse(error);
}
@@ -53,7 +48,7 @@ export const patchHandler: RouteHandler = async (req, ctx, params) => {
};
if (body.action === 'activate') {
requirePermission(ctx, 'reservations', 'activate');
requirePermission(ctx, 'tenancies', 'manage');
const result = await activate(
params.id!,
ctx.portId,
@@ -68,8 +63,8 @@ export const patchHandler: RouteHandler = async (req, ctx, params) => {
if (body.action === 'end') {
// `end` is lifecycle progression; same privilege as activate.
requirePermission(ctx, 'reservations', 'activate');
const result = await endReservation(
requirePermission(ctx, 'tenancies', 'manage');
const result = await endTenancy(
params.id!,
ctx.portId,
{ endDate: body.endDate, notes: body.notes },
@@ -79,7 +74,7 @@ export const patchHandler: RouteHandler = async (req, ctx, params) => {
}
// action === 'cancel'
requirePermission(ctx, 'reservations', 'cancel');
requirePermission(ctx, 'tenancies', 'cancel');
const result = await cancel(params.id!, ctx.portId, { reason: body.reason }, meta);
return NextResponse.json({ data: result });
} catch (error) {

View File

@@ -2,9 +2,9 @@ import { withAuth, withPermission } from '@/lib/api/helpers';
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
// on the `action` field in the body. `requirePermission` is called inside the
// handler after the body is parsed.
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 { parseQuery } from '@/lib/api/route-helpers';
import { errorResponse } from '@/lib/errors';
import { listReservations } from '@/lib/services/berth-reservations.service';
import { listReservationsSchema } from '@/lib/validators/reservations';
import { listTenancies } from '@/lib/services/berth-tenancies.service';
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
* the `withAuth(withPermission(...))` wrappers (matches the convention
* used throughout `src/app/api/v1/*`).
*/
export async function listHandler(req: Request, ctx: AuthContext): Promise<NextResponse> {
try {
const query = parseQuery(req as never, listReservationsSchema);
const result = await listReservations(ctx.portId, query);
const query = parseQuery(req as never, listTenanciesSchema);
const result = await listTenancies(ctx.portId, query);
const { page, limit } = query;
const totalPages = Math.ceil(result.total / limit);
return NextResponse.json({

View File

@@ -1,4 +1,4 @@
import { withAuth, withPermission } from '@/lib/api/helpers';
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 },
companies: { view: false, create: false, edit: false, delete: false },
memberships: { view: false, manage: false },
reservations: { view: false, create: false, activate: false, cancel: false },
tenancies: { view: false, manage: false, cancel: false },
admin: {
manage_users: false,
view_audit_log: false,
@@ -122,7 +122,7 @@ const GROUP_LABELS: Record<string, string> = {
yachts: 'Yachts',
companies: 'Companies',
memberships: 'Company Memberships',
reservations: 'Reservations',
tenancies: 'Tenancies',
admin: 'Administration',
residential_clients: 'Residential Clients',
residential_interests: 'Residential Interests',

View File

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

View File

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

View File

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

View File

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

View File

@@ -64,7 +64,7 @@ interface ClientData {
status: string;
};
}>;
activeReservations: Array<{
activeTenancies: Array<{
id: string;
berthId: string;
yachtId: string;
@@ -113,9 +113,9 @@ export function ClientDetail({ clientId, currentUserId }: ClientDetailProps) {
'yacht:ownership_transferred': [['clients', clientId]],
'company_membership:added': [['clients', clientId]],
'company_membership:ended': [['clients', clientId]],
'berth_reservation:activated': [['clients', clientId]],
'berth_reservation:ended': [['clients', clientId]],
'berth_reservation:cancelled': [['clients', clientId]],
'berth_tenancy:activated': [['clients', clientId]],
'berth_tenancy:ended': [['clients', clientId]],
'berth_tenancy:cancelled': [['clients', clientId]],
});
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 { ClientYachtsTab } from '@/components/clients/client-yachts-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 { ContactsEditor } from '@/components/clients/contacts-editor';
import { AddressesEditor, type Address } from '@/components/shared/addresses-editor';
@@ -123,7 +123,7 @@ interface ClientTabsOptions {
status: string;
};
}>;
activeReservations: Array<{
activeTenancies: Array<{
id: string;
berthId: string;
yachtId: string;
@@ -276,12 +276,10 @@ export function getClientTabs({ clientId, currentUserId, client }: ClientTabsOpt
content: <ClientCompaniesTab clientId={clientId} companies={client.companies} />,
},
{
id: 'reservations',
label: 'Reservations',
badge: client.activeReservations.length,
content: (
<ClientReservationsTab clientId={clientId} activeReservations={client.activeReservations} />
),
id: 'tenancies',
label: 'Tenancies',
badge: client.activeTenancies.length,
content: <ClientTenanciesTab clientId={clientId} activeTenancies={client.activeTenancies} />,
},
{
id: 'addresses',

View File

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

View File

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

View File

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

View File

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

View File

@@ -57,7 +57,7 @@ interface DetailDoc {
documentType: string;
documensoId: string | null;
signedFileId: string | null;
reservationId: string | null;
tenancyId: string | null;
interestId: string | null;
clientId: 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
// link.
const linkedRows: Array<{ href: string; label: string; sub: string | null }> = [];
if (doc.reservationId) {
if (doc.tenancyId) {
linkedRows.push({
href: `/${portSlug}/berth-reservations/${doc.reservationId}`,
label: 'Reservation',
href: `/${portSlug}/tenancies/${doc.tenancyId}`,
label: 'Tenancy',
sub: null,
});
}

View File

@@ -75,7 +75,7 @@ interface InterestData {
reminderDays: number | null;
reminderLastFired: string | null;
/** 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. */
dateDocumentDeclined: string | null;
dateReservationCancelled: string | null;

View File

@@ -17,7 +17,7 @@ const navItems = [
{ label: 'Dashboard', href: '/portal/dashboard', icon: LayoutDashboard },
{ label: 'Interests', href: '/portal/interests', icon: Anchor },
{ 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: 'Invoices', href: '/portal/invoices', icon: Receipt },
{ 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 }> {
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',
body: {
clientId: data.clientId!,
@@ -122,9 +122,9 @@ export function BerthReserveDialog({ open, onOpenChange, berthId }: BerthReserve
await createPending(data);
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['berths', berthId, 'reservations'] });
queryClient.invalidateQueries({ queryKey: ['berth-reservations'] });
toast.success('Reservation created');
queryClient.invalidateQueries({ queryKey: ['berths', berthId, 'tenancies'] });
queryClient.invalidateQueries({ queryKey: ['tenancies'] });
toast.success('Tenancy created');
onOpenChange(false);
},
onError: (err: unknown) => {
@@ -139,22 +139,22 @@ export function BerthReserveDialog({ open, onOpenChange, berthId }: BerthReserve
if (err) throw new Error(err);
const pending = await createPending(data);
// Immediately activate
await apiFetch(`/api/v1/berth-reservations/${pending.id}`, {
await apiFetch(`/api/v1/tenancies/${pending.id}`, {
method: 'PATCH',
body: { action: 'activate' },
});
},
onSuccess: () => {
queryClient.invalidateQueries({ queryKey: ['berths', berthId, 'reservations'] });
queryClient.invalidateQueries({ queryKey: ['berth-reservations'] });
toast.success('Reservation created and activated');
queryClient.invalidateQueries({ queryKey: ['berths', berthId, 'tenancies'] });
queryClient.invalidateQueries({ queryKey: ['tenancies'] });
toast.success('Tenancy created and activated');
onOpenChange(false);
},
onError: (err: unknown) => {
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(
'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 {
setFormError(msg);

View File

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

View File

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

View File

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

View File

@@ -9,7 +9,7 @@ import { FieldHistoryProvider, FieldHistoryIcon } from '@/components/shared/fiel
import { InlineTagEditor } from '@/components/shared/inline-tag-editor';
import { NotesList } from '@/components/shared/notes-list';
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 { YachtOwnershipHistory } from '@/components/yachts/yacht-ownership-history';
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 portSlug = routeParams?.portSlug ?? '';
const { data, isLoading } = useQuery<{ data: ReservationRow[] }>({
queryKey: ['berth-reservations', 'by-yacht', yachtId],
queryFn: () => apiFetch(`/api/v1/berth-reservations?yachtId=${yachtId}&limit=50&order=desc`),
const { data, isLoading } = useQuery<{ data: TenancyRow[] }>({
queryKey: ['tenancies', 'by-yacht', yachtId],
queryFn: () => apiFetch(`/api/v1/tenancies?yachtId=${yachtId}&limit=50&order=desc`),
});
if (isLoading) return <p className="text-sm text-muted-foreground">Loading</p>;
return (
<ReservationList
reservations={data?.data ?? []}
<TenancyList
tenancies={data?.data ?? []}
showBerth
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} />,
},
{
id: 'reservations',
label: 'Reservations',
content: <YachtReservationsTab yachtId={yachtId} />,
id: 'tenancies',
label: 'Tenancies',
content: <YachtTenanciesTab yachtId={yachtId} />,
},
{
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 { companies } from './companies';
import { interests } from './interests';
import { berthReservations } from './reservations';
import { berthTenancies } from './tenancies';
export const files = pgTable(
'files',
@@ -90,7 +90,7 @@ export const documents = pgTable(
clientId: text('client_id').references(() => clients.id, { onDelete: 'set null' }),
yachtId: text('yacht_id').references(() => yachts.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',
}),
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_documents_yacht').on(table.yachtId),
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_status_port').on(table.portId, table.status),
// Cover the file FKs Postgres doesn't auto-index. Without these,

View File

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

View File

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

View File

@@ -7,17 +7,17 @@ import { yachts } from './yachts';
import { interests } from './interests';
import { files } from './documents';
export const berthReservations = pgTable(
'berth_reservations',
export const berthTenancies = pgTable(
'berth_tenancies',
{
id: text('id')
.primaryKey()
.$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
// 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
// reservation legitimately outlives the originating deal.
// tenancy legitimately outlives the originating deal.
berthId: text('berth_id')
.notNull()
.references(() => berths.id, { onDelete: 'restrict' }),
@@ -36,7 +36,7 @@ export const berthReservations = pgTable(
endDate: timestamp('end_date', { withTimezone: true, mode: 'date' }),
// M-L01: canonical tenure_type union is
// `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
// own tenure shape. Configurable via the per-port vocabulary at
// /admin/vocabularies (key: berth_tenure_types).
@@ -48,21 +48,17 @@ export const berthReservations = pgTable(
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
},
(table) => [
index('idx_br_berth').on(table.berthId),
index('idx_br_client').on(table.clientId),
index('idx_br_yacht').on(table.yachtId),
index('idx_br_port').on(table.portId),
// Cover the FKs Postgres doesn't auto-index. Without these, deleting
// (or restrict-checking) the parent interest / contract file row
// requires a full scan of berth_reservations. (idx_br_interest is
// 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')
index('idx_bt_berth').on(table.berthId),
index('idx_bt_client').on(table.clientId),
index('idx_bt_yacht').on(table.yachtId),
index('idx_bt_port').on(table.portId),
index('idx_bt_interest').on(table.interestId),
index('idx_bt_contract_file').on(table.contractFileId),
uniqueIndex('idx_bt_active')
.on(table.berthId)
.where(sql`${table.status} = 'active'`),
],
);
export type BerthReservation = typeof berthReservations.$inferSelect;
export type NewBerthReservation = typeof berthReservations.$inferInsert;
export type BerthTenancy = typeof berthTenancies.$inferSelect;
export type NewBerthTenancy = typeof berthTenancies.$inferInsert;

View File

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

View File

@@ -37,7 +37,7 @@ import {
yachts,
yachtOwnershipHistory,
berths,
berthReservations,
berthTenancies,
interests,
interestBerths,
documentTemplates,
@@ -115,7 +115,7 @@ export interface SeedSummary {
companies: number;
yachts: number;
interests: number;
reservations: number;
tenancies: number;
}
// ─── 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 reservationValues: Array<typeof berthReservations.$inferInsert> = [];
const reservationValues: Array<typeof berthTenancies.$inferInsert> = [];
for (const a of activeAssignments) {
reservationValues.push({
@@ -1090,7 +1090,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
notes: 'Cancelled by client before activation.',
});
await tx.insert(berthReservations).values(reservationValues);
await tx.insert(berthTenancies).values(reservationValues);
return {
berths: berthRows.length,
@@ -1098,7 +1098,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
companies: companyRows.length,
yachts: yachtRows.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 },
companies: { view: true, create: true, edit: true, delete: true },
memberships: { view: true, manage: true },
reservations: { view: true, create: true, activate: true, cancel: true },
tenancies: { view: true, manage: true, cancel: true },
admin: {
manage_users: 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 },
companies: { view: true, create: true, edit: true, delete: true },
memberships: { view: true, manage: true },
reservations: { view: true, create: true, activate: true, cancel: true },
tenancies: { view: true, manage: true, cancel: true },
admin: {
manage_users: 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 },
companies: { view: true, create: true, edit: true, delete: false },
memberships: { view: true, manage: true },
reservations: { view: true, create: true, activate: true, cancel: true },
tenancies: { view: true, manage: true, cancel: true },
admin: {
manage_users: 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 },
companies: { view: true, create: true, edit: false, delete: false },
memberships: { view: true, manage: false },
reservations: { view: true, create: true, activate: true, cancel: false },
tenancies: { view: true, manage: true, cancel: false },
admin: {
manage_users: 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 },
companies: { view: true, create: false, edit: false, delete: false },
memberships: { view: true, manage: false },
reservations: { view: true, create: false, activate: false, cancel: false },
tenancies: { view: true, manage: false, cancel: false },
admin: {
manage_users: 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 },
companies: { view: false, create: false, edit: false, delete: false },
memberships: { view: false, manage: false },
reservations: { view: false, create: false, activate: false, cancel: false },
tenancies: { view: false, manage: false, cancel: false },
admin: {
manage_users: false,
view_audit_log: false,

View File

@@ -30,7 +30,7 @@ import {
yachts,
yachtOwnershipHistory,
berths,
berthReservations,
berthTenancies,
interests,
interestBerths,
} from './schema';
@@ -700,10 +700,10 @@ export async function seedSyntheticPortData(
// ── 9. Reservations ─────────────────────────────────────────────────────
// One active reservation on the under_offer berth held by Carla,
// 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.
const sharedYachtId = charterYachtRow[1]!.id;
await tx.insert(berthReservations).values([
await tx.insert(berthTenancies).values([
{
portId,
berthId: berthRows[5]!.id,

View File

@@ -39,7 +39,7 @@ async function seed() {
} else {
const x = s.summary;
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 { 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 { documents, documentSigners } from '@/lib/db/schema/documents';
import { expenses } from '@/lib/db/schema/financial';
@@ -39,20 +39,20 @@ function daysAgo(n: number): Date {
async function reservationNoAgreement(portId: string): Promise<AlertCandidate[]> {
const rows = await db
.select({
id: berthReservations.id,
startDate: berthReservations.startDate,
clientName: sql<string>`coalesce((SELECT full_name FROM clients WHERE id = ${berthReservations.clientId}), 'unknown')`,
yachtName: sql<string>`coalesce((SELECT name FROM yachts WHERE id = ${berthReservations.yachtId}), 'unknown')`,
id: berthTenancies.id,
startDate: berthTenancies.startDate,
clientName: sql<string>`coalesce((SELECT full_name FROM clients WHERE id = ${berthTenancies.clientId}), 'unknown')`,
yachtName: sql<string>`coalesce((SELECT name FROM yachts WHERE id = ${berthTenancies.yachtId}), 'unknown')`,
})
.from(berthReservations)
.from(berthTenancies)
.where(
and(
eq(berthReservations.portId, portId),
eq(berthReservations.status, 'active'),
lt(berthReservations.createdAt, daysAgo(3)),
eq(berthTenancies.portId, portId),
eq(berthTenancies.status, 'active'),
lt(berthTenancies.createdAt, daysAgo(3)),
sql`NOT EXISTS (
SELECT 1 FROM ${documents}
WHERE ${documents.reservationId} = ${berthReservations.id}
WHERE ${documents.tenancyId} = ${berthTenancies.id}
AND ${documents.documentType} = 'reservation_agreement'
AND ${documents.status} NOT IN ('cancelled', 'expired')
)`,
@@ -64,7 +64,7 @@ async function reservationNoAgreement(portId: string): Promise<AlertCandidate[]>
severity: 'warning',
title: `Reservation needs an agreement`,
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',
entityId: r.id,
}));

View File

@@ -1,6 +1,6 @@
import { and, eq, isNull } from 'drizzle-orm';
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 { clients } from '@/lib/db/schema/clients';
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 { emitToRoom } from '@/lib/socket/server';
import type { z } from 'zod';
import { createPendingSchema } from '@/lib/validators/reservations';
import { createPendingSchema } from '@/lib/validators/tenancies';
import type {
ActivateInput,
EndReservationInput,
EndTenancyInput,
CancelInput,
ListReservationsInput,
} from '@/lib/validators/reservations';
ListTenanciesInput,
} from '@/lib/validators/tenancies';
// Use z.input so callers (including tests) can omit fields with
// `.default()` like `tenureType`. The service re-parses below to get
// the post-coercion shape Drizzle expects (Date, defaulted tenureType).
type CreatePendingInput = z.input<typeof createPendingSchema>;
export type { BerthReservation };
export type { BerthTenancy };
// ─── Helpers ─────────────────────────────────────────────────────────────────
/**
* 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
* violations.
*/
@@ -46,11 +46,11 @@ function isBerthActiveConflict(err: unknown): boolean {
if (code !== '23505') return false;
const 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
* active (endDate IS NULL) company_membership on the owning company.
*/
@@ -73,14 +73,14 @@ async function assertClientOwnsOrRepresentsYacht(
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> {
const row = await db.query.berthReservations.findFirst({
where: and(eq(berthReservations.id, id), eq(berthReservations.portId, portId)),
async function loadScoped(id: string, portId: string): Promise<BerthTenancy> {
const row = await db.query.berthTenancies.findFirst({
where: and(eq(berthTenancies.id, id), eq(berthTenancies.portId, portId)),
});
if (!row) throw new NotFoundError('Reservation');
if (!row) throw new NotFoundError('Tenancy');
return row;
}
@@ -90,7 +90,7 @@ export async function createPending(
portId: string,
data: CreatePendingInput,
meta: AuditMeta,
): Promise<BerthReservation> {
): Promise<BerthTenancy> {
// Tenant-scoped existence checks (berth, client, yacht).
const berth = await db.query.berths.findFirst({
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.
const parsed = createPendingSchema.parse(data);
const [reservation] = await db
.insert(berthReservations)
const [tenancy] = await db
.insert(berthTenancies)
.values({
portId,
berthId: parsed.berthId,
@@ -138,48 +138,48 @@ export async function createPending(
userId: meta.userId,
portId,
action: 'create',
entityType: 'berth_reservation',
entityId: reservation!.id,
entityType: 'berth_tenancy',
entityId: tenancy!.id,
newValue: {
berthId: reservation!.berthId,
clientId: reservation!.clientId,
yachtId: reservation!.yachtId,
status: reservation!.status,
startDate: reservation!.startDate,
berthId: tenancy!.berthId,
clientId: tenancy!.clientId,
yachtId: tenancy!.yachtId,
status: tenancy!.status,
startDate: tenancy!.startDate,
},
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'berth_reservation:created', {
reservationId: reservation!.id,
berthId: reservation!.berthId,
emitToRoom(`port:${portId}`, 'berth_tenancy:created', {
tenancyId: tenancy!.id,
berthId: tenancy!.berthId,
});
return reservation!;
return tenancy!;
}
// ─── Activate (pending → active) ─────────────────────────────────────────────
export async function activate(
reservationId: string,
tenancyId: string,
portId: string,
data: ActivateInput,
meta: AuditMeta,
): Promise<BerthReservation> {
const existing = await loadScoped(reservationId, portId);
): Promise<BerthTenancy> {
const existing = await loadScoped(tenancyId, portId);
if (existing.status !== 'pending') {
throw new ValidationError(`invalid transition: ${existing.status} → active`);
}
const patch: Partial<typeof berthReservations.$inferInsert> = {
const patch: Partial<typeof berthTenancies.$inferInsert> = {
status: 'active',
updatedAt: new Date(),
};
if (data.contractFileId !== undefined) {
// 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
// export, portal contract download) would otherwise leak that
// foreign-port content.
@@ -197,27 +197,27 @@ export async function activate(
patch.startDate = data.effectiveDate;
}
let updated: BerthReservation | undefined;
let updated: BerthTenancy | undefined;
try {
const rows = await db
.update(berthReservations)
.update(berthTenancies)
.set(patch)
.where(and(eq(berthReservations.id, reservationId), eq(berthReservations.portId, portId)))
.where(and(eq(berthTenancies.id, tenancyId), eq(berthTenancies.portId, portId)))
.returning();
updated = rows[0];
} catch (err) {
if (isBerthActiveConflict(err)) {
const conflicting = await db.query.berthReservations.findFirst({
const conflicting = await db.query.berthTenancies.findFirst({
where: and(
eq(berthReservations.berthId, existing.berthId),
eq(berthReservations.status, 'active'),
eq(berthReservations.portId, portId),
eq(berthTenancies.berthId, existing.berthId),
eq(berthTenancies.status, 'active'),
eq(berthTenancies.portId, portId),
),
});
throw new ConflictError(
conflicting
? `berth already has active reservation (conflictingReservationId: ${conflicting.id})`
: 'berth already has active reservation',
? `berth already has active tenancy (conflictingTenancyId: ${conflicting.id})`
: 'berth already has active tenancy',
);
}
throw err;
@@ -227,16 +227,16 @@ export async function activate(
userId: meta.userId,
portId,
action: 'update',
entityType: 'berth_reservation',
entityId: reservationId,
entityType: 'berth_tenancy',
entityId: tenancyId,
oldValue: { status: existing.status },
newValue: { status: 'active', contractFileId: updated!.contractFileId },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'berth_reservation:activated', {
reservationId,
emitToRoom(`port:${portId}`, 'berth_tenancy:activated', {
tenancyId,
berthId: updated!.berthId,
});
@@ -245,27 +245,27 @@ export async function activate(
// ─── End (active → ended) ────────────────────────────────────────────────────
export async function endReservation(
reservationId: string,
export async function endTenancy(
tenancyId: string,
portId: string,
data: EndReservationInput,
data: EndTenancyInput,
meta: AuditMeta,
): Promise<BerthReservation> {
const existing = await loadScoped(reservationId, portId);
): Promise<BerthTenancy> {
const existing = await loadScoped(tenancyId, portId);
if (existing.status !== 'active') {
throw new ValidationError(`invalid transition: ${existing.status} → ended`);
}
const rows = await db
.update(berthReservations)
.update(berthTenancies)
.set({
status: 'ended',
endDate: data.endDate,
notes: data.notes ?? existing.notes,
updatedAt: new Date(),
})
.where(and(eq(berthReservations.id, reservationId), eq(berthReservations.portId, portId)))
.where(and(eq(berthTenancies.id, tenancyId), eq(berthTenancies.portId, portId)))
.returning();
const updated = rows[0]!;
@@ -274,16 +274,16 @@ export async function endReservation(
userId: meta.userId,
portId,
action: 'update',
entityType: 'berth_reservation',
entityId: reservationId,
entityType: 'berth_tenancy',
entityId: tenancyId,
oldValue: { status: existing.status },
newValue: { status: 'ended', endDate: updated.endDate },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'berth_reservation:ended', {
reservationId,
emitToRoom(`port:${portId}`, 'berth_tenancy:ended', {
tenancyId,
berthId: updated.berthId,
});
@@ -293,19 +293,19 @@ export async function endReservation(
// ─── Cancel (pending|active → cancelled) ─────────────────────────────────────
export async function cancel(
reservationId: string,
tenancyId: string,
portId: string,
data: CancelInput,
meta: AuditMeta,
): Promise<BerthReservation> {
const existing = await loadScoped(reservationId, portId);
): Promise<BerthTenancy> {
const existing = await loadScoped(tenancyId, portId);
if (existing.status !== 'pending' && existing.status !== 'active') {
throw new ValidationError(`invalid transition: ${existing.status} → cancelled`);
}
const rows = await db
.update(berthReservations)
.update(berthTenancies)
.set({
status: 'cancelled',
notes: data.reason
@@ -313,7 +313,7 @@ export async function cancel(
: existing.notes,
updatedAt: new Date(),
})
.where(and(eq(berthReservations.id, reservationId), eq(berthReservations.portId, portId)))
.where(and(eq(berthTenancies.id, tenancyId), eq(berthTenancies.portId, portId)))
.returning();
const updated = rows[0]!;
@@ -322,16 +322,16 @@ export async function cancel(
userId: meta.userId,
portId,
action: 'update',
entityType: 'berth_reservation',
entityId: reservationId,
entityType: 'berth_tenancy',
entityId: tenancyId,
oldValue: { status: existing.status },
newValue: { status: 'cancelled', reason: data.reason ?? null },
ipAddress: meta.ipAddress,
userAgent: meta.userAgent,
});
emitToRoom(`port:${portId}`, 'berth_reservation:cancelled', {
reservationId,
emitToRoom(`port:${portId}`, 'berth_tenancy:cancelled', {
tenancyId,
berthId: updated.berthId,
});
@@ -340,38 +340,38 @@ export async function cancel(
// ─── 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);
}
// ─── List ────────────────────────────────────────────────────────────────────
export async function listReservations(
export async function listTenancies(
portId: string,
query: ListReservationsInput,
): Promise<{ data: BerthReservation[]; total: number }> {
query: ListTenanciesInput,
): Promise<{ data: BerthTenancy[]; total: number }> {
const { page, limit, sort, order, search, status, berthId, clientId, yachtId } = query;
const filters = [];
if (status) filters.push(eq(berthReservations.status, status));
if (berthId) filters.push(eq(berthReservations.berthId, berthId));
if (clientId) filters.push(eq(berthReservations.clientId, clientId));
if (yachtId) filters.push(eq(berthReservations.yachtId, yachtId));
if (status) filters.push(eq(berthTenancies.status, status));
if (berthId) filters.push(eq(berthTenancies.berthId, berthId));
if (clientId) filters.push(eq(berthTenancies.clientId, clientId));
if (yachtId) filters.push(eq(berthTenancies.yachtId, yachtId));
let sortColumn:
| typeof berthReservations.startDate
| typeof berthReservations.createdAt
| typeof berthReservations.updatedAt = berthReservations.updatedAt;
if (sort === 'startDate') sortColumn = berthReservations.startDate;
else if (sort === 'createdAt') sortColumn = berthReservations.createdAt;
| typeof berthTenancies.startDate
| typeof berthTenancies.createdAt
| typeof berthTenancies.updatedAt = berthTenancies.updatedAt;
if (sort === 'startDate') sortColumn = berthTenancies.startDate;
else if (sort === 'createdAt') sortColumn = berthTenancies.createdAt;
const result = await buildListQuery<BerthReservation>({
table: berthReservations,
portIdColumn: berthReservations.portId,
const result = await buildListQuery<BerthTenancy>({
table: berthTenancies,
portIdColumn: berthTenancies.portId,
portId,
idColumn: berthReservations.id,
updatedAtColumn: berthReservations.updatedAt,
searchColumns: search ? [berthReservations.notes] : [],
idColumn: berthTenancies.id,
updatedAtColumn: berthTenancies.updatedAt,
searchColumns: search ? [berthTenancies.notes] : [],
searchTerm: search,
filters,
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 { interests, interestBerths } from '@/lib/db/schema/interests';
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 { documents } from '@/lib/db/schema/documents';
import { activeInterestsWhere } from '@/lib/services/active-interest';
@@ -84,8 +84,8 @@ export interface DossierCompany {
membershipRole: string | null;
}
export interface DossierReservation {
reservationId: string;
export interface DossierTenancy {
tenancyId: string;
berthId: string;
mooringNumber: string;
status: string; // typically 'active'
@@ -128,13 +128,13 @@ export interface ClientArchiveDossier {
berths: DossierBerth[];
yachts: DossierYacht[];
companies: DossierCompany[];
reservations: DossierReservation[];
tenancies: DossierTenancy[];
invoices: DossierInvoice[];
documents: DossierDocument[];
hasPortalUser: boolean;
/** 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). */
blockers: string[];
}
@@ -327,23 +327,23 @@ export async function getClientArchiveDossier(
),
);
// ─── Active reservations ─────────────────────────────────────────────────
const activeReservations = await db
// ─── Active tenancies ────────────────────────────────────────────────────
const activeTenancies = await db
.select({
id: berthReservations.id,
berthId: berthReservations.berthId,
id: berthTenancies.id,
berthId: berthTenancies.berthId,
mooringNumber: berths.mooringNumber,
status: berthReservations.status,
startDate: berthReservations.startDate,
status: berthTenancies.status,
startDate: berthTenancies.startDate,
berthStatus: berths.status,
})
.from(berthReservations)
.innerJoin(berths, eq(berthReservations.berthId, berths.id))
.from(berthTenancies)
.innerJoin(berths, eq(berthTenancies.berthId, berths.id))
.where(
and(
eq(berthReservations.clientId, clientId),
eq(berthReservations.portId, portId),
eq(berthReservations.status, 'active'),
eq(berthTenancies.clientId, clientId),
eq(berthTenancies.portId, portId),
eq(berthTenancies.status, 'active'),
),
);
@@ -376,14 +376,14 @@ export async function getClientArchiveDossier(
.limit(1);
// ─── 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
// 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[] = [];
for (const r of activeReservations) {
for (const r of activeTenancies) {
if (r.berthStatus === 'sold') {
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,
membershipRole: m.role,
})),
reservations: activeReservations.map((r) => ({
reservationId: r.id,
tenancies: activeTenancies.map((r) => ({
tenancyId: r.id,
berthId: r.berthId,
mooringNumber: r.mooringNumber,
status: r.status,

View File

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

View File

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

View File

@@ -11,7 +11,7 @@ import {
} from '@/lib/db/schema/clients';
import { companies, companyMemberships } from '@/lib/db/schema/companies';
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 { berths } from '@/lib/db/schema/berths';
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(
eq(berthReservations.clientId, id),
eq(berthReservations.portId, portId),
eq(berthReservations.status, 'active'),
eq(berthTenancies.clientId, id),
eq(berthTenancies.portId, portId),
eq(berthTenancies.status, 'active'),
),
columns: {
id: true,
@@ -450,7 +450,7 @@ export async function getClientById(id: string, portId: string) {
tags: clientTagRows.map((r) => r.tag),
yachts: yachtRows,
companies: membershipRows,
activeReservations,
activeTenancies,
interestCount: interestCountRow?.count ?? 0,
noteCount: noteCountRow?.count ?? 0,
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 { interests, interestBerths, interestNotes } from '@/lib/db/schema/interests';
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 { payments } from '@/lib/db/schema/pipeline';
import { documents } from '@/lib/db/schema/documents';
@@ -508,18 +508,18 @@ export async function getRecentActivity(portId: string, limit = 20) {
(r) => r.clientName,
),
loadLabels(
'berth_reservation',
'berth_tenancy',
(ids) =>
db
.select({
id: berthReservations.id,
id: berthTenancies.id,
mooring: berths.mooringNumber,
clientName: clients.fullName,
})
.from(berthReservations)
.innerJoin(berths, eq(berthReservations.berthId, berths.id))
.leftJoin(clients, eq(berthReservations.clientId, clients.id))
.where(and(eq(berthReservations.portId, portId), inArray(berthReservations.id, ids))),
.from(berthTenancies)
.innerJoin(berths, eq(berthTenancies.berthId, berths.id))
.leftJoin(clients, eq(berthTenancies.clientId, clients.id))
.where(and(eq(berthTenancies.portId, portId), inArray(berthTenancies.id, ids))),
(r) => `Berth ${r.mooring}${r.clientName ? ` · ${r.clientName}` : ''}`,
),
loadLabels(

View File

@@ -14,7 +14,7 @@ import { companies } from '@/lib/db/schema/companies';
import { yachts } from '@/lib/db/schema/yachts';
import { berths } from '@/lib/db/schema/berths';
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 { userProfiles, userPortRoles } from '@/lib/db/schema/users';
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 /
* 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
* port-B client and then exfiltrate the foreign client's name + email
* via sendForSigning's Documenso payload, or via the local watcher /
@@ -441,7 +441,7 @@ async function assertSubjectFksInPort(
interestId?: string | null;
companyId?: string | null;
yachtId?: string | null;
reservationId?: string | null;
tenancyId?: string | null;
},
): Promise<void> {
const checks: Array<Promise<void>> = [];
@@ -485,17 +485,14 @@ async function assertSubjectFksInPort(
}),
);
}
if (fks.reservationId) {
if (fks.tenancyId) {
checks.push(
db.query.berthReservations
db.query.berthTenancies
.findFirst({
where: and(
eq(berthReservations.id, fks.reservationId),
eq(berthReservations.portId, portId),
),
where: and(eq(berthTenancies.id, fks.tenancyId), eq(berthTenancies.portId, portId)),
})
.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));
// 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.
if (doc.documentType === 'reservation_agreement' && doc.reservationId) {
const { berthReservations } = await import('@/lib/db/schema/reservations');
if (doc.documentType === 'reservation_agreement' && doc.tenancyId) {
const { berthTenancies } = await import('@/lib/db/schema/tenancies');
await tx
.update(berthReservations)
.update(berthTenancies)
.set({ contractFileId: inserted.id, updatedAt: new Date() })
.where(eq(berthReservations.id, doc.reservationId));
.where(eq(berthTenancies.id, doc.tenancyId));
}
return inserted;
@@ -2427,7 +2424,7 @@ export async function createFromWizard(
interestId: data.interestId,
companyId: data.companyId,
yachtId: data.yachtId,
reservationId: data.reservationId,
tenancyId: data.tenancyId,
});
const [doc] = await db
@@ -2435,7 +2432,7 @@ export async function createFromWizard(
.values({
portId,
interestId: data.interestId ?? null,
reservationId: data.reservationId ?? null,
tenancyId: data.tenancyId ?? null,
clientId: data.clientId ?? null,
companyId: data.companyId ?? null,
yachtId: data.yachtId ?? null,
@@ -2516,7 +2513,7 @@ export async function createFromUpload(
interestId: data.interestId,
companyId: data.companyId,
yachtId: data.yachtId,
reservationId: data.reservationId,
tenancyId: data.tenancyId,
});
const [doc] = await db
@@ -2524,7 +2521,7 @@ export async function createFromUpload(
.values({
portId,
interestId: data.interestId ?? null,
reservationId: data.reservationId ?? null,
tenancyId: data.tenancyId ?? null,
clientId: data.clientId ?? null,
companyId: data.companyId ?? 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 { yachts } from '@/lib/db/schema/yachts';
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 { documents, files, formSubmissions } from '@/lib/db/schema/documents';
import { auditLogs } from '@/lib/db/schema/system';
@@ -141,8 +141,8 @@ export async function buildClientBundle(clientId: string, portId: string): Promi
db.query.interests.findMany({
where: and(eq(interests.clientId, clientId), eq(interests.portId, portId)),
}),
db.query.berthReservations.findMany({
where: and(eq(berthReservations.clientId, clientId), eq(berthReservations.portId, portId)),
db.query.berthTenancies.findMany({
where: and(eq(berthTenancies.clientId, clientId), eq(berthTenancies.portId, portId)),
}),
db.query.invoices.findMany({
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 { berths } from '@/lib/db/schema/berths';
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 { companyMemberships } from '@/lib/db/schema/companies';
import { tags } from '@/lib/db/schema/system';
@@ -622,14 +622,14 @@ export async function getInterestById(id: string, portId: string) {
)
.orderBy(desc(documentEvents.createdAt))
.limit(1),
// Latest cancelled berth_reservation row pointing at this interest.
// berth_reservations has no cancelled_at column; updatedAt is set when
// Latest cancelled berth_tenancy row pointing at this interest.
// berth_tenancies has no cancelled_at column; updatedAt is set when
// the row flips to status='cancelled', so it tracks the same moment.
db
.select({ at: berthReservations.updatedAt })
.from(berthReservations)
.where(and(eq(berthReservations.interestId, id), eq(berthReservations.status, 'cancelled')))
.orderBy(desc(berthReservations.updatedAt))
.select({ at: berthTenancies.updatedAt })
.from(berthTenancies)
.where(and(eq(berthTenancies.interestId, id), eq(berthTenancies.status, 'cancelled')))
.orderBy(desc(berthTenancies.updatedAt))
.limit(1),
// "Berth sold to another deal" - any of this interest's linked berths
// 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 { yachts } from '@/lib/db/schema/yachts';
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 { getCountryName } from '@/lib/i18n/countries';
@@ -32,7 +32,7 @@ export interface PortalDashboard {
invoices: number;
yachts: number;
memberships: number;
activeReservations: number;
activeTenancies: number;
};
}
@@ -40,7 +40,7 @@ export async function getPortalDashboard(
clientId: string,
portId: string,
): Promise<PortalDashboard | null> {
const [client, port, interestCount, documentCount, yachtList, membershipList, reservationList] =
const [client, port, interestCount, documentCount, yachtList, membershipList, tenancyList] =
await Promise.all([
db.query.clients.findFirst({
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))),
getPortalUserYachts(clientId, portId),
getPortalUserMemberships(clientId, portId),
getPortalUserReservations(clientId, portId),
getPortalUserTenancies(clientId, portId),
]);
if (!client || !port) return null;
@@ -96,7 +96,7 @@ export async function getPortalDashboard(
invoices: invoiceCount,
yachts: yachtList.length,
memberships: membershipList.length,
activeReservations: reservationList.length,
activeTenancies: tenancyList.length,
},
};
}
@@ -515,9 +515,9 @@ export async function getPortalUserMemberships(
return rows;
}
// ─── Reservations ─────────────────────────────────────────────────────────────
// ─── Tenancies ────────────────────────────────────────────────────────────────
export interface PortalReservation {
export interface PortalTenancy {
id: string;
berthId: string;
berthMooringNumber: string | null;
@@ -529,32 +529,32 @@ export interface PortalReservation {
tenureType: string;
}
export async function getPortalUserReservations(
export async function getPortalUserTenancies(
clientId: string,
portId: string,
): Promise<PortalReservation[]> {
): Promise<PortalTenancy[]> {
const rows = await db
.select({
id: berthReservations.id,
berthId: berthReservations.berthId,
id: berthTenancies.id,
berthId: berthTenancies.berthId,
berthMooringNumber: berths.mooringNumber,
yachtId: berthReservations.yachtId,
yachtId: berthTenancies.yachtId,
yachtName: yachts.name,
status: berthReservations.status,
startDate: berthReservations.startDate,
endDate: berthReservations.endDate,
tenureType: berthReservations.tenureType,
status: berthTenancies.status,
startDate: berthTenancies.startDate,
endDate: berthTenancies.endDate,
tenureType: berthTenancies.tenureType,
})
.from(berthReservations)
.innerJoin(berths, eq(berthReservations.berthId, berths.id))
.innerJoin(yachts, eq(berthReservations.yachtId, yachts.id))
.from(berthTenancies)
.innerJoin(berths, eq(berthTenancies.berthId, berths.id))
.innerJoin(yachts, eq(berthTenancies.yachtId, yachts.id))
.where(
and(
eq(berthReservations.clientId, clientId),
eq(berthReservations.portId, portId),
inArray(berthReservations.status, ['pending', 'active']),
eq(berthTenancies.clientId, clientId),
eq(berthTenancies.portId, portId),
inArray(berthTenancies.status, ['pending', 'active']),
),
)
.orderBy(desc(berthReservations.createdAt));
return rows as PortalReservation[];
.orderBy(desc(berthTenancies.createdAt));
return rows as PortalTenancy[];
}

View File

@@ -2,7 +2,7 @@ import { and, eq } from 'drizzle-orm';
import { db } from '@/lib/db';
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 { ports } from '@/lib/db/schema/ports';
import { yachts } from '@/lib/db/schema/yachts';
@@ -57,13 +57,13 @@ export type ReservationAgreementContext = {
* formatting helpers in the template language.
*/
export async function buildReservationAgreementContext(
reservationId: string,
tenancyId: string,
portId: string,
): Promise<ReservationAgreementContext> {
const reservation = await db.query.berthReservations.findFirst({
where: and(eq(berthReservations.id, reservationId), eq(berthReservations.portId, portId)),
const reservation = await db.query.berthTenancies.findFirst({
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([
db.query.clients.findFirst({

View File

@@ -3,7 +3,7 @@
* entity tabs, top-level page, dashboard widgets, webhook auto-create
* 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
* (b) an admin has explicitly enabled the module via
* `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 { 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';
/**
@@ -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.
// Once any port has a tenancy, the module's UX is justified.
const rowCheck = await db
.select({ id: berthReservations.id })
.from(berthReservations)
.where(eq(berthReservations.portId, portId))
.select({ id: berthTenancies.id })
.from(berthTenancies)
.where(eq(berthTenancies.portId, portId))
.limit(1);
return rowCheck.length > 0;
}

View File

@@ -36,10 +36,10 @@ export const WEBHOOK_EVENTS = [
'company_membership.added',
'company_membership.updated',
'company_membership.ended',
'berth_reservation.created',
'berth_reservation.activated',
'berth_reservation.ended',
'berth_reservation.cancelled',
'berth_tenancy.created',
'berth_tenancy.activated',
'berth_tenancy.ended',
'berth_tenancy.cancelled',
] as const;
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:updated': 'company_membership.updated',
'company_membership:ended': 'company_membership.ended',
'berth_reservation:created': 'berth_reservation.created',
'berth_reservation:activated': 'berth_reservation.activated',
'berth_reservation:ended': 'berth_reservation.ended',
'berth_reservation:cancelled': 'berth_reservation.cancelled',
'berth_tenancy:created': 'berth_tenancy.created',
'berth_tenancy:activated': 'berth_tenancy.activated',
'berth_tenancy:ended': 'berth_tenancy.ended',
'berth_tenancy:cancelled': 'berth_tenancy.cancelled',
};

View File

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

View File

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

View File

@@ -1,7 +1,7 @@
import { z } from 'zod';
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 createPendingSchema = z.object({
@@ -19,7 +19,7 @@ export const activateSchema = z.object({
effectiveDate: z.coerce.date().optional(),
});
export const endReservationSchema = z.object({
export const endTenancySchema = z.object({
endDate: z.coerce.date(),
notes: z.string().optional(),
});
@@ -28,8 +28,8 @@ export const cancelSchema = z.object({
reason: z.string().optional(),
});
export const listReservationsSchema = baseListQuerySchema.extend({
status: z.enum(RESERVATION_STATUSES).optional(),
export const listTenanciesSchema = baseListQuerySchema.extend({
status: z.enum(TENANCY_STATUSES).optional(),
berthId: z.string().optional(),
clientId: 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 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 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,
berthDecisions: [],
yachtDecisions: [],
reservationDecisions: [],
tenancyDecisions: [],
invoiceDecisions: [],
documentDecisions: [],
},

View File

@@ -31,7 +31,7 @@ export async function teardown() {
-- 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_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_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)

View File

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

View File

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

View File

@@ -1,15 +1,15 @@
/**
* Port-scoped global reservations list - locks in feat(marina): the new
* `GET /api/v1/berth-reservations` endpoint that powers the
* `[portSlug]/berth-reservations` page. The route is thin (parseQuery
* listReservations); the test guarantees port scoping at the handler
* Port-scoped global tenancies list - locks in feat(marina): the
* `GET /api/v1/tenancies` endpoint that powers the
* `[portSlug]/tenancies` page. The route is thin (parseQuery
* listTenancies); the test guarantees port scoping at the handler
* boundary so a future refactor of the service can't accidentally leak
* cross-port rows.
*/
import { describe, it, expect } from 'vitest';
import { listHandler } from '@/app/api/v1/berth-reservations/handlers';
import { createHandler as createReservationHandler } from '@/app/api/v1/berths/[id]/reservations/handlers';
import { listHandler } from '@/app/api/v1/tenancies/handlers';
import { createHandler as createTenancyHandler } from '@/app/api/v1/berths/[id]/tenancies/handlers';
import { makeMockCtx, makeMockRequest } from '../../helpers/route-tester';
import {
makeBerth,
@@ -19,13 +19,13 @@ import {
makeYacht,
} from '../../helpers/factories';
async function seedReservation(portId: string) {
async function seedTenancy(portId: string) {
const berth = await makeBerth({ portId });
const client = await makeClient({ portId });
const yacht = await makeYacht({ portId, ownerType: 'client', ownerId: client.id });
const ctx = makeMockCtx({ portId, permissions: makeFullPermissions() });
const res = await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, {
const res = await createTenancyHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.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 };
}
describe('GET /api/v1/berth-reservations', () => {
it('returns all reservations for the requesting port', async () => {
describe('GET /api/v1/tenancies', () => {
it('returns all tenancies for the requesting port', async () => {
const port = await makePort();
const r1 = await seedReservation(port.id);
const r2 = await seedReservation(port.id);
const r1 = await seedTenancy(port.id);
const r2 = await seedTenancy(port.id);
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
const res = await listHandler(
makeMockRequest('GET', 'http://localhost/api/v1/berth-reservations'),
ctx,
);
const res = await listHandler(makeMockRequest('GET', 'http://localhost/api/v1/tenancies'), ctx);
expect(res.status).toBe(200);
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 });
});
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 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 res = await listHandler(
makeMockRequest('GET', 'http://localhost/api/v1/berth-reservations'),
ctx,
);
const res = await listHandler(makeMockRequest('GET', 'http://localhost/api/v1/tenancies'), ctx);
expect(res.status).toBe(200);
const body = (await res.json()) as any;
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 () => {
const port = await makePort();
await seedReservation(port.id);
await seedReservation(port.id);
await seedReservation(port.id);
await seedTenancy(port.id);
await seedTenancy(port.id);
await seedTenancy(port.id);
const ctx = makeMockCtx({ portId: port.id, permissions: makeFullPermissions() });
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,
);
expect(res.status).toBe(200);

View File

@@ -4,14 +4,14 @@ import { eq } from 'drizzle-orm';
import {
createHandler as createReservationHandler,
listHandler as listReservationsHandler,
} from '@/app/api/v1/berths/[id]/reservations/handlers';
} from '@/app/api/v1/berths/[id]/tenancies/handlers';
import {
getHandler as getReservationHandler,
patchHandler as patchReservationHandler,
deleteHandler as deleteReservationHandler,
} from '@/app/api/v1/berth-reservations/[id]/handlers';
} from '@/app/api/v1/tenancies/[id]/handlers';
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 {
makeBerth,
@@ -22,9 +22,9 @@ import {
makeYacht,
} 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 () => {
const port = await makePort();
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 req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, {
const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
@@ -64,7 +64,7 @@ describe('POST /api/v1/berths/[id]/reservations', () => {
});
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: {
clientId: otherClient.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.
const ctxB = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const req = makeMockRequest(
'POST',
`http://localhost/api/v1/berths/${berthA.id}/reservations`,
{
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${berthA.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
);
});
const res = await createReservationHandler(req, ctxB, { id: berthA.id });
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 req = makeMockRequest(
'POST',
`http://localhost/api/v1/berths/${urlBerth.id}/reservations`,
{
body: {
berthId: bodyBerth.id,
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
const req = makeMockRequest('POST', `http://localhost/api/v1/berths/${urlBerth.id}/tenancies`, {
body: {
berthId: bodyBerth.id,
clientId: client.id,
yachtId: yacht.id,
startDate: new Date().toISOString(),
},
);
});
const res = await createReservationHandler(req, ctx, { id: urlBerth.id });
expect(res.status).toBe(201);
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 () => {
const port = await makePort();
const berthA = await makeBerth({ portId: port.id });
@@ -152,7 +144,7 @@ describe('GET /api/v1/berths/[id]/reservations', () => {
// Create a reservation for berthA.
await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berthA.id}/reservations`, {
makeMockRequest('POST', `http://localhost/api/v1/berths/${berthA.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
@@ -165,7 +157,7 @@ describe('GET /api/v1/berths/[id]/reservations', () => {
// Create a reservation for berthB.
await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berthB.id}/reservations`, {
makeMockRequest('POST', `http://localhost/api/v1/berths/${berthB.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
@@ -177,7 +169,7 @@ describe('GET /api/v1/berths/[id]/reservations', () => {
);
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,
{ 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 () => {
const port = await makePort();
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 createRes = await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, {
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
@@ -216,7 +208,7 @@ describe('GET /api/v1/berth-reservations/[id]', () => {
const reservation = ((await createRes.json()) as any).data;
const res = await getReservationHandler(
makeMockRequest('GET', `http://localhost/api/v1/berth-reservations/${reservation.id}`),
makeMockRequest('GET', `http://localhost/api/v1/tenancies/${reservation.id}`),
ctx,
{ id: reservation.id },
);
@@ -238,7 +230,7 @@ describe('GET /api/v1/berth-reservations/[id]', () => {
const ctxA = makeMockCtx({ portId: portA.id, permissions: makeFullPermissions() });
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: {
clientId: client.id,
yachtId: yacht.id,
@@ -252,7 +244,7 @@ describe('GET /api/v1/berth-reservations/[id]', () => {
const ctxB = makeMockCtx({ portId: portB.id, permissions: makeFullPermissions() });
const res = await getReservationHandler(
makeMockRequest('GET', `http://localhost/api/v1/berth-reservations/${reservation.id}`),
makeMockRequest('GET', `http://localhost/api/v1/tenancies/${reservation.id}`),
ctxB,
{ 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() {
const port = await makePort();
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 createRes = await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, {
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
@@ -292,7 +284,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
it('activate: pending → active (200)', async () => {
const { ctx, reservation } = await seedReservation();
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' },
}),
ctx,
@@ -308,7 +300,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// First activate.
await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, {
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' },
}),
ctx,
@@ -318,7 +310,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// Then end.
const endDate = new Date('2027-01-01T00:00:00.000Z');
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: 'end',
endDate: endDate.toISOString(),
@@ -337,7 +329,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
it('cancel: pending → cancelled (200)', async () => {
const { ctx, reservation } = await seedReservation();
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' },
}),
ctx,
@@ -353,7 +345,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// pending → active.
await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, {
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: { action: 'activate' },
}),
ctx,
@@ -361,7 +353,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
);
// active → ended.
await patchReservationHandler(
makeMockRequest('PATCH', `http://localhost/api/v1/berth-reservations/${reservation.id}`, {
makeMockRequest('PATCH', `http://localhost/api/v1/tenancies/${reservation.id}`, {
body: {
action: 'end',
endDate: new Date().toISOString(),
@@ -373,7 +365,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// ended → activate should fail.
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' },
}),
ctx,
@@ -385,7 +377,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
it('returns 400 on invalid body shape (action missing)', async () => {
const { ctx, reservation } = await seedReservation();
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' },
}),
ctx,
@@ -394,18 +386,18 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
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();
// Viewer-like permissions: no activate.
// Viewer-like permissions: no manage.
const ctx = makeMockCtx({
portId: port.id,
permissions: {
...makeSalesAgentPermissions(),
reservations: { view: true, create: true, activate: false, cancel: true },
tenancies: { view: true, manage: false, cancel: true },
},
});
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' },
}),
ctx,
@@ -414,15 +406,15 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
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();
// Sales agent - has activate but NOT cancel.
// Sales agent - has manage but NOT cancel.
const ctx = makeMockCtx({
portId: port.id,
permissions: makeSalesAgentPermissions(),
});
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' },
}),
ctx,
@@ -432,7 +424,7 @@ describe('PATCH /api/v1/berth-reservations/[id]', () => {
// But activate succeeds with the same permissions set.
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' },
}),
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 () => {
const port = await makePort();
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 createRes = await createReservationHandler(
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/reservations`, {
makeMockRequest('POST', `http://localhost/api/v1/berths/${berth.id}/tenancies`, {
body: {
clientId: client.id,
yachtId: yacht.id,
@@ -470,7 +462,7 @@ describe('DELETE /api/v1/berth-reservations/[id]', () => {
const reservation = ((await createRes.json()) as any).data;
const delRes = await deleteReservationHandler(
makeMockRequest('DELETE', `http://localhost/api/v1/berth-reservations/${reservation.id}`),
makeMockRequest('DELETE', `http://localhost/api/v1/tenancies/${reservation.id}`),
ctx,
{ id: reservation.id },
);
@@ -478,8 +470,8 @@ describe('DELETE /api/v1/berth-reservations/[id]', () => {
const [row] = await db
.select()
.from(berthReservations)
.where(eq(berthReservations.id, reservation.id));
.from(berthTenancies)
.where(eq(berthTenancies.id, reservation.id));
expect(row?.status).toBe('cancelled');
});
});

View File

@@ -6,7 +6,7 @@ import {
makeBerth,
makeYacht,
makeMembership,
makeReservation,
makeTenancy,
makeOwnershipTransfer,
} from '../helpers/factories';
import { db } from '@/lib/db';
@@ -23,7 +23,7 @@ describe('factory helpers smoke', () => {
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 berth = await makeBerth({ portId: port.id });
const client = await makeClient({ portId: port.id });
@@ -32,7 +32,7 @@ describe('factory helpers smoke', () => {
ownerType: 'client',
ownerId: client.id,
});
const r = await makeReservation({
const r = await makeTenancy({
berthId: berth.id,
portId: port.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 () => {
const ctx = makeCtx({ isSuperAdmin: true, permissions: null });
const handler = vi.fn(okHandler());
@@ -295,15 +295,15 @@ describe('new resources (yachts, companies, memberships, reservations)', () => {
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 activateRes = await withPermission('reservations', 'activate', vi.fn(okHandler()))(
const manageRes = await withPermission('tenancies', 'manage', vi.fn(okHandler()))(
makeRequest(),
ctx,
{},
);
expect(activateRes.status).toBe(200);
const cancelRes = await withPermission('reservations', 'cancel', vi.fn(okHandler()))(
expect(manageRes.status).toBe(200);
const cancelRes = await withPermission('tenancies', 'cancel', vi.fn(okHandler()))(
makeRequest(),
ctx,
{},

View File

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

View File

@@ -1,9 +1,9 @@
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 { ConflictError } from '@/lib/errors';
describe('reservation exclusivity', () => {
describe('tenancy exclusivity', () => {
it('two concurrent activates on same berth: one succeeds, one throws ConflictError', async () => {
const port = await makePort();
const berth = await makeBerth({ portId: port.id });
@@ -52,7 +52,7 @@ describe('reservation exclusivity', () => {
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 berth = await makeBerth({ portId: port.id });
const clientA = await makeClient({ portId: port.id });
@@ -74,12 +74,7 @@ describe('reservation exclusivity', () => {
makeAuditMeta({ portId: port.id }),
);
await activate(resA.id, port.id, {}, makeAuditMeta({ portId: port.id }));
await endReservation(
resA.id,
port.id,
{ endDate: new Date() },
makeAuditMeta({ portId: port.id }),
);
await endTenancy(resA.id, port.id, { endDate: new Date() }, makeAuditMeta({ portId: port.id }));
const resB = await createPending(
port.id,

View File

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

View File

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