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:
@@ -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,
|
||||
}));
|
||||
|
||||
@@ -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,
|
||||
@@ -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,
|
||||
|
||||
@@ -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 },
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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));
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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[];
|
||||
}
|
||||
|
||||
@@ -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({
|
||||
|
||||
@@ -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;
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
|
||||
Reference in New Issue
Block a user