Files
pn-new-crm/src/components/admin/users/user-list.tsx
Matt b3f87563c6 feat(audit-cleanup): finish all 15 outstanding items from verified backlog
Audit cleanup completion plan, all tiers shipped:

Tier 1 (security + data integrity)
- A.7 RTBF true wipe: redact email_messages body/subject/addresses for
  threads owned by deleted client; redact document_sends.recipient_email;
  collect file storage keys + delete blobs post-commit.
- A.8 user_permission_overrides FK: documented inline why cascade is
  correct (not set-null as audit suggested) — overrides have no value
  without their user.
- W2.14 PII redaction: camelCase normalization in audit.ts +
  error-events.service.ts isSensitiveKey; added city/postal/country/
  birth fragments. firstName/lastName/dateOfBirth/postalCode etc. now
  caught in BOTH masker paths. 12 new test cases lock the coverage.

Tier 2 (Documenso completion + refactor)
- C.2: documentEvents.recipient_email column + partial unique index for
  per-recipient webhook dedup (migration 0075). handleDocumentSigned
  now sets recipient_email on insert.
- Phase 2: completion_cc_emails distribution. handleDocumentCompleted
  reads documents.completionCcEmails, filters out signer-duplicates
  case-insensitively, fans signed PDF out to non-signer recipients.
- C.4: extracted createPublicInterest() service from the 346-line
  api/public/interests route. Route becomes a thin shell (rate-limit,
  port resolution, audit log, email fan-out). The trio creation logic
  is now unit-testable without an HTTP fixture.
- Phase 4: POST /api/v1/document-templates/[id]/detect-fields wired
  to document-field-detector.detectFields(). Sparkles "Auto-detect"
  button added to template-editor.tsx — maps DetectedField → marker
  with best-guess merge token (DATE / NAME / EMAIL); user retags.

Tier 3 (reporting + recommender snapshot lockfiles)
- W7.reports: extracted rollupStageRevenue / rollupStageCounts /
  computeTotalForecast / computeOccupancyRate / rollupBerthStatusCounts
  into src/lib/services/report-math.ts (pure functions). 16 new tests
  including an inline-snapshot lockfile on a representative 7-stage
  forecast. report-generators.ts now delegates.
- W7.recommender: 18 new toMatchSnapshot tripwires on classifyTier
  boundaries + computeHeat at canonical input points.

Tier 4 (rolling)
- W6.attach: fixed outdated CLAUDE.md claim — threshold banner is
  informational and never depended on IMAP; bounce monitoring (the
  IMAP poller) is separate.
- D.1 + D.2: documented deferral inline with full why-not-build-it
  reasoning so a future engineer sees the rationale.
- G.1: representative formatDate sweep (audit-log-list, user-list,
  document-templates merge tokens, document-signing email). Rest of
  the ~100 sites stay rolling.

Quality gates: 1420/1420 vitest (46 new tests above baseline of 1374),
tsc clean, 0 lint errors.

Plan: docs/superpowers/plans/2026-05-18-audit-cleanup-completion.md
Migration: 0075_c2_document_events_recipient_email.sql (applied to dev DB).

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

243 lines
8.0 KiB
TypeScript

