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:
129
src/lib/db/migrations/0085_rename_reservations_to_tenancies.sql
Normal file
129
src/lib/db/migrations/0085_rename_reservations_to_tenancies.sql
Normal 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';
|
||||
@@ -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,
|
||||
|
||||
@@ -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';
|
||||
|
||||
@@ -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],
|
||||
|
||||
@@ -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;
|
||||
@@ -130,10 +130,9 @@ export type RolePermissions = {
|
||||
view: boolean;
|
||||
manage: boolean;
|
||||
};
|
||||
reservations: {
|
||||
tenancies: {
|
||||
view: boolean;
|
||||
create: boolean;
|
||||
activate: boolean;
|
||||
manage: boolean;
|
||||
cancel: boolean;
|
||||
};
|
||||
admin: {
|
||||
|
||||
@@ -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,
|
||||
};
|
||||
});
|
||||
}
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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,
|
||||
|
||||
@@ -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`,
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -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',
|
||||
};
|
||||
|
||||
@@ -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;
|
||||
|
||||
@@ -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'],
|
||||
|
||||
@@ -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>;
|
||||
Reference in New Issue
Block a user