refactor(interests): migrate callers to interest_berths junction + drop berth_id
Phase 2b of the berth-recommender refactor (plan §3.4). Every caller of the legacy `interests.berth_id` column now reads / writes through the `interest_berths` junction via the helper service introduced in Phase 2a; the column itself is dropped in a final migration. Service-layer changes - interests.service: filter `?berthId=X` becomes EXISTS-against-junction; list enrichment uses `getPrimaryBerthsForInterests`; create/update/ linkBerth/unlinkBerth all dispatch through the junction helpers, with createInterest's row insert + junction write sharing a single transaction. - clients / dashboard / report-generators / search: leftJoin chains pivot through `interest_berths` filtered by `is_primary=true`. - eoi-context / document-templates / berth-rules-engine / portal / record-export / queue worker: read primary via `getPrimaryBerth(...)`. - interest-scoring: berthLinked is now derived from any junction row count. - dedup/migration-apply + public interest route: write a primary junction row alongside the interest insert when a berth is provided. API contract preserved: list/detail responses still emit `berthId` and `berthMooringNumber`, derived from the primary junction row, so frontend consumers (interest-form, interest-detail-header) need no changes. Schema + migration - Drop `interestsRelations.berth` and `idx_interests_berth`. - Replace `berthsRelations.interests` with `interestBerths`. - Migration 0029_puzzling_romulus drops `interests.berth_id` + the index. - Tests that previously inserted `interests.berthId` now seed a primary junction row alongside the interest. Verified: vitest 995 passing (1 unrelated pre-existing flake in maintenance-cleanup.test.ts), tsc clean. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
@@ -11,7 +11,7 @@ import { eq } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import { clients, clientContacts, clientNotes, clientMergeLog } from '@/lib/db/schema/clients';
|
||||
import { interests } from '@/lib/db/schema/interests';
|
||||
import { interests, interestBerths } from '@/lib/db/schema/interests';
|
||||
import { mergeClients } from '@/lib/services/client-merge.service';
|
||||
import { makeClient, makePort, makeBerth } from '../../helpers/factories';
|
||||
|
||||
@@ -40,12 +40,20 @@ describe('mergeClients', () => {
|
||||
content: 'Loser-side note',
|
||||
});
|
||||
const berth = await makeBerth({ portId: port.id });
|
||||
await db.insert(interests).values({
|
||||
portId: port.id,
|
||||
clientId: loser.id,
|
||||
const [legacyInterest] = await db
|
||||
.insert(interests)
|
||||
.values({
|
||||
portId: port.id,
|
||||
clientId: loser.id,
|
||||
pipelineStage: 'open',
|
||||
leadCategory: 'general_interest',
|
||||
})
|
||||
.returning();
|
||||
await db.insert(interestBerths).values({
|
||||
interestId: legacyInterest!.id,
|
||||
berthId: berth.id,
|
||||
pipelineStage: 'open',
|
||||
leadCategory: 'general_interest',
|
||||
isPrimary: true,
|
||||
isSpecificInterest: true,
|
||||
});
|
||||
|
||||
// ── Merge ─────────────────────────────────────────────────────────────
|
||||
|
||||
@@ -3,7 +3,10 @@ import { beforeAll, describe, expect, it } from 'vitest';
|
||||
import { db } from '@/lib/db';
|
||||
import { documentTemplates } from '@/lib/db/schema/documents';
|
||||
import { clientAddresses, clientContacts, clients as clientsTable } from '@/lib/db/schema/clients';
|
||||
import { interests as interestsTable } from '@/lib/db/schema/interests';
|
||||
import {
|
||||
interests as interestsTable,
|
||||
interestBerths as interestBerthsTable,
|
||||
} from '@/lib/db/schema/interests';
|
||||
import { getMergeFields, resolveTemplate } from '@/lib/services/document-templates';
|
||||
|
||||
import { makeBerth, makeClient, makeCompany, makePort, makeYacht } from '../helpers/factories';
|
||||
@@ -44,12 +47,22 @@ async function insertInterest(args: {
|
||||
portId: args.portId,
|
||||
clientId: args.clientId,
|
||||
yachtId: args.yachtId ?? null,
|
||||
berthId: args.berthId ?? null,
|
||||
pipelineStage: args.pipelineStage ?? 'open',
|
||||
leadCategory: args.leadCategory ?? null,
|
||||
notes: args.notes ?? null,
|
||||
})
|
||||
.returning();
|
||||
// Plan §3.4: legacy interest.berth_id was replaced by the
|
||||
// interest_berths junction. Tests that pass berthId now materialise a
|
||||
// primary junction row alongside the interest.
|
||||
if (args.berthId) {
|
||||
await db.insert(interestBerthsTable).values({
|
||||
interestId: row!.id,
|
||||
berthId: args.berthId,
|
||||
isPrimary: true,
|
||||
isSpecificInterest: true,
|
||||
});
|
||||
}
|
||||
return row!;
|
||||
}
|
||||
|
||||
@@ -299,10 +312,15 @@ describe('resolveTemplate — company-owned yacht', () => {
|
||||
portId: port.id,
|
||||
clientId: client.id,
|
||||
yachtId: yacht.id,
|
||||
berthId: berth.id,
|
||||
pipelineStage: 'open',
|
||||
})
|
||||
.returning();
|
||||
await db.insert(interestBerthsTable).values({
|
||||
interestId: interest!.id,
|
||||
berthId: berth.id,
|
||||
isPrimary: true,
|
||||
isSpecificInterest: true,
|
||||
});
|
||||
|
||||
const [tmpl] = await db
|
||||
.insert(documentTemplates)
|
||||
@@ -385,11 +403,16 @@ describe('resolveTemplate — legacy fallback (no interestId)', () => {
|
||||
portId: port.id,
|
||||
clientId: client.id,
|
||||
yachtId: null,
|
||||
berthId: berth.id,
|
||||
pipelineStage: 'open',
|
||||
leadCategory: 'casual',
|
||||
})
|
||||
.returning();
|
||||
await db.insert(interestBerthsTable).values({
|
||||
interestId: interest!.id,
|
||||
berthId: berth.id,
|
||||
isPrimary: true,
|
||||
isSpecificInterest: true,
|
||||
});
|
||||
|
||||
const [tmpl] = await db
|
||||
.insert(documentTemplates)
|
||||
|
||||
@@ -5,7 +5,10 @@ import { eq } from 'drizzle-orm';
|
||||
import { db } from '@/lib/db';
|
||||
import { documents, documentTemplates } from '@/lib/db/schema/documents';
|
||||
import { clientAddresses, clientContacts } from '@/lib/db/schema/clients';
|
||||
import { interests as interestsTable } from '@/lib/db/schema/interests';
|
||||
import {
|
||||
interests as interestsTable,
|
||||
interestBerths as interestBerthsTable,
|
||||
} from '@/lib/db/schema/interests';
|
||||
import { ValidationError } from '@/lib/errors';
|
||||
|
||||
import { makeBerth, makeClient, makePort, makeYacht } from '../helpers/factories';
|
||||
@@ -82,10 +85,16 @@ async function insertInterest(args: {
|
||||
portId: args.portId,
|
||||
clientId: args.clientId,
|
||||
yachtId: args.yachtId,
|
||||
berthId: args.berthId,
|
||||
pipelineStage: 'open',
|
||||
})
|
||||
.returning();
|
||||
// Plan §3.4: legacy interests.berth_id replaced by the junction.
|
||||
await db.insert(interestBerthsTable).values({
|
||||
interestId: row!.id,
|
||||
berthId: args.berthId,
|
||||
isPrimary: true,
|
||||
isSpecificInterest: true,
|
||||
});
|
||||
return row!;
|
||||
}
|
||||
|
||||
|
||||
@@ -8,7 +8,7 @@ import { eq } from 'drizzle-orm';
|
||||
|
||||
import { db } from '@/lib/db';
|
||||
import { documents, documentEvents } from '@/lib/db/schema/documents';
|
||||
import { interests } from '@/lib/db/schema/interests';
|
||||
import { interests, interestBerths } from '@/lib/db/schema/interests';
|
||||
import { handleDocumentExpired } from '@/lib/services/documents.service';
|
||||
import { makeBerth, makeClient, makePort } from '../helpers/factories';
|
||||
|
||||
@@ -55,12 +55,17 @@ describe('handleDocumentExpired', () => {
|
||||
.values({
|
||||
portId: port.id,
|
||||
clientId: client.id,
|
||||
berthId: berth.id,
|
||||
pipelineStage: 'eoi_sent',
|
||||
leadCategory: 'hot_lead',
|
||||
eoiStatus: 'sent',
|
||||
})
|
||||
.returning();
|
||||
await db.insert(interestBerths).values({
|
||||
interestId: interest!.id,
|
||||
berthId: berth.id,
|
||||
isPrimary: true,
|
||||
isSpecificInterest: true,
|
||||
});
|
||||
|
||||
const documensoId = `documenso-test-${Date.now()}-i`;
|
||||
await db.insert(documents).values({
|
||||
|
||||
@@ -38,6 +38,7 @@ vi.mock('drizzle-orm', async (importOriginal) => {
|
||||
|
||||
vi.mock('@/lib/db/schema/interests', () => ({
|
||||
interests: {},
|
||||
interestBerths: {},
|
||||
interestNotes: {},
|
||||
}));
|
||||
|
||||
@@ -69,6 +70,26 @@ function makeSelectChain(countValue: number) {
|
||||
return chain;
|
||||
}
|
||||
|
||||
/**
|
||||
* Create a sequence of fake db.select chains so the four parallel queries
|
||||
* inside calculateInterestScore (notes / reminders / email / interest_berths)
|
||||
* can each be given a distinct count. Order matches the call order in the
|
||||
* service.
|
||||
*/
|
||||
function makeSelectChainSequence(counts: {
|
||||
notes: number;
|
||||
reminders: number;
|
||||
email: number;
|
||||
berthLinks: number;
|
||||
}) {
|
||||
const sequence = [counts.notes, counts.reminders, counts.email, counts.berthLinks];
|
||||
let i = 0;
|
||||
return () => {
|
||||
const value = sequence[i++] ?? 0;
|
||||
return makeSelectChain(value);
|
||||
};
|
||||
}
|
||||
|
||||
function daysAgo(days: number): Date {
|
||||
return new Date(Date.now() - days * 24 * 60 * 60 * 1000);
|
||||
}
|
||||
@@ -152,14 +173,17 @@ describe('calculateInterestScore', () => {
|
||||
berthId: 'berth-1',
|
||||
});
|
||||
|
||||
// High engagement: 5 notes, 3 emails, 2 reminders
|
||||
// High engagement: 5 notes, 3 emails, 2 reminders. The 4th query is the
|
||||
// interest_berths count (plan §3.4 - berthLinked is derived from any
|
||||
// junction row).
|
||||
const selectChain = {
|
||||
from: vi.fn().mockReturnThis(),
|
||||
where: vi
|
||||
.fn()
|
||||
.mockResolvedValueOnce([{ value: 5 }]) // notes
|
||||
.mockResolvedValueOnce([{ value: 2 }]) // reminders
|
||||
.mockResolvedValueOnce([{ value: 3 }]), // emails
|
||||
.mockResolvedValueOnce([{ value: 3 }]) // emails
|
||||
.mockResolvedValueOnce([{ value: 1 }]), // interest_berths (≥1 = linked)
|
||||
};
|
||||
(db.select as ReturnType<typeof vi.fn>).mockReturnValue(selectChain);
|
||||
|
||||
@@ -238,7 +262,11 @@ describe('calculateInterestScore', () => {
|
||||
expect(result.breakdown.documentCompleteness).toBe(30);
|
||||
});
|
||||
|
||||
it('berthLinked is 25 when berthId is set, 0 when null', async () => {
|
||||
it('berthLinked is 25 when interest_berths has any row, 0 when none', async () => {
|
||||
// After the M:M refactor (plan §3.4) "berth linked" is derived from
|
||||
// the interest_berths junction count rather than the legacy
|
||||
// interests.berth_id column. The score awards 25 for any junction
|
||||
// row, 0 for none.
|
||||
const base = {
|
||||
portId: 'p1',
|
||||
clientId: 'c1',
|
||||
@@ -252,22 +280,25 @@ describe('calculateInterestScore', () => {
|
||||
dateDepositReceived: null,
|
||||
};
|
||||
|
||||
const selectChain = makeSelectChain(0);
|
||||
(db.select as ReturnType<typeof vi.fn>).mockReturnValue(selectChain);
|
||||
|
||||
// ── With a junction row ─────────────────────────────────────────────────
|
||||
(db.select as ReturnType<typeof vi.fn>).mockImplementation(
|
||||
makeSelectChainSequence({ notes: 0, reminders: 0, email: 0, berthLinks: 1 }),
|
||||
);
|
||||
(db.query.interests.findFirst as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
...base,
|
||||
id: 'i6',
|
||||
berthId: 'b1',
|
||||
});
|
||||
const withBerth = await calculateInterestScore('i6', 'p1');
|
||||
expect(withBerth.breakdown.berthLinked).toBe(25);
|
||||
|
||||
// ── Without a junction row ──────────────────────────────────────────────
|
||||
(redis.get as ReturnType<typeof vi.fn>).mockResolvedValue(null);
|
||||
(db.select as ReturnType<typeof vi.fn>).mockImplementation(
|
||||
makeSelectChainSequence({ notes: 0, reminders: 0, email: 0, berthLinks: 0 }),
|
||||
);
|
||||
(db.query.interests.findFirst as ReturnType<typeof vi.fn>).mockResolvedValue({
|
||||
...base,
|
||||
id: 'i7',
|
||||
berthId: null,
|
||||
});
|
||||
const withoutBerth = await calculateInterestScore('i7', 'p1');
|
||||
expect(withoutBerth.breakdown.berthLinked).toBe(0);
|
||||
|
||||
@@ -3,7 +3,13 @@ import { describe, it, expect } from 'vitest';
|
||||
import { buildEoiContext } from '@/lib/services/eoi-context';
|
||||
import { makePort, makeClient, makeCompany, makeBerth, makeYacht } from '../../helpers/factories';
|
||||
import { db } from '@/lib/db';
|
||||
import { interests, clientContacts, clientAddresses, companyAddresses } from '@/lib/db/schema';
|
||||
import {
|
||||
interests,
|
||||
interestBerths,
|
||||
clientContacts,
|
||||
clientAddresses,
|
||||
companyAddresses,
|
||||
} from '@/lib/db/schema';
|
||||
import { ValidationError, NotFoundError } from '@/lib/errors';
|
||||
|
||||
// ─── Helpers ──────────────────────────────────────────────────────────────────
|
||||
@@ -21,10 +27,20 @@ async function insertInterest(args: {
|
||||
portId: args.portId,
|
||||
clientId: args.clientId,
|
||||
yachtId: args.yachtId ?? null,
|
||||
berthId: args.berthId ?? null,
|
||||
pipelineStage: args.pipelineStage ?? 'open',
|
||||
})
|
||||
.returning();
|
||||
// Plan §3.4: legacy interests.berth_id replaced by the junction. Tests
|
||||
// that pass berthId materialise a primary junction row alongside the
|
||||
// interest so getPrimaryBerth() resolves it during EOI context build.
|
||||
if (args.berthId) {
|
||||
await db.insert(interestBerths).values({
|
||||
interestId: row!.id,
|
||||
berthId: args.berthId,
|
||||
isPrimary: true,
|
||||
isSpecificInterest: true,
|
||||
});
|
||||
}
|
||||
return row!;
|
||||
}
|
||||
|
||||
|
||||
Reference in New Issue
Block a user