Files
pn-new-crm/src/app/api/v1/admin/dashboard-stats/route.ts

144 lines
5.1 KiB
TypeScript
Raw Normal View History

feat(admin): inquiry inbox, send log, email-template overrides, reports dashboard, recommender keys, role-editor coverage; replace placeholder pages Closes the bulk of audit-pass-#1 admin gaps in one batch. New admin pages: - /admin/inquiries reads website_submissions with filter chips for berth/residence/contact + payload viewer per row. - /admin/sends reads document_sends with sent/failed filter chips and expandable body markdown; failures surface errorReason and any fallback-to-link reason from the SMTP retry. - /admin/email-templates lets per-port admins override the subject of each transactional template (8 templates catalogued in template-catalog.ts). Body editing is a follow-on; portal_activation + portal_reset are wired to honor the override via loadSubjectOverride. - /admin/reports replaces the "Coming in Layer 3" placeholder with a KPI dashboard: 4 KPI tiles, pipeline funnel bars, berth occupancy donut-bars, conversion %, refresh every 60s. - backup/import/onboarding admin pages replace placeholders with actionable guidance: backup posture + planned features, available CLI imports + planned UI, ordered onboarding checklist linking to admin pages. Existing pages widened: - settings-manager exposes the 9 berth-recommender tunables that were previously code-only (recommender_*, heat_weight_*, fallthrough_*, tier_ladder_hide_late_stage). - role-form covers all 19 RolePermissions schema groups; previously missing yachts/companies/memberships/reservations + missing documents.edit + files.edit checkboxes. snake_case residential labels replaced with friendly text. portal-auth.service.ts now also writes audit_log rows for portal invite, resend, activate, password-reset request, and reset (closes one more audit-pass-#2 gap while we were touching the file). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:58:17 +02:00
import { NextResponse } from 'next/server';
refactor(interests): drop pipelineStage='completed' sentinel convention `outcome` is the canonical terminal-state signal. Pre-2026-05-14 `setInterestOutcome` also forced `pipelineStage='completed'` (a value outside the 7-stage canon) which: - broke `safeStage()` (silently coerced to 'enquiry' downstream) - prevented analytics from answering "what stage was the deal at when it closed?" because every closed deal looked identical - forced belt-and-suspenders filters everywhere ('outcome=won' AND 'pipeline_stage=completed') that became redundant after migration 0062 Changes: - `setInterestOutcome` no longer touches pipelineStage. Deal stays at whatever stage it was on when the outcome was recorded; outcome is the terminal signal. Audit log + websocket emit now carry `stageAtOutcome` instead of the stale `oldStage`. - `clearInterestOutcome` smarter reopen-stage logic: if current stage is the legacy 'completed' sentinel (pre-existing rows from before this commit), default to 'qualified'. Otherwise preserve the stage the deal was at, so reopening drops the rep back where they were. Explicit data.reopenStage still wins. - `/api/v1/admin/dashboard-stats` route reworked: per-stage breakdown now filters `outcome IS NULL` (only active rows count per stage); `closedTotal` derives from a new `outcome IS NOT NULL` count query; `completed30d` switches from `pipelineStage='completed' AND updatedAt` to `outcome IS NOT NULL AND outcomeAt` (avoids long-closed deals leaking into the window on unrelated edits). - `berth-interests-tab.tsx` "active" filter switches from `pipelineStage !== 'completed'` to `!outcome && !archivedAt` — the legacy check stopped matching post-refactor. - Socket event type `interest:outcomeSet` renames `oldStage` → `stageAtOutcome` with a doc-comment explaining the semantics shift. PIPELINE_STAGES canon is now the only valid pipeline_stage value range for newly-set outcomes. Legacy rows still carry 'completed' until they naturally churn through reopen + re-close, at which point they enter the new convention. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:04:13 +02:00
import { and, eq, isNotNull, isNull, gte, sql } from 'drizzle-orm';
feat(admin): inquiry inbox, send log, email-template overrides, reports dashboard, recommender keys, role-editor coverage; replace placeholder pages Closes the bulk of audit-pass-#1 admin gaps in one batch. New admin pages: - /admin/inquiries reads website_submissions with filter chips for berth/residence/contact + payload viewer per row. - /admin/sends reads document_sends with sent/failed filter chips and expandable body markdown; failures surface errorReason and any fallback-to-link reason from the SMTP retry. - /admin/email-templates lets per-port admins override the subject of each transactional template (8 templates catalogued in template-catalog.ts). Body editing is a follow-on; portal_activation + portal_reset are wired to honor the override via loadSubjectOverride. - /admin/reports replaces the "Coming in Layer 3" placeholder with a KPI dashboard: 4 KPI tiles, pipeline funnel bars, berth occupancy donut-bars, conversion %, refresh every 60s. - backup/import/onboarding admin pages replace placeholders with actionable guidance: backup posture + planned features, available CLI imports + planned UI, ordered onboarding checklist linking to admin pages. Existing pages widened: - settings-manager exposes the 9 berth-recommender tunables that were previously code-only (recommender_*, heat_weight_*, fallthrough_*, tier_ladder_hide_late_stage). - role-form covers all 19 RolePermissions schema groups; previously missing yachts/companies/memberships/reservations + missing documents.edit + files.edit checkboxes. snake_case residential labels replaced with friendly text. portal-auth.service.ts now also writes audit_log rows for portal invite, resend, activate, password-reset request, and reset (closes one more audit-pass-#2 gap while we were touching the file). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:58:17 +02:00
import { withAuth, withPermission } from '@/lib/api/helpers';
import { db } from '@/lib/db';
import { interests } from '@/lib/db/schema/interests';
import { berths } from '@/lib/db/schema/berths';
import { clients } from '@/lib/db/schema/clients';
import { websiteSubmissions } from '@/lib/db/schema/website-submissions';
import { errorResponse } from '@/lib/errors';
import { PIPELINE_STAGES } from '@/lib/constants';
export const GET = withAuth(
withPermission('reports', 'view_dashboard', async (_req, ctx) => {
try {
const portId = ctx.portId;
const sevenDaysAgo = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
const thirtyDaysAgo = new Date(Date.now() - 30 * 24 * 60 * 60 * 1000);
const [pipelineRows, berthStatusRows, totals, recent] = await Promise.all([
refactor(interests): drop pipelineStage='completed' sentinel convention `outcome` is the canonical terminal-state signal. Pre-2026-05-14 `setInterestOutcome` also forced `pipelineStage='completed'` (a value outside the 7-stage canon) which: - broke `safeStage()` (silently coerced to 'enquiry' downstream) - prevented analytics from answering "what stage was the deal at when it closed?" because every closed deal looked identical - forced belt-and-suspenders filters everywhere ('outcome=won' AND 'pipeline_stage=completed') that became redundant after migration 0062 Changes: - `setInterestOutcome` no longer touches pipelineStage. Deal stays at whatever stage it was on when the outcome was recorded; outcome is the terminal signal. Audit log + websocket emit now carry `stageAtOutcome` instead of the stale `oldStage`. - `clearInterestOutcome` smarter reopen-stage logic: if current stage is the legacy 'completed' sentinel (pre-existing rows from before this commit), default to 'qualified'. Otherwise preserve the stage the deal was at, so reopening drops the rep back where they were. Explicit data.reopenStage still wins. - `/api/v1/admin/dashboard-stats` route reworked: per-stage breakdown now filters `outcome IS NULL` (only active rows count per stage); `closedTotal` derives from a new `outcome IS NOT NULL` count query; `completed30d` switches from `pipelineStage='completed' AND updatedAt` to `outcome IS NOT NULL AND outcomeAt` (avoids long-closed deals leaking into the window on unrelated edits). - `berth-interests-tab.tsx` "active" filter switches from `pipelineStage !== 'completed'` to `!outcome && !archivedAt` — the legacy check stopped matching post-refactor. - Socket event type `interest:outcomeSet` renames `oldStage` → `stageAtOutcome` with a doc-comment explaining the semantics shift. PIPELINE_STAGES canon is now the only valid pipeline_stage value range for newly-set outcomes. Legacy rows still carry 'completed' until they naturally churn through reopen + re-close, at which point they enter the new convention. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:04:13 +02:00
// Only active interests count toward per-stage breakdowns;
// terminal (outcome-set) interests are tracked separately via
// `closedTotal` below. Pre-2026-05-14 cleanup, terminal rows
// were grouped under the sentinel pipeline_stage='completed'
// bucket; the new convention leaves the stage where it was
// when the outcome was set, so we must filter by `outcome IS
// NULL` explicitly to keep the kanban breakdown honest.
feat(admin): inquiry inbox, send log, email-template overrides, reports dashboard, recommender keys, role-editor coverage; replace placeholder pages Closes the bulk of audit-pass-#1 admin gaps in one batch. New admin pages: - /admin/inquiries reads website_submissions with filter chips for berth/residence/contact + payload viewer per row. - /admin/sends reads document_sends with sent/failed filter chips and expandable body markdown; failures surface errorReason and any fallback-to-link reason from the SMTP retry. - /admin/email-templates lets per-port admins override the subject of each transactional template (8 templates catalogued in template-catalog.ts). Body editing is a follow-on; portal_activation + portal_reset are wired to honor the override via loadSubjectOverride. - /admin/reports replaces the "Coming in Layer 3" placeholder with a KPI dashboard: 4 KPI tiles, pipeline funnel bars, berth occupancy donut-bars, conversion %, refresh every 60s. - backup/import/onboarding admin pages replace placeholders with actionable guidance: backup posture + planned features, available CLI imports + planned UI, ordered onboarding checklist linking to admin pages. Existing pages widened: - settings-manager exposes the 9 berth-recommender tunables that were previously code-only (recommender_*, heat_weight_*, fallthrough_*, tier_ladder_hide_late_stage). - role-form covers all 19 RolePermissions schema groups; previously missing yachts/companies/memberships/reservations + missing documents.edit + files.edit checkboxes. snake_case residential labels replaced with friendly text. portal-auth.service.ts now also writes audit_log rows for portal invite, resend, activate, password-reset request, and reset (closes one more audit-pass-#2 gap while we were touching the file). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:58:17 +02:00
db
.select({
stage: interests.pipelineStage,
count: sql<number>`count(*)::int`,
})
.from(interests)
refactor(interests): drop pipelineStage='completed' sentinel convention `outcome` is the canonical terminal-state signal. Pre-2026-05-14 `setInterestOutcome` also forced `pipelineStage='completed'` (a value outside the 7-stage canon) which: - broke `safeStage()` (silently coerced to 'enquiry' downstream) - prevented analytics from answering "what stage was the deal at when it closed?" because every closed deal looked identical - forced belt-and-suspenders filters everywhere ('outcome=won' AND 'pipeline_stage=completed') that became redundant after migration 0062 Changes: - `setInterestOutcome` no longer touches pipelineStage. Deal stays at whatever stage it was on when the outcome was recorded; outcome is the terminal signal. Audit log + websocket emit now carry `stageAtOutcome` instead of the stale `oldStage`. - `clearInterestOutcome` smarter reopen-stage logic: if current stage is the legacy 'completed' sentinel (pre-existing rows from before this commit), default to 'qualified'. Otherwise preserve the stage the deal was at, so reopening drops the rep back where they were. Explicit data.reopenStage still wins. - `/api/v1/admin/dashboard-stats` route reworked: per-stage breakdown now filters `outcome IS NULL` (only active rows count per stage); `closedTotal` derives from a new `outcome IS NOT NULL` count query; `completed30d` switches from `pipelineStage='completed' AND updatedAt` to `outcome IS NOT NULL AND outcomeAt` (avoids long-closed deals leaking into the window on unrelated edits). - `berth-interests-tab.tsx` "active" filter switches from `pipelineStage !== 'completed'` to `!outcome && !archivedAt` — the legacy check stopped matching post-refactor. - Socket event type `interest:outcomeSet` renames `oldStage` → `stageAtOutcome` with a doc-comment explaining the semantics shift. PIPELINE_STAGES canon is now the only valid pipeline_stage value range for newly-set outcomes. Legacy rows still carry 'completed' until they naturally churn through reopen + re-close, at which point they enter the new convention. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:04:13 +02:00
.where(
and(
eq(interests.portId, portId),
isNull(interests.archivedAt),
isNull(interests.outcome),
),
)
feat(admin): inquiry inbox, send log, email-template overrides, reports dashboard, recommender keys, role-editor coverage; replace placeholder pages Closes the bulk of audit-pass-#1 admin gaps in one batch. New admin pages: - /admin/inquiries reads website_submissions with filter chips for berth/residence/contact + payload viewer per row. - /admin/sends reads document_sends with sent/failed filter chips and expandable body markdown; failures surface errorReason and any fallback-to-link reason from the SMTP retry. - /admin/email-templates lets per-port admins override the subject of each transactional template (8 templates catalogued in template-catalog.ts). Body editing is a follow-on; portal_activation + portal_reset are wired to honor the override via loadSubjectOverride. - /admin/reports replaces the "Coming in Layer 3" placeholder with a KPI dashboard: 4 KPI tiles, pipeline funnel bars, berth occupancy donut-bars, conversion %, refresh every 60s. - backup/import/onboarding admin pages replace placeholders with actionable guidance: backup posture + planned features, available CLI imports + planned UI, ordered onboarding checklist linking to admin pages. Existing pages widened: - settings-manager exposes the 9 berth-recommender tunables that were previously code-only (recommender_*, heat_weight_*, fallthrough_*, tier_ladder_hide_late_stage). - role-form covers all 19 RolePermissions schema groups; previously missing yachts/companies/memberships/reservations + missing documents.edit + files.edit checkboxes. snake_case residential labels replaced with friendly text. portal-auth.service.ts now also writes audit_log rows for portal invite, resend, activate, password-reset request, and reset (closes one more audit-pass-#2 gap while we were touching the file). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:58:17 +02:00
.groupBy(interests.pipelineStage),
db
.select({
status: berths.status,
count: sql<number>`count(*)::int`,
})
.from(berths)
.where(eq(berths.portId, portId))
.groupBy(berths.status),
Promise.all([
db
.select({ count: sql<number>`count(*)::int` })
.from(clients)
.where(and(eq(clients.portId, portId), isNull(clients.archivedAt))),
db
.select({ count: sql<number>`count(*)::int` })
.from(interests)
.where(and(eq(interests.portId, portId), isNull(interests.archivedAt))),
db
.select({ count: sql<number>`count(*)::int` })
.from(berths)
.where(eq(berths.portId, portId)),
refactor(interests): drop pipelineStage='completed' sentinel convention `outcome` is the canonical terminal-state signal. Pre-2026-05-14 `setInterestOutcome` also forced `pipelineStage='completed'` (a value outside the 7-stage canon) which: - broke `safeStage()` (silently coerced to 'enquiry' downstream) - prevented analytics from answering "what stage was the deal at when it closed?" because every closed deal looked identical - forced belt-and-suspenders filters everywhere ('outcome=won' AND 'pipeline_stage=completed') that became redundant after migration 0062 Changes: - `setInterestOutcome` no longer touches pipelineStage. Deal stays at whatever stage it was on when the outcome was recorded; outcome is the terminal signal. Audit log + websocket emit now carry `stageAtOutcome` instead of the stale `oldStage`. - `clearInterestOutcome` smarter reopen-stage logic: if current stage is the legacy 'completed' sentinel (pre-existing rows from before this commit), default to 'qualified'. Otherwise preserve the stage the deal was at, so reopening drops the rep back where they were. Explicit data.reopenStage still wins. - `/api/v1/admin/dashboard-stats` route reworked: per-stage breakdown now filters `outcome IS NULL` (only active rows count per stage); `closedTotal` derives from a new `outcome IS NOT NULL` count query; `completed30d` switches from `pipelineStage='completed' AND updatedAt` to `outcome IS NOT NULL AND outcomeAt` (avoids long-closed deals leaking into the window on unrelated edits). - `berth-interests-tab.tsx` "active" filter switches from `pipelineStage !== 'completed'` to `!outcome && !archivedAt` — the legacy check stopped matching post-refactor. - Socket event type `interest:outcomeSet` renames `oldStage` → `stageAtOutcome` with a doc-comment explaining the semantics shift. PIPELINE_STAGES canon is now the only valid pipeline_stage value range for newly-set outcomes. Legacy rows still carry 'completed' until they naturally churn through reopen + re-close, at which point they enter the new convention. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:04:13 +02:00
// closedTotal: all-time count of terminal (outcome-set)
// non-archived interests. Drives the conversion-rate tile.
db
.select({ count: sql<number>`count(*)::int` })
.from(interests)
.where(
and(
eq(interests.portId, portId),
isNull(interests.archivedAt),
isNotNull(interests.outcome),
),
),
feat(admin): inquiry inbox, send log, email-template overrides, reports dashboard, recommender keys, role-editor coverage; replace placeholder pages Closes the bulk of audit-pass-#1 admin gaps in one batch. New admin pages: - /admin/inquiries reads website_submissions with filter chips for berth/residence/contact + payload viewer per row. - /admin/sends reads document_sends with sent/failed filter chips and expandable body markdown; failures surface errorReason and any fallback-to-link reason from the SMTP retry. - /admin/email-templates lets per-port admins override the subject of each transactional template (8 templates catalogued in template-catalog.ts). Body editing is a follow-on; portal_activation + portal_reset are wired to honor the override via loadSubjectOverride. - /admin/reports replaces the "Coming in Layer 3" placeholder with a KPI dashboard: 4 KPI tiles, pipeline funnel bars, berth occupancy donut-bars, conversion %, refresh every 60s. - backup/import/onboarding admin pages replace placeholders with actionable guidance: backup posture + planned features, available CLI imports + planned UI, ordered onboarding checklist linking to admin pages. Existing pages widened: - settings-manager exposes the 9 berth-recommender tunables that were previously code-only (recommender_*, heat_weight_*, fallthrough_*, tier_ladder_hide_late_stage). - role-form covers all 19 RolePermissions schema groups; previously missing yachts/companies/memberships/reservations + missing documents.edit + files.edit checkboxes. snake_case residential labels replaced with friendly text. portal-auth.service.ts now also writes audit_log rows for portal invite, resend, activate, password-reset request, and reset (closes one more audit-pass-#2 gap while we were touching the file). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:58:17 +02:00
]),
Promise.all([
db
.select({ count: sql<number>`count(*)::int` })
.from(websiteSubmissions)
.where(
and(
eq(websiteSubmissions.portId, portId),
gte(websiteSubmissions.receivedAt, sevenDaysAgo),
),
),
refactor(interests): drop pipelineStage='completed' sentinel convention `outcome` is the canonical terminal-state signal. Pre-2026-05-14 `setInterestOutcome` also forced `pipelineStage='completed'` (a value outside the 7-stage canon) which: - broke `safeStage()` (silently coerced to 'enquiry' downstream) - prevented analytics from answering "what stage was the deal at when it closed?" because every closed deal looked identical - forced belt-and-suspenders filters everywhere ('outcome=won' AND 'pipeline_stage=completed') that became redundant after migration 0062 Changes: - `setInterestOutcome` no longer touches pipelineStage. Deal stays at whatever stage it was on when the outcome was recorded; outcome is the terminal signal. Audit log + websocket emit now carry `stageAtOutcome` instead of the stale `oldStage`. - `clearInterestOutcome` smarter reopen-stage logic: if current stage is the legacy 'completed' sentinel (pre-existing rows from before this commit), default to 'qualified'. Otherwise preserve the stage the deal was at, so reopening drops the rep back where they were. Explicit data.reopenStage still wins. - `/api/v1/admin/dashboard-stats` route reworked: per-stage breakdown now filters `outcome IS NULL` (only active rows count per stage); `closedTotal` derives from a new `outcome IS NOT NULL` count query; `completed30d` switches from `pipelineStage='completed' AND updatedAt` to `outcome IS NOT NULL AND outcomeAt` (avoids long-closed deals leaking into the window on unrelated edits). - `berth-interests-tab.tsx` "active" filter switches from `pipelineStage !== 'completed'` to `!outcome && !archivedAt` — the legacy check stopped matching post-refactor. - Socket event type `interest:outcomeSet` renames `oldStage` → `stageAtOutcome` with a doc-comment explaining the semantics shift. PIPELINE_STAGES canon is now the only valid pipeline_stage value range for newly-set outcomes. Legacy rows still carry 'completed' until they naturally churn through reopen + re-close, at which point they enter the new convention. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:04:13 +02:00
// "completed30d" = interests that hit a terminal outcome in
// the last 30 days (any outcome — won, lost, or cancelled).
// Use `outcome_at` not `updated_at` so unrelated edits to a
// long-closed deal don't drag it back into the window.
feat(admin): inquiry inbox, send log, email-template overrides, reports dashboard, recommender keys, role-editor coverage; replace placeholder pages Closes the bulk of audit-pass-#1 admin gaps in one batch. New admin pages: - /admin/inquiries reads website_submissions with filter chips for berth/residence/contact + payload viewer per row. - /admin/sends reads document_sends with sent/failed filter chips and expandable body markdown; failures surface errorReason and any fallback-to-link reason from the SMTP retry. - /admin/email-templates lets per-port admins override the subject of each transactional template (8 templates catalogued in template-catalog.ts). Body editing is a follow-on; portal_activation + portal_reset are wired to honor the override via loadSubjectOverride. - /admin/reports replaces the "Coming in Layer 3" placeholder with a KPI dashboard: 4 KPI tiles, pipeline funnel bars, berth occupancy donut-bars, conversion %, refresh every 60s. - backup/import/onboarding admin pages replace placeholders with actionable guidance: backup posture + planned features, available CLI imports + planned UI, ordered onboarding checklist linking to admin pages. Existing pages widened: - settings-manager exposes the 9 berth-recommender tunables that were previously code-only (recommender_*, heat_weight_*, fallthrough_*, tier_ladder_hide_late_stage). - role-form covers all 19 RolePermissions schema groups; previously missing yachts/companies/memberships/reservations + missing documents.edit + files.edit checkboxes. snake_case residential labels replaced with friendly text. portal-auth.service.ts now also writes audit_log rows for portal invite, resend, activate, password-reset request, and reset (closes one more audit-pass-#2 gap while we were touching the file). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:58:17 +02:00
db
.select({ count: sql<number>`count(*)::int` })
.from(interests)
.where(
and(
eq(interests.portId, portId),
refactor(interests): drop pipelineStage='completed' sentinel convention `outcome` is the canonical terminal-state signal. Pre-2026-05-14 `setInterestOutcome` also forced `pipelineStage='completed'` (a value outside the 7-stage canon) which: - broke `safeStage()` (silently coerced to 'enquiry' downstream) - prevented analytics from answering "what stage was the deal at when it closed?" because every closed deal looked identical - forced belt-and-suspenders filters everywhere ('outcome=won' AND 'pipeline_stage=completed') that became redundant after migration 0062 Changes: - `setInterestOutcome` no longer touches pipelineStage. Deal stays at whatever stage it was on when the outcome was recorded; outcome is the terminal signal. Audit log + websocket emit now carry `stageAtOutcome` instead of the stale `oldStage`. - `clearInterestOutcome` smarter reopen-stage logic: if current stage is the legacy 'completed' sentinel (pre-existing rows from before this commit), default to 'qualified'. Otherwise preserve the stage the deal was at, so reopening drops the rep back where they were. Explicit data.reopenStage still wins. - `/api/v1/admin/dashboard-stats` route reworked: per-stage breakdown now filters `outcome IS NULL` (only active rows count per stage); `closedTotal` derives from a new `outcome IS NOT NULL` count query; `completed30d` switches from `pipelineStage='completed' AND updatedAt` to `outcome IS NOT NULL AND outcomeAt` (avoids long-closed deals leaking into the window on unrelated edits). - `berth-interests-tab.tsx` "active" filter switches from `pipelineStage !== 'completed'` to `!outcome && !archivedAt` — the legacy check stopped matching post-refactor. - Socket event type `interest:outcomeSet` renames `oldStage` → `stageAtOutcome` with a doc-comment explaining the semantics shift. PIPELINE_STAGES canon is now the only valid pipeline_stage value range for newly-set outcomes. Legacy rows still carry 'completed' until they naturally churn through reopen + re-close, at which point they enter the new convention. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:04:13 +02:00
isNotNull(interests.outcome),
gte(interests.outcomeAt, thirtyDaysAgo),
feat(admin): inquiry inbox, send log, email-template overrides, reports dashboard, recommender keys, role-editor coverage; replace placeholder pages Closes the bulk of audit-pass-#1 admin gaps in one batch. New admin pages: - /admin/inquiries reads website_submissions with filter chips for berth/residence/contact + payload viewer per row. - /admin/sends reads document_sends with sent/failed filter chips and expandable body markdown; failures surface errorReason and any fallback-to-link reason from the SMTP retry. - /admin/email-templates lets per-port admins override the subject of each transactional template (8 templates catalogued in template-catalog.ts). Body editing is a follow-on; portal_activation + portal_reset are wired to honor the override via loadSubjectOverride. - /admin/reports replaces the "Coming in Layer 3" placeholder with a KPI dashboard: 4 KPI tiles, pipeline funnel bars, berth occupancy donut-bars, conversion %, refresh every 60s. - backup/import/onboarding admin pages replace placeholders with actionable guidance: backup posture + planned features, available CLI imports + planned UI, ordered onboarding checklist linking to admin pages. Existing pages widened: - settings-manager exposes the 9 berth-recommender tunables that were previously code-only (recommender_*, heat_weight_*, fallthrough_*, tier_ladder_hide_late_stage). - role-form covers all 19 RolePermissions schema groups; previously missing yachts/companies/memberships/reservations + missing documents.edit + files.edit checkboxes. snake_case residential labels replaced with friendly text. portal-auth.service.ts now also writes audit_log rows for portal invite, resend, activate, password-reset request, and reset (closes one more audit-pass-#2 gap while we were touching the file). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:58:17 +02:00
),
),
]),
]);
const pipeline = Object.fromEntries(PIPELINE_STAGES.map((s) => [s, 0])) as Record<
string,
number
>;
for (const row of pipelineRows) pipeline[row.stage] = row.count;
const berthStatus: Record<string, number> = {
available: 0,
under_offer: 0,
sold: 0,
};
for (const row of berthStatusRows) berthStatus[row.status] = row.count;
const totalClients = totals[0][0]?.count ?? 0;
const totalInterests = totals[1][0]?.count ?? 0;
const totalBerths = totals[2][0]?.count ?? 0;
refactor(interests): drop pipelineStage='completed' sentinel convention `outcome` is the canonical terminal-state signal. Pre-2026-05-14 `setInterestOutcome` also forced `pipelineStage='completed'` (a value outside the 7-stage canon) which: - broke `safeStage()` (silently coerced to 'enquiry' downstream) - prevented analytics from answering "what stage was the deal at when it closed?" because every closed deal looked identical - forced belt-and-suspenders filters everywhere ('outcome=won' AND 'pipeline_stage=completed') that became redundant after migration 0062 Changes: - `setInterestOutcome` no longer touches pipelineStage. Deal stays at whatever stage it was on when the outcome was recorded; outcome is the terminal signal. Audit log + websocket emit now carry `stageAtOutcome` instead of the stale `oldStage`. - `clearInterestOutcome` smarter reopen-stage logic: if current stage is the legacy 'completed' sentinel (pre-existing rows from before this commit), default to 'qualified'. Otherwise preserve the stage the deal was at, so reopening drops the rep back where they were. Explicit data.reopenStage still wins. - `/api/v1/admin/dashboard-stats` route reworked: per-stage breakdown now filters `outcome IS NULL` (only active rows count per stage); `closedTotal` derives from a new `outcome IS NOT NULL` count query; `completed30d` switches from `pipelineStage='completed' AND updatedAt` to `outcome IS NOT NULL AND outcomeAt` (avoids long-closed deals leaking into the window on unrelated edits). - `berth-interests-tab.tsx` "active" filter switches from `pipelineStage !== 'completed'` to `!outcome && !archivedAt` — the legacy check stopped matching post-refactor. - Socket event type `interest:outcomeSet` renames `oldStage` → `stageAtOutcome` with a doc-comment explaining the semantics shift. PIPELINE_STAGES canon is now the only valid pipeline_stage value range for newly-set outcomes. Legacy rows still carry 'completed' until they naturally churn through reopen + re-close, at which point they enter the new convention. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 15:04:13 +02:00
const closedTotal = totals[3][0]?.count ?? 0;
feat(admin): inquiry inbox, send log, email-template overrides, reports dashboard, recommender keys, role-editor coverage; replace placeholder pages Closes the bulk of audit-pass-#1 admin gaps in one batch. New admin pages: - /admin/inquiries reads website_submissions with filter chips for berth/residence/contact + payload viewer per row. - /admin/sends reads document_sends with sent/failed filter chips and expandable body markdown; failures surface errorReason and any fallback-to-link reason from the SMTP retry. - /admin/email-templates lets per-port admins override the subject of each transactional template (8 templates catalogued in template-catalog.ts). Body editing is a follow-on; portal_activation + portal_reset are wired to honor the override via loadSubjectOverride. - /admin/reports replaces the "Coming in Layer 3" placeholder with a KPI dashboard: 4 KPI tiles, pipeline funnel bars, berth occupancy donut-bars, conversion %, refresh every 60s. - backup/import/onboarding admin pages replace placeholders with actionable guidance: backup posture + planned features, available CLI imports + planned UI, ordered onboarding checklist linking to admin pages. Existing pages widened: - settings-manager exposes the 9 berth-recommender tunables that were previously code-only (recommender_*, heat_weight_*, fallthrough_*, tier_ladder_hide_late_stage). - role-form covers all 19 RolePermissions schema groups; previously missing yachts/companies/memberships/reservations + missing documents.edit + files.edit checkboxes. snake_case residential labels replaced with friendly text. portal-auth.service.ts now also writes audit_log rows for portal invite, resend, activate, password-reset request, and reset (closes one more audit-pass-#2 gap while we were touching the file). Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-06 14:58:17 +02:00
const newInquiries7d = recent[0][0]?.count ?? 0;
const completed30d = recent[1][0]?.count ?? 0;
const openTotal = totalInterests - closedTotal;
const conversionPct =
totalInterests > 0 ? Math.round((closedTotal / totalInterests) * 100) : 0;
return NextResponse.json({
data: {
totals: { totalClients, totalInterests, totalBerths },
recent: { newInquiries7d, completed30d },
pipeline,
berthStatus,
conversion: { closedTotal, openTotal, conversionPct },
},
});
} catch (error) {
return errorResponse(error);
}
}),
);