feat(post-audit): batch A+B quick-wins + audit-side residuals

Bundles the user-prioritised follow-ups from the post-audit punch-list.

Batch A — pipeline + EOI safety:
 - §1.1 timeline buildAuditDescription renders diff fields ("leadCategory → hot_lead").
 - §4.13 EOI rejection cascade: notification to assigned rep + audit row + rose banner.
 - §4.10b finish doc-detail: SigningProgress reuse, linked-entity names (server-resolved),
   per-event icons + tooltips + show-more in activity panel.
 - §7.2 stage guidance card replaces empty Payments slot pre-reservation.
 - §4.15 deal-pulse trigger audit (docs/deal-pulse-trigger-audit.md).

Batch B — UX consistency + docs:
 - §1.4 quick log-contact button on interest header.
 - §2.1 contact-log compose: Dialog → Sheet.
 - §7.1 docs/deal-pulse explainer page; /docs/ in PUBLIC_PATHS.
 - DocumentStatus now includes 'rejected' + 'declined' across constants, labels, tone maps.

Audit-side residuals:
 - M-NEW-1 /me/ports skips port-context requirement.
 - M-AU03 audit log CSV export endpoint + UI button.
 - M-IN03 dead receipt-scanner.ts deleted; live path already per-port.
 - M-P01 pg_trgm GIN indexes (migration 0071).
 - §10.1 webhook tests verified passing (was stale).

Deferred per user direction:
 - §11.3 email copy refactor (needs old-CRM reference).
 - M-EM03 IMAP bounce-to-interest linking.

Tests: 1374/1374. tsc + lint clean.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
This commit is contained in:
2026-05-18 14:22:11 +02:00
parent 4b5f85cb7d
commit 0f99f054b3
21 changed files with 1399 additions and 258 deletions

View File