'use client';
import { useState } from 'react';
import { useMutation, useQuery, useQueryClient } from '@tanstack/react-query';
import { type ColumnDef } from '@tanstack/react-table';
import { Pencil, Trash2, Plus, ShieldCheck, ShieldOff, Power, PowerOff } from 'lucide-react';
import { DataTable } from '@/components/shared/data-table';
import { PageHeader } from '@/components/shared/page-header';
import { ConfirmationDialog } from '@/components/shared/confirmation-dialog';
import { PermissionGate } from '@/components/shared/permission-gate';
import { Button } from '@/components/ui/button';
import { Badge } from '@/components/ui/badge';
import { StatusPill } from '@/components/ui/status-pill';
import { apiFetch } from '@/lib/api/client';
import { formatRole } from '@/lib/constants';
import { formatDate } from '@/lib/utils/format-date';
import { UserCard } from './user-card';
import { UserForm } from './user-form';
interface UserRow {
userId: string;
displayName: string;
email: string;
phone: string | null;
isActive: boolean;
isSuperAdmin: boolean;
lastLoginAt: string | null;
role: { id: string; name: string };
assignedAt: string;
}
const USERS_QUERY_KEY = ['admin', 'users'] as const;
export function UserList() {
const queryClient = useQueryClient();
const [formOpen, setFormOpen] = useState(false);
const [editingUser, setEditingUser] = useState<UserRow | null>(null);
const { data: users = [], isLoading: loading } = useQuery<UserRow[]>({
queryKey: USERS_QUERY_KEY,
queryFn: () => apiFetch<{ data: UserRow[] }>('/api/v1/admin/users').then((r) => r.data),
});
const fetchUsers = () => queryClient.invalidateQueries({ queryKey: USERS_QUERY_KEY });
const removeMutation = useMutation({
mutationFn: (userId: string) => apiFetch(`/api/v1/admin/users/${userId}`, { method: 'DELETE' }),
onSuccess: () => fetchUsers(),
});
const toggleMutation = useMutation({
mutationFn: (user: UserRow) =>
apiFetch(`/api/v1/admin/users/${user.userId}`, {
method: 'PATCH',
body: { isActive: !user.isActive },
}),
onSuccess: () => fetchUsers(),
});
const deletingId = removeMutation.isPending ? removeMutation.variables : null;
const togglingId = toggleMutation.isPending ? (toggleMutation.variables?.userId ?? null) : null;
function handleNewUser() {
setEditingUser(null);
setFormOpen(true);
}
function handleEditUser(user: UserRow) {
setEditingUser(user);
setFormOpen(true);
}
function handleRemoveUser(userId: string) {
removeMutation.mutate(userId);
}
function handleToggleActive(user: UserRow) {
toggleMutation.mutate(user);
}
const columns: ColumnDef<UserRow, unknown>[] = [
{
accessorKey: 'displayName',
header: 'Name',
cell: ({ row }) => (
<div className="flex flex-col">
<span className="font-medium">{row.original.displayName}</span>
<span className="text-xs text-muted-foreground">{row.original.email}</span>
</div>
),
},
{
accessorKey: 'role',
header: 'Role',
cell: ({ row }) => <Badge variant="secondary">{formatRole(row.original.role.name)}</Badge>,
},
{
accessorKey: 'isActive',
header: 'Status',
cell: ({ row }) =>
row.original.isActive ? (
<StatusPill status="enabled">
<ShieldCheck className="h-3 w-3" aria-hidden />
Active
</StatusPill>
) : (
<StatusPill status="disabled">
<ShieldOff className="h-3 w-3" aria-hidden />
Disabled
</StatusPill>
),
},
{
accessorKey: 'lastLoginAt',
header: 'Last Login',
cell: ({ row }) =>
row.original.lastLoginAt ? formatDate(row.original.lastLoginAt, 'date.medium') : 'Never',
},
{
id: 'actions',
header: '',
cell: ({ row }) => (
<div className="flex items-center justify-end gap-1">
<PermissionGate resource="admin" action="manage_users">
<Button
variant="ghost"
size="sm"
onClick={() => handleEditUser(row.original)}
title="Edit user"
>
<Pencil className="h-4 w-4" aria-hidden />
<span className="sr-only">Edit</span>
</Button>
</PermissionGate>
<PermissionGate resource="admin" action="manage_users">
<ConfirmationDialog
trigger={
<Button
variant="ghost"
size="sm"
title={row.original.isActive ? 'Disable sign-in' : 'Enable sign-in'}
disabled={togglingId === row.original.userId}
className={
row.original.isActive
? 'text-muted-foreground hover:text-foreground'
: 'text-emerald-600 hover:text-emerald-700'
}
>
{row.original.isActive ? (
<PowerOff className="h-4 w-4" aria-hidden />
) : (
<Power className="h-4 w-4" aria-hidden />
)}
<span className="sr-only">{row.original.isActive ? 'Disable' : 'Enable'}</span>
</Button>
}
title={row.original.isActive ? 'Disable user' : 'Enable user'}
description={
row.original.isActive
? `Disable sign-in for "${row.original.displayName}"? Their account stays intact; they just can't log in until you re-enable.`
: `Re-enable sign-in for "${row.original.displayName}"?`
}
confirmLabel={row.original.isActive ? 'Disable' : 'Enable'}
onConfirm={() => handleToggleActive(row.original)}
loading={togglingId === row.original.userId}
/>
</PermissionGate>
<PermissionGate resource="admin" action="manage_users">
<ConfirmationDialog
trigger={
<Button
variant="ghost"
size="sm"
title="Remove from port"
className="text-destructive hover:text-destructive"
>
<Trash2 className="h-4 w-4" aria-hidden />
<span className="sr-only">Remove</span>
</Button>
}
title="Remove User"
description={`Remove "${row.original.displayName}" from this port? They will lose access but their account remains.`}
confirmLabel="Remove"
onConfirm={() => handleRemoveUser(row.original.userId)}
loading={deletingId === row.original.userId}
/>
</PermissionGate>
</div>
),
enableSorting: false,
size: 120,
},
];
return (
<div>
<PageHeader
title="User Management"
description="Manage users and their roles for this port"
actions={
<Button onClick={handleNewUser}>
<Plus className="mr-1.5 h-4 w-4" aria-hidden />
New User
</Button>
}
/>
<DataTable
columns={columns}
data={users}
isLoading={loading}
getRowId={(row) => row.userId}
cardRender={(row) => (
<UserCard
user={row.original}
onEdit={handleEditUser}
onRemove={handleRemoveUser}
onToggleActive={handleToggleActive}
isRemoving={deletingId === row.original.userId}
isToggling={togglingId === row.original.userId}
/>
)}
emptyState={
<div className="text-center py-8">
<p className="text-muted-foreground">No users assigned to this port.</p>
<Button variant="link" onClick={handleNewUser} className="mt-2">
Add the first user
</Button>
</div>
}
/>
<UserForm
open={formOpen}
onOpenChange={setFormOpen}
user={editingUser}
onSuccess={fetchUsers}
/>
</div>
);
}