{
  "$schema": "https://ui.shadcn.com/schema/registry-item.json",
  "name": "dashboard-04",
  "title": "CRM dashboard",
  "description": "A CRM dashboard: sales stats, open pipeline by stage, monthly bookings, lead conversion, a quarter forecast by rep, deal activity and stuck deals, filtered by segment.",
  "registryDependencies": [
    "https://www.dashboardblocks.com/r/radix/activity-feed-01.json",
    "https://www.dashboardblocks.com/r/radix/block-state.json",
    "https://www.dashboardblocks.com/r/radix/chart-panel-04.json",
    "https://www.dashboardblocks.com/r/radix/dashboard-header.json",
    "https://www.dashboardblocks.com/r/radix/funnel-03.json",
    "https://www.dashboardblocks.com/r/radix/pipeline.json",
    "https://www.dashboardblocks.com/r/radix/pipeline-02.json",
    "https://www.dashboardblocks.com/r/radix/pipeline-03.json",
    "https://www.dashboardblocks.com/r/radix/pipeline-04.json",
    "https://www.dashboardblocks.com/r/radix/stat-group-02.json"
  ],
  "files": [
    {
      "path": "registry/components/dashboardblocks/dashboards/dashboard-04.tsx",
      "content": "'use client'\n\nimport {\n  type Activity,\n  ActivityFeed1,\n} from '@/registry/components/dashboardblocks/activity-feed/activity-feed-01'\nimport {\n  BlockBusy,\n  BlockStateProvider,\n  type BlockStateProps,\n} from '@/registry/components/dashboardblocks/block-state'\nimport { ChartPanel4 } from '@/registry/components/dashboardblocks/chart-panel/chart-panel-04'\nimport {\n  type DateRangePreset,\n  DateRangePicker,\n  ExportMenu,\n  FilterChip,\n  FilterMenu,\n  getDateRange,\n  getPreset,\n  getPreviousRange,\n} from '@/registry/components/dashboardblocks/dashboard-header'\nimport { Funnel3 } from '@/registry/components/dashboardblocks/funnel/funnel-03'\nimport type {\n  PipelineItem,\n  PipelineStage,\n} from '@/registry/components/dashboardblocks/pipeline'\nimport { Pipeline2 } from '@/registry/components/dashboardblocks/pipeline/pipeline-02'\nimport { Pipeline3 } from '@/registry/components/dashboardblocks/pipeline/pipeline-03'\nimport { Pipeline4 } from '@/registry/components/dashboardblocks/pipeline/pipeline-04'\nimport { StatGroup2 } from '@/registry/components/dashboardblocks/stat-group/stat-group-02'\nimport { IconPlaceholder } from '@/registry/icons/icon-placeholder'\nimport {\n  formatCurrency,\n  formatDate,\n  formatDateRange,\n  formatPercent,\n} from '@/registry/lib/dashboardblocks/format'\nimport { useEffect, useState } from 'react'\n\ninterface Dashboard4Props extends BlockStateProps {\n  empty?: boolean\n  title: string\n  /** The last day of every date range. */\n  today: Date\n}\n\nconst exampleProps: Dashboard4Props = {\n  title: 'Sales overview',\n  today: new Date(Date.UTC(2026, 8, 25)),\n}\n\nconst DAY = 86_400_000\nconst NOW_HOURS = 17\n\nconst SEGMENTS = [\n  { cycle: 24, deal: 9_400, leads: 6, name: 'SMB', rates: [0.36, 0.48, 0.34] },\n  { cycle: 48, deal: 36_500, leads: 3.5, name: 'Mid-market', rates: [0.42, 0.54, 0.29] },\n  { cycle: 96, deal: 96_000, leads: 3, name: 'Enterprise', rates: [0.5, 0.6, 0.24] },\n]\n\nconst STAGES: PipelineStage[] = [\n  { expectedDays: 7, id: 'lead', label: 'Lead', probability: 0.05 },\n  { expectedDays: 10, id: 'qualified', label: 'Qualified', probability: 0.1 },\n  { expectedDays: 14, id: 'discovery', label: 'Discovery', probability: 0.25 },\n  { expectedDays: 14, id: 'proposal', label: 'Proposal', probability: 0.5 },\n  { expectedDays: 10, id: 'negotiation', label: 'Negotiation', probability: 0.75 },\n]\n\nconst REPS = [\n  { name: 'Luis Romero', quota: 180_000, segment: 'SMB', share: 0.56 },\n  { name: 'Aiko Tanaka', quota: 175_000, segment: 'SMB', share: 0.44 },\n  { name: 'Jonas Weber', quota: 460_000, segment: 'Mid-market', share: 0.45 },\n  { name: 'Grace Kim', quota: 470_000, segment: 'Mid-market', share: 0.55 },\n  { name: 'Maya Patel', quota: 1_900_000, segment: 'Enterprise', share: 1 },\n]\n\nconst OPEN_DEALS: Record<string, number[]> = {\n  Enterprise: [4, 3, 3, 2, 2],\n  'Mid-market': [9, 7, 5, 4, 3],\n  SMB: [14, 10, 8, 5, 4],\n}\n\nconst COMPANIES = [\n  'Northwind',\n  'Brightline',\n  'Kestrel',\n  'Halcyon',\n  'Meridian',\n  'Lumen',\n  'Copperleaf',\n  'Bluefin',\n  'Ardent',\n  'Tidewater',\n  'Summit',\n  'Harbor',\n  'Evergreen',\n  'Foxglove',\n  'Granite',\n  'Juniper',\n  'Keystone',\n  'Larkspur',\n  'Mosaic',\n  'Nimbus',\n  'Orchard',\n  'Pinnacle',\n  'Quarry',\n  'Redwood',\n  'Silverline',\n  'Trellis',\n  'Upland',\n  'Vantage',\n  'Willow',\n  'Zephyr',\n]\nconst INDUSTRIES = [\n  'Labs',\n  'Health',\n  'Logistics',\n  'Foods',\n  'Capital',\n  'Robotics',\n  'Studio',\n  'Energy',\n  'Retail',\n  'Systems',\n  'Media',\n  'Bank',\n  'Freight',\n  'Clinics',\n  'Software',\n]\n\nfunction random(seed: number) {\n  let state = seed\n  return () => {\n    state = (state + 0x6d2b79f5) | 0\n    let value = Math.imul(state ^ (state >>> 15), 1 | state)\n    value = (value + Math.imul(value ^ (value >>> 7), 61 | value)) ^ value\n    return ((value ^ (value >>> 14)) >>> 0) / 4_294_967_296\n  }\n}\n\ninterface DealActivity extends Activity {\n  segment: string\n}\n\nconst ACTIVITY: (Omit<DealActivity, 'at'> & { minutesAgo: number })[] = [\n  {\n    action: 'moved Keystone Freight to',\n    actor: { name: 'Grace Kim' },\n    id: 'a1',\n    minutesAgo: 12,\n    segment: 'Mid-market',\n    target: 'Negotiation',\n  },\n  {\n    action: 'won a $11,200 deal with',\n    actor: { name: 'Luis Romero' },\n    id: 'a2',\n    minutesAgo: 47,\n    segment: 'SMB',\n    target: 'Orchard Foods',\n  },\n  {\n    action: 'sent a proposal to',\n    actor: { name: 'Maya Patel' },\n    id: 'a3',\n    minutesAgo: 95,\n    segment: 'Enterprise',\n    target: 'Meridian Bank',\n  },\n  {\n    action: 'booked a demo with',\n    actor: { name: 'Aiko Tanaka' },\n    id: 'a4',\n    minutesAgo: 160,\n    segment: 'SMB',\n    target: 'Foxglove Studio',\n  },\n  {\n    action: 'lost',\n    actor: { name: 'Jonas Weber' },\n    id: 'a5',\n    minutesAgo: 240,\n    segment: 'Mid-market',\n    target: 'Tidewater Logistics',\n  },\n  {\n    action: 'qualified',\n    actor: { name: 'Maya Patel' },\n    id: 'a6',\n    minutesAgo: 60 * 19,\n    segment: 'Enterprise',\n    target: 'Silverline Energy',\n  },\n  {\n    action: 'won a $42,800 deal with',\n    actor: { name: 'Grace Kim' },\n    id: 'a7',\n    minutesAgo: 60 * 21,\n    segment: 'Mid-market',\n    target: 'Lumen Clinics',\n  },\n  {\n    action: 'moved Pinnacle Retail to',\n    actor: { name: 'Luis Romero' },\n    id: 'a8',\n    minutesAgo: 60 * 23,\n    segment: 'SMB',\n    target: 'Proposal',\n  },\n  {\n    action: 'added a note to',\n    actor: { name: 'Maya Patel' },\n    id: 'a9',\n    minutesAgo: 60 * 26,\n    segment: 'Enterprise',\n    target: 'Vantage Capital',\n  },\n]\n\nconst PRESETS: DateRangePreset[] = ['7d', '30d', '90d']\n\nconst currency = (value: number) => formatCurrency(value)\n\ninterface Query {\n  preset: DateRangePreset\n  segment: string | null\n}\n\nfunction dayAt(segment: (typeof SEGMENTS)[number], offset: number, today: Date) {\n  const weekday = new Date(today.getTime() - offset * DAY).getUTCDay()\n  const weekend = weekday === 0 || weekday === 6\n  const leads =\n    segment.leads *\n    (1 - offset * 0.0015 + Math.sin(offset / 5 + segment.cycle) * 0.14) *\n    (weekend ? 0.3 : 1.25)\n  const qualified = leads * segment.rates[0]\n  const proposals = qualified * segment.rates[1]\n  const won =\n    proposals * segment.rates[2] * (1 + Math.sin(offset / 13) * 0.06 - offset * 0.0008)\n  const deal = segment.deal * (1 + Math.sin(offset / 7 + 1) * 0.08)\n  return {\n    cycle: segment.cycle * (1 + Math.sin(offset / 17) * 0.05 + offset * 0.001),\n    leads,\n    proposals,\n    qualified,\n    revenue: won * deal,\n    won,\n  }\n}\n\ntype Day = ReturnType<typeof dayAt>\n\nfunction totalAt(segments: typeof SEGMENTS, offset: number, today: Date): Day {\n  const days = segments.map((segment) => dayAt(segment, offset, today))\n  const sum = (key: keyof Day) => days.reduce((total, day) => total + day[key], 0)\n  const won = sum('won')\n  return {\n    cycle: days.reduce((total, day) => total + day.cycle * day.won, 0) / (won || 1),\n    leads: sum('leads'),\n    proposals: sum('proposals'),\n    qualified: sum('qualified'),\n    revenue: sum('revenue'),\n    won,\n  }\n}\n\nfunction buildOpenDeals(today: Date): (PipelineItem & { segment: string })[] {\n  const next = random(42)\n  let index = 0\n  return SEGMENTS.flatMap((segment) => {\n    const owners = REPS.filter((rep) => rep.segment === segment.name)\n    return STAGES.flatMap((stage, stageIndex) =>\n      Array.from({ length: OPEN_DEALS[segment.name][stageIndex] }, (_, dealIndex) => {\n        const company = COMPANIES[index % COMPANIES.length]\n        const industry =\n          INDUSTRIES[\n            (index * 7 + Math.floor(index / COMPANIES.length)) % INDUSTRIES.length\n          ]\n        index++\n        const days = Math.floor(next() ** 1.6 * (stage.expectedDays ?? 7) * 1.3)\n        const value = Math.round((segment.deal * (0.5 + next() * 1.1)) / 500) * 500\n        return {\n          enteredStageAt: new Date(today.getTime() - days * DAY),\n          id: `${segment.name}-${stage.id}-${dealIndex}`,\n          owner: owners[dealIndex % owners.length].name,\n          segment: segment.name,\n          stage: stage.id,\n          subtitle: segment.name,\n          title: `${company} ${industry}`,\n          value,\n        }\n      }),\n    )\n  })\n}\n\nfunction buildCrmData({ preset, segment }: Query, today: Date) {\n  const days = getPreset(preset).days\n  const range = getDateRange(preset, today)\n  const previousRange = getPreviousRange(range)\n  const segments = segment ? SEGMENTS.filter((item) => item.name === segment) : SEGMENTS\n\n  const series = (shift: number) =>\n    Array.from({ length: days }, (_, index) =>\n      totalAt(segments, days - 1 - index + shift, today),\n    )\n  const current = series(0)\n  const previous = series(days)\n  const totals = (points: Day[], whole = true) => {\n    const sum = (key: keyof Day) => points.reduce((total, point) => total + point[key], 0)\n    const count = (key: keyof Day) => (whole ? Math.round(sum(key)) : sum(key))\n    const exactWon = sum('won') || 1\n    const won = count('won')\n    const proposals = count('proposals')\n    const deal = sum('revenue') / exactWon\n    return {\n      cycle:\n        points.reduce((total, point) => total + point.cycle * point.won, 0) / exactWon,\n      deal,\n      leads: count('leads'),\n      proposals,\n      qualified: count('qualified'),\n      revenue: won * deal,\n      winRate: proposals > 0 ? (won / proposals) * 100 : 0,\n      won,\n    }\n  }\n  const now = totals(current)\n  const before = totals(previous)\n  const week = [...previous.slice(-6), ...current]\n  const trend = current.map((_, index) => totals(week.slice(index, index + 7), false))\n\n  const monthStart = (back: number) =>\n    Date.UTC(today.getUTCFullYear(), today.getUTCMonth() - back, 1)\n  const months = Array.from({ length: 12 }, (_, index) => {\n    const back = 12 - index\n    const start = monthStart(back)\n    const end = monthStart(back - 1)\n    let revenue = 0\n    for (let time = start; time < end; time += DAY) {\n      revenue += totalAt(segments, (today.getTime() - time) / DAY, today).revenue\n    }\n    return {\n      label: formatDate(new Date(start), 'month'),\n      value: Math.round(revenue / 100) * 100,\n    }\n  })\n\n  const quarter = Math.floor(today.getUTCMonth() / 3)\n  const quarterStart = Date.UTC(today.getUTCFullYear(), quarter * 3, 1)\n  const elapsed = Math.floor((today.getTime() - quarterStart) / DAY) + 1\n  const closedThisQuarter = (name: string) => {\n    const item = SEGMENTS.find((entry) => entry.name === name)\n    if (!item) return 0\n    return Array.from({ length: elapsed }, (_, offset) =>\n      dayAt(item, offset, today),\n    ).reduce((total, day) => total + day.revenue, 0)\n  }\n  const deals = buildOpenDeals(today).filter(\n    (deal) => !segment || deal.segment === segment,\n  )\n  const reps = REPS.filter((rep) => !segment || rep.segment === segment)\n  const bestMonth = months.reduce((best, month) =>\n    month.value > best.value ? month : best,\n  )\n\n  return {\n    activity: ACTIVITY.filter((item) => !segment || item.segment === segment)\n      .slice(0, 6)\n      .map(({ minutesAgo, ...item }) => ({\n        ...item,\n        at: new Date(today.getTime() + NOW_HOURS * 3_600_000 - minutesAgo * 60_000),\n      })),\n    deals,\n    funnel: [\n      { label: 'Leads', value: now.leads },\n      { label: 'Qualified', value: now.qualified },\n      { label: 'Proposal sent', value: now.proposals },\n      { label: 'Won', value: now.won },\n    ],\n    months,\n    owners: reps.map((rep) => ({\n      closed: Math.round((closedThisQuarter(rep.segment) * rep.share) / 1_000) * 1_000,\n      deals: deals\n        .filter((deal) => deal.owner === rep.name)\n        .map((deal) => ({ stage: deal.stage, value: deal.value ?? 0 })),\n      name: rep.name,\n      quota: rep.quota,\n    })),\n    bookingsSummary: `${bestMonth.label} was the best month of the last 12, with ${currency(bestMonth.value)} won.`,\n    previousLabel: formatDateRange(previousRange),\n    quarter: { label: `Q${quarter + 1} ${today.getUTCFullYear()}` },\n    stages: STAGES.map((stage) => {\n      const inStage = deals.filter((deal) => deal.stage === stage.id)\n      return {\n        count: inStage.length,\n        label: stage.label,\n        value: inStage.reduce((sum, deal) => sum + (deal.value ?? 0), 0),\n      }\n    }),\n    stats: [\n      {\n        formatter: currency,\n        history: trend.map((point) => Math.round(point.revenue)),\n        key: 'bookings',\n        label: 'Bookings',\n        previous: Math.round(before.revenue),\n        value: Math.round(now.revenue),\n      },\n      {\n        changeType: 'points' as const,\n        formatter: (value: number) =>\n          formatPercent(value / 100, { minimumFractionDigits: 1 }),\n        history: trend.map((point) => Number(point.winRate.toFixed(1))),\n        key: 'win-rate',\n        label: 'Win rate',\n        previous: Number(before.winRate.toFixed(1)),\n        value: Number(now.winRate.toFixed(1)),\n      },\n      {\n        formatter: currency,\n        history: trend.map((point) => Math.round(point.deal)),\n        key: 'deal-size',\n        label: 'Avg deal size',\n        previous: Math.round(before.deal),\n        value: Math.round(now.deal),\n      },\n      {\n        formatter: (value: number) => `${value} days`,\n        goodDirection: 'down' as const,\n        history: trend.map((point) => Math.round(point.cycle)),\n        key: 'cycle',\n        label: 'Sales cycle',\n        previous: Math.round(before.cycle),\n        value: Math.round(now.cycle),\n      },\n    ],\n  }\n}\n\nconst Dashboard4 = (props: Dashboard4Props) => {\n  const { empty = false, errorMessage, status, title, today } = props\n  const [query, setQuery] = useState<Query>({ preset: '90d', segment: null })\n  const [displayedQuery, setDisplayedQuery] = useState(query)\n  const busy = displayedQuery !== query\n\n  useEffect(() => {\n    if (displayedQuery === query) return\n    const timer = setTimeout(() => setDisplayedQuery(query), 500)\n    return () => clearTimeout(timer)\n  }, [query, displayedQuery])\n\n  const update = (patch: Partial<Query>) =>\n    setQuery((current) => ({ ...current, ...patch }))\n  const data = buildCrmData(displayedQuery, today)\n  const range = getDateRange(query.preset, today)\n\n  return (\n    <BlockStateProvider\n      errorMessage={errorMessage}\n      state={status ?? (empty ? 'empty' : undefined)}\n    >\n      <div className='@container flex w-full flex-col gap-8'>\n        <header className='flex flex-col gap-2'>\n          <div className='flex flex-wrap items-start justify-between gap-3'>\n            <h1 className='min-w-0 text-2xl font-semibold tracking-tight'>{title}</h1>\n            <ExportMenu disabled={status !== undefined || empty} onExport={() => {}} />\n          </div>\n          <div className='flex flex-wrap items-center justify-between gap-x-4 gap-y-2'>\n            <p className='text-muted-foreground min-w-0 leading-relaxed'>\n              Showing{' '}\n              <DateRangePicker\n                onValueChange={(preset) => update({ preset })}\n                presets={PRESETS}\n                today={today}\n                value={query.preset}\n                variant='inline'\n              />\n              <span aria-live='polite'>\n                , {formatDateRange(range)}, compared with{' '}\n                {formatDateRange(getPreviousRange(range))}.\n              </span>\n            </p>\n            <div className='flex flex-wrap items-center gap-2'>\n              {query.segment && (\n                <FilterChip\n                  field='Segment'\n                  value={query.segment}\n                  onRemove={() => update({ segment: null })}\n                />\n              )}\n              <FilterMenu\n                allLabel='All segments'\n                label='Segment'\n                onValueChange={(segment) => update({ segment })}\n                options={SEGMENTS.map((item) => item.name)}\n                value={query.segment}\n              >\n                <IconPlaceholder\n                  lucide='BuildingIcon'\n                  tabler='IconBuilding'\n                  hugeicons='Building03Icon'\n                  phosphor='BuildingIcon'\n                  remixicon='RiBuildingLine'\n                />\n                {query.segment ? 'Change segment' : 'Filter by segment'}\n              </FilterMenu>\n            </div>\n          </div>\n        </header>\n        <BlockBusy\n          busy={busy}\n          label='Updating the dashboard'\n          className='grid gap-4 @4xl:grid-cols-3'\n        >\n          <div className='grid @4xl:col-span-3'>\n            <StatGroup2\n              errorMessage={errorMessage}\n              status={status}\n              comparison={data.previousLabel}\n              metrics={empty ? [] : data.stats}\n              title='Sales performance'\n            />\n          </div>\n          <div className='grid @4xl:col-span-3'>\n            <Pipeline2\n              errorMessage={errorMessage}\n              status={status}\n              noun='deals'\n              stages={empty ? [] : data.stages}\n              title='Open pipeline'\n            />\n          </div>\n          <div className='grid @4xl:col-span-2'>\n            <ChartPanel4\n              errorMessage={errorMessage}\n              status={status}\n              data={empty ? [] : data.months}\n              description={status || empty ? '' : data.bookingsSummary}\n              formatter={currency}\n              title='Bookings'\n            />\n          </div>\n          <div className='grid'>\n            <Funnel3\n              errorMessage={errorMessage}\n              status={status}\n              description='How far new leads got, step by step.'\n              stages={empty ? [] : data.funnel}\n              title='Lead conversion'\n            />\n          </div>\n          <div className='grid @4xl:col-span-2'>\n            <Pipeline4\n              errorMessage={errorMessage}\n              status={status}\n              owners={empty ? [] : data.owners}\n              stages={STAGES}\n              title={`${data.quarter.label} forecast`}\n            />\n          </div>\n          <div className='grid'>\n            <ActivityFeed1\n              errorMessage={errorMessage}\n              status={status}\n              activities={empty ? [] : data.activity}\n              now={new Date(today.getTime() + NOW_HOURS * 3_600_000)}\n              title='Deal activity'\n            />\n          </div>\n          <div className='grid @4xl:col-span-3'>\n            <Pipeline3\n              errorMessage={errorMessage}\n              status={status}\n              items={empty ? [] : data.deals}\n              noun='open deals'\n              now={today}\n              stages={STAGES}\n              title='Stuck deals'\n            />\n          </div>\n        </BlockBusy>\n      </div>\n    </BlockStateProvider>\n  )\n}\n\nexport { Dashboard4, exampleProps as dashboard4ExampleProps, type Dashboard4Props }\n",
      "type": "registry:component",
      "target": "@components/dashboardblocks/dashboards/dashboard-04.tsx"
    }
  ],
  "meta": {
    "shows": "A full sales dashboard in shadcn Cards, with stats, open pipeline by stage, bookings, lead conversion, a quarter forecast and stuck deals.",
    "size": "page",
    "usedWith": [],
    "component": "Dashboard4",
    "props": "{ empty?: boolean; title: string; today: Date; errorMessage?: string; status?: \"loading\" | \"error\" }"
  },
  "type": "registry:block"
}
