/crm/leadsLeads
Every lead with their face, company, source, status, owner and value — facets on source and status, an advanced filter of rules the address carries, four figures that recount as you work, and a row menu that converts a lead into a qualified deal on the pipeline.
Every row is a db.leads record with its rep resolved against db.members, so both the lead and the owner are drawn with their avatarFor faces. The rows and REFERENCE_DATE go to one client island that renders the figures and the table together: open leads, their value, new leads over the last thirty days against the thirty before, and the win rate are counted from the same rows the table shows, so a conversion moves them in the render that turns its pill. Search reads the name, the company and the email together; the facets are source and status. Convert to deal runs convertLead, the dashboard's shared server action from actions-crm — the same one the CRM overview's leads table calls — returning Result: the lead is marked won and a qualified deal opens under its company for its value, owned by its rep, forecast a month out; a lead already won or lost, or gone from the store, is refused in a danger callout above the rows, and a success names the deal in an always-mounted status line with a link to the pipeline. Advanced filter, beside the quick facets, opens a FilterBuilder over the lead fields — Name and Company as text; Source and Status in the page's own words and Owner from the reps the rows name; Value as a number; Created as a day — whose rules stay a draft until Apply, with a count of the leads they would keep. Apply narrows the table, never the figures, which count the whole book; the status line says how many leads match, and the filter is written to ?filter= with filterToParam, so the view is a link. On load the page reads it back with filterFromParam against the same fields: a value it did not write reads as no filter, and a rule left without a value is dropped rather than matching nothing, so what is applied is what a reload reads. "In the last N days" counts back from REFERENCE_DATE. An active filter shows as a FilterChip counting its rules, the filter in words from describeFilter, and Clear, which takes it out of the address and hands the focus to the Advanced filter button — on a phone, where that button sits in the Filters sheet, to the sheet's own; the facets and the search narrow what it lets through. The island reads the address, so the page wraps it in a Suspense boundary with a skeleton, as a prerendered page must. Composes AppShell, PageHeader, StatCardGroup, StatCard, DataTable, DataTableColumnHeader, DataTableRowActions, UserCell, Badge, StatusBadge, NumberCell, TruncateCell, Callout, FilterBuilder, FilterChip, Popover, Skeleton, AdvancedFilter (block-local) and LeadsView (block-local).
Preview
import * as React from "react"
import { REFERENCE_DATE } from "@/lib/sample-data"
import { AppShell } from "@/components/ui/app-shell"
import { PageHeader } from "@/components/ui/page-header"
import { Skeleton } from "@/components/ui/skeleton"
import { signOut } from "./actions"
import { LeadsView } from "./components/leads-view"
import { currentUser, lastUpdated, leadRows, shellNotifications } from "./data"
import { NAV, ROUTES } from "@/lib/dashboards/crm/nav"
/**
* Every lead. A server component: it reads `db.leads` with each rep resolved,
* and hands the rows — and "now" — to the one island that counts them,
* filters them and converts them. The island reads `?filter=` off the URL, so
* it sits inside a Suspense boundary — a prerendered page that calls
* useSearchParams outside one fails the build.
*/
export default async function LeadsPage() {
return (
<AppShell
nav={NAV}
activeHref={ROUTES.leads}
user={currentUser()}
notifications={shellNotifications()}
now={REFERENCE_DATE}
onSignOut={signOut}
>
<PageHeader
titleId="crm-leads-title"
title="Leads"
description="Everyone who raised a hand: where they came from, how far they got, what they could be worth."
meta={lastUpdated()}
/>
<React.Suspense fallback={<Skeleton className="h-[44rem] w-full rounded-xl" />}>
<LeadsView titleId="crm-leads-title" rows={leadRows()} now={REFERENCE_DATE} />
</React.Suspense>
</AppShell>
)
}Install
npx shadcn@latest add @vibra/crm-leadsNeeds the @vibra registry in your components.json — set it up once.
Source
import * as React from "react"
import { REFERENCE_DATE } from "@/lib/sample-data"
import { AppShell } from "@/components/ui/app-shell"
import { PageHeader } from "@/components/ui/page-header"
import { Skeleton } from "@/components/ui/skeleton"
import { signOut } from "./actions"
import { LeadsView } from "./components/leads-view"
import { currentUser, lastUpdated, leadRows, shellNotifications } from "./data"
import { NAV, ROUTES } from "@/lib/dashboards/crm/nav"
/**
* Every lead. A server component: it reads `db.leads` with each rep resolved,
* and hands the rows — and "now" — to the one island that counts them,
* filters them and converts them. The island reads `?filter=` off the URL, so
* it sits inside a Suspense boundary — a prerendered page that calls
* useSearchParams outside one fails the build.
*/
export default async function LeadsPage() {
return (
<AppShell
nav={NAV}
activeHref={ROUTES.leads}
user={currentUser()}
notifications={shellNotifications()}
now={REFERENCE_DATE}
onSignOut={signOut}
>
<PageHeader
titleId="crm-leads-title"
title="Leads"
description="Everyone who raised a hand: where they came from, how far they got, what they could be worth."
meta={lastUpdated()}
/>
<React.Suspense fallback={<Skeleton className="h-[44rem] w-full rounded-xl" />}>
<LeadsView titleId="crm-leads-title" rows={leadRows()} now={REFERENCE_DATE} />
</React.Suspense>
</AppShell>
)
}/**
* What the leads page reads: every `db.leads` row, with the rep who owns it
* resolved against `db.members` so the table can show their face. The four
* figures over the table are worked out from these same rows in the island
* that holds them, so a converted lead moves them the moment it converts.
* "Now" is `REFERENCE_DATE`; nothing here reads a clock.
*/
import { formatDate, getInitials } from "@/lib/format"
import { avatarFor, db, REFERENCE_DATE, type Lead, type Member } from "@/lib/sample-data"
/** One row of the leads table. */
export type LeadRow = {
id: string
name: string
email: string
avatarUrl?: string
company: string
source: Lead["source"]
status: Lead["status"]
/** What the deal would be worth, in whole dollars. */
value: number
createdAt: Date
owner: { name: string; avatarUrl?: string }
}
/** Every lead on the books, newest first; the table filters, sorts and pages them itself. */
export function leadRows(): LeadRow[] {
const members = new Map(db.members.all().map((member) => [member.id, member]))
return db.leads
.all()
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime())
.map((lead) => {
const owner = members.get(lead.ownerId)
const ownerName = owner?.name ?? "Unassigned"
return {
id: lead.id,
name: lead.name,
email: lead.email,
avatarUrl: lead.avatarUrl ?? avatarFor(lead.name),
company: lead.company,
source: lead.source,
status: lead.status,
value: lead.valueCents / 100,
createdAt: lead.createdAt,
owner: { name: ownerName, avatarUrl: owner ? (owner.avatarUrl ?? avatarFor(owner.name)) : undefined },
}
})
}
/** The freshness line under the title, measured against REFERENCE_DATE. */
export function lastUpdated(): string {
return `Synced ${formatDate(REFERENCE_DATE, "medium", { timeZone: "UTC" })}`
}
function ownerRow(): Member {
return db.members.all().find((member) => member.role === "owner") ?? db.members.all()[0]
}
/** The person looking at the page: whoever owns this workspace. */
export function currentUser() {
const owner = ownerRow()
return { name: owner.name, email: owner.email, initials: getInitials(owner.name), avatarUrl: owner.avatarUrl }
}
/** The bell's contents: the newest notifications, unread first in the panel. */
export function shellNotifications() {
return db.notifications
.all()
.sort((a, b) => b.at.getTime() - a.at.getTime())
.slice(0, 6)
.map(({ id, title, description, at, read, href }) => ({ id, title, description, at, read, href }))
}"use server"
import { mockAuthAdapter } from "@/lib/auth-adapter"
import { type Result } from "@/lib/sample-data"
/**
* The one thing only this page changes. Converting a lead is the dashboard's
* — the overview's leads table does it too — so it lives once, as
* `convertLead` in `@/lib/dashboards/crm/actions`, and the
* leads table imports it from there.
*/
export async function signOut(): Promise<Result<{ signedOut: true }>> {
await mockAuthAdapter.signOut()
return { ok: true, data: { signedOut: true } }
}"use client"
import * as React from "react"
import { ListFilterIcon } from "lucide-react"
import { Button } from "@/components/ui/button"
import { FilterBuilder, type FilterField, type FilterValue } from "@/components/ui/filter-builder"
import { Popover, PopoverContent, PopoverTitle, PopoverTrigger } from "@/components/ui/popover"
export type AdvancedFilterProps = {
fields: FilterField[]
/** The filter the table is narrowed by: where the builder starts each time it opens. */
value: FilterValue
/** How many leads a filter lets through, for the count beside Apply. */
matching: (filter: FilterValue) => number
total: number
onApply: (filter: FilterValue) => void
}
/**
* "Advanced filter" beside the table's quick facets: a popover holding a
* FilterBuilder over the lead fields. The rules are a draft until Apply —
* the count beside it says what they would keep — and Cancel, Escape or a
* press outside leaves the table as it was. Each opening starts from the
* filter that is applied.
*/
export function AdvancedFilter({ fields, value, matching, total, onApply }: AdvancedFilterProps) {
const [open, setOpen] = React.useState(false)
const [draft, setDraft] = React.useState(value)
const count = matching(draft)
return (
<Popover
open={open}
onOpenChange={(next) => {
if (next) setDraft(value)
setOpen(next)
}}
>
<PopoverTrigger
render={
<Button type="button" variant="outline" size="sm" data-slot="leads-advanced-filter-trigger">
<ListFilterIcon data-icon="inline-start" aria-hidden="true" />
Advanced filter
</Button>
}
/>
{/* COUPLED TO registry/vibra/ui/popover.tsx: a builder's rows want more room than a popover's w-72 p-2.5. */}
<PopoverContent align="start" className="w-xl max-w-(--available-width) gap-3 p-3">
<PopoverTitle>Advanced filter</PopoverTitle>
<FilterBuilder aria-label="Filter leads" fields={fields} value={draft} onValueChange={setDraft} />
<div className="flex flex-wrap items-center gap-2 border-t border-rule pt-3">
<p className="text-xs text-muted-foreground tabular-nums">
{/* A run of its own, left to right: a right-to-left page would turn "12 of 40 leads" round. */}
<bdi dir="ltr">
{count} of {total} leads
</bdi>
</p>
<div className="ms-auto flex items-center gap-2">
<Button type="button" variant="ghost" size="sm" onClick={() => setOpen(false)}>
Cancel
</Button>
<Button
type="button"
size="sm"
onClick={() => {
onApply(draft)
setOpen(false)
}}
>
Apply
</Button>
</div>
</div>
</PopoverContent>
</Popover>
)
}"use client"
import { HandshakeIcon } from "lucide-react"
import { formatCurrency, formatDate } from "@/lib/format"
import { Badge } from "@/components/ui/badge"
import {
DataTableColumnHeader,
DataTableRowActions,
type DataTableColumnDef,
} from "@/components/ui/data-table"
import { StatusBadge } from "@/components/ui/status-badge"
import { NumberCell, TruncateCell } from "@/components/ui/table-cells"
import { UserCell } from "@/components/ui/user-cell"
import { type LeadRow } from "../data"
import { LEAD_STATUS_MAP, SOURCE_LABELS, STATUS_LABELS } from "./leads-vocabulary"
/**
* Columns step in as the table's own frame allows — a container query, not
* the viewport, because at 768 and 1024 the sidebar leaves the table less
* room than the window suggests. Below 28rem: the lead, its status and its
* menu; then the value, the company, the owner, the day it came in, and
* last the source.
*/
const FROM = {
value: "hidden @md/leads:table-cell",
company: "hidden @min-[43rem]/leads:table-cell",
owner: "hidden @min-[53rem]/leads:table-cell",
created: "hidden @min-[60rem]/leads:table-cell",
source: "hidden @min-[65rem]/leads:table-cell",
} as const
/**
* The leads table's columns. The lead column searches the name, the company
* and the email together, because those are what a rep remembers a lead by.
* Convert is offered on every row — the server owns which leads it applies
* to, and a refusal says why, which is more use than a greyed-out item.
*/
export function leadColumns({ onConvert }: { onConvert: (row: LeadRow) => void }): DataTableColumnDef<LeadRow>[] {
return [
{
id: "lead",
accessorFn: (row) => `${row.name} ${row.company} ${row.email}`,
header: ({ column }) => <DataTableColumnHeader column={column} title="Lead" />,
cell: ({ row }) => (
// In a narrow frame the email truncates, so the status and the menu stay in view.
<div className="max-w-[10.5rem] @min-[33rem]/leads:max-w-none">
<UserCell size="sm" name={row.original.name} email={row.original.email} src={row.original.avatarUrl} />
</div>
),
meta: { label: "Lead" },
},
{
accessorKey: "company",
header: ({ column }) => <DataTableColumnHeader column={column} title="Company" />,
cell: ({ row }) => <TruncateCell maxWidth={180}>{row.original.company}</TruncateCell>,
meta: { label: "Company", className: FROM.company },
},
{
accessorKey: "source",
header: ({ column }) => <DataTableColumnHeader column={column} title="Source" />,
cell: ({ row }) => <Badge variant="outline">{SOURCE_LABELS[row.original.source]}</Badge>,
meta: { label: "Source", className: FROM.source },
},
{
accessorKey: "status",
header: ({ column }) => <DataTableColumnHeader column={column} title="Status" />,
cell: ({ row }) => (
<StatusBadge status={row.original.status} map={LEAD_STATUS_MAP} label={STATUS_LABELS[row.original.status]} />
),
meta: { label: "Status" },
},
{
id: "owner",
accessorFn: (row) => row.owner.name,
header: ({ column }) => <DataTableColumnHeader column={column} title="Owner" />,
cell: ({ row }) => <UserCell size="sm" name={row.original.owner.name} src={row.original.owner.avatarUrl} />,
meta: { label: "Owner", className: FROM.owner },
},
{
accessorKey: "value",
header: ({ column }) => <DataTableColumnHeader column={column} title="Value" />,
cell: ({ row }) => (
<NumberCell
value={row.original.value}
format={(value) => formatCurrency(value, "USD", { maximumFractionDigits: 0 })}
/>
),
meta: { align: "right", label: "Value", className: FROM.value },
},
{
accessorKey: "createdAt",
header: ({ column }) => <DataTableColumnHeader column={column} title="Created" />,
cell: ({ row }) => (
<time
dateTime={new Date(row.original.createdAt).toISOString()}
className="block text-right whitespace-nowrap text-muted-foreground tabular-nums"
>
{formatDate(row.original.createdAt, "medium", { timeZone: "UTC" })}
</time>
),
meta: { align: "right", label: "Created", className: FROM.created },
},
{
id: "actions",
size: 44,
enableSorting: false,
enableHiding: false,
cell: ({ row }) => (
<DataTableRowActions
label={`Actions for ${row.original.name}`}
actions={[{ label: "Convert to deal", icon: <HandshakeIcon />, onSelect: () => onConvert(row.original) }]}
/>
),
},
]
}import { type FilterField } from "@/components/ui/filter-builder/filter"
import { type LeadRow } from "../data"
import { SOURCE_LABELS, STATUS_LABELS } from "./leads-vocabulary"
/**
* What a rule of the leads' advanced filter can name. Vocabulary, not data:
* the source and status options are the page's own words, and the owners are
* the reps the rows name, handed in by the island that holds the rows. The
* ids are what `?filter=` carries, so they are short and never renamed.
*/
export function leadFields(owners: string[]): FilterField[] {
const options = (labels: Record<string, string>) => Object.entries(labels).map(([value, label]) => ({ value, label }))
return [
{ id: "name", label: "Name", type: "text" },
{ id: "company", label: "Company", type: "text" },
{ id: "source", label: "Source", type: "enum", options: options(SOURCE_LABELS) },
{ id: "status", label: "Status", type: "enum", options: options(STATUS_LABELS) },
{ id: "owner", label: "Owner", type: "enum", options: owners.map((name) => ({ value: name, label: name })) },
{ id: "value", label: "Value", type: "number" },
{ id: "created", label: "Created", type: "date" },
]
}
/** A lead's value for a field: the owner by name, the day it came in, the rest under their own key. */
export function leadCell(row: LeadRow, field: string): unknown {
if (field === "owner") return row.owner.name
if (field === "created") return row.createdAt
return row[field as keyof LeadRow]
}"use client"
import { formatCurrency, formatNumber, formatPercent } from "@/lib/format"
import { StatCard } from "@/components/ui/stat-card"
import { StatCardGroup } from "@/components/ui/stat-card-group"
import { type LeadRow } from "../data"
import { OPEN_STATUSES } from "./leads-vocabulary"
const DAY_MS = 86_400_000
const WINDOW_DAYS = 30
/** Leads created in the window ending `offset` windows before `now`. */
function createdIn(rows: LeadRow[], now: Date, offset: number): number {
const end = now.getTime() - offset * WINDOW_DAYS * DAY_MS
const start = end - WINDOW_DAYS * DAY_MS
return rows.filter((row) => {
const at = new Date(row.createdAt).getTime()
return at > start && at <= end
}).length
}
/**
* The four figures over the table, worked out from the rows the table holds —
* so converting a lead takes it out of "open" here in the same render that
* turns its pill. New leads is the one figure with an earlier window to be
* measured against, so it is the one with a pill.
*/
export function LeadsStats({ rows, now }: { rows: LeadRow[]; now: Date }) {
const open = rows.filter((row) => OPEN_STATUSES.includes(row.status))
const qualified = rows.filter((row) => row.status === "qualified").length
const won = rows.filter((row) => row.status === "won").length
const lost = rows.filter((row) => row.status === "lost").length
const value = open.reduce((sum, row) => sum + row.value, 0)
const fresh = createdIn(rows, now, 0)
const before = createdIn(rows, now, 1)
return (
<StatCardGroup data-widget="widget-crm-leads-leads-stats" columns={4}>
<StatCard label="Open leads" value={formatNumber(open.length)} description={`${qualified} qualified`} />
<StatCard
label="Open value"
value={formatCurrency(value, "USD", { maximumFractionDigits: 0 })}
description="if every open lead closed"
/>
<StatCard
label="New leads"
value={formatNumber(fresh)}
// A rise from nothing is no percentage, so a window after an empty one carries no pill.
delta={before === 0 ? (fresh === 0 ? 0 : undefined) : fresh / before - 1}
description={`last ${WINDOW_DAYS} days`}
/>
<StatCard
label="Win rate"
value={won + lost === 0 ? "—" : formatPercent(won / (won + lost))}
description={`${won} won · ${lost} lost`}
/>
</StatCardGroup>
)
}"use client"
import * as React from "react"
import Link from "next/link"
import { usePathname, useRouter, useSearchParams } from "next/navigation"
import { cn } from "@/lib/utils"
import { ROUTES } from "@/lib/dashboards/crm/nav"
import { formatCurrency } from "@/lib/format"
import { Button, buttonVariants } from "@/components/ui/button"
import { Callout } from "@/components/ui/callout"
import { DataTable, type DataTableFacet } from "@/components/ui/data-table"
import {
EMPTY_FILTER,
applyFilter,
countRules,
describeFilter,
filterFromParam,
filterToParam,
type FilterValue,
} from "@/components/ui/filter-builder"
import { FilterChip } from "@/components/ui/filter-chip"
import { convertLead } from "@/lib/dashboards/crm/actions"
import { type LeadRow } from "../data"
import { AdvancedFilter } from "./advanced-filter"
import { leadColumns } from "./lead-columns"
import { leadCell, leadFields } from "./lead-fields"
import { LeadsStats } from "./leads-stats"
import { SOURCE_LABELS, STATUS_LABELS } from "./leads-vocabulary"
const FACETS: DataTableFacet<LeadRow>[] = [
{
columnId: "source",
title: "Source",
options: Object.entries(SOURCE_LABELS).map(([value, label]) => ({ label, value })),
},
{
columnId: "status",
title: "Status",
options: Object.entries(STATUS_LABELS).map(([value, label]) => ({ label, value })),
},
]
/** How many leads the filter keeps — a run of its own, left to right, or a right-to-left page would turn "12 leads match" round. */
const matchLine = (count: number) => (
<bdi dir="ltr">{count === 0 ? "No leads match" : count === 1 ? "1 lead matches" : `${count} leads match`}</bdi>
)
/**
* The leads, and the four figures over them, held in one island so they
* cannot disagree. Converting goes through the server: the row takes the
* status the `Result` carries, the figures are recounted from the rows, the
* status line names the deal that opened, and a refusal — a lead already won
* or lost, a lead gone from the store — gets its own alert above the table.
*
* The advanced filter narrows the table and not the figures, which count the
* whole book. It is read from `?filter=` once, on load — a value this page
* did not write reads as no filter — and written back on Apply and Clear, so
* a filtered view is a link. The quick facets and the search narrow what it
* lets through.
*/
export function LeadsView({ titleId, rows: initial, now }: { titleId: string; rows: LeadRow[]; now: Date }) {
const router = useRouter()
const pathname = usePathname()
const params = useSearchParams()
const [rows, setRows] = React.useState(initial)
const [notice, setNotice] = React.useState<{ text: React.ReactNode; pipeline: boolean }>({ text: "", pipeline: false })
const [refusal, setRefusal] = React.useState<string | null>(null)
const viewRef = React.useRef<HTMLDivElement>(null)
const owners = React.useMemo(() => [...new Set(initial.map((row) => row.owner.name))].sort((a, b) => a.localeCompare(b)), [initial])
const fields = React.useMemo(() => leadFields(owners), [owners])
const [filter, setFilter] = React.useState<FilterValue>(() => filterFromParam(params.get("filter") ?? "", fields) ?? EMPTY_FILTER)
// "In the last N days" counts back from the page's now, never the browser's clock.
const matching = React.useCallback((next: FilterValue) => applyFilter(rows, next, fields, { now, get: leadCell }), [rows, fields, now])
const shown = React.useMemo(() => matching(filter), [matching, filter])
const rules = countRules(filter)
const convert = React.useCallback(async (row: LeadRow) => {
setNotice({ text: "", pipeline: false })
setRefusal(null)
const result = await convertLead(row.id)
if (!result.ok) return setRefusal(result.error.message)
const { status, name, dealName, amountCents, ownerName } = result.data
setRows((current) => current.map((entry) => (entry.id === row.id ? { ...entry, status } : entry)))
setNotice({
text: `Converted ${name}: “${dealName}” is on the pipeline at ${formatCurrency(amountCents / 100, "USD", { maximumFractionDigits: 0 })}, owned by ${ownerName}.`,
pipeline: true,
})
}, [])
const columns = React.useMemo(() => leadColumns({ onConvert: (row) => void convert(row) }), [convert])
/** Narrows the table to `next` and writes it to the address; the line says how many leads it keeps. */
function applyAdvanced(next: FilterValue) {
// What is applied is what the address carries and a reload reads back:
// the round trip drops a rule left unfinished, so the chip counts only
// the rules that filter.
const kept = filterFromParam(filterToParam(next), fields) ?? EMPTY_FILTER
const active = countRules(kept) > 0
const query = new URLSearchParams(params.toString())
if (active) query.set("filter", filterToParam(kept))
else query.delete("filter")
const search = query.toString()
router.replace(search ? `${pathname}?${search}` : pathname, { scroll: false })
setFilter(active ? kept : EMPTY_FILTER)
setRefusal(null)
setNotice({ text: active ? matchLine(matching(kept).length) : `All ${rows.length} leads show.`, pipeline: false })
}
function clear() {
applyAdvanced(EMPTY_FILTER)
// The chip goes with the filter, so the focus goes to where a filter is
// made: the Advanced filter button, or on a phone the Filters button that
// holds it — never the top of the page.
requestAnimationFrame(() => {
const targets = viewRef.current?.querySelectorAll<HTMLElement>('[data-slot="leads-advanced-filter-trigger"], [data-slot="data-table-filters-trigger"]')
const seen = (target: HTMLElement) =>
typeof target.checkVisibility === "function" ? target.checkVisibility() : getComputedStyle(target).display !== "none"
;[...(targets ?? [])].find(seen)?.focus()
})
}
return (
<div ref={viewRef} className="flex flex-col gap-[var(--density-gap,1rem)]">
<LeadsStats rows={rows} now={now} />
{/* The container the table's columns measure themselves against. */}
<div className="@container/leads flex flex-col gap-3">
{refusal ? (
<Callout variant="danger" role="alert" title="Not converted">
{refusal}
</Callout>
) : null}
<div className={cn("flex flex-wrap items-baseline gap-x-2 text-sm text-muted-foreground", !notice.text && "sr-only")}>
<p data-slot="leads-status" role="status" aria-live="polite">
{notice.text}
</p>
{notice.pipeline ? (
<Link href={ROUTES.pipeline} className={cn(buttonVariants({ variant: "link", size: "sm" }), "h-auto px-0")}>
Open the pipeline
</Link>
) : null}
</div>
{rules > 0 ? (
// In view at every width: on a phone the Advanced filter button sits in the Filters sheet.
<div data-slot="leads-advanced-filter" className="flex flex-wrap items-center gap-x-2 gap-y-1">
<FilterChip label="Advanced filter" value={`${rules} ${rules === 1 ? "rule" : "rules"}`} />
<p className="min-w-0 text-xs text-pretty text-muted-foreground">{describeFilter(filter, fields)}</p>
<Button type="button" variant="ghost" size="sm" aria-label="Clear the advanced filter" onClick={clear}>
Clear
</Button>
</div>
) : null}
<DataTable
aria-labelledby={titleId}
columns={columns}
data={shown}
facets={FACETS}
toolbar={() => (
<AdvancedFilter fields={fields} value={filter} matching={(next) => matching(next).length} total={rows.length} onApply={applyAdvanced} />
)}
searchKey="lead"
searchPlaceholder="Search leads"
getRowId={(row) => row.id}
enableRowSelection={false}
emptyMessage="No leads match these filters."
pageSizeOptions={[10, 25, 50]}
/>
</div>
</div>
)
}import { type StatusVariant } from "@/components/ui/status-badge"
/**
* The words this page puts on a source and a status. Vocabulary, not data: it
* lives beside the islands that print it, because `data.ts` reads `db` and
* must never reach the browser. The CRM overview prints the same words.
*/
export const SOURCE_LABELS: Record<string, string> = {
website: "Website",
referral: "Referral",
ads: "Ads",
social: "Social",
event: "Event",
}
export const STATUS_LABELS: Record<string, string> = {
new: "New",
contacted: "Contacted",
qualified: "Qualified",
won: "Won",
lost: "Lost",
}
/** A funnel's own words are not status words, so every one of them is mapped. */
export const LEAD_STATUS_MAP: Record<string, StatusVariant> = {
new: "info",
contacted: "primary",
qualified: "warning",
won: "success",
lost: "danger",
}
/** The statuses a lead can still be converted from. */
export const OPEN_STATUSES = ["new", "contacted", "qualified"]