Files
pn-new-crm/src/lib/services/active-interest.ts
Matt b966d8106d feat(active-interest): canonical predicate + fix stale getHotDeals rank
Extract activeInterestsWhere(portId) as the single source of truth for
"active interest" SQL filtering: scoped + archived_at IS NULL + outcome
IS NULL. Won deals are now CLOSED, not active — pre-2026-05-14 the
dashboard used a permissive `outcome IS NULL OR outcome = 'won'` that
double-counted won revenue against the in-flight pipeline.

Locked in PRE-DEPLOY-PLAN § 1.1.2.

Bonus catch: getHotDeals rank-CASE referenced the OLD 9-stage pipeline
names ('completed', 'contract_signed', 'contract_sent', 'deposit_10pct',
'eoi_signed', 'eoi_sent', 'in_communication', 'details_sent'). Every
row hit the ELSE 0 branch under the new 7-stage model, collapsing
ordering to updatedAt only — the widget silently stopped surfacing
"closest to closing". Rebuilt the rank ladder against the current
canonical stages (enquiry → ... → contract).

Tests: 2 unit tests assert the predicate's compiled SQL contains
"archived_at" IS NULL + "outcome" IS NULL, and never the legacy 'won'
literal.

Remaining sweep targets queued for the next commit:
- client-archive-dossier.service.ts
- client-restore.service.ts
- client-archive.service.ts
- reminders.service.ts
- berths.service.ts (recommender feasibility)
- interests.service.ts
- report-generators.ts

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 14:53:58 +02:00

36 lines
1.4 KiB
TypeScript

import { and, eq, isNull, type SQL } from 'drizzle-orm';
import { interests } from '@/lib/db/schema/interests';
/**
* Canonical "active interest" predicate for SQL WHERE clauses.
*
* An interest is **active** when it is:
* - scoped to the given `portId`,
* - not soft-archived (`archived_at IS NULL`), and
* - not yet terminal (`outcome IS NULL` — i.e. not won, lost, or
* cancelled).
*
* "Won" deals are explicitly **not active** under this definition: a won
* deal is closed business, distinct from in-flight pipeline. The 7-stage
* pipeline carries deals through `contract` as the final motion stage;
* setting an `outcome` (won/lost/cancelled) terminates the deal and
* removes it from the active pool everywhere KPIs, kanban, hot deals,
* pipeline value, and revenue forecast are computed.
*
* Pre-2026-05-14 the dashboard used a broader `outcome IS NULL OR
* outcome = 'won'` predicate; the new pipeline overhaul collapsed
* intermediate completion states into explicit stages, making the
* stricter definition the correct one across every surface.
*
* Always combine with the table's own filters; this helper is a leaf
* predicate, not a complete WHERE.
*/
export function activeInterestsWhere(portId: string): SQL {
return and(
eq(interests.portId, portId),
isNull(interests.archivedAt),
isNull(interests.outcome),
) as SQL;
}