feat(alerts): split interest.stale into worked-then-quiet + new-untouched (interest.no_activity)

- interest.stale now fires only for interests with real in-system follow-up
  (contact log / note / update audit) that went quiet 14+ days.
- new interest.no_activity rule covers never-touched, non-imported interests.
- guard interest.high_value_silent against imported-untouched hot leads.
- keys off migration_source_links ledger to identify the bulk import, so the
  imported backlog matches neither rule and the engine auto-resolves the flood.
- test teardown: delete interest_contact_log + test migration ledger rows.

Co-Authored-By: Claude Fable 5 <noreply@anthropic.com>
This commit is contained in:
2026-06-17 17:49:22 +02:00
parent 7591231c47
commit 13efe177a5
4 changed files with 208 additions and 33 deletions

View File

@@ -47,6 +47,7 @@ export async function teardown() {
, del_files AS (DELETE FROM files WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_ft AS (DELETE FROM form_templates WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_gr AS (DELETE FROM generated_reports WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_icl AS (DELETE FROM interest_contact_log WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_int AS (DELETE FROM interests WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
, del_ib AS (DELETE FROM interest_berths WHERE berth_id IN (SELECT id FROM berths WHERE port_id IN (SELECT id FROM doomed)) RETURNING 1)
, del_inv AS (DELETE FROM invoices WHERE port_id IN (SELECT id FROM doomed) RETURNING 1)
@@ -69,5 +70,8 @@ export async function teardown() {
, del_ports AS (DELETE FROM ports WHERE id IN (SELECT id FROM doomed) RETURNING 1)
SELECT 1
`);
// migration_source_links has no port_id FK; purge test-only ledger rows by
// the marker applied_id our alert tests use.
await db.execute(sql`DELETE FROM migration_source_links WHERE applied_id = 'test-apply'`);
await closeDb();
}

View File

@@ -18,6 +18,8 @@ import { alerts } from '@/lib/db/schema/insights';
import { interests } from '@/lib/db/schema/interests';
import { berthTenancies } from '@/lib/db/schema/tenancies';
import { documents } from '@/lib/db/schema/documents';
import { interestContactLog } from '@/lib/db/schema/operations';
import { migrationSourceLinks } from '@/lib/db/schema/migration';
import { runAlertEngineForPorts } from '@/lib/services/alert-engine';
import { makePort, makeClient, makeBerth, makeYacht } from '../helpers/factories';
@@ -32,6 +34,30 @@ async function listOpenAlerts(portId: string, ruleId: string) {
.where(and(eq(alerts.portId, portId), eq(alerts.ruleId, ruleId), isNull(alerts.resolvedAt)));
}
/** Mark an interest as bulk-imported via the migration ledger. */
async function markImported(interestId: string) {
await db.insert(migrationSourceLinks).values({
sourceSystem: 'nocodb_interests',
sourceId: `legacy-${interestId}`,
targetEntityType: 'interest',
targetEntityId: interestId,
appliedId: 'test-apply',
});
}
/** A genuine in-system follow-up: a logged contact at `occurredAt`. */
async function logContact(portId: string, interestId: string, occurredAt: Date) {
await db.insert(interestContactLog).values({
portId,
interestId,
occurredAt,
channel: 'phone',
direction: 'outbound',
summary: 'Test follow-up',
createdBy: 'seed',
});
}
describe('alert engine', () => {
beforeEach(() => {
vi.clearAllMocks();
@@ -149,7 +175,7 @@ describe('alert engine', () => {
expect(allRows[0]!.resolvedAt).not.toBeNull();
});
it('interest.stale fires for old leads in mid-funnel stages', async () => {
it('interest.stale fires for worked leads gone quiet >14d', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
const stale = new Date(Date.now() - 30 * 86_400_000);
@@ -164,6 +190,9 @@ describe('alert engine', () => {
updatedAt: stale,
})
.returning();
// A real in-system follow-up 30 days ago → this is a worked-then-quiet lead,
// not an untouched import.
await logContact(port.id, interest!.id, stale);
await clearAlerts(port.id);
await runAlertEngineForPorts([port.id]);
@@ -172,6 +201,60 @@ describe('alert engine', () => {
expect(open).toHaveLength(1);
expect(open[0]!.entityId).toBe(interest!.id);
expect(open[0]!.severity).toBe('info');
// A worked lead must not also fire the new-untouched rule.
expect(await listOpenAlerts(port.id, 'interest.no_activity')).toHaveLength(0);
});
it('interest.stale does NOT fire for imported, never-touched interests', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
const migrationTime = new Date(Date.now() - 20 * 86_400_000);
const legacyDate = new Date(Date.now() - 3 * 365 * 86_400_000); // ~3yr back-dated
const [interest] = await db
.insert(interests)
.values({
portId: port.id,
clientId: client.id,
pipelineStage: 'qualified',
dateLastContact: legacyDate, // back-dated by the migration
createdAt: migrationTime,
updatedAt: migrationTime,
})
.returning();
await markImported(interest!.id);
await clearAlerts(port.id);
await runAlertEngineForPorts([port.id]);
// Imported + never touched in-system → neither interest rule should fire.
expect(await listOpenAlerts(port.id, 'interest.stale')).toHaveLength(0);
expect(await listOpenAlerts(port.id, 'interest.no_activity')).toHaveLength(0);
});
it('interest.no_activity fires for new, non-imported, untouched interests >14d old', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
const created = new Date(Date.now() - 20 * 86_400_000);
const [interest] = await db
.insert(interests)
.values({
portId: port.id,
clientId: client.id,
pipelineStage: 'enquiry',
dateLastContact: null,
createdAt: created,
updatedAt: created,
})
.returning();
await clearAlerts(port.id);
await runAlertEngineForPorts([port.id]);
const open = await listOpenAlerts(port.id, 'interest.no_activity');
expect(open).toHaveLength(1);
expect(open[0]!.entityId).toBe(interest!.id);
expect(open[0]!.severity).toBe('info');
expect(await listOpenAlerts(port.id, 'interest.stale')).toHaveLength(0);
});
it('interest.high_value_silent fires for hot leads silent >7d', async () => {
@@ -195,6 +278,31 @@ describe('alert engine', () => {
expect(open[0]!.severity).toBe('critical');
});
it('interest.high_value_silent skips imported, never-touched hot leads', async () => {
const port = await makePort();
const client = await makeClient({ portId: port.id });
const migrationTime = new Date(Date.now() - 20 * 86_400_000);
const legacyDate = new Date(Date.now() - 3 * 365 * 86_400_000);
const [interest] = await db
.insert(interests)
.values({
portId: port.id,
clientId: client.id,
pipelineStage: 'qualified',
leadCategory: 'hot_lead',
dateLastContact: legacyDate,
createdAt: migrationTime,
updatedAt: migrationTime,
})
.returning();
await markImported(interest!.id);
await clearAlerts(port.id);
await runAlertEngineForPorts([port.id]);
expect(await listOpenAlerts(port.id, 'interest.high_value_silent')).toHaveLength(0);
});
it('engine reports rule errors without crashing the sweep', async () => {
const port = await makePort();
const summary = await runAlertEngineForPorts([port.id]);