@@ -0,0 +1,128 @@
import { NextResponse } from 'next/server';
import { withAuth, withPermission } from '@/lib/api/helpers';
import { errorResponse } from '@/lib/errors';
import { searchAuditLogs } from '@/lib/services/audit-search.service';
/**
* M-AU03 — CSV export of audit log search results.
*
* Accepts the same query-string filters as `GET /api/v1/admin/audit`
* (q, userId, action, entityType, entityId, severity, source, from, to)
* and streams up to 10 000 rows back as a CSV download. The 10k cap
* keeps the response under a couple of megabytes; reps wanting deeper
* history should narrow the filter or run multiple exports.
*
* Permission gate matches the read endpoint: `admin.view_audit_log`.
*/
export const GET = withAuth(
withPermission('admin', 'view_audit_log', async (req, ctx) => {
try {
const url = new URL(req.url);
const params = url.searchParams;
const parseDate = (v: string | null): Date | undefined => {
if (!v) return undefined;
const d = new Date(v);
return Number.isFinite(d.getTime()) ? d : undefined;
};
// Cap the export at 10 000 rows. Anyone needing deeper history
// can scroll through the paginated UI or narrow the date range.
const HARD_CAP = 10_000;
let collected: Awaited<ReturnType<typeof searchAuditLogs>>['rows'] = [];
let cursor: { createdAt: Date; id: string } | undefined;
// Run a small loop so we paginate through the cursor-based search
// service to fill up to HARD_CAP rows.
while (collected.length < HARD_CAP) {
const remaining = HARD_CAP - collected.length;
const page = await searchAuditLogs({
portId: ctx.portId,
q: params.get('q') ?? undefined,
userId: params.get('userId') ?? undefined,
action: params.get('action') ?? undefined,
entityType: params.get('entityType') ?? undefined,
entityId: params.get('entityId') ?? undefined,
severity: params.get('severity') ?? undefined,
source: params.get('source') ?? undefined,
from: parseDate(params.get('from')),
to: parseDate(params.get('to')),
limit: Math.min(remaining, 500),
cursor,
});
collected = collected.concat(page.rows);
if (!page.nextCursor) break;
cursor = page.nextCursor;
}
const csv = buildCsv(collected);
const filename = `audit-log-${new Date().toISOString().slice(0, 10)}.csv`;
return new NextResponse(csv, {
headers: {
'Content-Type': 'text/csv; charset=utf-8',
'Content-Disposition': `attachment; filename="${filename}"`,
},
});
} catch (error) {
return errorResponse(error);
}
}),
);
/**
* RFC 4180 CSV serializer. Escapes embedded quotes by doubling them and
* wraps any field containing comma / quote / newline in double-quotes.
* Trailing CRLF terminator per spec.
*/
function buildCsv(rows: Awaited<ReturnType<typeof searchAuditLogs>>['rows']): string {
const headers = [
'createdAt',
'id',
'portId',
'userId',
'action',
'entityType',
'entityId',
'severity',
'source',
'ipAddress',
'userAgent',
'metadata',
'oldValue',
'newValue',
];
const escape = (v: unknown): string => {
if (v === null || v === undefined) return '';
const s = typeof v === 'object' ? JSON.stringify(v) : String(v);
if (/[",\n\r]/.test(s)) {
return `"${s.replace(/"/g, '""')}"`;
}
return s;
};
const lines = [headers.join(',')];
for (const r of rows) {
lines.push(
[
r.createdAt instanceof Date ? r.createdAt.toISOString() : r.createdAt,
r.id,
r.portId,
r.userId,
r.action,
r.entityType,
r.entityId,
r.severity,
r.source,
r.ipAddress,
r.userAgent,
r.metadata,
r.oldValue,
r.newValue,
]
.map(escape)
.join(','),
);
}
return lines.join('\r\n') + '\r\n';
}

View File

@@ -208,6 +208,77 @@ function buildAuditDescription(
if (action === 'update' && newValue?.pipelineStage) {
return `Stage changed to ${stageLabel(newValue.pipelineStage as string)}`;
}
if (action === 'update') return 'Interest updated';
if (action === 'update') {
// §1.1: surface which field(s) changed instead of a generic
// "Interest updated". We have the new-value bag in audit_logs;
// human-friendly labels for the most common fields.
return describeUpdateDiff(newValue);
}
return action;
}
/**
* Render a "leadCategory: hot_lead, source: website" style description from
* an audit log's newValue payload. Filters out audit-internal fields,
* passes through human-friendly labels for known fields, falls back to
* the raw key name when the field isn't in the catalog.
*/
function describeUpdateDiff(newValue: Record<string, unknown> | null): string {
if (!newValue) return 'Interest updated';
// Audit-internal / housekeeping fields skipped from the timeline copy.
const SKIP = new Set(['updatedAt', 'createdAt', 'id', 'portId']);
const FIELD_LABELS: Record<string, string> = {
leadCategory: 'lead category',
source: 'source',
assignedTo: 'owner',
yachtId: 'yacht',
berthId: 'primary berth',
eoiDocStatus: 'EOI status',
reservationDocStatus: 'reservation status',
contractDocStatus: 'contract status',
dateEoiSent: 'EOI sent date',
dateEoiSigned: 'EOI signed date',
dateReservationSigned: 'reservation signed date',
dateContractSent: 'contract sent date',
dateContractSigned: 'contract signed date',
depositExpectedAmount: 'expected deposit',
depositExpectedCurrency: 'deposit currency',
desiredLengthFt: 'desired length',
desiredWidthFt: 'desired width',
desiredDraftFt: 'desired draft',
desiredLengthM: 'desired length (m)',
desiredWidthM: 'desired width (m)',
desiredDraftM: 'desired draft (m)',
reminderEnabled: 'follow-up reminder',
reminderDays: 'reminder cadence',
reminderNote: 'reminder note',
outcome: 'outcome',
};
const changed: string[] = [];
for (const [key, value] of Object.entries(newValue)) {
if (SKIP.has(key)) continue;
if (key === 'pipelineStage') continue; // handled by the earlier branch
const label = FIELD_LABELS[key] ?? key;
const formatted = formatDiffValue(value);
changed.push(formatted ? `${label}${formatted}` : label);
}
if (changed.length === 0) return 'Interest updated';
if (changed.length === 1) return `Updated ${changed[0]}`;
if (changed.length <= 3) return `Updated ${changed.join(', ')}`;
return `Updated ${changed.slice(0, 3).join(', ')} and ${changed.length - 3} more`;
}
function formatDiffValue(v: unknown): string {
if (v === null || v === undefined) return 'cleared';
if (typeof v === 'boolean') return v ? 'on' : 'off';
if (typeof v === 'number') return String(v);
if (typeof v === 'string') {
// Truncate verbose strings so the timeline line stays one row.
return v.length > 40 ? `${v.slice(0, 37)}` : v;
}
return '';
}

View File

@@ -1,23 +1,42 @@
import { NextResponse } from 'next/server';
import { headers } from 'next/headers';
import { eq } from 'drizzle-orm';
import { withAuth } from '@/lib/api/helpers';
import { auth } from '@/lib/auth';
import { db } from '@/lib/db';
import { ports as portsTable } from '@/lib/db/schema/ports';
import { userPortRoles, userProfiles } from '@/lib/db/schema/users';
import { errorResponse } from '@/lib/errors';
// A17: bootstrap-friendly ports list for the calling user — sales-reps
// and viewers can hit this without the super-admin gate that blocks
// `/api/v1/admin/ports`. Returns only the ports the user actually has
// access to (super-admin sees every active port).
export const GET = withAuth(async (_req, ctx) => {
/**
* Bootstrap-friendly ports list for the calling user.
*
* M-NEW-1: this endpoint INTENTIONALLY skips `withAuth`'s port-context
* requirement. Callers hit /me/ports specifically to LEARN which ports
* they have access to — they can't have selected one yet, so the
* X-Port-Id header is by definition absent on the first call. Pre-fix
* this meant non-super-admins got a 400 "Port context required" and
* the client had to special-case the response shape.
*
* Auth is still enforced (session check); permissions logic skipped
* because the endpoint exposes only IDs+slugs+names of ports the user
* is already a member of — same surface area as a `me` profile read.
*/
export async function GET() {
try {
const profile = await db.query.userProfiles.findFirst({
where: eq(userProfiles.userId, ctx.userId),
});
const session = await auth.api.getSession({ headers: await headers() });
if (!session?.user) {
return NextResponse.json({ error: 'Authentication required' }, { status: 401 });
}
if (profile?.isSuperAdmin) {
const profile = await db.query.userProfiles.findFirst({
where: eq(userProfiles.userId, session.user.id),
});
if (!profile || !profile.isActive) {
return NextResponse.json({ error: 'Account disabled' }, { status: 403 });
}
if (profile.isSuperAdmin) {
const all = await db.query.ports.findMany({
where: eq(portsTable.isActive, true),
orderBy: portsTable.name,
@@ -27,7 +46,7 @@ export const GET = withAuth(async (_req, ctx) => {
}
const memberships = await db.query.userPortRoles.findMany({
where: eq(userPortRoles.userId, ctx.userId),
where: eq(userPortRoles.userId, profile.userId),
with: { port: { columns: { id: true, slug: true, name: true } } },
});
const data = memberships.map((m) => m.port);
@@ -35,4 +54,4 @@ export const GET = withAuth(async (_req, ctx) => {
} catch (error) {
return errorResponse(error);
}
});
}

View File

@@ -0,0 +1,145 @@
import type { Metadata } from 'next';
export const metadata: Metadata = {
title: 'Deal Pulse & Heat — Port Nimara CRM',
description:
'How the deal pulse chip + heat score work: signals, calibration, and what to do when a deal goes cold.',
};
/**
* §7.1 — public explainer page for the Deal Pulse + Heat scoring model.
* Linked from the popover in `deal-pulse-chip.tsx` ("Full guide"). Kept
* intentionally text-heavy + jargon-free so a new sales rep can read
* once and internalize the model without bouncing back to the kanban.
*
* Public route (no auth) so external docs links and email signatures
* resolve cleanly. The route lives outside (dashboard) for that reason
* — middleware lets `/docs/...` through.
*/
export default function DealPulseDocsPage() {
return (
<div className="mx-auto max-w-3xl px-6 py-10 text-sm leading-relaxed text-foreground">
<header className="mb-8 space-y-2 border-b pb-6">
<p className="text-xs font-semibold uppercase tracking-wider text-muted-foreground">
Port Nimara CRM · Sales playbook
</p>
<h1 className="text-2xl font-semibold">Deal Pulse &amp; Heat</h1>
<p className="text-muted-foreground">
What the chip on every interest card actually means, how it&apos;s scored, and how to act
on it.
</p>
</header>
<section className="space-y-4">
<h2 className="text-lg font-semibold">The chip in one sentence</h2>
<p>
The colored chip on each interest is a fast read of{' '}
<strong>how hot the deal is right now</strong> based on what&apos;s been happening on it
lately not a prediction, not an AI score, just a mechanical rollup of recent activity.
</p>
</section>
<section className="mt-8 space-y-4">
<h2 className="text-lg font-semibold">Levels</h2>
<dl className="space-y-3">
<div className="rounded-md border bg-rose-50 p-3">
<dt className="font-semibold text-rose-900">Hot</dt>
<dd className="text-rose-900/90">
Recent inbound contact, multiple touches in the last week, or a milestone (EOI sent,
deposit received) inside the last 7 days. Default-sort lists put these at the top.
</dd>
</div>
<div className="rounded-md border bg-amber-50 p-3">
<dt className="font-semibold text-amber-900">Warm</dt>
<dd className="text-amber-900/90">
Activity in the last 1430 days. The deal isn&apos;t neglected but the cadence has
slowed usually means a follow-up reminder is the right next action.
</dd>
</div>
<div className="rounded-md border bg-slate-100 p-3">
<dt className="font-semibold text-slate-700">Cold</dt>
<dd className="text-slate-700/90">
No movement in 30+ days. Time to either re-engage with intent or close the deal as
lost so the kanban stays honest.
</dd>
</div>
</dl>
</section>
<section className="mt-8 space-y-4">
<h2 className="text-lg font-semibold">What feeds the score</h2>
<ul className="list-disc space-y-2 pl-5">
<li>
<strong>Recency of last contact log entry.</strong> Inbound (client replied) counts more
than outbound (rep reached out).
</li>
<li>
<strong>Furthest pipeline stage reached.</strong> A deal at EOI scores higher than one
at Enquiry, all else equal.
</li>
<li>
<strong>Count of related interests on the same client.</strong> Volume signals intent.
</li>
<li>
<strong>Count of EOIs sent.</strong> Multiple EOIs = multiple berths under serious
consideration.
</li>
<li>
<strong>Time at current stage.</strong> Stagnation drags the score down even if other
signals look good a deal stuck at Reservation for six weeks should not read hot.
</li>
</ul>
<p className="text-muted-foreground">
The exact weights live in <code className="text-xs">system_settings</code> under
<code className="text-xs"> heat_weight_*</code> keys and can be tuned per-port from the
admin Settings page.
</p>
</section>
<section className="mt-8 space-y-4">
<h2 className="text-lg font-semibold">What to do with each level</h2>
<ul className="list-disc space-y-2 pl-5">
<li>
<strong>Hot:</strong> Don&apos;t lose the momentum. Send the next document or schedule
the in-person visit while they&apos;re engaged.
</li>
<li>
<strong>Warm:</strong> Log a follow-up contact attempt; set a reminder if you&apos;re
waiting on them.
</li>
<li>
<strong>Cold:</strong> Either &quot;Reopen with a fresh hook&quot; (price drop, new
inventory, event invite) or close the deal so the pipeline reflects reality.
</li>
</ul>
</section>
<section className="mt-8 space-y-4">
<h2 className="text-lg font-semibold">FAQ</h2>
<details className="rounded-md border p-3">
<summary className="cursor-pointer font-medium">Does this use AI?</summary>
<p className="mt-2 text-muted-foreground">
No. It&apos;s a deterministic SQL rollup of contact logs, milestones, and stage
transitions. The same inputs always produce the same chip color.
</p>
</details>
<details className="rounded-md border p-3">
<summary className="cursor-pointer font-medium">
Can I override the chip on a specific deal?
</summary>
<p className="mt-2 text-muted-foreground">
Not directly the chip is a read-only summary. To change it, change the inputs: log a
contact, advance a stage, or close the deal.
</p>
</details>
<details className="rounded-md border p-3">
<summary className="cursor-pointer font-medium">How often does it refresh?</summary>
<p className="mt-2 text-muted-foreground">
On every interest write. The kanban + list pages query a live materialized rollup, so
you should see the chip move within a few seconds of any update.
</p>
</details>
</section>
</div>
);
}