feat(pipeline): 9→7 stage refactor + v1.1 hardening wave
Replaces the legacy 9-stage pipeline with 7 canonical stages
(enquiry → qualified → eoi → reservation → deposit_paid → contract →
nurturing) plus three doc sub-status columns (eoi_doc_status,
reservation_doc_status, contract_doc_status) that track sent/signed
within a single stage instead of branching it.
Schema (migration 0062):
- interests gains assigned_to, deposit_expected_amount/currency,
three doc-status columns, two documenso-id columns, and
date_reservation_signed.
- New tables: qualification_criteria (per-port admin-configurable),
interest_qualifications (per-interest state), payments (deposit /
balance / refund records keyed to interest + client).
- Default qualification criteria seeded for every existing port.
- Dummy-data UPDATEs collapse Sent/Signed pairs and 'completed' into
the new stage + doc-status + outcome shape.
Migration 0063 adds interest_contact_log.voice_transcript and
template_used columns for v1.1-A/B (quick-template buttons + voice
transcription via Web Speech API).
v1.1 phase work bundled here:
- A/B: Quick-template buttons (Call / Visit / Email) + mic toggle on
the contact-log compose dialog (useVoiceTranscription hook).
- C: berth-rules-engine wraps state writes in pg_advisory_xact_lock
with an idempotent re-read; emits rule_evaluated audit traces.
- D: Documenso webhook: reservation/contract sub-status stamping
moved out of the PDF-download try-block so a download failure
no longer swallows the stamp. New integration test coverage.
- E: /admin/qualification-criteria CRUD page + admin component.
- F: default_new_interest_owner exposed in System Settings.
- G: recentActivityCount + active_engagement deal-pulse signal
surfaced as a chip on interests + hot-deals card.
- H: interest_assigned notification on assignedTo change (skips
self-assign, uses a dedupe key).
Plus the supporting components: AssignedToChip, DealPulseChip,
PaymentsSection, QualificationChecklist, MultiEoiChip,
SkipAheadBanner, WonStatusPanel, InterestBerthStatusBanner,
SupplementalInfoRequestButton, UserPicker.
Tests: 1370/1370 vitest pass (added deal-health unit suite +
expanded constants/validators/pipeline-transitions coverage). tsc
clean, eslint clean.
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
139
src/lib/db/migrations/0062_pipeline_refactor.sql
Normal file
139
src/lib/db/migrations/0062_pipeline_refactor.sql
Normal file
@@ -0,0 +1,139 @@
|
||||
-- 0062_pipeline_refactor.sql
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Pipeline refactor: 7 canonical stages, doc sub-status columns, qualification
|
||||
-- criteria, payment records, assigned_to ownership, expected deposit amount.
|
||||
-- Dummy-data only at this point; legacy-to-new migration for prod cutover is
|
||||
-- a separate one-shot tool to be written when production data is ready.
|
||||
|
||||
-- ─── interests: new columns ────────────────────────────────────────────────
|
||||
|
||||
ALTER TABLE interests
|
||||
ADD COLUMN IF NOT EXISTS assigned_to text REFERENCES user_profiles(user_id),
|
||||
ADD COLUMN IF NOT EXISTS deposit_expected_amount numeric,
|
||||
ADD COLUMN IF NOT EXISTS deposit_expected_currency text DEFAULT 'EUR',
|
||||
ADD COLUMN IF NOT EXISTS eoi_doc_status text,
|
||||
ADD COLUMN IF NOT EXISTS reservation_doc_status text,
|
||||
ADD COLUMN IF NOT EXISTS contract_doc_status text,
|
||||
ADD COLUMN IF NOT EXISTS reservation_documenso_id text,
|
||||
ADD COLUMN IF NOT EXISTS contract_documenso_id text,
|
||||
ADD COLUMN IF NOT EXISTS date_reservation_signed timestamptz;
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_interests_assigned_to ON interests (assigned_to);
|
||||
|
||||
-- ─── stage value migration (collapse Sent/Signed pairs) ────────────────────
|
||||
-- Dummy-data only — destructive UPDATE is safe.
|
||||
|
||||
UPDATE interests SET pipeline_stage = 'enquiry'
|
||||
WHERE pipeline_stage IN ('open', 'details_sent', 'in_communication');
|
||||
|
||||
UPDATE interests
|
||||
SET pipeline_stage = 'eoi', eoi_doc_status = 'sent'
|
||||
WHERE pipeline_stage = 'eoi_sent';
|
||||
|
||||
UPDATE interests
|
||||
SET pipeline_stage = 'eoi', eoi_doc_status = 'signed'
|
||||
WHERE pipeline_stage = 'eoi_signed';
|
||||
|
||||
UPDATE interests SET pipeline_stage = 'deposit_paid'
|
||||
WHERE pipeline_stage = 'deposit_10pct';
|
||||
|
||||
UPDATE interests
|
||||
SET pipeline_stage = 'contract', contract_doc_status = 'sent'
|
||||
WHERE pipeline_stage = 'contract_sent';
|
||||
|
||||
UPDATE interests
|
||||
SET pipeline_stage = 'contract', contract_doc_status = 'signed'
|
||||
WHERE pipeline_stage = 'contract_signed';
|
||||
|
||||
-- `completed` collapses into contract+signed+won (the old terminal stage
|
||||
-- always implied outcome=won; outcome field carries that forward).
|
||||
UPDATE interests
|
||||
SET pipeline_stage = 'contract',
|
||||
contract_doc_status = 'signed',
|
||||
outcome = COALESCE(outcome, 'won'),
|
||||
outcome_at = COALESCE(outcome_at, updated_at)
|
||||
WHERE pipeline_stage = 'completed';
|
||||
|
||||
-- ─── Qualification criteria (per-port, admin-configurable) ──────────────────
|
||||
|
||||
CREATE TABLE IF NOT EXISTS qualification_criteria (
|
||||
id text PRIMARY KEY DEFAULT gen_random_uuid()::text,
|
||||
port_id text NOT NULL REFERENCES ports(id) ON DELETE CASCADE,
|
||||
key text NOT NULL,
|
||||
label text NOT NULL,
|
||||
description text,
|
||||
enabled boolean NOT NULL DEFAULT true,
|
||||
display_order int NOT NULL DEFAULT 0,
|
||||
created_at timestamptz NOT NULL DEFAULT now(),
|
||||
updated_at timestamptz NOT NULL DEFAULT now(),
|
||||
UNIQUE (port_id, key)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_qualification_criteria_port
|
||||
ON qualification_criteria (port_id);
|
||||
|
||||
-- Seed the default criteria for every existing port. Port admins can later
|
||||
-- enable/disable or add port-specific entries.
|
||||
INSERT INTO qualification_criteria (port_id, key, label, description, enabled, display_order)
|
||||
SELECT p.id, 'dimensions', 'Dimensions confirmed',
|
||||
'We know the vessel''s length, width, and draft.', true, 1
|
||||
FROM ports p
|
||||
ON CONFLICT (port_id, key) DO NOTHING;
|
||||
|
||||
INSERT INTO qualification_criteria (port_id, key, label, description, enabled, display_order)
|
||||
SELECT p.id, 'intent', 'Intent confirmed',
|
||||
'Client has explicitly confirmed they want a berth at this marina.', true, 2
|
||||
FROM ports p
|
||||
ON CONFLICT (port_id, key) DO NOTHING;
|
||||
|
||||
-- These are built but disabled — admins enable per port when relevant.
|
||||
INSERT INTO qualification_criteria (port_id, key, label, description, enabled, display_order)
|
||||
SELECT p.id, 'signatory', 'Buyer signatory confirmed',
|
||||
'We know who is authorized to sign the EOI on the buyer side (owner / lawyer / company rep).',
|
||||
false, 3
|
||||
FROM ports p
|
||||
ON CONFLICT (port_id, key) DO NOTHING;
|
||||
|
||||
INSERT INTO qualification_criteria (port_id, key, label, description, enabled, display_order)
|
||||
SELECT p.id, 'timeline', 'Move-in timeline confirmed',
|
||||
'Client has indicated when they want to start using the berth.',
|
||||
false, 4
|
||||
FROM ports p
|
||||
ON CONFLICT (port_id, key) DO NOTHING;
|
||||
|
||||
-- ─── Per-interest qualification state ──────────────────────────────────────
|
||||
|
||||
CREATE TABLE IF NOT EXISTS interest_qualifications (
|
||||
interest_id text NOT NULL REFERENCES interests(id) ON DELETE CASCADE,
|
||||
criterion_key text NOT NULL,
|
||||
confirmed boolean NOT NULL DEFAULT false,
|
||||
confirmed_at timestamptz,
|
||||
confirmed_by text,
|
||||
notes text,
|
||||
PRIMARY KEY (interest_id, criterion_key)
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_interest_qualifications_interest
|
||||
ON interest_qualifications (interest_id);
|
||||
|
||||
-- ─── Payment records (no invoice generation) ───────────────────────────────
|
||||
|
||||
CREATE TABLE IF NOT EXISTS payments (
|
||||
id text PRIMARY KEY DEFAULT gen_random_uuid()::text,
|
||||
port_id text NOT NULL REFERENCES ports(id) ON DELETE CASCADE,
|
||||
interest_id text NOT NULL REFERENCES interests(id) ON DELETE CASCADE,
|
||||
client_id text NOT NULL REFERENCES clients(id) ON DELETE CASCADE,
|
||||
payment_type text NOT NULL, -- 'deposit' | 'balance' | 'refund' | 'other'
|
||||
amount numeric NOT NULL,
|
||||
currency text NOT NULL DEFAULT 'EUR',
|
||||
received_at timestamptz NOT NULL,
|
||||
receipt_file_id text REFERENCES files(id),
|
||||
notes text,
|
||||
recorded_by text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT now()
|
||||
);
|
||||
|
||||
CREATE INDEX IF NOT EXISTS idx_payments_interest ON payments (interest_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_payments_client ON payments (client_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_payments_port ON payments (port_id);
|
||||
CREATE INDEX IF NOT EXISTS idx_payments_type ON payments (port_id, payment_type);
|
||||
14
src/lib/db/migrations/0063_contact_log_voice_template.sql
Normal file
14
src/lib/db/migrations/0063_contact_log_voice_template.sql
Normal file
@@ -0,0 +1,14 @@
|
||||
-- 0063_contact_log_voice_template.sql
|
||||
-- ----------------------------------------------------------------------------
|
||||
-- Pipeline-refactor follow-up. The contact-log captures sales-rep
|
||||
-- interactions; the v1 UX adds two new columns:
|
||||
-- - voice_transcript: raw Web Speech API output, kept separate from the
|
||||
-- rep-polished `summary` so we can re-render the
|
||||
-- transcript verbatim if the rep wants to revisit it.
|
||||
-- - template_used: which of the 3 quick-template buttons was tapped, if
|
||||
-- any. Surfaces in reports so admins can see how reps
|
||||
-- actually log activity (call/visit/email).
|
||||
|
||||
ALTER TABLE interest_contact_log
|
||||
ADD COLUMN IF NOT EXISTS voice_transcript text,
|
||||
ADD COLUMN IF NOT EXISTS template_used text;
|
||||
@@ -68,5 +68,8 @@ export * from './website-submissions';
|
||||
// Pre-EOI supplemental form tokens
|
||||
export * from './supplemental-forms';
|
||||
|
||||
// Pipeline refactor — qualification criteria, payment records
|
||||
export * from './pipeline';
|
||||
|
||||
// Relations (must come last - references all tables)
|
||||
export * from './relations';
|
||||
|
||||
@@ -15,7 +15,8 @@ import { clients } from './clients';
|
||||
import { berths } from './berths';
|
||||
import { yachts } from './yachts';
|
||||
|
||||
// Pipeline stages: open, details_sent, in_communication, eoi_sent, eoi_signed, deposit_10pct, contract_sent, contract_signed, completed
|
||||
// Pipeline stages: enquiry, qualified, nurturing, eoi, reservation, deposit_paid, contract
|
||||
// (doc sub-status carried on eoi_doc_status / reservation_doc_status / contract_doc_status)
|
||||
|
||||
export const interests = pgTable(
|
||||
'interests',
|
||||
@@ -30,7 +31,19 @@ export const interests = pgTable(
|
||||
.notNull()
|
||||
.references(() => clients.id),
|
||||
yachtId: text('yacht_id').references(() => yachts.id, { onDelete: 'set null' }),
|
||||
pipelineStage: text('pipeline_stage').notNull().default('open'),
|
||||
/** Who owns this deal. Auto-assigned on create from system_settings
|
||||
* `default_new_interest_owner`; reassignable via the interest header. */
|
||||
assignedTo: text('assigned_to'),
|
||||
pipelineStage: text('pipeline_stage').notNull().default('enquiry'),
|
||||
/** Sub-status for the doc-signing stages. NULL while the deal hasn't
|
||||
* reached the stage yet; 'pending' | 'sent' | 'signed' | 'declined' | 'voided'. */
|
||||
eoiDocStatus: text('eoi_doc_status'),
|
||||
reservationDocStatus: text('reservation_doc_status'),
|
||||
contractDocStatus: text('contract_doc_status'),
|
||||
/** Documenso IDs per document type. EOI uses the existing `documensoId`
|
||||
* for backward compat with the template-generate path. */
|
||||
reservationDocumensoId: text('reservation_documenso_id'),
|
||||
contractDocumensoId: text('contract_documenso_id'),
|
||||
leadCategory: text('lead_category'), // general_interest, specific_qualified, hot_lead
|
||||
source: text('source'), // website, manual, referral, broker
|
||||
eoiStatus: text('eoi_status'), // null, waiting_for_signatures, signed, expired
|
||||
@@ -38,10 +51,16 @@ export const interests = pgTable(
|
||||
contractStatus: text('contract_status'),
|
||||
depositStatus: text('deposit_status'),
|
||||
reservationStatus: text('reservation_status'),
|
||||
/** Agreed deposit amount captured at reservation-agreement time. Lets
|
||||
* the payments running-total decide when the deposit is "fully paid"
|
||||
* and the stage advances automatically. */
|
||||
depositExpectedAmount: numeric('deposit_expected_amount'),
|
||||
depositExpectedCurrency: text('deposit_expected_currency').default('EUR'),
|
||||
dateFirstContact: timestamp('date_first_contact', { withTimezone: true }),
|
||||
dateLastContact: timestamp('date_last_contact', { withTimezone: true }),
|
||||
dateEoiSent: timestamp('date_eoi_sent', { withTimezone: true }),
|
||||
dateEoiSigned: timestamp('date_eoi_signed', { withTimezone: true }),
|
||||
dateReservationSigned: timestamp('date_reservation_signed', { withTimezone: true }),
|
||||
dateContractSent: timestamp('date_contract_sent', { withTimezone: true }),
|
||||
dateContractSigned: timestamp('date_contract_signed', { withTimezone: true }),
|
||||
dateDepositReceived: timestamp('date_deposit_received', { withTimezone: true }),
|
||||
@@ -86,6 +105,7 @@ export const interests = pgTable(
|
||||
.on(table.portId)
|
||||
.where(sql`${table.archivedAt} IS NULL`),
|
||||
index('idx_interests_outcome').on(table.portId, table.outcome),
|
||||
index('idx_interests_assigned_to').on(table.assignedTo),
|
||||
],
|
||||
);
|
||||
|
||||
|
||||
@@ -231,6 +231,13 @@ export const interestContactLog = pgTable(
|
||||
direction: text('direction').notNull().default('outbound'),
|
||||
/** Short free text — "Discussed yacht size, asked about tax structure". */
|
||||
summary: text('summary').notNull(),
|
||||
/** Raw Web Speech API transcript captured at log time, kept separate
|
||||
* from the rep-polished `summary` so the original utterance survives
|
||||
* edits to the summary text. NULL when the rep typed manually. */
|
||||
voiceTranscript: text('voice_transcript'),
|
||||
/** Which of the 3 quick-template buttons was tapped on the log modal
|
||||
* ('call' | 'visit' | 'email'). NULL when the rep filled in freeform. */
|
||||
templateUsed: text('template_used'),
|
||||
/** Optional. When set, a reminder is auto-created pointing back to
|
||||
* the interest for follow-up. Stored as the original choice so the
|
||||
* UI can re-render it; the actual reminder lives in `reminders`. */
|
||||
|
||||
125
src/lib/db/schema/pipeline.ts
Normal file
125
src/lib/db/schema/pipeline.ts
Normal file
@@ -0,0 +1,125 @@
|
||||
/**
|
||||
* Pipeline-refactor tables — per-port qualification criteria, per-interest
|
||||
* qualification state, and payment records (no invoice generation).
|
||||
*
|
||||
* See migrations/0062_pipeline_refactor.sql.
|
||||
*/
|
||||
|
||||
import {
|
||||
pgTable,
|
||||
text,
|
||||
boolean,
|
||||
integer,
|
||||
numeric,
|
||||
timestamp,
|
||||
index,
|
||||
primaryKey,
|
||||
} from 'drizzle-orm/pg-core';
|
||||
|
||||
import { ports } from './ports';
|
||||
import { interests } from './interests';
|
||||
import { clients } from './clients';
|
||||
import { files } from './documents';
|
||||
|
||||
/**
|
||||
* Per-port qualification criteria. Admin-configurable: enable/disable,
|
||||
* rename labels, reorder. The default seed is 2 enabled (dimensions +
|
||||
* intent) and 2 disabled (signatory + timeline) per port.
|
||||
*/
|
||||
export const qualificationCriteria = pgTable(
|
||||
'qualification_criteria',
|
||||
{
|
||||
id: text('id')
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
portId: text('port_id')
|
||||
.notNull()
|
||||
.references(() => ports.id, { onDelete: 'cascade' }),
|
||||
/** Stable key for code references. e.g. 'dimensions', 'intent'. */
|
||||
key: text('key').notNull(),
|
||||
/** Display label shown on the qualification checklist UI. */
|
||||
label: text('label').notNull(),
|
||||
/** Optional short description shown as helper text under the checkbox. */
|
||||
description: text('description'),
|
||||
enabled: boolean('enabled').notNull().default(true),
|
||||
displayOrder: integer('display_order').notNull().default(0),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
updatedAt: timestamp('updated_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => [index('idx_qualification_criteria_port').on(table.portId)],
|
||||
);
|
||||
|
||||
/**
|
||||
* Per-interest qualification state. Composite PK (interest_id, criterion_key)
|
||||
* lets the same key exist across ports without conflicts and gives O(1)
|
||||
* lookup for the "all enabled criteria confirmed" check.
|
||||
*/
|
||||
export const interestQualifications = pgTable(
|
||||
'interest_qualifications',
|
||||
{
|
||||
interestId: text('interest_id')
|
||||
.notNull()
|
||||
.references(() => interests.id, { onDelete: 'cascade' }),
|
||||
criterionKey: text('criterion_key').notNull(),
|
||||
confirmed: boolean('confirmed').notNull().default(false),
|
||||
confirmedAt: timestamp('confirmed_at', { withTimezone: true }),
|
||||
confirmedBy: text('confirmed_by'),
|
||||
notes: text('notes'),
|
||||
},
|
||||
(table) => [
|
||||
primaryKey({ columns: [table.interestId, table.criterionKey] }),
|
||||
index('idx_interest_qualifications_interest').on(table.interestId),
|
||||
],
|
||||
);
|
||||
|
||||
/**
|
||||
* Payment records. The CRM does NOT generate invoices — clients pay banks
|
||||
* directly. We record that money was received (or refunded) with an
|
||||
* optional uploaded receipt for audit purposes.
|
||||
*
|
||||
* The "deposit_paid" stage auto-advances when SUM(payments where type=deposit)
|
||||
* for an interest reaches the `interests.depositExpectedAmount`.
|
||||
*/
|
||||
export const payments = pgTable(
|
||||
'payments',
|
||||
{
|
||||
id: text('id')
|
||||
.primaryKey()
|
||||
.$defaultFn(() => crypto.randomUUID()),
|
||||
portId: text('port_id')
|
||||
.notNull()
|
||||
.references(() => ports.id, { onDelete: 'cascade' }),
|
||||
interestId: text('interest_id')
|
||||
.notNull()
|
||||
.references(() => interests.id, { onDelete: 'cascade' }),
|
||||
clientId: text('client_id')
|
||||
.notNull()
|
||||
.references(() => clients.id, { onDelete: 'cascade' }),
|
||||
/** 'deposit' | 'balance' | 'refund' | 'other' — `refund` rows carry
|
||||
* negative amounts so the running total nets out correctly. */
|
||||
paymentType: text('payment_type').notNull(),
|
||||
amount: numeric('amount').notNull(),
|
||||
currency: text('currency').notNull().default('EUR'),
|
||||
receivedAt: timestamp('received_at', { withTimezone: true }).notNull(),
|
||||
/** Optional uploaded receipt PDF. The UI warns reps that recording
|
||||
* without a receipt may make later verification harder, but doesn't
|
||||
* block the save. */
|
||||
receiptFileId: text('receipt_file_id').references(() => files.id),
|
||||
notes: text('notes'),
|
||||
recordedBy: text('recorded_by').notNull(),
|
||||
createdAt: timestamp('created_at', { withTimezone: true }).notNull().defaultNow(),
|
||||
},
|
||||
(table) => [
|
||||
index('idx_payments_interest').on(table.interestId),
|
||||
index('idx_payments_client').on(table.clientId),
|
||||
index('idx_payments_port').on(table.portId),
|
||||
index('idx_payments_type').on(table.portId, table.paymentType),
|
||||
],
|
||||
);
|
||||
|
||||
export type QualificationCriterion = typeof qualificationCriteria.$inferSelect;
|
||||
export type NewQualificationCriterion = typeof qualificationCriteria.$inferInsert;
|
||||
export type InterestQualification = typeof interestQualifications.$inferSelect;
|
||||
export type NewInterestQualification = typeof interestQualifications.$inferInsert;
|
||||
export type Payment = typeof payments.$inferSelect;
|
||||
export type NewPayment = typeof payments.$inferInsert;
|
||||
@@ -828,15 +828,13 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
berthIdx: number | null;
|
||||
yachtIdx: number | null;
|
||||
pipelineStage:
|
||||
| 'open'
|
||||
| 'details_sent'
|
||||
| 'in_communication'
|
||||
| 'eoi_sent'
|
||||
| 'eoi_signed'
|
||||
| 'deposit_10pct'
|
||||
| 'contract_sent'
|
||||
| 'contract_signed'
|
||||
| 'completed';
|
||||
| 'enquiry'
|
||||
| 'qualified'
|
||||
| 'nurturing'
|
||||
| 'eoi'
|
||||
| 'reservation'
|
||||
| 'deposit_paid'
|
||||
| 'contract';
|
||||
leadCategory: 'general_interest' | 'specific_qualified' | 'hot_lead';
|
||||
source: 'website' | 'manual' | 'referral' | 'broker';
|
||||
daysAgoFirst: number;
|
||||
@@ -846,7 +844,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 0,
|
||||
berthIdx: 0,
|
||||
yachtIdx: 0,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
leadCategory: 'general_interest',
|
||||
source: 'website',
|
||||
daysAgoFirst: 5,
|
||||
@@ -855,7 +853,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 1,
|
||||
berthIdx: 1,
|
||||
yachtIdx: 1,
|
||||
pipelineStage: 'details_sent',
|
||||
pipelineStage: 'qualified',
|
||||
leadCategory: 'general_interest',
|
||||
source: 'website',
|
||||
daysAgoFirst: 12,
|
||||
@@ -864,7 +862,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 2,
|
||||
berthIdx: 2,
|
||||
yachtIdx: 2,
|
||||
pipelineStage: 'in_communication',
|
||||
pipelineStage: 'qualified',
|
||||
leadCategory: 'specific_qualified',
|
||||
source: 'referral',
|
||||
daysAgoFirst: 25,
|
||||
@@ -873,7 +871,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 3,
|
||||
berthIdx: 3,
|
||||
yachtIdx: 6,
|
||||
pipelineStage: 'eoi_sent',
|
||||
pipelineStage: 'eoi',
|
||||
leadCategory: 'specific_qualified',
|
||||
source: 'referral',
|
||||
daysAgoFirst: 40,
|
||||
@@ -882,7 +880,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 4,
|
||||
berthIdx: 4,
|
||||
yachtIdx: null,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
leadCategory: 'general_interest',
|
||||
source: 'broker',
|
||||
daysAgoFirst: 8,
|
||||
@@ -891,7 +889,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 5,
|
||||
berthIdx: 5,
|
||||
yachtIdx: 3,
|
||||
pipelineStage: 'eoi_signed',
|
||||
pipelineStage: 'eoi',
|
||||
leadCategory: 'hot_lead',
|
||||
source: 'manual',
|
||||
daysAgoFirst: 55,
|
||||
@@ -900,7 +898,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 6,
|
||||
berthIdx: 6,
|
||||
yachtIdx: 4,
|
||||
pipelineStage: 'deposit_10pct',
|
||||
pipelineStage: 'deposit_paid',
|
||||
leadCategory: 'hot_lead',
|
||||
source: 'referral',
|
||||
daysAgoFirst: 70,
|
||||
@@ -909,7 +907,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 0,
|
||||
berthIdx: 7,
|
||||
yachtIdx: 5,
|
||||
pipelineStage: 'contract_signed',
|
||||
pipelineStage: 'contract',
|
||||
leadCategory: 'hot_lead',
|
||||
source: 'broker',
|
||||
daysAgoFirst: 90,
|
||||
@@ -918,7 +916,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 1,
|
||||
berthIdx: 10,
|
||||
yachtIdx: 1,
|
||||
pipelineStage: 'completed',
|
||||
pipelineStage: 'contract',
|
||||
leadCategory: 'hot_lead',
|
||||
source: 'referral',
|
||||
daysAgoFirst: 240,
|
||||
@@ -927,7 +925,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 7,
|
||||
berthIdx: 11,
|
||||
yachtIdx: 11,
|
||||
pipelineStage: 'completed',
|
||||
pipelineStage: 'contract',
|
||||
leadCategory: 'hot_lead',
|
||||
source: 'manual',
|
||||
daysAgoFirst: 320,
|
||||
@@ -936,7 +934,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 2,
|
||||
berthIdx: null,
|
||||
yachtIdx: null,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
leadCategory: 'general_interest',
|
||||
source: 'website',
|
||||
daysAgoFirst: 3,
|
||||
@@ -945,7 +943,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 3,
|
||||
berthIdx: 8,
|
||||
yachtIdx: 6,
|
||||
pipelineStage: 'in_communication',
|
||||
pipelineStage: 'qualified',
|
||||
leadCategory: 'specific_qualified',
|
||||
source: 'website',
|
||||
daysAgoFirst: 18,
|
||||
@@ -954,7 +952,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 5,
|
||||
berthIdx: null,
|
||||
yachtIdx: 3,
|
||||
pipelineStage: 'details_sent',
|
||||
pipelineStage: 'qualified',
|
||||
leadCategory: 'general_interest',
|
||||
source: 'referral',
|
||||
daysAgoFirst: 10,
|
||||
@@ -964,7 +962,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 4,
|
||||
berthIdx: 2,
|
||||
yachtIdx: null,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
leadCategory: 'general_interest',
|
||||
source: 'website',
|
||||
daysAgoFirst: 180,
|
||||
@@ -974,7 +972,7 @@ export async function seedPortData(portId: string, portSlug: string): Promise<Se
|
||||
clientIdx: 6,
|
||||
berthIdx: 9,
|
||||
yachtIdx: 4,
|
||||
pipelineStage: 'eoi_sent',
|
||||
pipelineStage: 'eoi',
|
||||
leadCategory: 'specific_qualified',
|
||||
source: 'broker',
|
||||
daysAgoFirst: 45,
|
||||
|
||||
@@ -100,9 +100,14 @@ interface SyntheticClientSpec {
|
||||
postalCode: string;
|
||||
/** Pipeline stage of the (single) interest. Omit for archived-only clients. */
|
||||
stage?: PipelineStage;
|
||||
/** Sub-status badges for the doc-signing stages (eoi / reservation / contract).
|
||||
* Only meaningful when stage matches; otherwise null/undefined. */
|
||||
eoiDocStatus?: 'sent' | 'signed';
|
||||
reservationDocStatus?: 'sent' | 'signed';
|
||||
contractDocStatus?: 'sent' | 'signed';
|
||||
/** Index into BERTH_SNAPSHOT for the primary linked berth. */
|
||||
berthIdx?: number;
|
||||
/** Mark interest as won/lost when stage = completed. */
|
||||
/** Mark interest as won/lost when stage = contract+signed. */
|
||||
outcome?: 'won' | 'lost_unqualified' | 'lost_no_response';
|
||||
/** Archive the CLIENT after creation. When 'rich', fabricate
|
||||
* archive_metadata so the smart-restore wizard surfaces reversals. */
|
||||
@@ -145,7 +150,7 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'London',
|
||||
street: '14 Cheyne Walk',
|
||||
postalCode: 'SW3 5RA',
|
||||
stage: 'open',
|
||||
stage: 'enquiry',
|
||||
source: 'website',
|
||||
createdDaysAgo: 4,
|
||||
// Open stage: no berth link yet
|
||||
@@ -159,7 +164,7 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'Miami',
|
||||
street: '880 Brickell Bay Drive',
|
||||
postalCode: '33131',
|
||||
stage: 'details_sent',
|
||||
stage: 'enquiry',
|
||||
berthIdx: 0,
|
||||
source: 'broker',
|
||||
createdDaysAgo: 12,
|
||||
@@ -173,7 +178,7 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'Palma de Mallorca',
|
||||
street: 'Carrer de Sant Magí 23',
|
||||
postalCode: '07013',
|
||||
stage: 'in_communication',
|
||||
stage: 'qualified',
|
||||
berthIdx: 5,
|
||||
source: 'referral',
|
||||
createdDaysAgo: 28,
|
||||
@@ -187,7 +192,8 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'Genoa',
|
||||
street: 'Via XX Settembre 47',
|
||||
postalCode: '16121',
|
||||
stage: 'eoi_sent',
|
||||
stage: 'eoi',
|
||||
eoiDocStatus: 'sent',
|
||||
berthIdx: 6,
|
||||
source: 'broker',
|
||||
createdDaysAgo: 45,
|
||||
@@ -201,7 +207,8 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'Nice',
|
||||
street: '8 Promenade des Anglais',
|
||||
postalCode: '06000',
|
||||
stage: 'eoi_signed',
|
||||
stage: 'eoi',
|
||||
eoiDocStatus: 'signed',
|
||||
berthIdx: 7,
|
||||
source: 'website',
|
||||
createdDaysAgo: 72,
|
||||
@@ -215,7 +222,7 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'Athens',
|
||||
street: 'Vouliagmenis Avenue 142',
|
||||
postalCode: '16674',
|
||||
stage: 'deposit_10pct',
|
||||
stage: 'deposit_paid',
|
||||
berthIdx: 8,
|
||||
source: 'referral',
|
||||
createdDaysAgo: 95,
|
||||
@@ -229,7 +236,8 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'Dublin',
|
||||
street: '12 Merrion Square North',
|
||||
postalCode: 'D02 E2X3',
|
||||
stage: 'contract_sent',
|
||||
stage: 'contract',
|
||||
contractDocStatus: 'sent',
|
||||
berthIdx: 9,
|
||||
source: 'manual',
|
||||
createdDaysAgo: 118,
|
||||
@@ -243,7 +251,8 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'Lisbon',
|
||||
street: 'Rua Garrett 88',
|
||||
postalCode: '1200-205',
|
||||
stage: 'contract_signed',
|
||||
stage: 'contract',
|
||||
contractDocStatus: 'signed',
|
||||
berthIdx: 4,
|
||||
source: 'broker',
|
||||
createdDaysAgo: 156,
|
||||
@@ -257,7 +266,8 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'Panama City',
|
||||
street: 'Calle 50, Torre Banistmo Piso 18',
|
||||
postalCode: '0816',
|
||||
stage: 'completed',
|
||||
stage: 'contract',
|
||||
contractDocStatus: 'signed',
|
||||
berthIdx: 10,
|
||||
outcome: 'won',
|
||||
source: 'referral',
|
||||
@@ -272,7 +282,7 @@ const PIPELINE_CLIENTS: SyntheticClientSpec[] = [
|
||||
city: 'Hamburg',
|
||||
street: 'Alsterufer 28',
|
||||
postalCode: '20354',
|
||||
stage: 'completed',
|
||||
stage: 'enquiry',
|
||||
berthIdx: 1,
|
||||
outcome: 'lost_unqualified',
|
||||
source: 'website',
|
||||
@@ -552,19 +562,21 @@ export async function seedSyntheticPortData(
|
||||
|
||||
// ── 6. Berth status overrides for linked moorings ───────────────────────
|
||||
// Match the dossier classification to the berth's pipeline stage.
|
||||
// For under_offer-wave clients (eoi_sent → contract_sent), force the
|
||||
// berth to under_offer. For completed-won, mark the berth sold.
|
||||
// Sold = contract+signed+won. Under offer = active berth-bearing stages
|
||||
// (eoi / reservation / deposit_paid / contract-not-yet-won).
|
||||
const stageToBerthStatus = (
|
||||
stage: PipelineStage | undefined,
|
||||
spec: SyntheticClientSpec,
|
||||
): 'available' | 'under_offer' | 'sold' | null => {
|
||||
const stage = spec.stage;
|
||||
if (!stage) return null;
|
||||
if (stage === 'completed') return 'sold';
|
||||
if (stage === 'contract' && spec.contractDocStatus === 'signed' && spec.outcome === 'won') {
|
||||
return 'sold';
|
||||
}
|
||||
if (
|
||||
stage === 'eoi_sent' ||
|
||||
stage === 'eoi_signed' ||
|
||||
stage === 'deposit_10pct' ||
|
||||
stage === 'contract_sent' ||
|
||||
stage === 'contract_signed'
|
||||
stage === 'eoi' ||
|
||||
stage === 'reservation' ||
|
||||
stage === 'deposit_paid' ||
|
||||
stage === 'contract'
|
||||
) {
|
||||
return 'under_offer';
|
||||
}
|
||||
@@ -573,7 +585,7 @@ export async function seedSyntheticPortData(
|
||||
|
||||
for (const spec of PIPELINE_CLIENTS) {
|
||||
if (spec.berthIdx === undefined) continue;
|
||||
const newStatus = stageToBerthStatus(spec.stage);
|
||||
const newStatus = stageToBerthStatus(spec);
|
||||
if (!newStatus) continue;
|
||||
const berthId = berthRows[spec.berthIdx]!.id;
|
||||
await tx.update(berths).set({ status: newStatus }).where(eq(berths.id, berthId));
|
||||
@@ -584,20 +596,33 @@ export async function seedSyntheticPortData(
|
||||
for (const spec of PIPELINE_CLIENTS) {
|
||||
if (!spec.stage) continue;
|
||||
const clientId = idByTag.get(spec.tag)!;
|
||||
// Derive deal age from the (stage, doc-sub-status) pair so a
|
||||
// contract+signed+won record looks older than a brand-new enquiry.
|
||||
const stageDaysAgoMap: Record<PipelineStage, number> = {
|
||||
open: 1,
|
||||
details_sent: 5,
|
||||
in_communication: 10,
|
||||
eoi_sent: 20,
|
||||
eoi_signed: 35,
|
||||
deposit_10pct: 60,
|
||||
contract_sent: 80,
|
||||
contract_signed: 110,
|
||||
completed: spec.outcome === 'won' ? 200 : 60,
|
||||
enquiry: 5,
|
||||
qualified: 10,
|
||||
nurturing: 30,
|
||||
eoi: spec.eoiDocStatus === 'signed' ? 35 : 20,
|
||||
reservation: 50,
|
||||
deposit_paid: 60,
|
||||
contract: spec.outcome === 'won' ? 200 : spec.contractDocStatus === 'signed' ? 110 : 80,
|
||||
};
|
||||
const ageDays = stageDaysAgoMap[spec.stage];
|
||||
const yachtId = spec.tag === 'completed-won' ? charterYachtRow[0]!.id : null;
|
||||
|
||||
// Stage-progression flags so the date_* timestamps cascade correctly.
|
||||
// Anything past "eoi+sent" implies the EOI was at least sent.
|
||||
const eoiReached =
|
||||
spec.stage === 'eoi' ||
|
||||
spec.stage === 'reservation' ||
|
||||
spec.stage === 'deposit_paid' ||
|
||||
spec.stage === 'contract';
|
||||
const eoiSigned =
|
||||
(spec.stage === 'eoi' && spec.eoiDocStatus === 'signed') ||
|
||||
spec.stage === 'reservation' ||
|
||||
spec.stage === 'deposit_paid' ||
|
||||
spec.stage === 'contract';
|
||||
|
||||
const [intRow] = await tx
|
||||
.insert(interests)
|
||||
.values({
|
||||
@@ -605,40 +630,24 @@ export async function seedSyntheticPortData(
|
||||
clientId,
|
||||
yachtId,
|
||||
pipelineStage: spec.stage,
|
||||
eoiDocStatus: spec.eoiDocStatus ?? (eoiSigned ? 'signed' : null),
|
||||
reservationDocStatus: spec.reservationDocStatus ?? null,
|
||||
contractDocStatus: spec.contractDocStatus ?? null,
|
||||
leadCategory:
|
||||
spec.stage === 'open'
|
||||
spec.stage === 'enquiry'
|
||||
? 'general_interest'
|
||||
: spec.stage === 'details_sent' || spec.stage === 'in_communication'
|
||||
: spec.stage === 'qualified' || spec.stage === 'nurturing'
|
||||
? 'specific_qualified'
|
||||
: 'hot_lead',
|
||||
source: 'manual' as const,
|
||||
dateFirstContact: daysAgo(ageDays),
|
||||
dateLastContact: daysAgo(Math.max(0, ageDays - 2)),
|
||||
dateEoiSent:
|
||||
spec.stage === 'eoi_sent' ||
|
||||
spec.stage === 'eoi_signed' ||
|
||||
spec.stage === 'deposit_10pct' ||
|
||||
spec.stage === 'contract_sent' ||
|
||||
spec.stage === 'contract_signed' ||
|
||||
spec.stage === 'completed'
|
||||
? daysAgo(Math.max(0, ageDays - 5))
|
||||
: null,
|
||||
dateEoiSigned:
|
||||
spec.stage === 'eoi_signed' ||
|
||||
spec.stage === 'deposit_10pct' ||
|
||||
spec.stage === 'contract_sent' ||
|
||||
spec.stage === 'contract_signed' ||
|
||||
spec.stage === 'completed'
|
||||
? daysAgo(Math.max(0, ageDays - 10))
|
||||
: null,
|
||||
dateEoiSent: eoiReached ? daysAgo(Math.max(0, ageDays - 5)) : null,
|
||||
dateEoiSigned: eoiSigned ? daysAgo(Math.max(0, ageDays - 10)) : null,
|
||||
eoiStatus:
|
||||
spec.stage === 'eoi_sent'
|
||||
spec.stage === 'eoi' && spec.eoiDocStatus === 'sent'
|
||||
? 'waiting_for_signatures'
|
||||
: spec.stage === 'eoi_signed' ||
|
||||
spec.stage === 'deposit_10pct' ||
|
||||
spec.stage === 'contract_sent' ||
|
||||
spec.stage === 'contract_signed' ||
|
||||
spec.stage === 'completed'
|
||||
: eoiSigned
|
||||
? 'signed'
|
||||
: null,
|
||||
outcome: spec.outcome ?? null,
|
||||
@@ -656,7 +665,7 @@ export async function seedSyntheticPortData(
|
||||
berthId,
|
||||
isPrimary: true,
|
||||
isSpecificInterest: true,
|
||||
isInEoiBundle: spec.stage !== 'open' && spec.stage !== 'details_sent',
|
||||
isInEoiBundle: spec.stage !== 'enquiry' && spec.stage !== 'qualified',
|
||||
addedBy: SUPER_ADMIN_USER_ID,
|
||||
});
|
||||
}
|
||||
@@ -672,7 +681,7 @@ export async function seedSyntheticPortData(
|
||||
portId,
|
||||
clientId: carlaId,
|
||||
yachtId: null,
|
||||
pipelineStage: 'open',
|
||||
pipelineStage: 'enquiry',
|
||||
leadCategory: 'general_interest',
|
||||
source: 'website' as const,
|
||||
dateFirstContact: daysAgo(2),
|
||||
|
||||
@@ -187,9 +187,9 @@ export async function seedWideSyntheticPortData(
|
||||
yachtId: null,
|
||||
pipelineStage: stage,
|
||||
leadCategory:
|
||||
stage === 'open'
|
||||
stage === 'enquiry'
|
||||
? 'general_interest'
|
||||
: stage === 'details_sent' || stage === 'in_communication'
|
||||
: stage === 'qualified' || stage === 'nurturing'
|
||||
? 'specific_qualified'
|
||||
: 'hot_lead',
|
||||
source: sourceChoice.source,
|
||||
|
||||
@@ -25,8 +25,9 @@ export async function withTransaction<T>(callback: (tx: typeof db) => Promise<T>
|
||||
}
|
||||
|
||||
/**
|
||||
* Soft-deletes a record by setting `archived_at` to now.
|
||||
* The table must have an `archived_at` column.
|
||||
* Soft-deletes a record by setting `archivedAt` to now.
|
||||
* The table must have an `archivedAt` JS property mapping to the
|
||||
* `archived_at` column.
|
||||
*
|
||||
* @example
|
||||
* await softDelete(clients, clients.id, clientId);
|
||||
@@ -36,15 +37,22 @@ export async function softDelete<TTable extends PgTable>(
|
||||
idColumn: PgColumn,
|
||||
id: string,
|
||||
): Promise<void> {
|
||||
// Drizzle's `.set()` API expects the JS property name (`archivedAt`),
|
||||
// not the snake-case column name. The previous version passed
|
||||
// `{ archived_at: ... }` which silently produced an empty SET clause
|
||||
// (Drizzle skipped the unknown property) → `UPDATE ... where ...`
|
||||
// syntax error from Postgres. Caught by QA: archive an interest
|
||||
// with a berth attached → 500. Same fix in restore() below.
|
||||
await db
|
||||
.update(table)
|
||||
.set({ archived_at: sql`now()` } as Record<string, unknown>)
|
||||
.set({ archivedAt: sql`now()` } as Record<string, unknown>)
|
||||
.where(eq(idColumn, id));
|
||||
}
|
||||
|
||||
/**
|
||||
* Restores a soft-deleted record by clearing `archived_at`.
|
||||
* The table must have an `archived_at` column.
|
||||
* Restores a soft-deleted record by clearing `archivedAt`.
|
||||
* The table must have an `archivedAt` JS property mapping to the
|
||||
* `archived_at` column.
|
||||
*
|
||||
* @example
|
||||
* await restore(clients, clients.id, clientId);
|
||||
@@ -56,6 +64,6 @@ export async function restore<TTable extends PgTable>(
|
||||
): Promise<void> {
|
||||
await db
|
||||
.update(table)
|
||||
.set({ archived_at: null } as Record<string, unknown>)
|
||||
.set({ archivedAt: null } as Record<string, unknown>)
|
||||
.where(eq(idColumn, id));
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user