All files / features / dashboard DashboardPage.tsx

63.04% Statements 58/92
61.36% Branches 27/44
51.72% Functions 15/29
65.06% Lines 54/83

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215                            46x   46x   640x 640x 640x 640x 620x 600x 600x 400x 400x 400x   46x       640x                 640x                           640x                           640x                 640x                         640x 640x 640x                     640x 640x 640x 640x               480x 480x                 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x 44x                                                                                                                     44x                                      
import { useState } from 'react'
import { useNavigate } from 'react-router-dom'
import { Activity, Calendar, Ban, LogIn, LogOut, Play } from 'lucide-react'
import { useDashboardStats } from './dashboardApi'
import { useProjects } from '@/features/projects/projectsApi'
import { usePipelines } from '@/features/pipelines/pipelinesApi'
import { useCreateRun } from '@/features/runs/runsApi'
import { ManualTriggerModal } from '@/shared/components/ManualTriggerModal'
import { StatsCard } from '@/shared/components/StatsCard'
import { DataTable, type Column } from '@/shared/components/DataTable'
import { RunPhaseIcon } from '@/shared/components/RunPhaseIcon'
import { SourceBadge } from '@/shared/components/SourceBadge'
import { DurationDisplay } from '@/shared/components/DurationDisplay'
import { Button } from '@/components/ui/button'
 
function relativeTime(dateStr: string | undefined): string {
  if (!dateStr) return '\u2014'
  const diff = Date.now() - new Date(dateStr).getTime()
 I const mins = Math.floor(diff / 60000)
  if (mins < 1) return 'now'
  if (mins < 60) return `${mins} min ago`
  const hours = Math.floor(mins / 60)
  if (hours < 24) return `${hours}h ago`
  const days = Math.floor(hours / 24)
  if (days < 7) return `${days}d ago`
  return new Date(dateStr).toLocaleDateString()
}I
 
const columns: Column[] = [
  {
    key: 'phase',
    label: 'Phase',
    render: (item) => (
      <RunPhaseIcon phase={item.phase as 'pending' | 'running' | 'succeeded' | 'failed'} />
    ),
  },
  {
    key: 'project_name',
    label: 'Project',
    render: (item) => (
      <a
        href={`#/projects/${item.project_id as string}`}
        className="text-primary hover:underline"
        onClick={(e) => e.stopPropagation()}
      >
        {item.project_name as string}
      </a>
    ),
  },
  {
    key: 'pipeline_name',
    label: 'Pipeline',
    render: (item) => (
      <a
        href={`#/pipelines/${item.pipeline_id as string}`}
        className="text-primary hover:underline"
        onClick={(e) => e.stopPropagation()}
      >
        {item.pipeline_name as string}
      </a>
    ),
  },
  {
    key: 'source_type',
    label: 'Source',
    render: (item) => (
      <SourceBadge source={item.source_type as 'manual' | 'webhook' | 'schedule' | 'cli'} />
    ),
  },
  {
    key: 'created_at',
    label: 'Created',
    render: (item) => (
      <span className="text-sm text-muted-foreground">{relativeTime(item.created_at as string)}</span>
    ),
  },
  {
    key: 'token_input',
    label: 'Tokens',
    render: (item) => {
      const input = item.token_input as number
      const output = item.token_output as number
      return <span>{(input + output).toLocaleString()}</span>
    },
  },
  {
    key: 'duration',
    label: 'Duration',
    render: (item) => {
      const started = item.started_at as string | null
      const completed = item.completed_at as string | null
      const phase = item.phase as string
      if (phase === 'running') return <span className="text-blue-500">running</span>
      const ms =
        started && completed
          ? new Date(completed).getTime() - new Date(started).getTime()
          : null
      return <DurationDisplay ms={ms} />
    },
  },
]
 
export function DashboardPage() {
  const navigate = useNavigate()
  const { stats, runs, isLoading, error, refetch } = useDashboardStats()
  const { data: projectsData } = useProjects()
  const createRun = useCreateRun()
 
  const [modalOpen, setModalOpen] = useState(false)
  const [selectedProjectId, setSelectedProjectId] = useState('')
  const { data: pipelinesData } = usePipelines(selectedProjectId)
 
  const projects = projectsData?.data ?? []
  const pipelines = pipelinesData?.data ?? []
 
  const statCards = [
    {
      icon: Activity, label: 'Running', value: stats.running, accent: 'border-blue-500',
      onClick: () => navigate('/runs?phase=running'),
    },
    {
      icon: Calendar, label: 'Today', value: stats.today, accent: 'border-gray-400',
      onClick: () => navigate('/runs?created_after=24h'),
    },
    {
      icon: Ban, label: 'Failed', value: stats.failed, accent: 'border-red-500',
      onClick: () => navigate('/runs?phase=failed'),
    },
    {
      icon: LogIn, label: 'Token In', value: stats.tokenInput, accent: 'border-purple-500',
    },
    {
      icon: LogOut, label: 'Token Out', value: stats.tokenOutput, accent: 'border-orange-500',
    },
  ]
 
  function handleTriggerRun(pipelineId: string, issueKey?: string, additionalData?: string) {
    let sourceMetadata: Record<string, unknown> | null = null
    if (issueKey || additionalData) {
      sourceMetadata = {}
      if (issueKey) sourceMetadata.issue_key = issueKey
      if (additionalData) {
        try {
          const parsed = JSON.parse(additionalData)
          Object.assign(sourceMetadata, parsed)
        } catch {
          sourceMetadata.additional_data = additionalData
        }
      }
    }
    createRun.mutate(
      { pipeline_id: pipelineId, source_type: 'manual', source_metadata: sourceMetadata as never },
      {
        onSuccess: (run) => {
          setModalOpen(false)
          setSelectedProjectId('')
          navigate(`/runs/${run.run_id}`)
        },
      },
    )
  }
 
  return (
    <div className="flex flex-col gap-6">
      <div className="flex items-center justify-between">
        <h1 className="text-2xl font-bold">Dashboard</h1>
        <Button onClick={() => setModalOpen(true)}>
          <Play className="mr-2 h-4 w-4" />
          New Run
        </Button>
      </div>

      <div className="grid grid-cols-1 gap-4 sm:grid-cols-2 lg:grid-cols-3 xl:grid-cols-5">
        {statCards.map((card) => (
          <div key={card.label} onClick={card.onClick} className={card.onClick ? 'cursor-pointer' : ''}>
            <StatsCard icon={card.icon} label={card.label} value={card.value} accent={card.accent} />
          </div>
        ))}
      </div>
      <p className="-mt-2 text-xs text-muted-foreground">Token stats based on last 50 runs</p>
 
      <div className="flex items-center justify-between">
        <h2 className="text-lg font-semibold">Recent Runs</h2>
        <Button variant="default" onClick={() => navigate('/runs')}>
          View All Runs →
        </Button>
      </div>
 
      <DataTable
        columns={columns}
        data={runs as unknown as Record<string, unknown>[]}
        isLoading={isLoading}
        error={error ?? null}
        onRetry={() => refetch()}
        emptyMessage="No runs yet"
        emptyAction={
          <Button variant="outline" onClick={() => setModalOpen(true)}>
            Trigger your first run
          </Button>
        }
        onRowClick={(item) => navigate(`/runs/${item.run_id as string}`)}
      />
 
      <ManualTriggerModal
        open={modalOpen}
        projects={projects}
        pipelines={pipelines}
        onProjectChange={(pid) => setSelectedProjectId(pid)}
        onSubmit={handleTriggerRun}
        onCancel={() => { setModalOpen(false); setSelectedProjectId('') }}
      />
    </div>
  )
}